context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: helloworld.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Helloworld {
/// <summary>Holder for reflection information generated from helloworld.proto</summary>
public static partial class HelloworldReflection {
#region Descriptor
/// <summary>File descriptor for helloworld.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static HelloworldReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChBoZWxsb3dvcmxkLnByb3RvEgpoZWxsb3dvcmxkIhwKDEhlbGxvUmVxdWVz",
"dBIMCgRuYW1lGAEgASgJIh0KCkhlbGxvUmVwbHkSDwoHbWVzc2FnZRgBIAEo",
"CTJJCgdHcmVldGVyEj4KCFNheUhlbGxvEhguaGVsbG93b3JsZC5IZWxsb1Jl",
"cXVlc3QaFi5oZWxsb3dvcmxkLkhlbGxvUmVwbHkiAEI2Chtpby5ncnBjLmV4",
"YW1wbGVzLmhlbGxvd29ybGRCD0hlbGxvV29ybGRQcm90b1ABogIDSExXYgZw",
"cm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Helloworld.HelloRequest), global::Helloworld.HelloRequest.Parser, new[]{ "Name" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Helloworld.HelloReply), global::Helloworld.HelloReply.Parser, new[]{ "Message" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// The request message containing the user's name.
/// </summary>
public sealed partial class HelloRequest : pb::IMessage<HelloRequest> {
private static readonly pb::MessageParser<HelloRequest> _parser = new pb::MessageParser<HelloRequest>(() => new HelloRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<HelloRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Helloworld.HelloworldReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HelloRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HelloRequest(HelloRequest other) : this() {
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HelloRequest Clone() {
return new HelloRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as HelloRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(HelloRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(HelloRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The response message containing the greetings
/// </summary>
public sealed partial class HelloReply : pb::IMessage<HelloReply> {
private static readonly pb::MessageParser<HelloReply> _parser = new pb::MessageParser<HelloReply>(() => new HelloReply());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<HelloReply> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Helloworld.HelloworldReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HelloReply() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HelloReply(HelloReply other) : this() {
message_ = other.message_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public HelloReply Clone() {
return new HelloReply(this);
}
/// <summary>Field number for the "message" field.</summary>
public const int MessageFieldNumber = 1;
private string message_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Message {
get { return message_; }
set {
message_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as HelloReply);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(HelloReply other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Message != other.Message) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Message.Length != 0) hash ^= Message.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Message.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Message);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Message.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Message);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(HelloReply other) {
if (other == null) {
return;
}
if (other.Message.Length != 0) {
Message = other.Message;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Message = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute;
using Encoding = System.Text.Encoding;
namespace System.Xml.Linq
{
/// <summary>
/// Represents an XML document.
/// </summary>
/// <remarks>
/// An <see cref="XDocument"/> can contain:
/// <list>
/// <item>
/// A Document Type Declaration (DTD), see <see cref="XDocumentType"/>
/// </item>
/// <item>One root element.</item>
/// <item>Zero or more <see cref="XComment"/> objects.</item>
/// <item>Zero or more <see cref="XProcessingInstruction"/> objects.</item>
/// </list>
/// </remarks>
public class XDocument : XContainer
{
private XDeclaration _declaration;
///<overloads>
/// Initializes a new instance of the <see cref="XDocument"/> class.
/// Overloaded constructors are provided for creating a new empty
/// <see cref="XDocument"/>, creating an <see cref="XDocument"/> with
/// a parameter list of initial content, and as a copy of another
/// <see cref="XDocument"/> object.
/// </overloads>
/// <summary>
/// Initializes a new instance of the <see cref="XDocument"/> class.
/// </summary>
public XDocument()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="XDocument"/> class with the specified content.
/// </summary>
/// <param name="content">
/// A parameter list of content objects to add to this document.
/// </param>
/// <remarks>
/// Valid content includes:
/// <list>
/// <item>Zero or one <see cref="XDocumentType"/> objects</item>
/// <item>Zero or one elements</item>
/// <item>Zero or more comments</item>
/// <item>Zero or more processing instructions</item>
/// </list>
/// See <see cref="XContainer.Add(object)"/> for details about the content that can be added
/// using this method.
/// </remarks>
public XDocument(params object[] content)
: this()
{
AddContentSkipNotify(content);
}
/// <summary>
/// Initializes a new instance of the <see cref="XDocument"/> class
/// with the specified <see cref="XDeclaration"/> and content.
/// </summary>
/// <param name="declaration">
/// The XML declaration for the document.
/// </param>
/// <param name="content">
/// The contents of the document.
/// </param>
/// <remarks>
/// Valid content includes:
/// <list>
/// <item>Zero or one <see cref="XDocumentType"/> objects</item>
/// <item>Zero or one elements</item>
/// <item>Zero or more comments</item>
/// <item>Zero or more processing instructions</item>
/// <item></item>
/// </list>
/// See <see cref="XContainer.Add(object)"/> for details about the content that can be added
/// using this method.
/// </remarks>
public XDocument(XDeclaration declaration, params object[] content)
: this(content)
{
_declaration = declaration;
}
/// <summary>
/// Initializes a new instance of the <see cref="XDocument"/> class from an
/// existing XDocument object.
/// </summary>
/// <param name="other">
/// The <see cref="XDocument"/> object that will be copied.
/// </param>
public XDocument(XDocument other)
: base(other)
{
if (other._declaration != null)
{
_declaration = new XDeclaration(other._declaration);
}
}
/// <summary>
/// Gets the XML declaration for this document.
/// </summary>
public XDeclaration Declaration
{
get { return _declaration; }
set { _declaration = value; }
}
/// <summary>
/// Gets the Document Type Definition (DTD) for this document.
/// </summary>
public XDocumentType DocumentType
{
get
{
return GetFirstNode<XDocumentType>();
}
}
/// <summary>
/// Gets the node type for this node.
/// </summary>
/// <remarks>
/// This property will always return XmlNodeType.Document.
/// </remarks>
public override XmlNodeType NodeType
{
get
{
return XmlNodeType.Document;
}
}
/// <summary>
/// Gets the root element of the XML Tree for this document.
/// </summary>
public XElement Root
{
get
{
return GetFirstNode<XElement>();
}
}
/// <overloads>
/// The Load method provides multiple strategies for creating a new
/// <see cref="XDocument"/> and initializing it from a data source containing
/// raw XML. Load from a file (passing in a URI to the file), a
/// <see cref="Stream"/>, a <see cref="TextReader"/>, or an
/// <see cref="XmlReader"/>. Note: Use <see cref="XDocument.Parse(string)"/>
/// to create an <see cref="XDocument"/> from a string containing XML.
/// <seealso cref="XDocument.Parse(string)"/>
/// </overloads>
/// <summary>
/// Create a new <see cref="XDocument"/> based on the contents of the file
/// referenced by the URI parameter passed in. Note: Use
/// <see cref="XDocument.Parse(string)"/> to create an <see cref="XDocument"/> from
/// a string containing XML.
/// <seealso cref="XmlReader.Create(string)"/>
/// <seealso cref="XDocument.Parse(string)"/>
/// </summary>
/// <remarks>
/// This method uses the <see cref="XmlReader.Create(string)"/> method to create
/// an <see cref="XmlReader"/> to read the raw XML into the underlying
/// XML tree.
/// </remarks>
/// <param name="uri">
/// A URI string referencing the file to load into a new <see cref="XDocument"/>.
/// </param>
/// <returns>
/// An <see cref="XDocument"/> initialized with the contents of the file referenced
/// in the passed in uri parameter.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "Back-compat with System.Xml.")]
public static XDocument Load(string uri)
{
return Load(uri, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XDocument"/> based on the contents of the file
/// referenced by the URI parameter passed in. Optionally, whitespace can be preserved.
/// <see cref="XmlReader.Create(string)"/>
/// </summary>
/// <remarks>
/// This method uses the <see cref="XmlReader.Create(string)"/> method to create
/// an <see cref="XmlReader"/> to read the raw XML into an underlying
/// XML tree. If LoadOptions.PreserveWhitespace is enabled then
/// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="uri">
/// A string representing the URI of the file to be loaded into a new <see cref="XDocument"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// An <see cref="XDocument"/> initialized with the contents of the file referenced
/// in the passed uri parameter. If LoadOptions.PreserveWhitespace is enabled then
/// all whitespace will be preserved.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "Back-compat with System.Xml.")]
public static XDocument Load(string uri, LoadOptions options)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
using (XmlReader r = XmlReader.Create(uri, rs))
{
return Load(r, options);
}
}
/// <summary>
/// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using
/// the passed <see cref="Stream"/> parameter.
/// </summary>
/// <param name="stream">
/// A <see cref="Stream"/> containing the raw XML to read into the newly
/// created <see cref="XDocument"/>.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed in
/// <see cref="Stream"/>.
/// </returns>
public static XDocument Load(Stream stream)
{
return Load(stream, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using
/// the passed <see cref="Stream"/> parameter. Optionally whitespace handling
/// can be preserved.
/// </summary>
/// <remarks>
/// If LoadOptions.PreserveWhitespace is enabled then
/// the underlying <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> containing the raw XML to read into the newly
/// created <see cref="XDocument"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed in
/// <see cref="Stream"/>.
/// </returns>
public static XDocument Load(Stream stream, LoadOptions options)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
using (XmlReader r = XmlReader.Create(stream, rs))
{
return Load(r, options);
}
}
/// <summary>
/// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using
/// the passed <see cref="Stream"/> parameter. Optionally whitespace handling
/// can be preserved.
/// </summary>
/// <remarks>
/// If LoadOptions.PreserveWhitespace is enabled then
/// the underlying <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> containing the raw XML to read into the newly
/// created <see cref="XDocument"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <param name="cancellationToken">
/// A cancellation token.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed in
/// <see cref="Stream"/>.
/// </returns>
public static async Task<XDocument> LoadAsync(Stream stream, LoadOptions options, CancellationToken cancellationToken)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
rs.Async = true;
using (XmlReader r = XmlReader.Create(stream, rs))
{
return await LoadAsync(r, options, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using
/// the passed <see cref="TextReader"/> parameter.
/// </summary>
/// <param name="textReader">
/// A <see cref="TextReader"/> containing the raw XML to read into the newly
/// created <see cref="XDocument"/>.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed in
/// <see cref="TextReader"/>.
/// </returns>
public static XDocument Load(TextReader textReader)
{
return Load(textReader, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using
/// the passed <see cref="TextReader"/> parameter. Optionally whitespace handling
/// can be preserved.
/// </summary>
/// <remarks>
/// If LoadOptions.PreserveWhitespace is enabled then
/// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="textReader">
/// A <see cref="TextReader"/> containing the raw XML to read into the newly
/// created <see cref="XDocument"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed in
/// <see cref="TextReader"/>.
/// </returns>
public static XDocument Load(TextReader textReader, LoadOptions options)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
using (XmlReader r = XmlReader.Create(textReader, rs))
{
return Load(r, options);
}
}
/// <summary>
/// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using
/// the passed <see cref="TextReader"/> parameter. Optionally whitespace handling
/// can be preserved.
/// </summary>
/// <remarks>
/// If LoadOptions.PreserveWhitespace is enabled then
/// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="textReader">
/// A <see cref="TextReader"/> containing the raw XML to read into the newly
/// created <see cref="XDocument"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <param name="cancellationToken">
/// A cancellation token.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed in
/// <see cref="TextReader"/>.
/// </returns>
public static async Task<XDocument> LoadAsync(TextReader textReader, LoadOptions options, CancellationToken cancellationToken)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
rs.Async = true;
using (XmlReader r = XmlReader.Create(textReader, rs))
{
return await LoadAsync(r, options, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Create a new <see cref="XDocument"/> containing the contents of the
/// passed in <see cref="XmlReader"/>.
/// </summary>
/// <param name="reader">
/// An <see cref="XmlReader"/> containing the XML to be read into the new
/// <see cref="XDocument"/>.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed
/// in <see cref="XmlReader"/>.
/// </returns>
public static XDocument Load(XmlReader reader)
{
return Load(reader, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XDocument"/> containing the contents of the
/// passed in <see cref="XmlReader"/>.
/// </summary>
/// <param name="reader">
/// An <see cref="XmlReader"/> containing the XML to be read into the new
/// <see cref="XDocument"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed
/// in <see cref="XmlReader"/>.
/// </returns>
public static XDocument Load(XmlReader reader, LoadOptions options)
{
if (reader == null) throw new ArgumentNullException(nameof(reader));
if (reader.ReadState == ReadState.Initial) reader.Read();
XDocument d = InitLoad(reader, options);
d.ReadContentFrom(reader, options);
if( !reader.EOF) throw new InvalidOperationException(SR.InvalidOperation_ExpectedEndOfFile);
if (d.Root == null) throw new InvalidOperationException(SR.InvalidOperation_MissingRoot);
return d;
}
/// <summary>
/// Create a new <see cref="XDocument"/> containing the contents of the
/// passed in <see cref="XmlReader"/>.
/// </summary>
/// <param name="reader">
/// An <see cref="XmlReader"/> containing the XML to be read into the new
/// <see cref="XDocument"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <param name="cancellationToken">
/// A cancellation token.
/// </param>
/// <returns>
/// A new <see cref="XDocument"/> containing the contents of the passed
/// in <see cref="XmlReader"/>.
/// </returns>
public static Task<XDocument> LoadAsync(XmlReader reader, LoadOptions options, CancellationToken cancellationToken)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<XDocument>(cancellationToken);
return LoadAsyncInternal(reader, options, cancellationToken);
}
private static async Task<XDocument> LoadAsyncInternal(XmlReader reader, LoadOptions options, CancellationToken cancellationToken)
{
if (reader.ReadState == ReadState.Initial)
{
await reader.ReadAsync().ConfigureAwait(false);
}
XDocument d = InitLoad(reader, options);
await d.ReadContentFromAsync(reader, options, cancellationToken).ConfigureAwait(false);
if (!reader.EOF) throw new InvalidOperationException(SR.InvalidOperation_ExpectedEndOfFile);
if (d.Root == null) throw new InvalidOperationException(SR.InvalidOperation_MissingRoot);
return d;
}
/// <summary>
/// Performs shared initialization between Load and LoadAsync.
/// </summary>
static XDocument InitLoad(XmlReader reader, LoadOptions options)
{
XDocument d = new XDocument();
if ((options & LoadOptions.SetBaseUri) != 0)
{
string baseUri = reader.BaseURI;
if (!string.IsNullOrEmpty(baseUri))
{
d.SetBaseUri(baseUri);
}
}
if ((options & LoadOptions.SetLineInfo) != 0)
{
IXmlLineInfo li = reader as IXmlLineInfo;
if (li != null && li.HasLineInfo())
{
d.SetLineInfo(li.LineNumber, li.LinePosition);
}
}
if (reader.NodeType == XmlNodeType.XmlDeclaration)
{
d.Declaration = new XDeclaration(reader);
}
return d;
}
/// <overloads>
/// Create a new <see cref="XDocument"/> from a string containing
/// XML. Optionally whitespace can be preserved.
/// </overloads>
/// <summary>
/// Create a new <see cref="XDocument"/> from a string containing
/// XML.
/// </summary>
/// <param name="text">
/// A string containing XML.
/// </param>
/// <returns>
/// An <see cref="XDocument"/> containing an XML tree initialized from the
/// passed in XML string.
/// </returns>
public static XDocument Parse(string text)
{
return Parse(text, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XDocument"/> from a string containing
/// XML. Optionally whitespace can be preserved.
/// </summary>
/// <remarks>
/// This method uses <see cref="XmlReader.Create(TextReader, XmlReaderSettings)"/>,
/// passing it a StringReader constructed from the passed in XML String. If
/// <see cref="LoadOptions.PreserveWhitespace"/> is enabled then
/// <see cref="XmlReaderSettings.IgnoreWhitespace"/> is set to false. See
/// <see cref="XmlReaderSettings.IgnoreWhitespace"/> for more information on
/// whitespace handling.
/// </remarks>
/// <param name="text">
/// A string containing XML.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// An <see cref="XDocument"/> containing an XML tree initialized from the
/// passed in XML string.
/// </returns>
public static XDocument Parse(string text, LoadOptions options)
{
using (StringReader sr = new StringReader(text))
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
using (XmlReader r = XmlReader.Create(sr, rs))
{
return Load(r, options);
}
}
}
/// <summary>
/// Output this <see cref="XDocument"/> to the passed in <see cref="Stream"/>.
/// </summary>
/// <remarks>
/// The format will be indented by default. If you want
/// no indenting then use the SaveOptions version of Save (see
/// <see cref="XDocument.Save(Stream, SaveOptions)"/>) enabling
/// SaveOptions.DisableFormatting
/// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations.
/// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options.
/// </remarks>
/// <param name="stream">
/// The <see cref="Stream"/> to output this <see cref="XDocument"/> to.
/// </param>
public void Save(Stream stream)
{
Save(stream, GetSaveOptionsFromAnnotations());
}
/// <summary>
/// Output this <see cref="XDocument"/> to a <see cref="Stream"/>.
/// </summary>
/// <param name="stream">
/// The <see cref="Stream"/> to output the XML to.
/// </param>
/// <param name="options">
/// If SaveOptions.DisableFormatting is enabled the output is not indented.
/// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed.
/// </param>
public void Save(Stream stream, SaveOptions options)
{
XmlWriterSettings ws = GetXmlWriterSettings(options);
if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding))
{
try
{
ws.Encoding = Encoding.GetEncoding(_declaration.Encoding);
}
catch (ArgumentException)
{
}
}
using (XmlWriter w = XmlWriter.Create(stream, ws))
{
Save(w);
}
}
/// <summary>
/// Output this <see cref="XDocument"/> to a <see cref="Stream"/>.
/// </summary>
/// <param name="stream">
/// The <see cref="Stream"/> to output the XML to.
/// </param>
/// <param name="options">
/// If SaveOptions.DisableFormatting is enabled the output is not indented.
/// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed.
/// </param>
/// <param name="cancellationToken">A cancellation token.</param>
public async Task SaveAsync(Stream stream, SaveOptions options, CancellationToken cancellationToken)
{
XmlWriterSettings ws = GetXmlWriterSettings(options);
ws.Async = true;
if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding))
{
try
{
ws.Encoding = Encoding.GetEncoding(_declaration.Encoding);
}
catch (ArgumentException)
{
}
}
using (XmlWriter w = XmlWriter.Create(stream, ws))
{
await WriteToAsync(w, cancellationToken).ConfigureAwait(false);
await w.FlushAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Output this <see cref="XDocument"/> to the passed in <see cref="TextWriter"/>.
/// </summary>
/// <remarks>
/// The format will be indented by default. If you want
/// no indenting then use the SaveOptions version of Save (see
/// <see cref="XDocument.Save(TextWriter, SaveOptions)"/>) enabling
/// SaveOptions.DisableFormatting
/// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations.
/// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options.
/// </remarks>
/// <param name="textWriter">
/// The <see cref="TextWriter"/> to output this <see cref="XDocument"/> to.
/// </param>
public void Save(TextWriter textWriter)
{
Save(textWriter, GetSaveOptionsFromAnnotations());
}
/// <summary>
/// Output this <see cref="XDocument"/> to a <see cref="TextWriter"/>.
/// </summary>
/// <param name="textWriter">
/// The <see cref="TextWriter"/> to output the XML to.
/// </param>
/// <param name="options">
/// If SaveOptions.DisableFormatting is enabled the output is not indented.
/// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed.
/// </param>
public void Save(TextWriter textWriter, SaveOptions options)
{
XmlWriterSettings ws = GetXmlWriterSettings(options);
using (XmlWriter w = XmlWriter.Create(textWriter, ws))
{
Save(w);
}
}
/// <summary>
/// Output this <see cref="XDocument"/> to an <see cref="XmlWriter"/>.
/// </summary>
/// <param name="writer">
/// The <see cref="XmlWriter"/> to output the XML to.
/// </param>
public void Save(XmlWriter writer)
{
WriteTo(writer);
}
/// <summary>
/// Output this <see cref="XDocument"/> to a <see cref="TextWriter"/>.
/// </summary>
/// <param name="textWriter">
/// The <see cref="TextWriter"/> to output the XML to.
/// </param>
/// <param name="options">
/// If SaveOptions.DisableFormatting is enabled the output is not indented.
/// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed.
/// </param>
/// <param name="cancellationToken">A cancellation token.</param>
public async Task SaveAsync(TextWriter textWriter, SaveOptions options, CancellationToken cancellationToken)
{
XmlWriterSettings ws = GetXmlWriterSettings(options);
ws.Async = true;
using (XmlWriter w = XmlWriter.Create(textWriter, ws))
{
await WriteToAsync(w, cancellationToken).ConfigureAwait(false);
await w.FlushAsync().ConfigureAwait(false);
}
}
///<overloads>
/// Outputs this <see cref="XDocument"/>'s underlying XML tree. The output can
/// be saved to a file, a <see cref="Stream"/>, a <see cref="TextWriter"/>,
/// or an <see cref="XmlWriter"/>. Optionally whitespace can be preserved.
/// </overloads>
/// <summary>
/// Output this <see cref="XDocument"/> to a file.
/// </summary>
/// <remarks>
/// The format will be indented by default. If you want
/// no indenting then use the SaveOptions version of Save (see
/// <see cref="XDocument.Save(string, SaveOptions)"/>) enabling
/// SaveOptions.DisableFormatting.
/// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations.
/// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options.
/// </remarks>
/// <param name="fileName">
/// The name of the file to output the XML to.
/// </param>
public void Save(string fileName)
{
Save(fileName, GetSaveOptionsFromAnnotations());
}
/// <summary>
/// Output this <see cref="XDocument"/> to an <see cref="XmlWriter"/>.
/// </summary>
/// <param name="writer">
/// The <see cref="XmlWriter"/> to output the XML to.
/// </param>
/// <param name="cancellationToken">
/// A cancellation token.
/// </param>
public Task SaveAsync(XmlWriter writer, CancellationToken cancellationToken)
{
return WriteToAsync(writer, cancellationToken);
}
/// <summary>
/// Output this <see cref="XDocument"/> to a file.
/// </summary>
/// <param name="fileName">
/// The name of the file to output the XML to.
/// </param>
/// <param name="options">
/// If SaveOptions.DisableFormatting is enabled the output is not indented.
/// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed.
/// </param>
public void Save(string fileName, SaveOptions options)
{
XmlWriterSettings ws = GetXmlWriterSettings(options);
if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding))
{
try
{
ws.Encoding = Encoding.GetEncoding(_declaration.Encoding);
}
catch (ArgumentException)
{
}
}
using (XmlWriter w = XmlWriter.Create(fileName, ws))
{
Save(w);
}
}
/// <summary>
/// Output this <see cref="XDocument"/>'s underlying XML tree to the
/// passed in <see cref="XmlWriter"/>.
/// <seealso cref="XDocument.Save(XmlWriter)"/>
/// </summary>
/// <param name="writer">
/// The <see cref="XmlWriter"/> to output the content of this
/// <see cref="XDocument"/>.
/// </param>
public override void WriteTo(XmlWriter writer)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
if (_declaration != null && _declaration.Standalone == "yes")
{
writer.WriteStartDocument(true);
}
else if (_declaration != null && _declaration.Standalone == "no")
{
writer.WriteStartDocument(false);
}
else
{
writer.WriteStartDocument();
}
WriteContentTo(writer);
writer.WriteEndDocument();
}
/// <summary>
/// Output this <see cref="XDocument"/>'s underlying XML tree to the
/// passed in <see cref="XmlWriter"/>.
/// <seealso cref="XDocument.Save(XmlWriter)"/>
/// </summary>
/// <param name="writer">
/// The <see cref="XmlWriter"/> to output the content of this
/// <see cref="XDocument"/>.
/// </param>
/// <param name="cancellationToken">A cancellation token.</param>
public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken)
{
if (writer == null)
throw new ArgumentNullException(nameof(writer));
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
return WriteToAsyncInternal(writer, cancellationToken);
}
private async Task WriteToAsyncInternal(XmlWriter writer, CancellationToken cancellationToken)
{
Task tStart;
if (_declaration != null && _declaration.Standalone == "yes")
{
tStart = writer.WriteStartDocumentAsync(true);
}
else if (_declaration != null && _declaration.Standalone == "no")
{
tStart = writer.WriteStartDocumentAsync(false);
}
else
{
tStart = writer.WriteStartDocumentAsync();
}
await tStart.ConfigureAwait(false);
await WriteContentToAsync(writer, cancellationToken).ConfigureAwait(false);
await writer.WriteEndDocumentAsync().ConfigureAwait(false);
}
internal override void AddAttribute(XAttribute a)
{
throw new ArgumentException(SR.Argument_AddAttribute);
}
internal override void AddAttributeSkipNotify(XAttribute a)
{
throw new ArgumentException(SR.Argument_AddAttribute);
}
internal override XNode CloneNode()
{
return new XDocument(this);
}
internal override bool DeepEquals(XNode node)
{
XDocument other = node as XDocument;
return other != null && ContentsEqual(other);
}
internal override int GetDeepHashCode()
{
return ContentsHashCode();
}
private T GetFirstNode<T>() where T : XNode
{
XNode n = content as XNode;
if (n != null)
{
do
{
n = n.next;
T e = n as T;
if (e != null) return e;
} while (n != content);
}
return null;
}
internal static bool IsWhitespace(string s)
{
foreach (char ch in s)
{
if (ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n') return false;
}
return true;
}
internal override void ValidateNode(XNode node, XNode previous)
{
switch (node.NodeType)
{
case XmlNodeType.Text:
ValidateString(((XText)node).Value);
break;
case XmlNodeType.Element:
ValidateDocument(previous, XmlNodeType.DocumentType, XmlNodeType.None);
break;
case XmlNodeType.DocumentType:
ValidateDocument(previous, XmlNodeType.None, XmlNodeType.Element);
break;
case XmlNodeType.CDATA:
throw new ArgumentException(SR.Format(SR.Argument_AddNode, XmlNodeType.CDATA));
case XmlNodeType.Document:
throw new ArgumentException(SR.Format(SR.Argument_AddNode, XmlNodeType.Document));
}
}
private void ValidateDocument(XNode previous, XmlNodeType allowBefore, XmlNodeType allowAfter)
{
XNode n = content as XNode;
if (n != null)
{
if (previous == null) allowBefore = allowAfter;
do
{
n = n.next;
XmlNodeType nt = n.NodeType;
if (nt == XmlNodeType.Element || nt == XmlNodeType.DocumentType)
{
if (nt != allowBefore) throw new InvalidOperationException(SR.InvalidOperation_DocumentStructure);
allowBefore = XmlNodeType.None;
}
if (n == previous) allowBefore = allowAfter;
} while (n != content);
}
}
internal override void ValidateString(string s)
{
if (!IsWhitespace(s)) throw new ArgumentException(SR.Argument_AddNonWhitespace);
}
}
}
| |
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 PocoDemo.Web.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>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <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 factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private 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 to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified 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) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), 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="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <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.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
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,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[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;
}
}
}
| |
// <copyright file="FtpLoginStateMachine.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FubarDev.FtpServer.Authentication;
using FubarDev.FtpServer.Authorization;
namespace FubarDev.FtpServer
{
/// <summary>
/// A state machine for FTP logins.
/// </summary>
public class FtpLoginStateMachine : FtpStateMachine<SecurityStatus>, IFtpLoginStateMachine
{
private static readonly List<Transition> _transitions = new List<Transition>
{
new Transition(SecurityStatus.Unauthenticated, SecurityStatus.Unauthenticated, "AUTH", 4),
new Transition(SecurityStatus.Unauthenticated, SecurityStatus.Unauthenticated, "AUTH", 5),
new Transition(SecurityStatus.Unauthenticated, SecurityStatus.Authenticated, "AUTH", SecurityActionResult.SecurityDataExchangeComplete),
new Transition(SecurityStatus.Unauthenticated, SecurityStatus.NeedSecurityData, "AUTH", SecurityActionResult.RequestedSecurityMechanismOkay),
new Transition(SecurityStatus.NeedSecurityData, SecurityStatus.Unauthenticated, "ADAT", 4),
new Transition(SecurityStatus.NeedSecurityData, SecurityStatus.Unauthenticated, "ADAT", 5),
new Transition(SecurityStatus.NeedSecurityData, SecurityStatus.Authenticated, "ADAT", SecurityActionResult.SecurityDataExchangeSuccessful),
new Transition(SecurityStatus.NeedSecurityData, SecurityStatus.NeedSecurityData, "ADAT", SecurityActionResult.SecurityDataAcceptable),
new Transition(SecurityStatus.Unauthenticated, SecurityStatus.Authorized, "USER", 2),
new Transition(SecurityStatus.Unauthenticated, SecurityStatus.NeedPassword, "USER", 3),
new Transition(SecurityStatus.Unauthenticated, SecurityStatus.Authenticated, "USER", 4),
new Transition(SecurityStatus.Unauthenticated, SecurityStatus.Authenticated, "USER", 5),
new Transition(SecurityStatus.Authenticated, SecurityStatus.Authorized, "USER", 2),
new Transition(SecurityStatus.Authenticated, SecurityStatus.NeedPassword, "USER", 3),
new Transition(SecurityStatus.Authenticated, SecurityStatus.Authenticated, "USER", 4),
new Transition(SecurityStatus.Authenticated, SecurityStatus.Authenticated, "USER", 5),
new Transition(SecurityStatus.NeedPassword, SecurityStatus.Authorized, "PASS", 2),
new Transition(SecurityStatus.NeedPassword, SecurityStatus.NeedAccount, "PASS", 3),
new Transition(SecurityStatus.NeedPassword, SecurityStatus.Authenticated, "PASS", 4),
new Transition(SecurityStatus.NeedPassword, SecurityStatus.Authenticated, "PASS", 5),
new Transition(SecurityStatus.NeedAccount, SecurityStatus.Authorized, "ACCT", 2),
new Transition(SecurityStatus.NeedAccount, SecurityStatus.Authorized, "ACCT", 3),
new Transition(SecurityStatus.NeedAccount, SecurityStatus.Authenticated, "ACCT", 4),
new Transition(SecurityStatus.NeedAccount, SecurityStatus.Authenticated, "ACCT", 5),
};
private readonly IFtpHostSelector _hostSelector;
private IAuthenticationMechanism? _filteredAuthenticationMechanism;
private IAuthorizationMechanism? _filteredAuthorizationMechanism;
private IAuthenticationMechanism? _selectedAuthenticationMechanism;
private IAuthorizationMechanism? _selectedAuthorizationMechanism;
private IAuthenticationMechanism? _preselectedAuthenticationMechanism;
/// <summary>
/// Initializes a new instance of the <see cref="FtpLoginStateMachine"/> class.
/// </summary>
/// <param name="connection">The FTP connection.</param>
/// <param name="hostSelector">The FTP host selector.</param>
public FtpLoginStateMachine(
IFtpConnection connection,
IFtpHostSelector hostSelector)
: base(connection, _transitions, SecurityStatus.Unauthenticated)
{
_hostSelector = hostSelector;
}
/// <inheritdoc />
public IAuthenticationMechanism? SelectedAuthenticationMechanism => _selectedAuthenticationMechanism;
/// <inheritdoc />
public IAuthorizationMechanism? SelectedAuthorizationMechanism => _selectedAuthorizationMechanism;
/// <summary>
/// Gets the selected host.
/// </summary>
public IFtpHost SelectedHost => _hostSelector.SelectedHost;
/// <inheritdoc />
public void Activate(IAuthenticationMechanism authenticationMechanism)
{
_selectedAuthenticationMechanism = _filteredAuthenticationMechanism =
_preselectedAuthenticationMechanism = authenticationMechanism;
SetStatus(SecurityStatus.Authenticated);
}
/// <inheritdoc />
public override void Reset()
{
base.Reset();
if (_preselectedAuthenticationMechanism != null)
{
Activate(_preselectedAuthenticationMechanism);
}
}
/// <inheritdoc />
protected override async Task<IFtpResponse?> ExecuteCommandAsync(FtpCommand ftpCommand, CancellationToken cancellationToken = default)
{
switch (ftpCommand.Name.Trim().ToUpperInvariant())
{
case "AUTH":
return await HandleAuthAsync(ftpCommand.Argument, cancellationToken)
.ConfigureAwait(false);
case "ADAT":
return await HandleAdatAsync(ftpCommand.Argument, cancellationToken)
.ConfigureAwait(false);
case "USER":
return await HandleUserAsync(ftpCommand.Argument, cancellationToken)
.ConfigureAwait(false);
case "PASS":
return await HandlePassAsync(ftpCommand.Argument, cancellationToken)
.ConfigureAwait(false);
case "ACCT":
return await HandleAcctAsync(ftpCommand.Argument, cancellationToken)
.ConfigureAwait(false);
default:
return await UnhandledCommandAsync(ftpCommand, cancellationToken)
.ConfigureAwait(false);
}
}
/// <inheritdoc />
protected override void OnStatusChanged(SecurityStatus from, SecurityStatus to)
{
if (to == SecurityStatus.Unauthenticated)
{
_filteredAuthenticationMechanism = null;
_selectedAuthenticationMechanism = null;
foreach (var authenticationMechanism in SelectedHost.AuthenticationMechanisms)
{
authenticationMechanism.Reset();
}
}
else if (to == SecurityStatus.Authenticated)
{
_selectedAuthorizationMechanism = null;
_filteredAuthorizationMechanism = null;
foreach (var authorizationMechanism in SelectedHost.AuthorizationMechanisms)
{
authorizationMechanism.Reset(SelectedAuthenticationMechanism);
}
if (from == SecurityStatus.Unauthenticated || from == SecurityStatus.NeedSecurityData)
{
// Successfull AUTH or ADAT
_selectedAuthenticationMechanism = _filteredAuthenticationMechanism;
}
}
else if (to == SecurityStatus.Authorized)
{
_selectedAuthorizationMechanism = _filteredAuthorizationMechanism;
}
}
/// <summary>
/// Called when the command couldn't be handled.
/// </summary>
/// <param name="ftpCommand">The FTP command causing the problem.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The FTP response to be returned.</returns>
protected virtual Task<IFtpResponse> UnhandledCommandAsync(FtpCommand ftpCommand, CancellationToken cancellationToken)
{
return Task.FromResult<IFtpResponse>(new FtpResponse(421, T("Service not available")));
}
private async Task<IFtpResponse> HandleAuthAsync(string argument, CancellationToken cancellationToken)
{
var authenticationMechanism = SelectedHost.AuthenticationMechanisms
.SingleOrDefault(x => x.CanHandle(argument));
if (authenticationMechanism == null)
{
return new FtpResponse(504, T("Unsupported security mechanism"));
}
_filteredAuthenticationMechanism = authenticationMechanism;
return await authenticationMechanism.HandleAuthAsync(argument, cancellationToken).ConfigureAwait(false);
}
private Task<IFtpResponse> HandleAdatAsync(string argument, CancellationToken cancellationToken)
{
if (_filteredAuthenticationMechanism is null)
{
return Task.FromResult<IFtpResponse>(new FtpResponse(503, T("Bad sequence of commands")));
}
byte[] data;
if (string.IsNullOrWhiteSpace(argument))
{
data = new byte[0];
}
else
{
try
{
data = Convert.FromBase64String(argument);
}
catch (FormatException)
{
return Task.FromResult<IFtpResponse>(new FtpResponse(501, T("Syntax error in parameters or arguments.")));
}
}
return _filteredAuthenticationMechanism.HandleAdatAsync(data, cancellationToken);
}
private async Task<IFtpResponse> HandleUserAsync(string argument, CancellationToken cancellationToken)
{
var results = new List<Tuple<IFtpResponse, IAuthorizationMechanism>>();
foreach (var authorizationMechanism in SelectedHost.AuthorizationMechanisms)
{
var response = await authorizationMechanism.HandleUserAsync(argument, cancellationToken)
.ConfigureAwait(false);
if (response.Code >= 200 && response.Code < 300)
{
_filteredAuthorizationMechanism = authorizationMechanism;
return response;
}
results.Add(Tuple.Create(response, authorizationMechanism));
}
var mechanismNeedingPassword = results.FirstOrDefault(x => x.Item1.Code >= 300 && x.Item1.Code < 400);
if (mechanismNeedingPassword != null)
{
_filteredAuthorizationMechanism = mechanismNeedingPassword.Item2;
return mechanismNeedingPassword.Item1;
}
return results.First().Item1;
}
private Task<IFtpResponse> HandlePassAsync(string argument, CancellationToken cancellationToken)
{
if (_filteredAuthorizationMechanism is null)
{
return Task.FromResult<IFtpResponse>(new FtpResponse(503, T("Bad sequence of commands")));
}
return _filteredAuthorizationMechanism.HandlePassAsync(argument, cancellationToken);
}
private Task<IFtpResponse> HandleAcctAsync(string argument, CancellationToken cancellationToken)
{
if (_filteredAuthorizationMechanism is null)
{
return Task.FromResult<IFtpResponse>(new FtpResponse(503, T("Bad sequence of commands")));
}
return _filteredAuthorizationMechanism.HandleAcctAsync(argument, cancellationToken);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace EasyStitch.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.Project.Automation
{
[ComVisible(true), CLSCompliant(false)]
public class OAProjectItem<T> : EnvDTE.ProjectItem
where T : HierarchyNode
{
#region fields
private T node;
private OAProject project;
#endregion
#region properties
protected T Node
{
get
{
return this.node;
}
}
/// <summary>
/// Returns the automation project
/// </summary>
protected OAProject Project
{
get
{
return this.project;
}
}
#endregion
#region ctors
public OAProjectItem(OAProject project, T node)
{
this.node = node;
this.project = project;
}
#endregion
#region EnvDTE.ProjectItem
/// <summary>
/// Gets the requested Extender if it is available for this object
/// </summary>
/// <param name="extenderName">The name of the extender.</param>
/// <returns>The extender object.</returns>
public virtual object get_Extender(string extenderName)
{
return null;
}
/// <summary>
/// Gets an object that can be accessed by name at run time.
/// </summary>
public virtual object Object
{
get
{
return this.node.Object;
}
}
/// <summary>
/// Gets the Document associated with the item, if one exists.
/// </summary>
public virtual EnvDTE.Document Document
{
get
{
return null;
}
}
/// <summary>
/// Gets the number of files associated with a ProjectItem.
/// </summary>
public virtual short FileCount
{
get
{
return (short)1;
}
}
/// <summary>
/// Gets a collection of all properties that pertain to the object.
/// </summary>
public virtual EnvDTE.Properties Properties
{
get
{
if(this.node.NodeProperties == null)
{
return null;
}
return new OAProperties(this.node.NodeProperties);
}
}
/// <summary>
/// Gets the FileCodeModel object for the project item.
/// </summary>
public virtual EnvDTE.FileCodeModel FileCodeModel
{
get
{
return null;
}
}
/// <summary>
/// Gets a ProjectItems for the object.
/// </summary>
public virtual EnvDTE.ProjectItems ProjectItems
{
get
{
return null;
}
}
/// <summary>
/// Gets a GUID string indicating the kind or type of the object.
/// </summary>
public virtual string Kind
{
get
{
Guid guid;
ErrorHandler.ThrowOnFailure(this.node.GetGuidProperty((int)__VSHPROPID.VSHPROPID_TypeGuid, out guid));
return guid.ToString("B");
}
}
/// <summary>
/// Saves the project item.
/// </summary>
/// <param name="fileName">The name with which to save the project or project item.</param>
/// <remarks>Implemented by subclasses.</remarks>
public virtual void Save(string fileName)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the top-level extensibility object.
/// </summary>
public virtual EnvDTE.DTE DTE
{
get
{
return (EnvDTE.DTE)this.project.DTE;
}
}
/// <summary>
/// Gets the ProjectItems collection containing the ProjectItem object supporting this property.
/// </summary>
public virtual EnvDTE.ProjectItems Collection
{
get
{
// Get the parent node
HierarchyNode parentNode = this.node.Parent;
Debug.Assert(parentNode != null, "Failed to get the parent node");
// Get the ProjectItems object for the parent node
if(parentNode is ProjectNode)
{
// The root node for the project
return ((OAProject)parentNode.GetAutomationObject()).ProjectItems;
}
else if(parentNode is FileNode && parentNode.FirstChild != null)
{
// The item has children
return ((OAProjectItem<FileNode>)parentNode.GetAutomationObject()).ProjectItems;
}
else if(parentNode is FolderNode)
{
return ((OAProjectItem<FolderNode>)parentNode.GetAutomationObject()).ProjectItems;
}
else
{
// Not supported. Override this method in derived classes to return appropriate collection object
throw new NotImplementedException();
}
}
}
/// <summary>
/// Gets a list of available Extenders for the object.
/// </summary>
public virtual object ExtenderNames
{
get
{
return null;
}
}
/// <summary>
/// Gets the ConfigurationManager object for this ProjectItem.
/// </summary>
/// <remarks>We do not support config management based per item.</remarks>
public virtual EnvDTE.ConfigurationManager ConfigurationManager
{
get
{
return null;
}
}
/// <summary>
/// Gets the project hosting the ProjectItem.
/// </summary>
public virtual EnvDTE.Project ContainingProject
{
get
{
return this.project;
}
}
/// <summary>
/// Gets or sets a value indicating whether or not the object has been modified since last being saved or opened.
/// </summary>
public virtual bool Saved
{
get
{
return !this.IsDirty;
}
set
{
throw new NotImplementedException();
}
}
/// <summary>
/// Gets the Extender category ID (CATID) for the object.
/// </summary>
public virtual string ExtenderCATID
{
get
{
return null;
}
}
/// <summary>
/// If the project item is the root of a subproject, then the SubProject property returns the Project object for the subproject.
/// </summary>
public virtual EnvDTE.Project SubProject
{
get
{
return null;
}
}
/// <summary>
/// Microsoft Internal Use Only. Checks if the document associated to this item is dirty.
/// </summary>
public virtual bool IsDirty
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
/// <summary>
/// Gets or sets the name of the object.
/// </summary>
public virtual string Name
{
get
{
return this.node.Caption;
}
set
{
if(this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed || this.node.ProjectMgr.Site == null)
{
throw new InvalidOperationException();
}
using(AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site))
{
this.node.SetEditLabel(value);
}
}
}
/// <summary>
/// Removes the project item from hierarchy.
/// </summary>
public virtual void Remove()
{
if(this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed || this.node.ProjectMgr.Site == null)
{
throw new InvalidOperationException();
}
using(AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site))
{
this.node.Remove(false);
}
}
/// <summary>
/// Removes the item from its project and its storage.
/// </summary>
public virtual void Delete()
{
if(this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed || this.node.ProjectMgr.Site == null)
{
throw new InvalidOperationException();
}
using(AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site))
{
this.node.Remove(true);
}
}
/// <summary>
/// Saves the project item.
/// </summary>
/// <param name="newFileName">The file name with which to save the solution, project, or project item. If the file exists, it is overwritten.</param>
/// <returns>true if save was successful</returns>
/// <remarks>This method is implemented on subclasses.</remarks>
public virtual bool SaveAs(string newFileName)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets a value indicating whether the project item is open in a particular view type.
/// </summary>
/// <param name="viewKind">A Constants.vsViewKind* indicating the type of view to check./param>
/// <returns>A Boolean value indicating true if the project is open in the given view type; false if not. </returns>
public virtual bool get_IsOpen(string viewKind)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the full path and names of the files associated with a project item.
/// </summary>
/// <param name="index"> The index of the item</param>
/// <returns>The full path of the associated item</returns>
/// <exception cref="ArgumentOutOfRangeException">Is thrown if index is not one</exception>
public virtual string get_FileNames(short index)
{
// This method should really only be called with 1 as the parameter, but
// there used to be a bug in VB/C# that would work with 0. To avoid breaking
// existing automation they are still accepting 0. To be compatible with them
// we accept it as well.
Debug.Assert(index > 0, "Index is 1 based.");
if(index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
return this.node.Url;
}
/// <summary>
/// Expands the view of Solution Explorer to show project items.
/// </summary>
public virtual void ExpandView()
{
if(this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed || this.node.ProjectMgr.Site == null)
{
throw new InvalidOperationException();
}
using(AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site))
{
IVsUIHierarchyWindow uiHierarchy = UIHierarchyUtilities.GetUIHierarchyWindow(this.node.ProjectMgr.Site, HierarchyNode.SolutionExplorer);
if(uiHierarchy == null)
{
throw new InvalidOperationException();
}
ErrorHandler.ThrowOnFailure(uiHierarchy.ExpandItem(this.node.ProjectMgr, this.node.ID, EXPANDFLAGS.EXPF_ExpandFolder));
}
}
/// <summary>
/// Opens the project item in the specified view. Not implemented because this abstract class dont know what to open
/// </summary>
/// <param name="ViewKind">Specifies the view kind in which to open the item</param>
/// <returns>Window object</returns>
public virtual EnvDTE.Window Open(string ViewKind)
{
throw new NotImplementedException();
}
#endregion
}
}
| |
using Decal.Adapter;
using Decal.Adapter.Wrappers;
//using Decal.Interop.Inject;
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using Zegeger.Data;
using Zegeger.Decal;
using Zegeger.Diagnostics;
using Zegeger.Decal.Chat;
using Zegeger.Decal.Data;
using Zegeger.Decal.VVS;
using Zegeger.Versioning;
namespace Zegeger.Decal.Plugins.AgentC
{
public enum PluginState
{
Init,
Starting,
Running,
ShuttingDown,
ShutDown,
Unknown
}
public partial class PluginCore : PluginBase
{
internal static PluginHost MyHost;
internal static IView View;
List<Component> ComponentList;
SettingsComponent settingsComp;
PluginState State;
EchoFilter Echo;
Updater UpdateChecker;
internal static ChatType NormalType;
internal static ChatType ErrorType;
internal const string PluginName = "AgentC";
internal const string PluginVersion = "1.0.0.0";
internal const string PluginAuthor = "Zegeger of Harvestgain";
private int filesUpdated;
private VersionNumber latestVersion;
protected override void Startup()
{
try
{
State = PluginState.Init;
MyHost = Host;
ComponentList = new List<Component>();
string dllPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6) + @"\";
string profilePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\Decal Plugins\Zegeger\AgentC\";
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Zegeger\AgentC\";
TraceLogger.StartUp(appDataPath + @"Logs");
TraceLogger.LoggingLevel = TraceLevel.Noise;
TraceLogger.Write("START");
TraceLogger.Write("dllPath: " + dllPath, TraceLevel.Verbose);
TraceLogger.Write("profilePath: " + profilePath, TraceLevel.Verbose);
TraceLogger.Write("appDataPath: " + appDataPath, TraceLevel.Verbose);
Constants.StartUp(appDataPath + @"RefData\");
if (Constants.AutoUpdate)
{
Update(appDataPath);
}
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Zegeger.Decal.Plugins.AgentC.ViewXML.mainView.xml"))
{
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
View = Zegeger.Decal.VVS.ViewSystemSelector.CreateViewResource(PluginCore.MyHost, result);
}
}
ZTimer.StartUp(Core);
DataHandler.StartUp(profilePath + @"Data\");
SettingsProfileHandler.StartUp(profilePath + @"Settings\");
Core.PluginInitComplete += new EventHandler<EventArgs>(Core_PluginInitComplete);
Core.CharacterFilter.LoginComplete += new EventHandler(CharacterFilter_LoginComplete);
CommandHandler.StartUp(Core, "ac", new string[] { PluginName + " " + PluginVersion, "By " + PluginAuthor }, WriteToChat);
Echo = new EchoFilter(Core);
settingsComp = new SettingsComponent(Core, View);
settingsComp.ComponentStateChange += new ComponentStateChangeEvent(ComponentStateChange);
ComponentList.Add(settingsComp);
ChatLogger chatLogger = new ChatLogger(Core, View);
chatLogger.BasePath = profilePath + @"Chat Logs\";
chatLogger.ComponentStateChange += new ComponentStateChangeEvent(ComponentStateChange);
ComponentList.Add(chatLogger);
ChatColor chatColor = new ChatColor(Core, View, dllPath);
chatColor.ComponentStateChange += new ComponentStateChangeEvent(ComponentStateChange);
Echo.KillMessage += chatColor.OnKillMessageEvent;
ComponentList.Add(chatColor);
ChatCustom chatCustom = new ChatCustom(Core, View, dllPath);
chatCustom.ComponentStateChange += new ComponentStateChangeEvent(ComponentStateChange);
ComponentList.Add(chatCustom);
ChatFilter chatFilter = new ChatFilter(Core, View);
chatCustom.ComponentStateChange += new ComponentStateChangeEvent(ComponentStateChange);
ComponentList.Add(chatFilter);
Alias alias = new Alias(Core, View);
alias.ComponentStateChange += new ComponentStateChangeEvent(ComponentStateChange);
ComponentList.Add(alias);
ChatOptions chatOptions = new ChatOptions(Core, View);
chatOptions.ComponentStateChange += new ComponentStateChangeEvent(ComponentStateChange);
ComponentList.Add(chatOptions);
State = PluginState.Starting;
TraceLogger.Write("Startup End");
}
catch (Exception ex)
{
TraceLogger.Write(ex);
WriteToChat(ex.ToString());
}
}
void Update(string appDataPath)
{
TraceLogger.Write("Enter. Beginning up check to " + Constants.UpdateURL);
try
{
UpdateChecker = new Updater(Constants.UpdateURL);
UpdateChecker.BeginCheckVersions(PluginName, PluginVersion, ir =>
{
try
{
TraceLogger.Write("Check Versions Complete");
UpdateCheckResults results = UpdateChecker.EndCheckVersions(ir);
TraceLogger.Write("Check Versions result: " + results.Status);
if (results.Status == ResultStatus.Success)
{
List<UpdateResult> removalList = new List<UpdateResult>();
foreach (UpdateResult result in results.Results)
{
if (result.action == UpdateAction.Application)
{
TraceLogger.Write("Current application version: " + result.newVersion);
latestVersion = new VersionNumber(result.newVersion);
removalList.Add(result);
}
else
{
if (Constants.FileInfo.ContainsKey(result.fileName))
{
if (result.action == UpdateAction.CreateUpdate)
{
if (new VersionNumber(Constants.FileInfo[result.fileName]) >= new VersionNumber(result.newVersion))
{
TraceLogger.Write("Existing file is up-to-date: " + result.fileName);
removalList.Add(result);
}
}
else if (result.action == UpdateAction.Delete)
{
TraceLogger.Write("Existing file should be removed: " + result.fileName);
File.Move(appDataPath + @"RefData\" + result.fileName, appDataPath + @"RefData\" + result.fileName + ".bak");
removalList.Add(result);
}
}
}
}
foreach (UpdateResult file in removalList)
{
results.Results.Remove(file);
}
filesUpdated = results.Results.Count;
if (results.Results.Count > 0)
{
TraceLogger.Write("Beginning to fetch files, count: " + results.Results.Count);
UpdateChecker.BeginFetchFiles(results.Results, ir2 =>
{
try
{
TraceLogger.Write("Fetch Files Complete");
FilesFetchedResults fileResult = UpdateChecker.EndFetchFiles(ir2);
TraceLogger.Write("Fetch Files result: " + fileResult.Status);
if (fileResult.Status == ResultStatus.Success)
{
bool restart = false;
foreach (FetchedFile file in fileResult.Files)
{
if (file.fileName != "Application" && file.file.Length > 0)
{
TraceLogger.Write("Deleting existing backup file: " + appDataPath + @"RefData\" + file.fileName + ".bak");
File.Delete(appDataPath + @"RefData\" + file.fileName + ".bak");
TraceLogger.Write("Backing up existing file: " + appDataPath + @"RefData\" + file.fileName);
File.Move(appDataPath + @"RefData\" + file.fileName, appDataPath + @"RefData\" + file.fileName + ".bak");
TraceLogger.Write("Writing new file: " + appDataPath + @"RefData\" + file.fileName);
using (FileStream fileStream = new FileStream(appDataPath + @"RefData\" + file.fileName, FileMode.Create))
{
fileStream.Write(file.file, 0, file.file.Length);
fileStream.Close();
TraceLogger.Write("File written");
restart = true;
}
}
}
if (restart)
{
TraceLogger.Write("Restarting plugin after updating data files.", TraceLevel.Warning);
Shutdown();
Startup();
}
}
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
}, null);
}
}
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
}, null);
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
TraceLogger.Write("Exit");
}
void ComponentStateChange(object sender, ComponentStateChangeEventArgs e)
{
Component component = (Component)sender;
TraceLogger.Write("Enter Component: " + component.ComponentName + ", State: " + e.NewState.ToString());
if (State == PluginState.Running && e.NewState != ComponentState.Running && component.Critical == true )
{
TraceLogger.Write("Critical component in incorrect state! Shutting down plugin!", TraceLevel.Fatal);
Termiante("Critical component transitioned to an incorrect state " + component.ComponentName);
}
TraceLogger.Write("Exit");
}
void Core_PluginInitComplete(object sender, EventArgs e)
{
TraceLogger.Write("Enter");
try
{
ZChatWrapper.Initialize(Core, "AgentC");
TraceLogger.Write("ChatMode: " + ZChatWrapper.ChatMode.ToString());
NormalType = ZChatWrapper.CreateChatType(Constants.ChatColors("Purple"), true, false, false, false, false);
ErrorType = ZChatWrapper.CreateChatType(Constants.ChatColors("DarkRed"), true, false, false, false, false);
foreach (Component c in ComponentList)
{
c.PostPluginInit();
}
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
TraceLogger.Write("Exit");
}
void CharacterFilter_LoginComplete(object sender, EventArgs e)
{
TraceLogger.Write("Enter");
try
{
DataHandler.PostLogin(Core.CharacterFilter.Name, Core.CharacterFilter.Server);
SettingsProfileHandler.PostLogin(settingsComp.SettingId);
foreach (Component c in ComponentList)
{
c.PostLogin();
}
foreach (Component c in ComponentList)
{
if (c.Critical && c.State != ComponentState.Running)
{
TraceLogger.Write("Critical component in incorrect state! Shutting down plugin!", TraceLevel.Fatal);
Termiante("Critical component failed to load properly " + c.ComponentName);
return;
}
}
State = PluginState.Running;
WriteToChat("Plugin Loaded! Type /ac help for commands.");
if (latestVersion != null)
{
if (new VersionNumber(PluginVersion) < latestVersion)
{
WriteToChat("There is a newer version (" + latestVersion.ToString() + ") available. Please download it from " + Constants.DownloadURL);
}
}
if (filesUpdated > 0)
{
WriteToChat(filesUpdated.ToString() + " files updated.");
}
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
TraceLogger.Write("Exit");
}
private void Termiante(string error = "")
{
WriteToChatError("An error occured: " + error + ". Terminating plugin operation...");
Shutdown();
}
protected override void Shutdown()
{
TraceLogger.Write("Shutdown Start");
try
{
if (State != PluginState.ShutDown && State != PluginState.ShuttingDown)
{
State = PluginState.ShuttingDown;
foreach (Component c in ComponentList)
{
c.Shutdown();
}
ComponentList.Clear();
SettingsProfileHandler.Shutdown();
DataHandler.Shutdown();
CommandHandler.Shutdown();
Core.PluginInitComplete -= new EventHandler<EventArgs>(Core_PluginInitComplete);
Core.CharacterFilter.LoginComplete -= new EventHandler(CharacterFilter_LoginComplete);
ZChatWrapper.Dispose();
Constants.Shutdown();
MyHost = null;
TraceLogger.Write("Shutdown End");
TraceLogger.ShutDown();
State = PluginState.ShutDown;
}
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
}
internal static void WriteToChat(string message)
{
TraceLogger.Write("Enter message: " + message, TraceLevel.Verbose);
try
{
ZChatWrapper.WriteToChat("<AgentC> " + message, NormalType);
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
TraceLogger.Write("Exit", TraceLevel.Verbose);
}
internal static void WriteToChatError(string message)
{
TraceLogger.Write("Enter message: " + message, TraceLevel.Error);
try
{
ZChatWrapper.WriteToChat("<AgentC> " + message, ErrorType);
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
TraceLogger.Write("Exit", TraceLevel.Verbose);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V10.Services
{
/// <summary>Settings for <see cref="AdGroupCriterionServiceClient"/> instances.</summary>
public sealed partial class AdGroupCriterionServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AdGroupCriterionServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AdGroupCriterionServiceSettings"/>.</returns>
public static AdGroupCriterionServiceSettings GetDefault() => new AdGroupCriterionServiceSettings();
/// <summary>
/// Constructs a new <see cref="AdGroupCriterionServiceSettings"/> object with default settings.
/// </summary>
public AdGroupCriterionServiceSettings()
{
}
private AdGroupCriterionServiceSettings(AdGroupCriterionServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateAdGroupCriteriaSettings = existing.MutateAdGroupCriteriaSettings;
OnCopy(existing);
}
partial void OnCopy(AdGroupCriterionServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupCriterionServiceClient.MutateAdGroupCriteria</c> and
/// <c>AdGroupCriterionServiceClient.MutateAdGroupCriteriaAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateAdGroupCriteriaSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AdGroupCriterionServiceSettings"/> object.</returns>
public AdGroupCriterionServiceSettings Clone() => new AdGroupCriterionServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AdGroupCriterionServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class AdGroupCriterionServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupCriterionServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AdGroupCriterionServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AdGroupCriterionServiceClientBuilder()
{
UseJwtAccessWithScopes = AdGroupCriterionServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AdGroupCriterionServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupCriterionServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AdGroupCriterionServiceClient Build()
{
AdGroupCriterionServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AdGroupCriterionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AdGroupCriterionServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AdGroupCriterionServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AdGroupCriterionServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AdGroupCriterionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AdGroupCriterionServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AdGroupCriterionServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupCriterionServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupCriterionServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AdGroupCriterionService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage ad group criteria.
/// </remarks>
public abstract partial class AdGroupCriterionServiceClient
{
/// <summary>
/// The default endpoint for the AdGroupCriterionService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AdGroupCriterionService scopes.</summary>
/// <remarks>
/// The default AdGroupCriterionService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AdGroupCriterionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupCriterionServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AdGroupCriterionServiceClient"/>.</returns>
public static stt::Task<AdGroupCriterionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AdGroupCriterionServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AdGroupCriterionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupCriterionServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AdGroupCriterionServiceClient"/>.</returns>
public static AdGroupCriterionServiceClient Create() => new AdGroupCriterionServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AdGroupCriterionServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AdGroupCriterionServiceSettings"/>.</param>
/// <returns>The created <see cref="AdGroupCriterionServiceClient"/>.</returns>
internal static AdGroupCriterionServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupCriterionServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AdGroupCriterionService.AdGroupCriterionServiceClient grpcClient = new AdGroupCriterionService.AdGroupCriterionServiceClient(callInvoker);
return new AdGroupCriterionServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AdGroupCriterionService client</summary>
public virtual AdGroupCriterionService.AdGroupCriterionServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupCriteriaResponse MutateAdGroupCriteria(MutateAdGroupCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(MutateAdGroupCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(MutateAdGroupCriteriaRequest request, st::CancellationToken cancellationToken) =>
MutateAdGroupCriteriaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupCriteriaResponse MutateAdGroupCriteria(string customerId, scg::IEnumerable<AdGroupCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupCriteria(new MutateAdGroupCriteriaRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(string customerId, scg::IEnumerable<AdGroupCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupCriteriaAsync(new MutateAdGroupCriteriaRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(string customerId, scg::IEnumerable<AdGroupCriterionOperation> operations, st::CancellationToken cancellationToken) =>
MutateAdGroupCriteriaAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AdGroupCriterionService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage ad group criteria.
/// </remarks>
public sealed partial class AdGroupCriterionServiceClientImpl : AdGroupCriterionServiceClient
{
private readonly gaxgrpc::ApiCall<MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse> _callMutateAdGroupCriteria;
/// <summary>
/// Constructs a client wrapper for the AdGroupCriterionService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="AdGroupCriterionServiceSettings"/> used within this client.
/// </param>
public AdGroupCriterionServiceClientImpl(AdGroupCriterionService.AdGroupCriterionServiceClient grpcClient, AdGroupCriterionServiceSettings settings)
{
GrpcClient = grpcClient;
AdGroupCriterionServiceSettings effectiveSettings = settings ?? AdGroupCriterionServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateAdGroupCriteria = clientHelper.BuildApiCall<MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse>(grpcClient.MutateAdGroupCriteriaAsync, grpcClient.MutateAdGroupCriteria, effectiveSettings.MutateAdGroupCriteriaSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAdGroupCriteria);
Modify_MutateAdGroupCriteriaApiCall(ref _callMutateAdGroupCriteria);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_MutateAdGroupCriteriaApiCall(ref gaxgrpc::ApiCall<MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse> call);
partial void OnConstruction(AdGroupCriterionService.AdGroupCriterionServiceClient grpcClient, AdGroupCriterionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AdGroupCriterionService client</summary>
public override AdGroupCriterionService.AdGroupCriterionServiceClient GrpcClient { get; }
partial void Modify_MutateAdGroupCriteriaRequest(ref MutateAdGroupCriteriaRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateAdGroupCriteriaResponse MutateAdGroupCriteria(MutateAdGroupCriteriaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupCriteriaRequest(ref request, ref callSettings);
return _callMutateAdGroupCriteria.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdGroupCriterionError]()
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [BiddingError]()
/// [BiddingStrategyError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MultiplierError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [PolicyViolationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateAdGroupCriteriaResponse> MutateAdGroupCriteriaAsync(MutateAdGroupCriteriaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupCriteriaRequest(ref request, ref callSettings);
return _callMutateAdGroupCriteria.Async(request, callSettings);
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.iMote2
{
using System;
using RT = Microsoft.Zelig.Runtime;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
public sealed class Storage : RT.Storage
{
const uint DRAMSize = 2 * 8 * 1024 * 1024;
const uint DRAMBase = 0xA0000000 + DRAMSize;
const uint DRAMEnd = DRAMBase + DRAMSize;
const uint DRAMMask = ~(DRAMSize - 1);
const byte ErasedValueByte = (byte)0xFFu;
const ushort ErasedValue = (ushort)0xFFFFu;
const uint ErasedValuePair = 0xFFFFFFFFu;
//
// State
//
//
// Helper Methods
//
public override unsafe void InitializeStorage()
{
}
//--//
public override unsafe bool EraseSectors( UIntPtr addressStart ,
UIntPtr addressEnd )
{
if(ValidateAddress ( addressStart ) &&
ValidateAddressPlus1( addressEnd ) )
{
Memory.Fill( addressStart, addressEnd, ErasedValuePair );
return true;
}
return false;
}
public override unsafe bool WriteByte( UIntPtr address ,
byte val )
{
if(ValidateAddress( address ))
{
byte* ptr = (byte*)address.ToPointer();
*ptr = val;
return true;
}
return false;
}
public override unsafe bool WriteShort( UIntPtr address ,
ushort val )
{
if(IsOddAddress( address ))
{
return WriteByte( address, (byte) val ) &&
WriteByte( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (byte)(val >> 8) ) ;
}
else
{
if(ValidateAddress( address ))
{
ushort* wordAddress = (ushort*)address.ToPointer();
*wordAddress = val;
return true;
}
return false;
}
}
public override bool WriteWord( UIntPtr address ,
uint val )
{
if(IsOddAddress( address ))
{
return WriteByte ( address, (byte ) val ) &&
WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (ushort)(val >> 8) ) &&
WriteByte ( Microsoft.Zelig.AddressMath.Increment( address, 3 ), (byte )(val >> 24) ) ;
}
else
{
return WriteShort( address, (ushort) val ) &&
WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 2 ), (ushort)(val >> 16) ) ;
}
}
public override bool Write( UIntPtr address ,
byte[] buffer ,
uint offset ,
uint numBytes )
{
if(numBytes > 0)
{
if(IsOddAddress( address ))
{
if(WriteByte( address, buffer[offset] ) == false)
{
return false;
}
address = Microsoft.Zelig.AddressMath.Increment( address, 1 );
offset += 1;
numBytes -= 1;
}
while(numBytes >= 2)
{
uint val;
val = (uint)buffer[ offset++ ];
val |= (uint)buffer[ offset++ ] << 8;
if(WriteShort( address, (ushort)val ) == false)
{
return false;
}
address = Microsoft.Zelig.AddressMath.Increment( address, 2 );
numBytes -= 2;
}
if(numBytes != 0)
{
if(WriteByte( address, buffer[offset] ) == false)
{
return false;
}
}
}
return true;
}
//--//
public override unsafe byte ReadByte( UIntPtr address )
{
if(ValidateAddress( address ))
{
byte* ptr = (byte*)address.ToPointer();
return ptr[0];
}
return ErasedValueByte;
}
public override unsafe ushort ReadShort( UIntPtr address )
{
if(ValidateAddress( address ))
{
byte* ptr = (byte*)address.ToPointer();
return (ushort)((uint)ptr[0] |
(uint)ptr[1] << 8 );
}
return ErasedValue;
}
public override unsafe uint ReadWord( UIntPtr address )
{
if(ValidateAddress( address ))
{
byte* ptr = (byte*)address.ToPointer();
return ((uint)ptr[0] |
(uint)ptr[1] << 8 |
(uint)ptr[2] << 16 |
(uint)ptr[3] << 24 );
}
return ErasedValuePair;
}
public override void Read( UIntPtr address ,
byte[] buffer ,
uint offset ,
uint numBytes )
{
while(numBytes != 0)
{
buffer[offset++] = ReadByte( address );
address = Microsoft.Zelig.AddressMath.Increment( address, 1 );
numBytes--;
}
}
public override void SubstituteFirmware( UIntPtr addressDestination ,
UIntPtr addressSource ,
uint numBytes )
{
throw new NotImplementedException();
}
public override void RebootDevice()
{
throw new System.NotImplementedException();
}
//--//
[RT.Inline]
static bool ValidateAddress( UIntPtr address )
{
if(Zelig.AddressMath.IsLessThan( address, new UIntPtr( DRAMBase ) ))
{
return false;
}
if(Zelig.AddressMath.IsGreaterThanOrEqual( address, new UIntPtr( DRAMEnd ) ))
{
return false;
}
return true;
}
[RT.Inline]
static bool ValidateAddressPlus1( UIntPtr address )
{
if(Zelig.AddressMath.IsLessThanOrEqual( address, new UIntPtr( DRAMBase ) ))
{
return false;
}
if(Zelig.AddressMath.IsGreaterThan( address, new UIntPtr( DRAMEnd ) ))
{
return false;
}
return true;
}
[RT.Inline]
static bool IsOddAddress( UIntPtr address )
{
return Zelig.AddressMath.IsAlignedTo16bits( address ) == false;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.DiaSymReader;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Utilities;
using Roslyn.Utilities;
using ShellInterop = Microsoft.VisualStudio.Shell.Interop;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
using VsThreading = Microsoft.VisualStudio.Threading;
using Document = Microsoft.CodeAnalysis.Document;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue
{
internal sealed class VsENCRebuildableProjectImpl
{
private readonly AbstractProject _vsProject;
// number of projects that are in the debug state:
private static int s_debugStateProjectCount;
// number of projects that are in the break state:
private static int s_breakStateProjectCount;
// projects that entered the break state:
private static readonly List<KeyValuePair<ProjectId, ProjectReadOnlyReason>> s_breakStateEnteredProjects = new List<KeyValuePair<ProjectId, ProjectReadOnlyReason>>();
// active statements of projects that entered the break state:
private static readonly List<VsActiveStatement> s_pendingActiveStatements = new List<VsActiveStatement>();
private static VsReadOnlyDocumentTracker s_readOnlyDocumentTracker;
internal static readonly TraceLog log = new TraceLog(2048, "EnC");
private static Solution s_breakStateEntrySolution;
private static EncDebuggingSessionInfo s_encDebuggingSessionInfo;
private readonly IEditAndContinueWorkspaceService _encService;
private readonly IActiveStatementTrackingService _trackingService;
private readonly EditAndContinueDiagnosticUpdateSource _diagnosticProvider;
private readonly IDebugEncNotify _debugEncNotify;
private readonly INotificationService _notifications;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
#region Per Project State
private bool _changesApplied;
// maps VS Active Statement Id, which is unique within this project, to our id
private Dictionary<uint, ActiveStatementId> _activeStatementIds;
private ProjectAnalysisSummary _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges;
private HashSet<uint> _activeMethods;
private List<VsExceptionRegion> _exceptionRegions;
private EmitBaseline _committedBaseline;
private EmitBaseline _pendingBaseline;
private Project _projectBeingEmitted;
private ImmutableArray<DocumentId> _documentsWithEmitError = ImmutableArray<DocumentId>.Empty;
/// <summary>
/// Initialized when the project switches to debug state.
/// Null if the project has no output file or we can't read the MVID.
/// </summary>
private ModuleMetadata _metadata;
private ISymUnmanagedReader3 _pdbReader;
private IntPtr _pdbReaderObjAsStream;
#endregion
private bool IsDebuggable
{
get { return _metadata != null; }
}
internal VsENCRebuildableProjectImpl(AbstractProject project)
{
_vsProject = project;
_encService = _vsProject.Workspace.Services.GetService<IEditAndContinueWorkspaceService>();
_trackingService = _vsProject.Workspace.Services.GetService<IActiveStatementTrackingService>();
_notifications = _vsProject.Workspace.Services.GetService<INotificationService>();
_debugEncNotify = (IDebugEncNotify)project.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger));
var componentModel = (IComponentModel)project.ServiceProvider.GetService(typeof(SComponentModel));
_diagnosticProvider = componentModel.GetService<EditAndContinueDiagnosticUpdateSource>();
_editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();
Debug.Assert(_encService != null);
Debug.Assert(_trackingService != null);
Debug.Assert(_diagnosticProvider != null);
Debug.Assert(_editorAdaptersFactoryService != null);
}
// called from an edit filter if an edit of a read-only buffer is attempted:
internal bool OnEdit(DocumentId documentId)
{
SessionReadOnlyReason sessionReason;
ProjectReadOnlyReason projectReason;
if (_encService.IsProjectReadOnly(documentId.ProjectId, out sessionReason, out projectReason))
{
OnReadOnlyDocumentEditAttempt(documentId, sessionReason, projectReason);
return true;
}
return false;
}
private void OnReadOnlyDocumentEditAttempt(
DocumentId documentId,
SessionReadOnlyReason sessionReason,
ProjectReadOnlyReason projectReason)
{
if (sessionReason == SessionReadOnlyReason.StoppedAtException)
{
_debugEncNotify.NotifyEncEditAttemptedAtInvalidStopState();
return;
}
var visualStudioWorkspace = _vsProject.Workspace as VisualStudioWorkspaceImpl;
var hostProject = visualStudioWorkspace?.GetHostProject(documentId.ProjectId) as AbstractRoslynProject;
if (hostProject?.EditAndContinueImplOpt?._metadata != null)
{
_debugEncNotify.NotifyEncEditDisallowedByProject(hostProject.Hierarchy);
return;
}
// NotifyEncEditDisallowedByProject is broken if the project isn't built at the time the debugging starts (debugger bug 877586).
string message;
if (sessionReason == SessionReadOnlyReason.Running)
{
message = "Changes are not allowed while code is running.";
}
else
{
Debug.Assert(sessionReason == SessionReadOnlyReason.None);
switch (projectReason)
{
case ProjectReadOnlyReason.MetadataNotAvailable:
message = "Changes are not allowed if the project wasn't built when debugging started.";
break;
case ProjectReadOnlyReason.NotLoaded:
message = "Changes are not allowed if the assembly has not been loaded.";
break;
default:
throw ExceptionUtilities.UnexpectedValue(projectReason);
}
}
_notifications.SendNotification(message, title: FeaturesResources.EditAndContinue, severity: NotificationSeverity.Error);
}
/// <summary>
/// Since we can't await asynchronous operations we need to wait for them to complete.
/// The default SynchronizationContext.Wait pumps messages giving the debugger a chance to
/// reenter our EnC implementation. To avoid that we use a specialized SynchronizationContext
/// that doesn't pump messages. We need to make sure though that the async methods we wait for
/// don't dispatch to foreground thread, otherwise we would end up in a deadlock.
/// </summary>
private static VsThreading.SpecializedSyncContext NonReentrantContext
{
get
{
return VsThreading.ThreadingTools.Apply(VsThreading.NoMessagePumpSyncContext.Default);
}
}
public bool HasCustomMetadataEmitter()
{
return true;
}
/// <summary>
/// Invoked when the debugger transitions from Design mode to Run mode or Break mode.
/// </summary>
public int StartDebuggingPE()
{
try
{
log.Write("Enter Debug Mode: project '{0}'", _vsProject.DisplayName);
// EnC service is global (per solution), but the debugger calls this for each project.
// Avoid starting the debug session if it has already been started.
if (_encService.DebuggingSession == null)
{
Debug.Assert(s_debugStateProjectCount == 0);
Debug.Assert(s_breakStateProjectCount == 0);
Debug.Assert(s_breakStateEnteredProjects.Count == 0);
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run);
_encService.StartDebuggingSession(_vsProject.Workspace.CurrentSolution);
s_encDebuggingSessionInfo = new EncDebuggingSessionInfo();
s_readOnlyDocumentTracker = new VsReadOnlyDocumentTracker(_encService, _editorAdaptersFactoryService, _vsProject);
}
string outputPath = _vsProject.TryGetObjOutputPath();
// The project doesn't produce a debuggable binary or we can't read it.
// Continue on since the debugger ignores HResults and we need to handle subsequent calls.
if (outputPath != null)
{
try
{
InjectFault_MvidRead();
_metadata = ModuleMetadata.CreateFromStream(new FileStream(outputPath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete));
_metadata.GetModuleVersionId();
}
catch (FileNotFoundException)
{
// If the project isn't referenced by the project being debugged it might not be built.
// In that case EnC is never allowed for the project, and thus we can assume the project hasn't entered debug state.
log.Write("StartDebuggingPE: '{0}' metadata file not found: '{1}'", _vsProject.DisplayName, outputPath);
_metadata = null;
}
catch (Exception e)
{
log.Write("StartDebuggingPE: error reading MVID of '{0}' ('{1}'): {2}", _vsProject.DisplayName, outputPath, e.Message);
_metadata = null;
var descriptor = new DiagnosticDescriptor("Metadata", "Metadata", ServicesVSResources.ErrorWhileReading, DiagnosticCategory.EditAndContinue, DiagnosticSeverity.Error, isEnabledByDefault: true, customTags: DiagnosticCustomTags.EditAndContinue);
_diagnosticProvider.ReportDiagnostics(
new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId),
_encService.DebuggingSession.InitialSolution,
_vsProject.Id,
new[] { Diagnostic.Create(descriptor, Location.None, outputPath, e.Message) });
}
}
else
{
log.Write("StartDebuggingPE: project has no output path '{0}'", _vsProject.DisplayName);
_metadata = null;
}
if (_metadata != null)
{
// The debugger doesn't call EnterBreakStateOnPE for projects that don't have MVID.
// However a project that's initially not loaded (but it might be in future) enters
// both the debug and break states.
s_debugStateProjectCount++;
}
_activeMethods = new HashSet<uint>();
_exceptionRegions = new List<VsExceptionRegion>();
_activeStatementIds = new Dictionary<uint, ActiveStatementId>();
// The HResult is ignored by the debugger.
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
public int StopDebuggingPE()
{
try
{
log.Write("Exit Debug Mode: project '{0}'", _vsProject.DisplayName);
Debug.Assert(s_breakStateEnteredProjects.Count == 0);
// Clear the solution stored while projects were entering break mode.
// It should be cleared as soon as all tracked projects enter the break mode
// but if the entering break mode fails for some projects we should avoid leaking the solution.
Debug.Assert(s_breakStateEntrySolution == null);
s_breakStateEntrySolution = null;
// EnC service is global (per solution), but the debugger calls this for each project.
// Avoid ending the debug session if it has already been ended.
if (_encService.DebuggingSession != null)
{
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design);
_encService.EndDebuggingSession();
LogEncSession();
s_encDebuggingSessionInfo = null;
s_readOnlyDocumentTracker.Dispose();
s_readOnlyDocumentTracker = null;
}
if (_metadata != null)
{
_metadata.Dispose();
_metadata = null;
s_debugStateProjectCount--;
}
else
{
// an error might have been reported:
var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId);
_diagnosticProvider.ClearDiagnostics(errorId, _vsProject.Workspace.CurrentSolution, _vsProject.Id, documentIdOpt: null);
}
_activeMethods = null;
_exceptionRegions = null;
_committedBaseline = null;
_activeStatementIds = null;
Debug.Assert((_pdbReaderObjAsStream == IntPtr.Zero) || (_pdbReader == null));
if (_pdbReader != null)
{
Marshal.ReleaseComObject(_pdbReader);
_pdbReader = null;
}
// The HResult is ignored by the debugger.
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private static void LogEncSession()
{
var sessionId = DebugLogMessage.GetNextId();
Logger.Log(FunctionId.Debugging_EncSession, DebugLogMessage.Create(sessionId, s_encDebuggingSessionInfo));
foreach (var editSession in s_encDebuggingSessionInfo.EditSessions)
{
var editSessionId = DebugLogMessage.GetNextId();
Logger.Log(FunctionId.Debugging_EncSession_EditSession, DebugLogMessage.Create(sessionId, editSessionId, editSession));
if (editSession.EmitDeltaErrorIds != null)
{
foreach (var error in editSession.EmitDeltaErrorIds)
{
Logger.Log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, DebugLogMessage.Create(sessionId, editSessionId, error));
}
}
foreach (var rudeEdit in editSession.RudeEdits)
{
Logger.Log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, DebugLogMessage.Create(sessionId, editSessionId, rudeEdit, blocking: editSession.HadRudeEdits));
}
}
}
/// <summary>
/// Get MVID and file name of the project's output file.
/// </summary>
/// <remarks>
/// The MVID is used by the debugger to identify modules loaded into debuggee that correspond to this project.
/// The path seems to be unused.
///
/// The output file path might be different from the path of the module loaded into the process.
/// For example, the binary produced by the C# compiler is stores in obj directory,
/// and then copied to bin directory from which it is loaded to the debuggee.
///
/// The binary produced by the compiler can also be rewritten by post-processing tools.
/// The debugger assumes that the MVID of the compiler's output file at the time we start debugging session
/// is the same as the MVID of the module loaded into debuggee. The original MVID might be different though.
/// </remarks>
public int GetPEidentity(Guid[] pMVID, string[] pbstrPEName)
{
Debug.Assert(_encService.DebuggingSession != null);
if (_metadata == null)
{
return VSConstants.E_FAIL;
}
if (pMVID != null && pMVID.Length != 0)
{
pMVID[0] = _metadata.GetModuleVersionId();
}
if (pbstrPEName != null && pbstrPEName.Length != 0)
{
var outputPath = _vsProject.TryGetObjOutputPath();
Debug.Assert(outputPath != null);
pbstrPEName[0] = Path.GetFileName(outputPath);
}
return VSConstants.S_OK;
}
/// <summary>
/// Called by the debugger when entering a Break state.
/// </summary>
/// <param name="encBreakReason">Reason for transition to Break state.</param>
/// <param name="pActiveStatements">Statements active when the debuggee is stopped.</param>
/// <param name="cActiveStatements">Length of <paramref name="pActiveStatements"/>.</param>
public int EnterBreakStateOnPE(Interop.ENC_BREAKSTATE_REASON encBreakReason, ShellInterop.ENC_ACTIVE_STATEMENT[] pActiveStatements, uint cActiveStatements)
{
try
{
using (NonReentrantContext)
{
log.Write("Enter {2}Break Mode: project '{0}', AS#: {1}", _vsProject.DisplayName, pActiveStatements != null ? pActiveStatements.Length : -1, encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION ? "Exception " : "");
Debug.Assert(cActiveStatements == (pActiveStatements != null ? pActiveStatements.Length : 0));
Debug.Assert(s_breakStateProjectCount < s_debugStateProjectCount);
Debug.Assert(s_breakStateProjectCount > 0 || _exceptionRegions.Count == 0);
Debug.Assert(s_breakStateProjectCount == s_breakStateEnteredProjects.Count);
Debug.Assert(IsDebuggable);
if (s_breakStateEntrySolution == null)
{
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break);
s_breakStateEntrySolution = _vsProject.Workspace.CurrentSolution;
// TODO: This is a workaround for a debugger bug in which not all projects exit the break state.
// Reset the project count.
s_breakStateProjectCount = 0;
}
ProjectReadOnlyReason state;
if (pActiveStatements != null)
{
AddActiveStatements(s_breakStateEntrySolution, pActiveStatements);
state = ProjectReadOnlyReason.None;
}
else
{
// unfortunately the debugger doesn't provide details:
state = ProjectReadOnlyReason.NotLoaded;
}
// If pActiveStatements is null the EnC Manager failed to retrieve the module corresponding
// to the project in the debuggee. We won't include such projects in the edit session.
s_breakStateEnteredProjects.Add(KeyValuePair.Create(_vsProject.Id, state));
s_breakStateProjectCount++;
// EnC service is global, but the debugger calls this for each project.
// Avoid starting the edit session until all projects enter break state.
if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount)
{
Debug.Assert(_encService.EditSession == null);
Debug.Assert(s_pendingActiveStatements.TrueForAll(s => s.Owner._activeStatementIds.Count == 0));
var byDocument = new Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>>();
// note: fills in activeStatementIds of projects that own the active statements:
GroupActiveStatements(s_pendingActiveStatements, byDocument);
// When stopped at exception: All documents are read-only, but the files might be changed outside of VS.
// So we start an edit session as usual and report a rude edit for all changes we see.
bool stoppedAtException = encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION;
var projectStates = ImmutableDictionary.CreateRange(s_breakStateEnteredProjects);
_encService.StartEditSession(s_breakStateEntrySolution, byDocument, projectStates, stoppedAtException);
_trackingService.StartTracking(_encService.EditSession);
s_readOnlyDocumentTracker.UpdateWorkspaceDocuments();
// When tracking is started the tagger is notified and the active statements are highlighted.
// Add the handler that notifies the debugger *after* that initial tagger notification,
// so that it's not triggered unless an actual change in leaf AS occurs.
_trackingService.TrackingSpansChanged += TrackingSpansChanged;
}
}
// The debugger ignores the result.
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
finally
{
// TODO: This is a workaround for a debugger bug.
// Ensure that the state gets reset even if if `GroupActiveStatements` throws an exception.
if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount)
{
// we don't need these anymore:
s_pendingActiveStatements.Clear();
s_breakStateEnteredProjects.Clear();
s_breakStateEntrySolution = null;
}
}
}
private void TrackingSpansChanged(bool leafChanged)
{
//log.Write("Tracking spans changed: {0}", leafChanged);
//if (leafChanged)
//{
// // fire and forget:
// Application.Current.Dispatcher.InvokeAsync(() =>
// {
// log.Write("Notifying debugger of active statement change.");
// var debugNotify = (IDebugEncNotify)_vsProject.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger));
// debugNotify.NotifyEncUpdateCurrentStatement();
// });
//}
}
private struct VsActiveStatement
{
public readonly DocumentId DocumentId;
public readonly uint StatementId;
public readonly ActiveStatementSpan Span;
public readonly VsENCRebuildableProjectImpl Owner;
public VsActiveStatement(VsENCRebuildableProjectImpl owner, uint statementId, DocumentId documentId, ActiveStatementSpan span)
{
this.Owner = owner;
this.StatementId = statementId;
this.DocumentId = documentId;
this.Span = span;
}
}
private struct VsExceptionRegion
{
public readonly uint ActiveStatementId;
public readonly int Ordinal;
public readonly uint MethodToken;
public readonly LinePositionSpan Span;
public VsExceptionRegion(uint activeStatementId, int ordinal, uint methodToken, LinePositionSpan span)
{
this.ActiveStatementId = activeStatementId;
this.Span = span;
this.MethodToken = methodToken;
this.Ordinal = ordinal;
}
}
// See InternalApis\vsl\inc\encbuild.idl
private const int TEXT_POSITION_ACTIVE_STATEMENT = 1;
private void AddActiveStatements(Solution solution, ShellInterop.ENC_ACTIVE_STATEMENT[] vsActiveStatements)
{
Debug.Assert(_activeMethods.Count == 0);
Debug.Assert(_exceptionRegions.Count == 0);
foreach (var vsActiveStatement in vsActiveStatements)
{
log.DebugWrite("+AS[{0}]: {1} {2} {3} {4} '{5}'",
vsActiveStatement.id,
vsActiveStatement.tsPosition.iStartLine,
vsActiveStatement.tsPosition.iStartIndex,
vsActiveStatement.tsPosition.iEndLine,
vsActiveStatement.tsPosition.iEndIndex,
vsActiveStatement.filename);
// TODO (tomat):
// Active statement is in user hidden code. The only information that we have from the debugger
// is the method token. We don't need to track the statement (it's not in user code anyways),
// but we should probably track the list of such methods in order to preserve their local variables.
// Not sure what's exactly the scenario here, perhaps modifying async method/iterator?
// Dev12 just ignores these.
if (vsActiveStatement.posType != TEXT_POSITION_ACTIVE_STATEMENT)
{
continue;
}
var flags = (ActiveStatementFlags)vsActiveStatement.ASINFO;
// Finds a document id in the solution with the specified file path.
DocumentId documentId = solution.GetDocumentIdsWithFilePath(vsActiveStatement.filename)
.Where(dId => dId.ProjectId == _vsProject.Id).SingleOrDefault();
if (documentId != null)
{
var document = solution.GetDocument(documentId);
Debug.Assert(document != null);
SourceText source = document.GetTextAsync(default(CancellationToken)).Result;
LinePositionSpan lineSpan = vsActiveStatement.tsPosition.ToLinePositionSpan();
// If the PDB is out of sync with the source we might get bad spans.
var sourceLines = source.Lines;
if (lineSpan.End.Line >= sourceLines.Count || sourceLines.GetPosition(lineSpan.End) > sourceLines[sourceLines.Count - 1].EndIncludingLineBreak)
{
log.Write("AS out of bounds (line count is {0})", source.Lines.Count);
continue;
}
SyntaxNode syntaxRoot = document.GetSyntaxRootAsync(default(CancellationToken)).Result;
var analyzer = document.Project.LanguageServices.GetService<IEditAndContinueAnalyzer>();
s_pendingActiveStatements.Add(new VsActiveStatement(
this,
vsActiveStatement.id,
document.Id,
new ActiveStatementSpan(flags, lineSpan)));
bool isLeaf = (flags & ActiveStatementFlags.LeafFrame) != 0;
var ehRegions = analyzer.GetExceptionRegions(source, syntaxRoot, lineSpan, isLeaf);
for (int i = 0; i < ehRegions.Length; i++)
{
_exceptionRegions.Add(new VsExceptionRegion(
vsActiveStatement.id,
i,
vsActiveStatement.methodToken,
ehRegions[i]));
}
}
_activeMethods.Add(vsActiveStatement.methodToken);
}
}
private static void GroupActiveStatements(
IEnumerable<VsActiveStatement> activeStatements,
Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>> byDocument)
{
var spans = new List<ActiveStatementSpan>();
foreach (var grouping in activeStatements.GroupBy(s => s.DocumentId))
{
var documentId = grouping.Key;
foreach (var activeStatement in grouping.OrderBy(s => s.Span.Span.Start))
{
int ordinal = spans.Count;
// register vsid with the project that owns the active statement:
activeStatement.Owner._activeStatementIds.Add(activeStatement.StatementId, new ActiveStatementId(documentId, ordinal));
spans.Add(activeStatement.Span);
}
byDocument.Add(documentId, spans.AsImmutable());
spans.Clear();
}
}
/// <summary>
/// Returns the number of exception regions around current active statements.
/// This is called when the project is entering a break right after
/// <see cref="EnterBreakStateOnPE"/> and prior to <see cref="GetExceptionSpans"/>.
/// </summary>
/// <remarks>
/// Called by EnC manager.
/// </remarks>
public int GetExceptionSpanCount(out uint pcExceptionSpan)
{
pcExceptionSpan = (uint)_exceptionRegions.Count;
return VSConstants.S_OK;
}
/// <summary>
/// Returns information about exception handlers in the source.
/// </summary>
/// <remarks>
/// Called by EnC manager.
/// </remarks>
public int GetExceptionSpans(uint celt, ShellInterop.ENC_EXCEPTION_SPAN[] rgelt, ref uint pceltFetched)
{
Debug.Assert(celt == rgelt.Length);
Debug.Assert(celt == _exceptionRegions.Count);
for (int i = 0; i < _exceptionRegions.Count; i++)
{
rgelt[i] = new ShellInterop.ENC_EXCEPTION_SPAN()
{
id = (uint)i,
methodToken = _exceptionRegions[i].MethodToken,
tsPosition = _exceptionRegions[i].Span.ToVsTextSpan()
};
}
pceltFetched = celt;
return VSConstants.S_OK;
}
/// <summary>
/// Called by the debugger whenever it needs to determine a position of an active statement.
/// E.g. the user clicks on a frame in a call stack.
/// </summary>
/// <remarks>
/// Called when applying change, when setting current IP, a notification is received from
/// <see cref="IDebugEncNotify.NotifyEncUpdateCurrentStatement"/>, etc.
/// In addition this API is exposed on IDebugENC2 COM interface so it can be used anytime by other components.
/// </remarks>
public int GetCurrentActiveStatementPosition(uint vsId, VsTextSpan[] ptsNewPosition)
{
try
{
using (NonReentrantContext)
{
Debug.Assert(IsDebuggable);
var session = _encService.EditSession;
var ids = _activeStatementIds;
// Can be called anytime, even outside of an edit/debug session.
// We might not have an active statement available if PDB got out of sync with the source.
ActiveStatementId id;
if (session == null || ids == null || !ids.TryGetValue(vsId, out id))
{
log.Write("GetCurrentActiveStatementPosition failed for AS {0}.", vsId);
return VSConstants.E_FAIL;
}
Document document = _vsProject.Workspace.CurrentSolution.GetDocument(id.DocumentId);
SourceText text = document.GetTextAsync(default(CancellationToken)).Result;
// Try to get spans from the tracking service first.
// We might get an imprecise result if the document analysis hasn't been finished yet and
// the active statement has structurally changed, but that's ok. The user won't see an updated tag
// for the statement until the analysis finishes anyways.
TextSpan span;
LinePositionSpan lineSpan;
if (_trackingService.TryGetSpan(id, text, out span) && span.Length > 0)
{
lineSpan = text.Lines.GetLinePositionSpan(span);
}
else
{
var activeSpans = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken)).ActiveStatements;
if (activeSpans.IsDefault)
{
// The document has syntax errors and the tracking span is gone.
log.Write("Position not available for AS {0} due to syntax errors", vsId);
return VSConstants.E_FAIL;
}
lineSpan = activeSpans[id.Ordinal];
}
ptsNewPosition[0] = lineSpan.ToVsTextSpan();
log.DebugWrite("AS position: {0} {1} {2}", vsId, lineSpan,
session.BaseActiveStatements[id.DocumentId][id.Ordinal].Flags);
return VSConstants.S_OK;
}
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
/// <summary>
/// Returns the state of the changes made to the source.
/// The EnC manager calls this to determine whether there are any changes to the source
/// and if so whether there are any rude edits.
/// </summary>
public int GetENCBuildState(ShellInterop.ENC_BUILD_STATE[] pENCBuildState)
{
try
{
using (NonReentrantContext)
{
Debug.Assert(pENCBuildState != null && pENCBuildState.Length == 1);
// GetENCBuildState is called outside of edit session (at least) in following cases:
// 1) when the debugger is determining whether a source file checksum matches the one in PDB.
// 2) when the debugger is setting the next statement and a change is pending
// See CDebugger::SetNextStatement(CTextPos* pTextPos, bool WarnOnFunctionChange):
//
// pENC2->ExitBreakState();
// >>> hr = GetCodeContextOfPosition(pTextPos, &pCodeContext, &pProgram, true, true);
// pENC2->EnterBreakState(m_pSession, GetEncBreakReason());
//
// The debugger seem to expect ENC_NOT_MODIFIED in these cases, otherwise errors occur.
if (_changesApplied || _encService.EditSession == null)
{
_lastEditSessionSummary = ProjectAnalysisSummary.NoChanges;
}
else
{
// Fetch the latest snapshot of the project and get an analysis summary for any changes
// made since the break mode was entered.
var currentProject = _vsProject.Workspace.CurrentSolution.GetProject(_vsProject.Id);
if (currentProject == null)
{
// If the project has yet to be loaded into the solution (which may be the case,
// since they are loaded on-demand), then it stands to reason that it has not yet
// been modified.
// TODO (https://github.com/dotnet/roslyn/issues/1204): this check should be unnecessary.
_lastEditSessionSummary = ProjectAnalysisSummary.NoChanges;
log.Write($"Project '{_vsProject.DisplayName}' has not yet been loaded into the solution");
}
else
{
_projectBeingEmitted = currentProject;
_lastEditSessionSummary = GetProjectAnalysisSummary(_projectBeingEmitted);
}
_encService.EditSession.LogBuildState(_lastEditSessionSummary);
}
switch (_lastEditSessionSummary)
{
case ProjectAnalysisSummary.NoChanges:
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NOT_MODIFIED;
break;
case ProjectAnalysisSummary.CompilationErrors:
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_COMPILE_ERRORS;
break;
case ProjectAnalysisSummary.RudeEdits:
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NONCONTINUABLE_ERRORS;
break;
case ProjectAnalysisSummary.ValidChanges:
case ProjectAnalysisSummary.ValidInsignificantChanges:
// The debugger doesn't distinguish between these two.
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_APPLY_READY;
break;
default:
throw ExceptionUtilities.Unreachable;
}
log.Write("EnC state of '{0}' queried: {1}{2}",
_vsProject.DisplayName,
pENCBuildState[0],
_encService.EditSession != null ? "" : " (no session)");
return VSConstants.S_OK;
}
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private ProjectAnalysisSummary GetProjectAnalysisSummary(Project project)
{
if (!IsDebuggable)
{
return ProjectAnalysisSummary.NoChanges;
}
var cancellationToken = default(CancellationToken);
return _encService.EditSession.GetProjectAnalysisSummaryAsync(project, cancellationToken).Result;
}
public int ExitBreakStateOnPE()
{
try
{
using (NonReentrantContext)
{
// The debugger calls Exit without previously calling Enter if the project's MVID isn't available.
if (!IsDebuggable)
{
return VSConstants.S_OK;
}
log.Write("Exit Break Mode: project '{0}'", _vsProject.DisplayName);
// EnC service is global, but the debugger calls this for each project.
// Avoid ending the edit session if it has already been ended.
if (_encService.EditSession != null)
{
Debug.Assert(s_breakStateProjectCount == s_debugStateProjectCount);
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run);
_encService.EditSession.LogEditSession(s_encDebuggingSessionInfo);
_encService.EndEditSession();
_trackingService.EndTracking();
s_readOnlyDocumentTracker.UpdateWorkspaceDocuments();
_trackingService.TrackingSpansChanged -= TrackingSpansChanged;
}
_exceptionRegions.Clear();
_activeMethods.Clear();
_activeStatementIds.Clear();
s_breakStateProjectCount--;
Debug.Assert(s_breakStateProjectCount >= 0);
_changesApplied = false;
_diagnosticProvider.ClearDiagnostics(
new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId),
_vsProject.Workspace.CurrentSolution,
_vsProject.Id,
_documentsWithEmitError);
_documentsWithEmitError = ImmutableArray<DocumentId>.Empty;
}
// HResult ignored by the debugger
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
public unsafe int BuildForEnc(object pUpdatePE)
{
try
{
log.Write("Applying changes to {0}", _vsProject.DisplayName);
Debug.Assert(_encService.EditSession != null);
Debug.Assert(!_encService.EditSession.StoppedAtException);
// Non-debuggable project has no changes.
Debug.Assert(IsDebuggable);
if (_changesApplied)
{
log.Write("Changes already applied to {0}, can't apply again", _vsProject.DisplayName);
throw ExceptionUtilities.Unreachable;
}
// The debugger always calls GetENCBuildState right before BuildForEnc.
Debug.Assert(_projectBeingEmitted != null);
Debug.Assert(_lastEditSessionSummary == GetProjectAnalysisSummary(_projectBeingEmitted));
// The debugger should have called GetENCBuildState before calling BuildForEnc.
// Unfortunately, there is no way how to tell the debugger that the changes were not significant,
// so we'll to emit an empty delta. See bug 839558.
Debug.Assert(_lastEditSessionSummary == ProjectAnalysisSummary.ValidInsignificantChanges ||
_lastEditSessionSummary == ProjectAnalysisSummary.ValidChanges);
var updater = (IDebugUpdateInMemoryPE2)pUpdatePE;
if (_committedBaseline == null)
{
var hr = MarshalPdbReader(updater, out _pdbReaderObjAsStream);
if (hr != VSConstants.S_OK)
{
return hr;
}
_committedBaseline = EmitBaseline.CreateInitialBaseline(_metadata, GetBaselineEncDebugInfo);
}
// ISymUnmanagedReader can only be accessed from an MTA thread,
// so dispatch it to one of thread pool threads, which are MTA.
var emitTask = Task.Factory.SafeStartNew(EmitProjectDelta, CancellationToken.None, TaskScheduler.Default);
Deltas delta;
using (NonReentrantContext)
{
delta = emitTask.Result;
}
var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId);
// Clear diagnostics, in case the project was built before and failed due to errors.
_diagnosticProvider.ClearDiagnostics(errorId, _projectBeingEmitted.Solution, _vsProject.Id, _documentsWithEmitError);
if (!delta.EmitResult.Success)
{
var errors = delta.EmitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error);
_documentsWithEmitError = _diagnosticProvider.ReportDiagnostics(errorId, _projectBeingEmitted.Solution, _vsProject.Id, errors);
_encService.EditSession.LogEmitProjectDeltaErrors(errors.Select(e => e.Id));
return VSConstants.E_FAIL;
}
_documentsWithEmitError = ImmutableArray<DocumentId>.Empty;
SetFileUpdates(updater, delta.LineEdits);
updater.SetDeltaIL(delta.IL.Value, (uint)delta.IL.Value.Length);
updater.SetDeltaPdb(SymUnmanagedStreamFactory.CreateStream(delta.Pdb.Stream));
updater.SetRemapMethods(delta.Pdb.UpdatedMethods, (uint)delta.Pdb.UpdatedMethods.Length);
updater.SetDeltaMetadata(delta.Metadata.Bytes, (uint)delta.Metadata.Bytes.Length);
_pendingBaseline = delta.EmitResult.Baseline;
#if DEBUG
fixed (byte* deltaMetadataPtr = &delta.Metadata.Bytes[0])
{
var reader = new System.Reflection.Metadata.MetadataReader(deltaMetadataPtr, delta.Metadata.Bytes.Length);
var moduleDef = reader.GetModuleDefinition();
log.DebugWrite("Gen {0}: MVID={1}, BaseId={2}, EncId={3}",
moduleDef.Generation,
reader.GetGuid(moduleDef.Mvid),
reader.GetGuid(moduleDef.BaseGenerationId),
reader.GetGuid(moduleDef.GenerationId));
}
#endif
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private unsafe void SetFileUpdates(
IDebugUpdateInMemoryPE2 updater,
List<KeyValuePair<DocumentId, ImmutableArray<LineChange>>> edits)
{
int totalEditCount = edits.Sum(e => e.Value.Length);
if (totalEditCount == 0)
{
return;
}
var lineUpdates = new LINEUPDATE[totalEditCount];
fixed (LINEUPDATE* lineUpdatesPtr = lineUpdates)
{
int index = 0;
var fileUpdates = new FILEUPDATE[edits.Count];
for (int f = 0; f < fileUpdates.Length; f++)
{
var documentId = edits[f].Key;
var deltas = edits[f].Value;
fileUpdates[f].FileName = _vsProject.GetDocumentOrAdditionalDocument(documentId).FilePath;
fileUpdates[f].LineUpdateCount = (uint)deltas.Length;
fileUpdates[f].LineUpdates = (IntPtr)(lineUpdatesPtr + index);
for (int l = 0; l < deltas.Length; l++)
{
lineUpdates[index + l].Line = (uint)deltas[l].OldLine;
lineUpdates[index + l].UpdatedLine = (uint)deltas[l].NewLine;
}
index += deltas.Length;
}
// The updater makes a copy of all data, we can release the buffer after the call.
updater.SetFileUpdates(fileUpdates, (uint)fileUpdates.Length);
}
}
private Deltas EmitProjectDelta()
{
Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA);
var emitTask = _encService.EditSession.EmitProjectDeltaAsync(_projectBeingEmitted, _committedBaseline, default(CancellationToken));
return emitTask.Result;
}
private EditAndContinueMethodDebugInformation GetBaselineEncDebugInfo(MethodDefinitionHandle methodHandle)
{
Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA);
if (_pdbReader == null)
{
// Unmarshal the symbol reader (being marshalled cross thread from STA -> MTA).
Debug.Assert(_pdbReaderObjAsStream != IntPtr.Zero);
object pdbReaderObjMta;
int hr = NativeMethods.GetObjectForStream(_pdbReaderObjAsStream, out pdbReaderObjMta);
_pdbReaderObjAsStream = IntPtr.Zero;
if (hr != VSConstants.S_OK)
{
log.Write("Error unmarshaling object from stream.");
return default(EditAndContinueMethodDebugInformation);
}
_pdbReader = (ISymUnmanagedReader3)pdbReaderObjMta;
}
int methodToken = MetadataTokens.GetToken(methodHandle);
byte[] debugInfo = _pdbReader.GetCustomDebugInfoBytes(methodToken, methodVersion: 1);
if (debugInfo != null)
{
try
{
var localSlots = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLocalSlotMap);
var lambdaMap = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLambdaMap);
return EditAndContinueMethodDebugInformation.Create(localSlots, lambdaMap);
}
catch (Exception e) when (e is InvalidOperationException || e is InvalidDataException)
{
log.Write($"Error reading CDI of method 0x{methodToken:X8}: {e.Message}");
}
}
return default(EditAndContinueMethodDebugInformation);
}
public int EncApplySucceeded(int hrApplyResult)
{
try
{
log.Write("Change applied to {0}", _vsProject.DisplayName);
Debug.Assert(IsDebuggable);
Debug.Assert(_encService.EditSession != null);
Debug.Assert(!_encService.EditSession.StoppedAtException);
Debug.Assert(_pendingBaseline != null);
// Since now on until exiting the break state, we consider the changes applied and the project state should be NoChanges.
_changesApplied = true;
_committedBaseline = _pendingBaseline;
_pendingBaseline = null;
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
/// <summary>
/// Called when changes are being applied.
/// </summary>
/// <param name="exceptionRegionId">
/// The value of <see cref="ShellInterop.ENC_EXCEPTION_SPAN.id"/>.
/// Set by <see cref="GetExceptionSpans(uint, ShellInterop.ENC_EXCEPTION_SPAN[], ref uint)"/> to the index into <see cref="_exceptionRegions"/>.
/// </param>
/// <param name="ptsNewPosition">Output value holder.</param>
public int GetCurrentExceptionSpanPosition(uint exceptionRegionId, VsTextSpan[] ptsNewPosition)
{
try
{
using (NonReentrantContext)
{
Debug.Assert(IsDebuggable);
Debug.Assert(_encService.EditSession != null);
Debug.Assert(!_encService.EditSession.StoppedAtException);
Debug.Assert(ptsNewPosition.Length == 1);
var exceptionRegion = _exceptionRegions[(int)exceptionRegionId];
var session = _encService.EditSession;
var asid = _activeStatementIds[exceptionRegion.ActiveStatementId];
var document = _projectBeingEmitted.GetDocument(asid.DocumentId);
var analysis = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken));
var regions = analysis.ExceptionRegions;
// the method shouldn't be called in presence of errors:
Debug.Assert(!analysis.HasChangesAndErrors);
Debug.Assert(!regions.IsDefault);
// Absence of rude edits guarantees that the exception regions around AS haven't semantically changed.
// Only their spans might have changed.
ptsNewPosition[0] = regions[asid.Ordinal][exceptionRegion.Ordinal].ToVsTextSpan();
}
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private static int MarshalPdbReader(IDebugUpdateInMemoryPE2 updater, out IntPtr pdbReaderPointer)
{
// ISymUnmanagedReader can only be accessed from an MTA thread, however, we need
// fetch the IUnknown instance (call IENCSymbolReaderProvider.GetSymbolReader) here
// in the STA. To further complicate things, we need to return synchronously from
// this method. Waiting for the MTA thread to complete so we can return synchronously
// blocks the STA thread, so we need to make sure the CLR doesn't try to marshal
// ISymUnmanagedReader calls made in an MTA back to the STA for execution (if this
// happens we'll be deadlocked). We'll use CoMarshalInterThreadInterfaceInStream to
// achieve this. First, we'll marshal the object in a Stream and pass a Stream pointer
// over to the MTA. In the MTA, we'll get the Stream from the pointer and unmarshal
// the object. The reader object was originally created on an MTA thread, and the
// instance we retrieved in the STA was a proxy. When we unmarshal the Stream in the
// MTA, it "unwraps" the proxy, allowing us to directly call the implementation.
// Another way to achieve this would be for the symbol reader to implement IAgileObject,
// but the symbol reader we use today does not. If that changes, we should consider
// removing this marshal/unmarshal code.
IENCDebugInfo debugInfo;
updater.GetENCDebugInfo(out debugInfo);
var symbolReaderProvider = (IENCSymbolReaderProvider)debugInfo;
object pdbReaderObjSta;
symbolReaderProvider.GetSymbolReader(out pdbReaderObjSta);
int hr = NativeMethods.GetStreamForObject(pdbReaderObjSta, out pdbReaderPointer);
Marshal.ReleaseComObject(pdbReaderObjSta);
return hr;
}
#region Testing
#if DEBUG
// Fault injection:
// If set we'll fail to read MVID of specified projects to test error reporting.
internal static ImmutableArray<string> InjectMvidReadingFailure;
private void InjectFault_MvidRead()
{
if (!InjectMvidReadingFailure.IsDefault && InjectMvidReadingFailure.Contains(_vsProject.DisplayName))
{
throw new IOException("Fault injection");
}
}
#else
[Conditional("DEBUG")]
private void InjectFault_MvidRead()
{
}
#endif
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//-----------------------------------------------------------------------------
//
// Description:
// This is a class for representing a PackageRelationshipCollection. This is an internal
// class for manipulating relationships associated with a part
//
// Details:
// This class handles serialization to/from relationship parts, creation of those parts
// and offers methods to create, delete and enumerate relationships. This code was
// moved from the PackageRelationshipCollection class.
//
//-----------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Xml; // for XmlReader/Writer
using System.Diagnostics;
namespace System.IO.Packaging
{
/// <summary>
/// Collection of all the relationships corresponding to a given source PackagePart
/// </summary>
internal class InternalRelationshipCollection : IEnumerable<PackageRelationship>
{
// Mono will parse a URI starting with '/' as an absolute URI, while .NET Core and
// .NET Framework will parse this as relative. This will break internal relationships
// in packaging. For more information, see
// http://www.mono-project.com/docs/faq/known-issues/urikind-relativeorabsolute/
private static readonly UriKind DotNetRelativeOrAbsolute = Type.GetType ("Mono.Runtime") == null ? UriKind.RelativeOrAbsolute : (UriKind)300;
#region IEnumerable
/// <summary>
/// Returns an enumerator over all the relationships for a Package or a PackagePart
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return _relationships.GetEnumerator();
}
/// <summary>
/// Returns an enumerator over all the relationships for a Package or a PackagePart
/// </summary>
/// <returns></returns>
IEnumerator<PackageRelationship> IEnumerable<PackageRelationship>.GetEnumerator()
{
return _relationships.GetEnumerator();
}
/// <summary>
/// Returns an enumerator over all the relationships for a Package or a PackagePart
/// </summary>
/// <returns></returns>
public List<PackageRelationship>.Enumerator GetEnumerator()
{
return _relationships.GetEnumerator();
}
#endregion
#region Internal Methods
/// <summary>
/// Constructor
/// </summary>
/// <remarks>For use by PackagePart</remarks>
internal InternalRelationshipCollection(PackagePart part) : this(part.Package, part)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <remarks>For use by Package</remarks>
internal InternalRelationshipCollection(Package package) : this(package, null)
{
}
/// <summary>
/// Add new relationship
/// </summary>
/// <param name="targetUri">target</param>
/// <param name="targetMode">Enumeration indicating the base uri for the target uri</param>
/// <param name="relationshipType">relationship type that uniquely defines the role of the relationship</param>
/// <param name="id">String that conforms to the xsd:ID datatype. Unique across the source's relationships.
/// Null OK (ID will be generated).</param>
internal PackageRelationship Add(Uri targetUri, TargetMode targetMode, string relationshipType, string id)
{
return Add(targetUri, targetMode, relationshipType, id, parsing: false);
}
/// <summary>
/// Return the relationship whose id is 'id', and null if not found.
/// </summary>
internal PackageRelationship GetRelationship(string id)
{
int index = GetRelationshipIndex(id);
if (index == -1)
return null;
return _relationships[index];
}
/// <summary>
/// Delete relationship with ID 'id'
/// </summary>
/// <param name="id">ID of the relationship to remove</param>
internal void Delete(string id)
{
int index = GetRelationshipIndex(id);
if (index == -1)
return;
_relationships.RemoveAt(index);
_dirty = true;
}
/// <summary>
/// Clear all the relationships in this collection
/// Today it is only used when the entire relationship part is being deleted
/// </summary>
internal void Clear()
{
_relationships.Clear();
_dirty = true;
}
/// <summary>
/// Flush to stream (destructive)
/// </summary>
/// <remarks>
/// Flush part.
/// </remarks>
internal void Flush()
{
if (!_dirty)
return;
if (_relationships.Count == 0) // empty?
{
// delete the part
if (_package.PartExists(_uri))
{
_package.DeletePart(_uri);
}
_relationshipPart = null;
}
else
{
EnsureRelationshipPart(); // lazy init
// write xml
WriteRelationshipPart(_relationshipPart);
}
_dirty = false;
}
internal static void ThrowIfInvalidRelationshipType(string relationshipType)
{
// Look for empty string or string with just spaces
if (relationshipType.Trim() == string.Empty)
throw new ArgumentException(SR.InvalidRelationshipType);
}
// If 'id' is not of the xsd type ID, throw an exception.
internal static void ThrowIfInvalidXsdId(string id)
{
Debug.Assert(id != null, "id should not be null");
try
{
// An XSD ID is an NCName that is unique.
XmlConvert.VerifyNCName(id);
}
catch (XmlException exception)
{
throw new XmlException(SR.Format(SR.NotAValidXmlIdString, id), exception);
}
}
#endregion Internal Methods
#region Private Methods
/// <summary>
/// Constructor
/// </summary>
/// <param name="package">package</param>
/// <param name="part">part will be null if package is the source of the relationships</param>
/// <remarks>Shared constructor</remarks>
private InternalRelationshipCollection(Package package, PackagePart part)
{
Debug.Assert(package != null, "package parameter passed should never be null");
_package = package;
_sourcePart = part;
//_sourcePart may be null representing that the relationships are at the package level
_uri = GetRelationshipPartUri(_sourcePart);
_relationships = new List<PackageRelationship>(4);
// Load if available (not applicable to write-only mode).
if ((package.FileOpenAccess == FileAccess.Read ||
package.FileOpenAccess == FileAccess.ReadWrite) && package.PartExists(_uri))
{
_relationshipPart = package.GetPart(_uri);
ThrowIfIncorrectContentType(_relationshipPart.ValidatedContentType);
ParseRelationshipPart(_relationshipPart);
}
//Any initialization in the constructor should not set the dirty flag to true.
_dirty = false;
}
/// <summary>
/// Returns the associated RelationshipPart for this part
/// </summary>
/// <param name="part">may be null</param>
/// <returns>name of relationship part for the given part</returns>
private static Uri GetRelationshipPartUri(PackagePart part)
{
Uri sourceUri;
if (part == null)
sourceUri = PackUriHelper.PackageRootUri;
else
sourceUri = part.Uri;
return PackUriHelper.GetRelationshipPartUri(sourceUri);
}
/// <summary>
/// Parse PackageRelationship Stream
/// </summary>
/// <param name="part">relationship part</param>
/// <exception cref="XmlException">Thrown if XML is malformed</exception>
private void ParseRelationshipPart(PackagePart part)
{
//We can safely open the stream as FileAccess.Read, as this code
//should only be invoked if the Package has been opened in Read or ReadWrite mode.
Debug.Assert(_package.FileOpenAccess == FileAccess.Read || _package.FileOpenAccess == FileAccess.ReadWrite,
"This method should only be called when FileAccess is Read or ReadWrite");
using (Stream s = part.GetStream(FileMode.Open, FileAccess.Read))
{
// load from the relationship part associated with the given part
using (XmlReader baseReader = XmlReader.Create(s))
{
using (XmlCompatibilityReader reader = new XmlCompatibilityReader(baseReader, s_relationshipKnownNamespaces))
{
//This method expects the reader to be in ReadState.Initial.
//It will make the first read call.
PackagingUtilities.PerformInitialReadAndVerifyEncoding(baseReader);
//Note: After the previous method call the reader should be at the first tag in the markup.
//MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
// look for our tag and namespace pair - throw if other elements are encountered
// Make sure that the current node read is an Element
if (reader.NodeType == XmlNodeType.Element
&& (reader.Depth == 0)
&& (string.CompareOrdinal(s_relationshipsTagName, reader.LocalName) == 0)
&& (string.CompareOrdinal(PackagingUtilities.RelationshipNamespaceUri, reader.NamespaceURI) == 0))
{
ThrowIfXmlBaseAttributeIsPresent(reader);
//There should be a namespace Attribute present at this level.
//Also any other attribute on the <Relationships> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0)
throw new XmlException(SR.RelationshipsTagHasExtraAttributes, null, reader.LineNumber, reader.LinePosition);
// start tag encountered for Relationships
// now parse individual Relationship tags
while (reader.Read())
{
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
//If MoveToContent() takes us to the end of the content
if (reader.NodeType == XmlNodeType.None)
continue;
if (reader.NodeType == XmlNodeType.Element
&& (reader.Depth == 1)
&& (string.CompareOrdinal(s_relationshipTagName, reader.LocalName) == 0)
&& (string.CompareOrdinal(PackagingUtilities.RelationshipNamespaceUri, reader.NamespaceURI) == 0))
{
ThrowIfXmlBaseAttributeIsPresent(reader);
int expectedAttributesCount = 3;
string targetModeAttributeValue = reader.GetAttribute(s_targetModeAttributeName);
if (targetModeAttributeValue != null)
expectedAttributesCount++;
//check if there are expected number of attributes.
//Also any other attribute on the <Relationship> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) == expectedAttributesCount)
{
ProcessRelationshipAttributes(reader);
//Skip the EndElement for Relationship
if (!reader.IsEmptyElement)
ProcessEndElementForRelationshipTag(reader);
}
else
{
throw new XmlException(SR.RelationshipTagDoesntMatchSchema, null, reader.LineNumber, reader.LinePosition);
}
}
else
if (!(string.CompareOrdinal(s_relationshipsTagName, reader.LocalName) == 0 && (reader.NodeType == XmlNodeType.EndElement)))
throw new XmlException(SR.UnknownTagEncountered, null, reader.LineNumber, reader.LinePosition);
}
}
else throw new XmlException(SR.ExpectedRelationshipsElementTag, null, reader.LineNumber, reader.LinePosition);
}
}
}
}
//This method processes the attributes that are present on the Relationship element
private void ProcessRelationshipAttributes(XmlCompatibilityReader reader)
{
// Attribute : TargetMode
string targetModeAttributeValue = reader.GetAttribute(s_targetModeAttributeName);
//If the TargetMode attribute is missing in the underlying markup then we assume it to be internal
TargetMode relationshipTargetMode = TargetMode.Internal;
if (targetModeAttributeValue != null)
{
try
{
relationshipTargetMode = (TargetMode)(Enum.Parse(typeof(TargetMode), targetModeAttributeValue, ignoreCase: false));
}
catch (ArgumentNullException argNullEx)
{
ThrowForInvalidAttributeValue(reader, s_targetModeAttributeName, argNullEx);
}
catch (ArgumentException argEx)
{
//if the targetModeAttributeValue is not Internal|External then Argument Exception will be thrown.
ThrowForInvalidAttributeValue(reader, s_targetModeAttributeName, argEx);
}
}
// Attribute : Target
// create a new PackageRelationship
string targetAttributeValue = reader.GetAttribute(s_targetAttributeName);
if (string.IsNullOrEmpty(targetAttributeValue))
throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_targetAttributeName), null, reader.LineNumber, reader.LinePosition);
Uri targetUri = new Uri(targetAttributeValue, DotNetRelativeOrAbsolute);
// Attribute : Type
string typeAttributeValue = reader.GetAttribute(s_typeAttributeName);
if (string.IsNullOrEmpty(typeAttributeValue))
throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_typeAttributeName), null, reader.LineNumber, reader.LinePosition);
// Attribute : Id
// Get the Id attribute (required attribute).
string idAttributeValue = reader.GetAttribute(s_idAttributeName);
if (string.IsNullOrEmpty(idAttributeValue))
throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_idAttributeName), null, reader.LineNumber, reader.LinePosition);
// Add the relationship to the collection
Add(targetUri, relationshipTargetMode, typeAttributeValue, idAttributeValue, parsing: true);
}
//If End element is present for Relationship then we process it
private void ProcessEndElementForRelationshipTag(XmlCompatibilityReader reader)
{
Debug.Assert(!reader.IsEmptyElement, "This method should only be called if the Relationship Element is not empty");
reader.Read();
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
reader.MoveToContent();
if (reader.NodeType == XmlNodeType.EndElement && string.CompareOrdinal(s_relationshipTagName, reader.LocalName) == 0)
return;
else
throw new XmlException(SR.Format(SR.ElementIsNotEmptyElement, s_relationshipTagName), null, reader.LineNumber, reader.LinePosition);
}
/// <summary>
/// Add new relationship to the Collection
/// </summary>
/// <param name="targetUri">target</param>
/// <param name="targetMode">Enumeration indicating the base uri for the target uri</param>
/// <param name="relationshipType">relationship type that uniquely defines the role of the relationship</param>
/// <param name="id">String that conforms to the xsd:ID datatype. Unique across the source's relationships.
/// Null OK (ID will be generated).</param>
/// <param name="parsing">Indicates whether the add call is made while parsing existing relationships
/// from a relationship part, or we are adding a new relationship</param>
private PackageRelationship Add(Uri targetUri, TargetMode targetMode, string relationshipType, string id, bool parsing)
{
if (targetUri == null)
throw new ArgumentNullException(nameof(targetUri));
if (relationshipType == null)
throw new ArgumentNullException(nameof(relationshipType));
ThrowIfInvalidRelationshipType(relationshipType);
//Verify if the Enum value is valid
if (targetMode < TargetMode.Internal || targetMode > TargetMode.External)
throw new ArgumentOutOfRangeException(nameof(targetMode));
// don't accept absolute Uri's if targetMode is Internal.
if (targetMode == TargetMode.Internal && targetUri.IsAbsoluteUri)
throw new ArgumentException(SR.RelationshipTargetMustBeRelative, nameof(targetUri));
// don't allow relationships to relationships
// This check should be made for following cases
// 1. Uri is absolute and it is pack Uri
// 2. Uri is NOT absolute and its target mode is internal (or NOT external)
// Note: if the target is absolute uri and its not a pack scheme then we cannot determine if it is a rels part
// Note: if the target is relative uri and target mode is external, we cannot determine if it is a rels part
if ((!targetUri.IsAbsoluteUri && targetMode != TargetMode.External)
|| (targetUri.IsAbsoluteUri && targetUri.Scheme == PackUriHelper.UriSchemePack))
{
Uri resolvedUri = GetResolvedTargetUri(targetUri, targetMode);
//GetResolvedTargetUri returns a null if the target mode is external and the
//target Uri is a packUri with no "part" component, so in that case we know that
//its not a relationship part.
if (resolvedUri != null)
{
if (PackUriHelper.IsRelationshipPartUri(resolvedUri))
throw new ArgumentException(SR.RelationshipToRelationshipIllegal, nameof(targetUri));
}
}
// Generate an ID if id is null. Throw exception if neither null nor a valid unique xsd:ID.
if (id == null)
id = GenerateUniqueRelationshipId();
else
ValidateUniqueRelationshipId(id);
// create and add
PackageRelationship relationship = new PackageRelationship(_package, _sourcePart, targetUri, targetMode, relationshipType, id);
_relationships.Add(relationship);
//If we are adding relationships as a part of Parsing the underlying relationship part, we should not set
//the dirty flag to false.
_dirty = !parsing;
return relationship;
}
/// <summary>
/// Write PackageRelationship Stream
/// </summary>
/// <param name="part">part to persist to</param>
private void WriteRelationshipPart(PackagePart part)
{
using (Stream partStream = part.GetStream())
using (IgnoreFlushAndCloseStream s = new IgnoreFlushAndCloseStream(partStream))
{
if (_package.FileOpenAccess != FileAccess.Write)
{
s.SetLength(0); // truncate to resolve PS 954048
}
// use UTF-8 encoding by default
using (XmlWriter writer = XmlWriter.Create(s, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 }))
{
writer.WriteStartDocument();
// start outer Relationships tag
writer.WriteStartElement(s_relationshipsTagName, PackagingUtilities.RelationshipNamespaceUri);
// Write Relationship elements.
WriteRelationshipsAsXml(
writer,
_relationships,
false /* do not systematically write target mode */
);
// end of Relationships tag
writer.WriteEndElement();
// close the document
writer.WriteEndDocument();
}
}
}
/// <summary>
/// Write one Relationship element for each member of relationships.
/// This method is used by XmlDigitalSignatureProcessor code as well
/// </summary>
internal static void WriteRelationshipsAsXml(XmlWriter writer, IEnumerable<PackageRelationship> relationships, bool alwaysWriteTargetModeAttribute)
{
foreach (PackageRelationship relationship in relationships)
{
writer.WriteStartElement(s_relationshipTagName);
// Write RelationshipType attribute.
writer.WriteAttributeString(s_typeAttributeName, relationship.RelationshipType);
// Write Target attribute.
// We would like to persist the uri as passed in by the user and so we use the
// OriginalString property. This makes the persisting behavior consistent
// for relative and absolute Uris.
// Since we accepted the Uri as a string, we are at the minimum guaranteed that
// the string can be converted to a valid Uri.
// Also, we are just using it here to persist the information and we are not
// resolving or fetching a resource based on this Uri.
writer.WriteAttributeString(s_targetAttributeName, relationship.TargetUri.OriginalString);
// TargetMode is optional attribute in the markup and its default value is TargetMode="Internal"
if (alwaysWriteTargetModeAttribute || relationship.TargetMode == TargetMode.External)
writer.WriteAttributeString(s_targetModeAttributeName, relationship.TargetMode.ToString());
// Write Id attribute.
writer.WriteAttributeString(s_idAttributeName, relationship.Id);
writer.WriteEndElement();
}
}
/// <summary>
/// Ensures that the PackageRelationship PackagePart has been created - lazy init
/// </summary>
/// <remarks>
/// </remarks>
private void EnsureRelationshipPart()
{
if (_relationshipPart == null || _relationshipPart.IsDeleted)
{
if (_package.PartExists(_uri))
{
_relationshipPart = _package.GetPart(_uri);
ThrowIfIncorrectContentType(_relationshipPart.ValidatedContentType);
}
else
{
CompressionOption compressionOption = _sourcePart == null ? CompressionOption.NotCompressed : _sourcePart.CompressionOption;
_relationshipPart = _package.CreatePart(_uri, PackagingUtilities.RelationshipPartContentType.ToString(), compressionOption);
}
}
}
/// <summary>
/// Resolves the target uri in the relationship against the source part or the
/// package root. This resolved Uri is then used by the Add method to figure
/// out if a relationship is being created to another relationship part.
/// </summary>
/// <param name="target">PackageRelationship target uri</param>
/// <param name="targetMode"> Enum value specifying the interpretation of the base uri
/// for the relationship target uri</param>
/// <returns>Resolved Uri</returns>
private Uri GetResolvedTargetUri(Uri target, TargetMode targetMode)
{
Debug.Assert(targetMode == TargetMode.Internal);
Debug.Assert(!target.IsAbsoluteUri, "Uri should be relative at this stage");
if (_sourcePart == null) //indicates that the source is the package root
return PackUriHelper.ResolvePartUri(PackUriHelper.PackageRootUri, target);
else
return PackUriHelper.ResolvePartUri(_sourcePart.Uri, target);
}
//Throws an exception if the relationship part does not have the correct content type
private void ThrowIfIncorrectContentType(ContentType contentType)
{
if (!contentType.AreTypeAndSubTypeEqual(PackagingUtilities.RelationshipPartContentType))
throw new FileFormatException(SR.RelationshipPartIncorrectContentType);
}
//Throws an exception if the xml:base attribute is present in the Relationships XML
private void ThrowIfXmlBaseAttributeIsPresent(XmlCompatibilityReader reader)
{
string xmlBaseAttributeValue = reader.GetAttribute(s_xmlBaseAttributeName);
if (xmlBaseAttributeValue != null)
throw new XmlException(SR.Format(SR.InvalidXmlBaseAttributePresent, s_xmlBaseAttributeName), null, reader.LineNumber, reader.LinePosition);
}
//Throws an XML exception if the attribute value is invalid
private void ThrowForInvalidAttributeValue(XmlCompatibilityReader reader, string attributeName, Exception ex)
{
throw new XmlException(SR.Format(SR.InvalidValueForTheAttribute, attributeName), ex, reader.LineNumber, reader.LinePosition);
}
// Generate a unique relation ID.
private string GenerateUniqueRelationshipId()
{
string id;
do
{
id = GenerateRelationshipId();
} while (GetRelationship(id) != null);
return id;
}
// Build an ID string consisting of the letter 'R' followed by an 8-byte GUID timestamp.
// Guid.ToString() outputs the bytes in the big-endian order (higher order byte first)
private string GenerateRelationshipId()
{
// The timestamp consists of the first 8 hex octets of the GUID.
return string.Concat("R", Guid.NewGuid().ToString("N").Substring(0, s_timestampLength));
}
// If 'id' is not of the xsd type ID or is not unique for this collection, throw an exception.
private void ValidateUniqueRelationshipId(string id)
{
// An XSD ID is an NCName that is unique.
ThrowIfInvalidXsdId(id);
// Check for uniqueness.
if (GetRelationshipIndex(id) >= 0)
throw new XmlException(SR.Format(SR.NotAUniqueRelationshipId, id));
}
// Retrieve a relationship's index in _relationships given its id.
// Return a negative value if not found.
private int GetRelationshipIndex(string id)
{
for (int index = 0; index < _relationships.Count; ++index)
if (string.Equals(_relationships[index].Id, id, StringComparison.Ordinal))
return index;
return -1;
}
#endregion
#region Private Properties
#endregion Private Properties
#region Private Members
private List<PackageRelationship> _relationships;
private bool _dirty; // true if we have uncommitted changes to _relationships
private Package _package; // our package - in case _sourcePart is null
private PackagePart _sourcePart; // owning part - null if package is the owner
private PackagePart _relationshipPart; // where our relationships are persisted
private Uri _uri; // the URI of our relationship part
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
// segment that indicates a relationship part
private static readonly int s_timestampLength = 16;
private static readonly string s_relationshipsTagName = "Relationships";
private static readonly string s_relationshipTagName = "Relationship";
private static readonly string s_targetAttributeName = "Target";
private static readonly string s_typeAttributeName = "Type";
private static readonly string s_idAttributeName = "Id";
private static readonly string s_xmlBaseAttributeName = "xml:base";
private static readonly string s_targetModeAttributeName = "TargetMode";
private static readonly string[] s_relationshipKnownNamespaces
= new string[] { PackagingUtilities.RelationshipNamespaceUri };
#endregion
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using AutoMapper;
using Microsoft.Azure.Commands.Network.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Microsoft.Azure.Management.Network;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using MNM = Microsoft.Azure.Management.Network.Models;
namespace Microsoft.Azure.Commands.Network
{
[Cmdlet(VerbsCommon.New, "AzureRmApplicationGateway", SupportsShouldProcess = true),
OutputType(typeof(PSApplicationGateway))]
public class NewAzureApplicationGatewayCommand : ApplicationGatewayBaseCmdlet
{
[Alias("ResourceName")]
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource name.")]
[ValidateNotNullOrEmpty]
public virtual string Name { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ValidateNotNullOrEmpty]
public virtual string ResourceGroupName { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "location.")]
[ValidateNotNullOrEmpty]
public virtual string Location { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The SKU of application gateway")]
[ValidateNotNullOrEmpty]
public virtual PSApplicationGatewaySku Sku { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of IPConfiguration (subnet)")]
[ValidateNotNullOrEmpty]
public List<PSApplicationGatewayIPConfiguration> GatewayIPConfigurations { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of ssl certificate")]
public List<PSApplicationGatewaySslCertificate> SslCertificates { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of frontend IP config")]
public List<PSApplicationGatewayFrontendIPConfiguration> FrontendIPConfigurations { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of frontend port")]
public List<PSApplicationGatewayFrontendPort> FrontendPorts { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of probe")]
public List<PSApplicationGatewayProbe> Probes { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of backend address pool")]
public List<PSApplicationGatewayBackendAddressPool> BackendAddressPools { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of backend http settings")]
public List<PSApplicationGatewayBackendHttpSettings> BackendHttpSettingsCollection { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of http listener")]
public List<PSApplicationGatewayHttpListener> HttpListeners { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of UrlPathMap")]
public List<PSApplicationGatewayUrlPathMap> UrlPathMaps { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of request routing rule")]
public List<PSApplicationGatewayRequestRoutingRule> RequestRoutingRules { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "A hashtable which represents resource tags.")]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "Do not ask for confirmation if you want to overrite a resource")]
public SwitchParameter Force { get; set; }
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
WriteWarning("The output object type of this cmdlet will be modified in a future release.");
var present = this.IsApplicationGatewayPresent(this.ResourceGroupName, this.Name);
ConfirmAction(
Force.IsPresent,
string.Format(Microsoft.Azure.Commands.Network.Properties.Resources.OverwritingResource, Name),
Microsoft.Azure.Commands.Network.Properties.Resources.OverwritingResourceMessage,
Name,
() =>
{
var applicationGateway = CreateApplicationGateway();
WriteObject(applicationGateway);
},
() => present);
}
private PSApplicationGateway CreateApplicationGateway()
{
var applicationGateway = new PSApplicationGateway();
applicationGateway.Name = this.Name;
applicationGateway.ResourceGroupName = this.ResourceGroupName;
applicationGateway.Location = this.Location;
applicationGateway.Sku = this.Sku;
if (this.GatewayIPConfigurations != null)
{
applicationGateway.GatewayIPConfigurations = this.GatewayIPConfigurations;
}
if (this.SslCertificates != null)
{
applicationGateway.SslCertificates = this.SslCertificates;
}
if (this.FrontendIPConfigurations != null)
{
applicationGateway.FrontendIPConfigurations = this.FrontendIPConfigurations;
}
if (this.FrontendPorts != null)
{
applicationGateway.FrontendPorts = this.FrontendPorts;
}
if (this.Probes != null)
{
applicationGateway.Probes = this.Probes;
}
if (this.BackendAddressPools != null)
{
applicationGateway.BackendAddressPools = this.BackendAddressPools;
}
if (this.BackendHttpSettingsCollection != null)
{
applicationGateway.BackendHttpSettingsCollection = this.BackendHttpSettingsCollection;
}
if (this.HttpListeners != null)
{
applicationGateway.HttpListeners = this.HttpListeners;
}
if (this.UrlPathMaps != null)
{
applicationGateway.UrlPathMaps = this.UrlPathMaps;
}
if (this.RequestRoutingRules != null)
{
applicationGateway.RequestRoutingRules = this.RequestRoutingRules;
}
// Normalize the IDs
ApplicationGatewayChildResourceHelper.NormalizeChildResourcesId(applicationGateway);
// Map to the sdk object
var appGwModel = Mapper.Map<MNM.ApplicationGateway>(applicationGateway);
appGwModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true);
// Execute the Create ApplicationGateway call
this.ApplicationGatewayClient.CreateOrUpdate(this.ResourceGroupName, this.Name, appGwModel);
var getApplicationGateway = this.GetApplicationGateway(this.ResourceGroupName, this.Name);
return getApplicationGateway;
}
}
}
| |
// 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 gcsv = Google.Cloud.SecretManager.V1;
using sys = System;
namespace Google.Cloud.SecretManager.V1
{
/// <summary>Resource name for the <c>Secret</c> resource.</summary>
public sealed partial class SecretName : gax::IResourceName, sys::IEquatable<SecretName>
{
/// <summary>The possible contents of <see cref="SecretName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/secrets/{secret}</c>.</summary>
ProjectSecret = 1,
}
private static gax::PathTemplate s_projectSecret = new gax::PathTemplate("projects/{project}/secrets/{secret}");
/// <summary>Creates a <see cref="SecretName"/> 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="SecretName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static SecretName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SecretName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SecretName"/> with the pattern <c>projects/{project}/secrets/{secret}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="secretId">The <c>Secret</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SecretName"/> constructed from the provided ids.</returns>
public static SecretName FromProjectSecret(string projectId, string secretId) =>
new SecretName(ResourceNameType.ProjectSecret, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), secretId: gax::GaxPreconditions.CheckNotNullOrEmpty(secretId, nameof(secretId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecretName"/> with pattern
/// <c>projects/{project}/secrets/{secret}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="secretId">The <c>Secret</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecretName"/> with pattern
/// <c>projects/{project}/secrets/{secret}</c>.
/// </returns>
public static string Format(string projectId, string secretId) => FormatProjectSecret(projectId, secretId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecretName"/> with pattern
/// <c>projects/{project}/secrets/{secret}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="secretId">The <c>Secret</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecretName"/> with pattern
/// <c>projects/{project}/secrets/{secret}</c>.
/// </returns>
public static string FormatProjectSecret(string projectId, string secretId) =>
s_projectSecret.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(secretId, nameof(secretId)));
/// <summary>Parses the given resource name string into a new <see cref="SecretName"/> 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}/secrets/{secret}</c></description></item>
/// </list>
/// </remarks>
/// <param name="secretName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SecretName"/> if successful.</returns>
public static SecretName Parse(string secretName) => Parse(secretName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SecretName"/> 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}/secrets/{secret}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="secretName">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="SecretName"/> if successful.</returns>
public static SecretName Parse(string secretName, bool allowUnparsed) =>
TryParse(secretName, allowUnparsed, out SecretName 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="SecretName"/> 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}/secrets/{secret}</c></description></item>
/// </list>
/// </remarks>
/// <param name="secretName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SecretName"/>, 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 secretName, out SecretName result) => TryParse(secretName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SecretName"/> 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}/secrets/{secret}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="secretName">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="SecretName"/>, 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 secretName, bool allowUnparsed, out SecretName result)
{
gax::GaxPreconditions.CheckNotNull(secretName, nameof(secretName));
gax::TemplatedResourceName resourceName;
if (s_projectSecret.TryParseName(secretName, out resourceName))
{
result = FromProjectSecret(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(secretName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SecretName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string secretId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ProjectId = projectId;
SecretId = secretId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SecretName"/> class from the component parts of pattern
/// <c>projects/{project}/secrets/{secret}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="secretId">The <c>Secret</c> ID. Must not be <c>null</c> or empty.</param>
public SecretName(string projectId, string secretId) : this(ResourceNameType.ProjectSecret, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), secretId: gax::GaxPreconditions.CheckNotNullOrEmpty(secretId, nameof(secretId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Secret</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string SecretId { 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.ProjectSecret: return s_projectSecret.Expand(ProjectId, SecretId);
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 SecretName);
/// <inheritdoc/>
public bool Equals(SecretName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SecretName a, SecretName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SecretName a, SecretName b) => !(a == b);
}
/// <summary>Resource name for the <c>SecretVersion</c> resource.</summary>
public sealed partial class SecretVersionName : gax::IResourceName, sys::IEquatable<SecretVersionName>
{
/// <summary>The possible contents of <see cref="SecretVersionName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/secrets/{secret}/versions/{secret_version}</c>.
/// </summary>
ProjectSecretSecretVersion = 1,
}
private static gax::PathTemplate s_projectSecretSecretVersion = new gax::PathTemplate("projects/{project}/secrets/{secret}/versions/{secret_version}");
/// <summary>Creates a <see cref="SecretVersionName"/> 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="SecretVersionName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static SecretVersionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SecretVersionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SecretVersionName"/> with the pattern
/// <c>projects/{project}/secrets/{secret}/versions/{secret_version}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="secretId">The <c>Secret</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="secretVersionId">The <c>SecretVersion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SecretVersionName"/> constructed from the provided ids.</returns>
public static SecretVersionName FromProjectSecretSecretVersion(string projectId, string secretId, string secretVersionId) =>
new SecretVersionName(ResourceNameType.ProjectSecretSecretVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), secretId: gax::GaxPreconditions.CheckNotNullOrEmpty(secretId, nameof(secretId)), secretVersionId: gax::GaxPreconditions.CheckNotNullOrEmpty(secretVersionId, nameof(secretVersionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecretVersionName"/> with pattern
/// <c>projects/{project}/secrets/{secret}/versions/{secret_version}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="secretId">The <c>Secret</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="secretVersionId">The <c>SecretVersion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecretVersionName"/> with pattern
/// <c>projects/{project}/secrets/{secret}/versions/{secret_version}</c>.
/// </returns>
public static string Format(string projectId, string secretId, string secretVersionId) =>
FormatProjectSecretSecretVersion(projectId, secretId, secretVersionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecretVersionName"/> with pattern
/// <c>projects/{project}/secrets/{secret}/versions/{secret_version}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="secretId">The <c>Secret</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="secretVersionId">The <c>SecretVersion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecretVersionName"/> with pattern
/// <c>projects/{project}/secrets/{secret}/versions/{secret_version}</c>.
/// </returns>
public static string FormatProjectSecretSecretVersion(string projectId, string secretId, string secretVersionId) =>
s_projectSecretSecretVersion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(secretId, nameof(secretId)), gax::GaxPreconditions.CheckNotNullOrEmpty(secretVersionId, nameof(secretVersionId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="SecretVersionName"/> 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}/secrets/{secret}/versions/{secret_version}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="secretVersionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SecretVersionName"/> if successful.</returns>
public static SecretVersionName Parse(string secretVersionName) => Parse(secretVersionName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SecretVersionName"/> 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}/secrets/{secret}/versions/{secret_version}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="secretVersionName">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="SecretVersionName"/> if successful.</returns>
public static SecretVersionName Parse(string secretVersionName, bool allowUnparsed) =>
TryParse(secretVersionName, allowUnparsed, out SecretVersionName 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="SecretVersionName"/> 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}/secrets/{secret}/versions/{secret_version}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="secretVersionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SecretVersionName"/>, 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 secretVersionName, out SecretVersionName result) =>
TryParse(secretVersionName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SecretVersionName"/> 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}/secrets/{secret}/versions/{secret_version}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="secretVersionName">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="SecretVersionName"/>, 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 secretVersionName, bool allowUnparsed, out SecretVersionName result)
{
gax::GaxPreconditions.CheckNotNull(secretVersionName, nameof(secretVersionName));
gax::TemplatedResourceName resourceName;
if (s_projectSecretSecretVersion.TryParseName(secretVersionName, out resourceName))
{
result = FromProjectSecretSecretVersion(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(secretVersionName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SecretVersionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string secretId = null, string secretVersionId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ProjectId = projectId;
SecretId = secretId;
SecretVersionId = secretVersionId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SecretVersionName"/> class from the component parts of pattern
/// <c>projects/{project}/secrets/{secret}/versions/{secret_version}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="secretId">The <c>Secret</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="secretVersionId">The <c>SecretVersion</c> ID. Must not be <c>null</c> or empty.</param>
public SecretVersionName(string projectId, string secretId, string secretVersionId) : this(ResourceNameType.ProjectSecretSecretVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), secretId: gax::GaxPreconditions.CheckNotNullOrEmpty(secretId, nameof(secretId)), secretVersionId: gax::GaxPreconditions.CheckNotNullOrEmpty(secretVersionId, nameof(secretVersionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Secret</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string SecretId { get; }
/// <summary>
/// The <c>SecretVersion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string SecretVersionId { 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.ProjectSecretSecretVersion: return s_projectSecretSecretVersion.Expand(ProjectId, SecretId, SecretVersionId);
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 SecretVersionName);
/// <inheritdoc/>
public bool Equals(SecretVersionName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SecretVersionName a, SecretVersionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SecretVersionName a, SecretVersionName b) => !(a == b);
}
/// <summary>Resource name for the <c>Topic</c> resource.</summary>
public sealed partial class TopicName : gax::IResourceName, sys::IEquatable<TopicName>
{
/// <summary>The possible contents of <see cref="TopicName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/topics/{topic}</c>.</summary>
ProjectTopic = 1,
}
private static gax::PathTemplate s_projectTopic = new gax::PathTemplate("projects/{project}/topics/{topic}");
/// <summary>Creates a <see cref="TopicName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="TopicName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static TopicName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new TopicName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="TopicName"/> with the pattern <c>projects/{project}/topics/{topic}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="TopicName"/> constructed from the provided ids.</returns>
public static TopicName FromProjectTopic(string projectId, string topicId) =>
new TopicName(ResourceNameType.ProjectTopic, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), topicId: gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TopicName"/> with pattern
/// <c>projects/{project}/topics/{topic}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TopicName"/> with pattern <c>projects/{project}/topics/{topic}</c>
/// .
/// </returns>
public static string Format(string projectId, string topicId) => FormatProjectTopic(projectId, topicId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TopicName"/> with pattern
/// <c>projects/{project}/topics/{topic}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TopicName"/> with pattern <c>projects/{project}/topics/{topic}</c>
/// .
/// </returns>
public static string FormatProjectTopic(string projectId, string topicId) =>
s_projectTopic.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId)));
/// <summary>Parses the given resource name string into a new <see cref="TopicName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>projects/{project}/topics/{topic}</c></description></item></list>
/// </remarks>
/// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="TopicName"/> if successful.</returns>
public static TopicName Parse(string topicName) => Parse(topicName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="TopicName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>projects/{project}/topics/{topic}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="TopicName"/> if successful.</returns>
public static TopicName Parse(string topicName, bool allowUnparsed) =>
TryParse(topicName, allowUnparsed, out TopicName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TopicName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>projects/{project}/topics/{topic}</c></description></item></list>
/// </remarks>
/// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TopicName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string topicName, out TopicName result) => TryParse(topicName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TopicName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>projects/{project}/topics/{topic}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TopicName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string topicName, bool allowUnparsed, out TopicName result)
{
gax::GaxPreconditions.CheckNotNull(topicName, nameof(topicName));
gax::TemplatedResourceName resourceName;
if (s_projectTopic.TryParseName(topicName, out resourceName))
{
result = FromProjectTopic(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(topicName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private TopicName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string topicId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ProjectId = projectId;
TopicId = topicId;
}
/// <summary>
/// Constructs a new instance of a <see cref="TopicName"/> class from the component parts of pattern
/// <c>projects/{project}/topics/{topic}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param>
public TopicName(string projectId, string topicId) : this(ResourceNameType.ProjectTopic, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), topicId: gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Topic</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TopicId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectTopic: return s_projectTopic.Expand(ProjectId, TopicId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as TopicName);
/// <inheritdoc/>
public bool Equals(TopicName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(TopicName a, TopicName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(TopicName a, TopicName b) => !(a == b);
}
public partial class Secret
{
/// <summary>
/// <see cref="gcsv::SecretName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::SecretName SecretName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::SecretName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class SecretVersion
{
/// <summary>
/// <see cref="gcsv::SecretVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::SecretVersionName SecretVersionName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::SecretVersionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Topic
{
/// <summary>
/// <see cref="gcsv::TopicName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::TopicName TopicName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::TopicName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// 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.
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.Contracts;
using System.Linq;
namespace UserFeedback
{
namespace Peli
{
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestClass]
public class UnitTest1
{
public class Bar
{
public Bar(int i)
{
this.ID = i;
}
public int ID { get; set; }
}
[ContractClass(typeof(CFoo))]
public interface IFoo
{
Bar GetValue(int i);
void TestException(Bar b, int i);
}
[ContractClassFor(typeof(IFoo))]
class CFoo : IFoo
{
Bar IFoo.GetValue(int i)
{
Contract.Requires(i >= 0, "peli1");
Contract.Requires(i < 10);
Contract.Ensures(
Contract.Result<Bar>() == null ||
Contract.Result<Bar>().ID == 0, "peli2");
return null;
}
void IFoo.TestException(Bar b, int i)
{
Contract.EnsuresOnThrow<IndexOutOfRangeException>(b.ID >= 0);
Contract.EnsuresOnThrow<ArgumentException>(b.ID == 0, "Peli3");
}
}
public class Foo : IFoo
{
int x;
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(x > 0);
Contract.Invariant(x < 10, "upper bound");
}
public Foo()
{
x = 1;
}
public Foo(int init)
{
x = init;
}
public Bar GetValue(int i)
{
if (i == 1) { return new Bar(1); }
return new Bar(0);
}
public void TestException(Bar b, int i)
{
b.ID = i;
if (i == -1) throw new IndexOutOfRangeException();
if (i == 1) throw new ArgumentException();
if (i == 0) throw new ArgumentException();
}
}
[TestMethod]
public void TestProperlyRewrittenResult()
{
new Foo().GetValue(0);
}
[TestMethod]
public void TestInvariantStrings1()
{
new Foo(2);
}
[TestMethod]
public void TestInvariantStrings2()
{
try
{
new Foo(0);
throw new Exception();
}
catch (TestRewriterMethods.InvariantException i)
{
Assert.AreEqual("x > 0", i.Condition);
Assert.AreEqual(null, i.User);
}
}
[TestMethod]
public void TestInvariantStrings3()
{
try
{
new Foo(10);
throw new Exception();
}
catch (TestRewriterMethods.InvariantException i)
{
Assert.AreEqual("x < 10", i.Condition);
Assert.AreEqual("upper bound", i.User);
}
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void TestOnThrowPositive()
{
Bar b = new Bar(0);
new Foo().TestException(b, 0);
}
[TestMethod]
public void TestOnThrowNegative1()
{
Bar b = new Bar(0);
try
{
new Foo().TestException(b, 1);
throw new Exception();
}
catch (TestRewriterMethods.PostconditionOnThrowException p)
{
Assert.AreEqual("b.ID == 0", p.Condition);
Assert.AreEqual("Peli3", p.User);
}
}
[TestMethod]
public void TestOnThrowNegative2()
{
Bar b = new Bar(0);
try
{
new Foo().TestException(b, -1);
throw new Exception();
}
catch (TestRewriterMethods.PostconditionOnThrowException p)
{
Assert.AreEqual("b.ID >= 0", p.Condition);
Assert.AreEqual(null, p.User);
}
}
[TestMethod]
public void TestRequiresConditionStringAndUserString()
{
try
{
new Foo().GetValue(-1);
throw new Exception();
}
catch (TestRewriterMethods.PreconditionException e)
{
if (e.Condition != "i >= 0") throw new Exception();
if (e.User != "peli1") throw new Exception();
return;
}
}
[TestMethod]
public void TestRequiresConditionStringOnly()
{
try
{
new Foo().GetValue(10);
throw new Exception();
}
catch (TestRewriterMethods.PreconditionException e)
{
if (e.Condition != "i < 10") throw new Exception();
if (e.User != null) throw new Exception();
return;
}
}
[TestMethod]
public void TestEnsuresConditionStringAndUserString()
{
try
{
new Foo().GetValue(1);
}
catch (TestRewriterMethods.PostconditionException e)
{
Assert.AreEqual("Contract.Result<Bar>() == null || Contract.Result<Bar>().ID == 0", e.Condition);
Assert.AreEqual("peli2", e.User);
return;
}
}
}
public static class StringExtensions
{
public static string TrimSuffix(string source, string suffix)
{
Contract.Requires(source != null);
Contract.Requires(!String.IsNullOrEmpty(suffix));
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(!Contract.Result<string>().EndsWith(suffix));
#region Body
var result = source;
while (result.EndsWith(suffix))
{
var oldLength = result.Length;
Contract.Assert(result.Length >= suffix.Length);
Contract.Assert(suffix.Length > 0);
var remainder = result.Length - suffix.Length;
Contract.Assert(remainder < result.Length);
result = result.Substring(0, remainder);
Contract.Assert(result.Length < oldLength);
}
return result;
#endregion
}
}
}
namespace WinSharp
{
using System.Linq;
class MyDict<TKey, TValue> : IDictionary<TKey, TValue>
{
Dictionary<TKey, TValue> innerDictionary = new Dictionary<TKey, TValue>();
public bool ContainsKey(TKey key)
{
TValue local;
return this.TryGetValue(key, out local);
}
public bool TryGetValue(TKey key, out TValue value)
{
return this.innerDictionary.TryGetValue(key, out value);
}
#region IDictionary<TKey,TValue> Members
public void Add(TKey key, TValue value)
{
throw new NotImplementedException();
}
public ICollection<TKey> Keys
{
get { throw new NotImplementedException(); }
}
public bool Remove(TKey key)
{
throw new NotImplementedException();
}
public ICollection<TValue> Values
{
get { throw new NotImplementedException(); }
}
public TValue this[TKey key]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
#region ICollection<KeyValuePair<TKey,TValue>> Members
public void Add(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public int Count
{
get { throw new NotImplementedException(); }
}
public bool IsReadOnly
{
get { throw new NotImplementedException(); }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable<KeyValuePair<TKey,TValue>> Members
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
public class ExplicitlyRecursive
{
[Pure]
public static bool Odd(int x)
{
Contract.Ensures(Contract.Result<bool>() == !Even(x));
return Math.Abs(x) % 2 == 1;
}
[Pure]
public static bool Even(int x)
{
Contract.Ensures(Contract.Result<bool>() == !Odd(x));
return Math.Abs(x) % 2 == 0;
}
[Pure]
public static int SubOdd(int x)
{
Contract.Requires(SubEven(x - 1) == 0);
if (x <= 0) return 0;
if (Odd(x)) return SubEven(x - 1);
return 0;
}
[Pure]
public static int SubEven(int x)
{
Contract.Requires(SubOdd(x - 1) == 0);
if (x <= 0) return 0;
if (Even(x)) return SubOdd(x - 1);
return 0;
}
[Pure]
public static bool ThrowOnOdd(int x)
{
Contract.EnsuresOnThrow<ArgumentException>(Odd(x) && !ThrowOnEven(x));
Contract.Ensures(!ThrowOnEven(x + 1));
if (Odd(x)) throw new ArgumentException();
return false;
}
[Pure]
public static bool ThrowOnEven(int x)
{
Contract.EnsuresOnThrow<ArgumentException>(Even(x) && !ThrowOnOdd(x));
Contract.Ensures(!ThrowOnOdd(x + 1));
if (Even(x)) throw new ArgumentException();
return false;
}
}
[TestClass]
public class RecursionChecks
{
[TestMethod]
public void RecursionTest1()
{
var mydict = new MyDict<string, int>();
var result = mydict.ContainsKey("foo");
Assert.IsFalse(result);
}
[TestMethod]
public void RecursionTest2()
{
var result = ExplicitlyRecursive.Odd(5);
Assert.IsTrue(result);
}
[TestMethod]
public void RecursionTest3()
{
var result = ExplicitlyRecursive.Odd(6);
Assert.IsFalse(result);
}
[TestMethod]
public void RecursionTest4()
{
var result = ExplicitlyRecursive.Even(7);
Assert.IsFalse(result);
}
[TestMethod]
public void RecursionTest5()
{
var result = ExplicitlyRecursive.Even(8);
Assert.IsTrue(result);
}
[TestMethod]
public void RecursionTest6()
{
var result = ExplicitlyRecursive.SubEven(8);
Assert.AreEqual(0, result);
}
[TestMethod]
public void RecursionTest7()
{
var result = ExplicitlyRecursive.SubEven(5);
Assert.AreEqual(0, result);
}
[TestMethod]
public void RecursionTest8()
{
var result = ExplicitlyRecursive.SubOdd(8);
Assert.AreEqual(0, result);
}
[TestMethod]
public void RecursionTest9()
{
var result = ExplicitlyRecursive.SubOdd(5);
Assert.AreEqual(0, result);
}
[TestMethod]
public void RecursionTest10()
{
var result = ExplicitlyRecursive.ThrowOnEven(5);
Assert.IsFalse(result);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void RecursionTest11()
{
var result = ExplicitlyRecursive.ThrowOnEven(4);
Assert.IsFalse(true);
}
[TestMethod]
public void RecursionTest12()
{
var result = ExplicitlyRecursive.ThrowOnOdd(4);
Assert.IsFalse(result);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void RecursionTest13()
{
var result = ExplicitlyRecursive.ThrowOnOdd(3);
Assert.IsFalse(true);
}
}
public class Program
{
public static void Main2(string[] args)
{
IList<string> items = new Foo().Items;
}
}
public sealed class Foo
: IFoo
{
private readonly IList<string> items;
public IList<string> Items
{
get
{
return this.items;
}
}
public Foo()
{
this.items = new List<string>();
}
public bool ContainsItem(string s)
{
return this.items.Contains(s);
}
}
[ContractClass(typeof(IFooContract))]
public interface IFoo
{
IList<string> Items
{
get;
}
bool ContainsItem(string s);
}
[ContractClassFor(typeof(IFoo))]
public sealed class IFooContract
: IFoo
{
private IFooContract()
{
}
IList<string> IFoo.Items
{
get
{
Contract.Ensures(Contract.Result<IList<string>>() != null);
Contract.Ensures(Contract.Result<IList<string>>().All(s => ((IFoo)this).ContainsItem(s)));
throw new Exception();
}
}
bool IFoo.ContainsItem(string s)
{
Contract.Ensures(Contract.Result<bool>() == ((IFoo)this).Items.Contains(s));
throw new Exception();
}
}
}
namespace Multani
{
[TestClass]
public class MultaniTestClass1
{
[TestMethod]
public void PositiveMultani1()
{
double[] initialValues = new[] { 1.0, 2.0, 3.0 };
double[] stDevs = new[] { 0.1, 0.2, 0.3 };
double[] drifts = new[] { 0.1, 0.1, 0.1 };
double[,] correlations = new double[3,3] { {0.1,0.1,0.1}, {0.1,0.1,0.1}, {0.1,0.1,0.1} };
int randomSeed = 44;
var c = new CorrelatedGeometricBrownianMotionFuelPriceSimulator(initialValues, stDevs, drifts, correlations, randomSeed);
}
[TestMethod]
[ExpectedException(typeof(TestRewriterMethods.PreconditionException))]
public void NegativeMultani1()
{
double[] initialValues = null;
double[] stDevs = new[] { 0.1, -0.2, 0.3 };
double[] drifts = null;
double[,] correlations = null;
int randomSeed = 44;
var c = new CorrelatedGeometricBrownianMotionFuelPriceSimulator(initialValues, stDevs, drifts, correlations, randomSeed);
}
}
public class CorrelatedGeometricBrownianMotionFuelPriceSimulator
{
public CorrelatedGeometricBrownianMotionFuelPriceSimulator(double[] initialValues, double[] stDevs, double[] drifts, double[,] correlations, int randomSeed)
{
Contract.Requires(Contract.ForAll(0, stDevs.Length, index => stDevs[index] >= 0));
}
}
}
namespace Somebody
{
public static class ContractedLINQMethods
{
#region GroupBy with posconditions
//The following code shows how to put some posconditions to GroupBy method
public static IEnumerable<IGrouping<K, T>> GroupBy<T, K>(this IEnumerable<T> source, Func<T, K> selector)
{
//This poscondition produces an unexpected error during injection of the code in the assembly (see attached image)
Contract.Ensures(Contract.ForAll<T>(source, (x => source != null && Contract.Result<IEnumerable<IGrouping<K, T>>>().Any(y => y.Contains(x)))),
"Ensures that each item from the source belongs to some group");
//When changing the above poscondition to the following one, then there is no error
//Contract.Ensures(Contract.ForAll(source, (x => Enumerable.GroupBy(source, selector).Any(y => y.Contains(x)))),
// "Ensures that each item from the source belongs to some group");
//...Others GroupBy posconditions
//GroupBy implementation
return Enumerable.GroupBy(source, selector);
}
#endregion
#region ...Other query methods
//...
#endregion
}
[TestClass]
public class TestResourceStringUserMessage
{
public static string Message2 = "This is message2";
public static string Message3 { get { return "This is message3"; } }
public void RequiresWithInternalResourceMessage(string s)
{
Contract.Requires(s != null, Tests.Properties.Resources.UserMessage1);
}
public void RequiresWithPublicFieldMessage(string s)
{
Contract.Requires(s != null, Message2);
}
public void RequiresWithPublicGetterMessage(string s)
{
Contract.Requires(s != null, Message3);
}
[TestMethod]
public void PositiveTestUserMessages()
{
RequiresWithInternalResourceMessage("hello");
RequiresWithPublicFieldMessage("hello");
RequiresWithPublicGetterMessage("hello");
}
[TestMethod]
public void NegativeTestInternalUserMessageString()
{
try
{
RequiresWithInternalResourceMessage(null);
throw new Exception();
}
catch (TestRewriterMethods.PreconditionException p)
{
// resource not as visible as the contract method
Assert.AreEqual(null, p.User);
}
}
[TestMethod]
public void NegativeTestPublicFieldUserMessageString()
{
try
{
RequiresWithPublicFieldMessage(null);
throw new Exception();
}
catch (TestRewriterMethods.PreconditionException p)
{
// resource not as visible as the contract method
Assert.AreEqual(Message2, p.User);
}
}
[TestMethod]
public void NegativeTestPublicGetterUserMessageString()
{
try
{
RequiresWithPublicGetterMessage(null);
throw new Exception();
}
catch (TestRewriterMethods.PreconditionException p)
{
// resource not as visible as the contract method
Assert.AreEqual(Message3, p.User);
}
}
}
}
namespace PDC
{
public class Invariants
{
public int Age { get; set; }
string name;
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(Age > 0);
Contract.Invariant(name != null);
}
public Invariants(string name, int age)
{
this.Age = age;
this.name = name;
}
}
public class Invariants<T> where T:class
{
int age;
public T Name { get; set; }
public int X { get; set; }
public int Y { get; set; }
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(Name != null);
Contract.Invariant(age > 0);
Contract.Invariant(X > Y);
}
public Invariants(T name, int age, int x, int y)
{
this.Name = name;
this.age = age;
this.Y = y;
this.X = x;
}
}
public interface IValid
{
bool IsValid { get; }
}
public class TrickyAutoPropInvariants<T> where T:IValid
{
public T Value { get; set; }
public int Age { get; set; }
public bool Flag { get; set; }
public TrickyAutoPropInvariants(T value, int age, bool flag)
{
this.Value = value;
this.Age = age;
this.Flag = flag;
}
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(Flag ? Age > 0 : Age == 0 && Value.IsValid);
}
public void Change(bool flag, int age)
{
this.Flag = flag;
this.Age = age;
}
public void LeaveObjectInconsistent()
{
throw new ApplicationException();
}
public void LeaveObjectConsistent()
{
try
{
LeaveObjectInconsistent();
}
catch (ApplicationException)
{
}
}
public void LeaveObjectConsistentViaAdvertisedException()
{
Contract.EnsuresOnThrow<ApplicationException>(true);
throw new ApplicationException();
}
}
class Valid : IValid {
bool valid;
public Valid(bool valid)
{
this.valid = valid;
}
public bool IsValid { get { return this.valid; } }
}
[TestClass]
public class DontCheckInvariantsDuringConstructors
{
[TestMethod]
public void PositiveTrickyAutoProp1()
{
var tricky = new TrickyAutoPropInvariants<Valid>(new Valid(true), 0, false);
tricky.Change(true, 5);
}
[TestMethod]
public void PositiveTrickyAutoProp2()
{
var tricky = new TrickyAutoPropInvariants<Valid>(new Valid(true), 0, false);
try
{
tricky.LeaveObjectInconsistent();
}
catch (ApplicationException) { }
// now we can violate invariant further without being punished
tricky.Change(false, 5);
}
[TestMethod]
public void PositiveTrickyAutoProp3()
{
var tricky = new TrickyAutoPropInvariants<Valid>(new Valid(true), 0, false);
try
{
tricky.LeaveObjectInconsistent();
}
catch (ApplicationException) { }
// now we can violate invariant further without being punished
tricky.Age = 5;
}
[TestMethod]
public void NegativeTrickyAutoProp1()
{
try
{
var tricky = new TrickyAutoPropInvariants<Valid>(new Valid(true), 0, false);
tricky.Change(false, 5);
throw new Exception();
}
catch (TestRewriterMethods.InvariantException i)
{
Assert.AreEqual("Flag ? Age > 0 : Age == 0 && Value.IsValid", i.Condition);
}
}
[TestMethod]
public void NegativeTrickyAutoProp2()
{
try
{
var tricky = new TrickyAutoPropInvariants<Valid>(new Valid(true), 0, false);
tricky.Age = 5;
throw new Exception();
}
catch (TestRewriterMethods.PreconditionException i)
{
Assert.AreEqual("Flag ? Age > 0 : Age == 0 && Value.IsValid", i.Condition);
}
}
[TestMethod]
public void NegativeTrickyAutoProp3()
{
try
{
var tricky = new TrickyAutoPropInvariants<Valid>(new Valid(true), 0, false);
tricky.LeaveObjectConsistent();
tricky.Age = 5; // should fail precondition
throw new Exception();
}
catch (TestRewriterMethods.PreconditionException i)
{
Assert.AreEqual("Flag ? Age > 0 : Age == 0 && Value.IsValid", i.Condition);
}
}
[TestMethod]
public void NegativeTrickyAutoProp4()
{
try
{
var tricky = new TrickyAutoPropInvariants<Valid>(new Valid(true), 0, false);
try
{
tricky.LeaveObjectConsistentViaAdvertisedException();
}
catch (ApplicationException) { }
tricky.Age = 5; // should fail precondition
throw new Exception();
}
catch (TestRewriterMethods.PreconditionException i)
{
Assert.AreEqual("Flag ? Age > 0 : Age == 0 && Value.IsValid", i.Condition);
}
}
[TestMethod]
public void PositiveInvariantOffDuringConstruction1()
{
var p = new Invariants("Joe", 42);
}
[TestMethod]
public void NegativeInvariantOffDuringConstruction1()
{
try
{
var p = new Invariants(null, 1);
throw new Exception();
}
catch (TestRewriterMethods.InvariantException i)
{
Assert.AreEqual("name != null", i.Condition);
}
}
[TestMethod]
public void PositiveInvariantOffDuringConstruction2()
{
var p = new Invariants<string>("Joe", 42, 2, 1);
}
[TestMethod]
public void NegativeInvariantOffDuringConstruction2()
{
try
{
var p = new Invariants<string>("Joe", 0, 1, 2);
throw new Exception();
}
catch (TestRewriterMethods.InvariantException i)
{
Assert.AreEqual("age > 0", i.Condition);
}
}
[TestMethod]
public void NegativeInvariantOfAutoPropIntoRequires1()
{
try
{
var p = new Invariants<string>(null, 0, 1, 2);
throw new Exception();
}
catch (TestRewriterMethods.InvariantException p)
{
Assert.AreEqual("Name != null", p.Condition);
}
}
[TestMethod]
public void NegativeInvariantOfAutoPropIntoRequires2()
{
try
{
var p = new Invariants<string>("Joe", 0, 1, 2);
throw new Exception();
}
catch (TestRewriterMethods.InvariantException p)
{
Assert.AreEqual("age > 0", p.Condition);
}
}
[TestMethod]
public void NegativeInvariantOfAutoPropIntoRequires3()
{
try
{
var p = new Invariants<string>("Joe", 1, 1, 2);
throw new Exception();
}
catch (TestRewriterMethods.InvariantException p)
{
Assert.AreEqual("X > Y", p.Condition);
}
}
[TestMethod]
public void NegativeInvariantOfAutoPropIntoRequires4()
{
try
{
var p = new Invariants<string>("Joe", 1, 2, 1);
p.Name = null;
throw new Exception();
}
catch (TestRewriterMethods.PreconditionException p)
{
Assert.AreEqual("Name != null", p.Condition);
}
}
[TestMethod]
public void NegativeInvariantOfAutoPropIntoRequires5()
{
try
{
var p = new Invariants<string>("Joe", 1, 2, 1);
p.X = 1;
throw new Exception();
}
catch (TestRewriterMethods.PreconditionException p)
{
Assert.AreEqual("X > Y", p.Condition);
}
}
[TestMethod]
public void NegativeInvariantOfAutoPropIntoRequires6()
{
try
{
var p = new Invariants<string>("Joe", 1, 2, 1);
p.Y = 2;
throw new Exception();
}
catch (TestRewriterMethods.PreconditionException p)
{
Assert.AreEqual("X > Y", p.Condition);
}
}
}
}
namespace Arnott {
[TestClass]
public class C {
public void M(object x) {
Contract.Requires<ArgumentNullException>(x != null || x != null, "x");
}
[TestMethod]
public void PositiveRequiresWithException() {
M(this);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NegativeRequiresWithException() {
M(null);
}
public void OkayOrder(int[] args) {
Contract.Requires<ArgumentOutOfRangeException>(args.Length > 10, "args");
if (args == null) throw new Exception();
Contract.EndContractBlock();
}
public void BadOrder(int[] args) {
if (args == null) throw new Exception();
Contract.Requires<ArgumentOutOfRangeException>(args.Length > 10, "args");
Contract.EndContractBlock();
}
[TestMethod]
public void WorksCorrectlyWithThisOrder() {
OkayOrder(new int[20]);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void WorksInCorrectlyWithThisOrder() {
BadOrder(new int[10]);
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// Describes an Auto Scaling group.
/// </summary>
public partial class AutoScalingGroup
{
private string _autoScalingGroupARN;
private string _autoScalingGroupName;
private List<string> _availabilityZones = new List<string>();
private DateTime? _createdTime;
private int? _defaultCooldown;
private int? _desiredCapacity;
private List<EnabledMetric> _enabledMetrics = new List<EnabledMetric>();
private int? _healthCheckGracePeriod;
private string _healthCheckType;
private List<Instance> _instances = new List<Instance>();
private string _launchConfigurationName;
private List<string> _loadBalancerNames = new List<string>();
private int? _maxSize;
private int? _minSize;
private string _placementGroup;
private string _status;
private List<SuspendedProcess> _suspendedProcesses = new List<SuspendedProcess>();
private List<TagDescription> _tags = new List<TagDescription>();
private List<string> _terminationPolicies = new List<string>();
private string _vpcZoneIdentifier;
/// <summary>
/// Gets and sets the property AutoScalingGroupARN.
/// <para>
/// The Amazon Resource Name (ARN) of the group.
/// </para>
/// </summary>
public string AutoScalingGroupARN
{
get { return this._autoScalingGroupARN; }
set { this._autoScalingGroupARN = value; }
}
// Check to see if AutoScalingGroupARN property is set
internal bool IsSetAutoScalingGroupARN()
{
return this._autoScalingGroupARN != null;
}
/// <summary>
/// Gets and sets the property AutoScalingGroupName.
/// <para>
/// The name of the group.
/// </para>
/// </summary>
public string AutoScalingGroupName
{
get { return this._autoScalingGroupName; }
set { this._autoScalingGroupName = value; }
}
// Check to see if AutoScalingGroupName property is set
internal bool IsSetAutoScalingGroupName()
{
return this._autoScalingGroupName != null;
}
/// <summary>
/// Gets and sets the property AvailabilityZones.
/// <para>
/// One or more Availability Zones for the group.
/// </para>
/// </summary>
public List<string> AvailabilityZones
{
get { return this._availabilityZones; }
set { this._availabilityZones = value; }
}
// Check to see if AvailabilityZones property is set
internal bool IsSetAvailabilityZones()
{
return this._availabilityZones != null && this._availabilityZones.Count > 0;
}
/// <summary>
/// Gets and sets the property CreatedTime.
/// <para>
/// The date and time the group was created.
/// </para>
/// </summary>
public DateTime CreatedTime
{
get { return this._createdTime.GetValueOrDefault(); }
set { this._createdTime = value; }
}
// Check to see if CreatedTime property is set
internal bool IsSetCreatedTime()
{
return this._createdTime.HasValue;
}
/// <summary>
/// Gets and sets the property DefaultCooldown.
/// <para>
/// The number of seconds after a scaling activity completes before any further scaling
/// activities can start.
/// </para>
/// </summary>
public int DefaultCooldown
{
get { return this._defaultCooldown.GetValueOrDefault(); }
set { this._defaultCooldown = value; }
}
// Check to see if DefaultCooldown property is set
internal bool IsSetDefaultCooldown()
{
return this._defaultCooldown.HasValue;
}
/// <summary>
/// Gets and sets the property DesiredCapacity.
/// <para>
/// The size of the group.
/// </para>
/// </summary>
public int DesiredCapacity
{
get { return this._desiredCapacity.GetValueOrDefault(); }
set { this._desiredCapacity = value; }
}
// Check to see if DesiredCapacity property is set
internal bool IsSetDesiredCapacity()
{
return this._desiredCapacity.HasValue;
}
/// <summary>
/// Gets and sets the property EnabledMetrics.
/// <para>
/// The metrics enabled for this Auto Scaling group.
/// </para>
/// </summary>
public List<EnabledMetric> EnabledMetrics
{
get { return this._enabledMetrics; }
set { this._enabledMetrics = value; }
}
// Check to see if EnabledMetrics property is set
internal bool IsSetEnabledMetrics()
{
return this._enabledMetrics != null && this._enabledMetrics.Count > 0;
}
/// <summary>
/// Gets and sets the property HealthCheckGracePeriod.
/// <para>
/// The amount of time that Auto Scaling waits before checking an instance's health status.
/// The grace period begins when an instance comes into service.
/// </para>
/// </summary>
public int HealthCheckGracePeriod
{
get { return this._healthCheckGracePeriod.GetValueOrDefault(); }
set { this._healthCheckGracePeriod = value; }
}
// Check to see if HealthCheckGracePeriod property is set
internal bool IsSetHealthCheckGracePeriod()
{
return this._healthCheckGracePeriod.HasValue;
}
/// <summary>
/// Gets and sets the property HealthCheckType.
/// <para>
/// The service of interest for the health status check, which can be either <code>EC2</code>
/// for Amazon EC2 or <code>ELB</code> for Elastic Load Balancing.
/// </para>
/// </summary>
public string HealthCheckType
{
get { return this._healthCheckType; }
set { this._healthCheckType = value; }
}
// Check to see if HealthCheckType property is set
internal bool IsSetHealthCheckType()
{
return this._healthCheckType != null;
}
/// <summary>
/// Gets and sets the property Instances.
/// <para>
/// The EC2 instances associated with the group.
/// </para>
/// </summary>
public List<Instance> Instances
{
get { return this._instances; }
set { this._instances = value; }
}
// Check to see if Instances property is set
internal bool IsSetInstances()
{
return this._instances != null && this._instances.Count > 0;
}
/// <summary>
/// Gets and sets the property LaunchConfigurationName.
/// <para>
/// The name of the associated launch configuration.
/// </para>
/// </summary>
public string LaunchConfigurationName
{
get { return this._launchConfigurationName; }
set { this._launchConfigurationName = value; }
}
// Check to see if LaunchConfigurationName property is set
internal bool IsSetLaunchConfigurationName()
{
return this._launchConfigurationName != null;
}
/// <summary>
/// Gets and sets the property LoadBalancerNames.
/// <para>
/// One or more load balancers associated with the group.
/// </para>
/// </summary>
public List<string> LoadBalancerNames
{
get { return this._loadBalancerNames; }
set { this._loadBalancerNames = value; }
}
// Check to see if LoadBalancerNames property is set
internal bool IsSetLoadBalancerNames()
{
return this._loadBalancerNames != null && this._loadBalancerNames.Count > 0;
}
/// <summary>
/// Gets and sets the property MaxSize.
/// <para>
/// The maximum size of the group.
/// </para>
/// </summary>
public int MaxSize
{
get { return this._maxSize.GetValueOrDefault(); }
set { this._maxSize = value; }
}
// Check to see if MaxSize property is set
internal bool IsSetMaxSize()
{
return this._maxSize.HasValue;
}
/// <summary>
/// Gets and sets the property MinSize.
/// <para>
/// The minimum size of the group.
/// </para>
/// </summary>
public int MinSize
{
get { return this._minSize.GetValueOrDefault(); }
set { this._minSize = value; }
}
// Check to see if MinSize property is set
internal bool IsSetMinSize()
{
return this._minSize.HasValue;
}
/// <summary>
/// Gets and sets the property PlacementGroup.
/// <para>
/// The name of the placement group into which you'll launch your instances, if any. For
/// more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html">Placement
/// Groups</a>.
/// </para>
/// </summary>
public string PlacementGroup
{
get { return this._placementGroup; }
set { this._placementGroup = value; }
}
// Check to see if PlacementGroup property is set
internal bool IsSetPlacementGroup()
{
return this._placementGroup != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The current state of the Auto Scaling group when a <a>DeleteAutoScalingGroup</a> action
/// is in progress.
/// </para>
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property SuspendedProcesses.
/// <para>
/// The suspended processes associated with the group.
/// </para>
/// </summary>
public List<SuspendedProcess> SuspendedProcesses
{
get { return this._suspendedProcesses; }
set { this._suspendedProcesses = value; }
}
// Check to see if SuspendedProcesses property is set
internal bool IsSetSuspendedProcesses()
{
return this._suspendedProcesses != null && this._suspendedProcesses.Count > 0;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// The tags for the Auto Scaling group.
/// </para>
/// </summary>
public List<TagDescription> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property TerminationPolicies.
/// <para>
/// The termination policies for this Auto Scaling group.
/// </para>
/// </summary>
public List<string> TerminationPolicies
{
get { return this._terminationPolicies; }
set { this._terminationPolicies = value; }
}
// Check to see if TerminationPolicies property is set
internal bool IsSetTerminationPolicies()
{
return this._terminationPolicies != null && this._terminationPolicies.Count > 0;
}
/// <summary>
/// Gets and sets the property VPCZoneIdentifier.
/// <para>
/// One or more subnet IDs, if applicable, separated by commas.
/// </para>
///
/// <para>
/// If you specify <code>VPCZoneIdentifier</code> and <code>AvailabilityZones</code>,
/// ensure that the Availability Zones of the subnets match the values for <code>AvailabilityZones</code>.
/// </para>
/// </summary>
public string VPCZoneIdentifier
{
get { return this._vpcZoneIdentifier; }
set { this._vpcZoneIdentifier = value; }
}
// Check to see if VPCZoneIdentifier property is set
internal bool IsSetVPCZoneIdentifier()
{
return this._vpcZoneIdentifier != null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DotVVM.Framework.Parser
{
public abstract class TokenizerBase<TToken, TTokenType> where TToken : TokenBase<TTokenType>, new()
{
public const char NullChar = '\0';
private IReader reader;
/// <summary>
/// Gets the type of the text token.
/// </summary>
protected abstract TTokenType TextTokenType { get; }
/// <summary>
/// Gets the type of the white space token.
/// </summary>
protected abstract TTokenType WhiteSpaceTokenType { get; }
/// <summary>
/// Gets or sets the current line number.
/// </summary>
protected int CurrentLine { get; private set; }
/// <summary>
/// Gets or sets the position on current line.
/// </summary>
protected int PositionOnLine { get; private set; }
/// <summary>
/// Gets the last token position.
/// </summary>
protected int LastTokenPosition { get; private set; }
/// <summary>
/// Gets the last token.
/// </summary>
protected TToken LastToken { get; private set; }
/// <summary>
/// Gets the distance since last token.
/// </summary>
protected int DistanceSinceLastToken
{
get { return reader.Position - LastTokenPosition; }
}
/// <summary>
/// Gets or sets the current token chars.
/// </summary>
protected StringBuilder CurrentTokenChars { get; private set; }
/// <summary>
/// Occurs when a token is found.
/// </summary>
public event Action<TToken> TokenFound;
/// <summary>
/// Gets the list of tokens.
/// </summary>
public List<TToken> Tokens { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="TokenizerBase"/> class.
/// </summary>
public TokenizerBase()
{
CurrentTokenChars = new StringBuilder();
Tokens = new List<TToken>();
}
/// <summary>
/// Tokenizes the input.
/// </summary>
public void Tokenize(IReader reader)
{
this.reader = reader;
try
{
CurrentLine = 1;
PositionOnLine = 0;
LastToken = null;
LastTokenPosition = 0;
Tokens.Clear();
CurrentTokenChars.Clear();
TokenizeCore();
}
finally
{
reader.Dispose();
}
}
/// <summary>
/// Tokenizes the core.
/// </summary>
protected abstract void TokenizeCore();
/// <summary>
/// Skips the whitespace.
/// </summary>
protected void SkipWhitespace(bool allowEndLine = true)
{
while (char.IsWhiteSpace(Peek()) && (allowEndLine || (Peek() != '\r' && Peek() != '\n')))
{
if (Read() == NullChar)
{
break;
}
}
if (DistanceSinceLastToken > 0)
{
CreateToken(WhiteSpaceTokenType);
}
}
/// <summary>
/// Skips the until new line or when it hits the specified stop chars.
/// When the new line is hit, the method automatically consumes it and creates WhiteSpace token.
/// When the stopchar is hit, it is not consumed.
/// </summary>
protected void ReadTextUntilNewLine(TTokenType tokenType, params char[] stopChars)
{
while (Peek() != '\r' && Peek() != '\n' && !stopChars.Contains(Peek()))
{
if (Read() == NullChar)
{
break;
}
}
if (DistanceSinceLastToken > 0)
{
CreateToken(tokenType);
}
if (Peek() == '\r')
{
// \r can be followed by \n which is still one new line
Read();
}
if (Peek() == '\n')
{
Read();
}
if (DistanceSinceLastToken > 0)
{
CreateToken(WhiteSpaceTokenType);
}
}
protected bool ReadTextUntil(TTokenType tokenType, string stopString, bool stopOnNewLine)
{
var startLine = CurrentLine;
var stopStringIndex = 0;
while (stopStringIndex != stopString.Length)
{
var ch = Read();
if (ch == NullChar)
{
return false;
}
else if (ch == stopString[stopStringIndex])
{
stopStringIndex++;
}
else
{
stopStringIndex = 0;
}
if (stopOnNewLine && startLine != CurrentLine)
{
return false;
}
}
CreateToken(tokenType, stopString.Length);
return true;
}
protected string ReadOneOf(params string[] strings)
{
int index = 0;
while (strings.Length > 0 && !strings.Any(s => s.Length <= index))
{
var ch = Peek();
strings = strings.Where(s => s[index] == ch).ToArray();
index++;
Read();
}
return strings.FirstOrDefault(s => s.Length == index);
}
/// <summary>
/// Creates the token.
/// </summary>
protected TToken CreateToken(TTokenType type, int charsFromEndToSkip = 0, Func<TToken, TokenError> errorProvider = null)
{
LastToken = new TToken()
{
LineNumber = CurrentLine,
ColumnNumber = PositionOnLine,
StartPosition = LastTokenPosition,
Length = DistanceSinceLastToken - charsFromEndToSkip,
Type = type,
Text = CurrentTokenChars.ToString().Substring(0, DistanceSinceLastToken - charsFromEndToSkip)
};
Tokens.Add(LastToken);
if (errorProvider != null)
{
LastToken.Error = errorProvider(LastToken);
}
CurrentTokenChars.Remove(0, LastToken.Length);
LastTokenPosition = reader.Position - charsFromEndToSkip;
OnTokenFound(LastToken);
return LastToken;
}
protected TokenError CreateTokenError()
{
return new NullTokenError<TToken, TTokenType>(this);
}
protected TokenError CreateTokenError(TToken lastToken, TTokenType firstTokenType, string errorMessage)
{
return new BeginWithLastTokenOfTypeTokenError<TToken, TTokenType>(errorMessage, this, lastToken, firstTokenType);
}
protected TokenError CreateTokenError(TToken token, string errorMessage)
{
return new SimpleTokenError<TToken, TTokenType>(errorMessage, this, token);
}
/// <summary>
/// Called when a token is found.
/// </summary>
protected virtual void OnTokenFound(TToken token)
{
var handler = TokenFound;
if (handler != null)
{
handler(token);
}
}
/// <summary>
/// Peeks the current char.
/// </summary>
protected char Peek()
{
return reader.Peek();
}
/// <summary>
/// Returns the current char and advances to the next one.
/// </summary>
protected char Read()
{
var ch = reader.Read();
if (ch != NullChar)
{
CurrentTokenChars.Append(ch);
if (ch == '\r' && Peek() != '\n')
{
CurrentLine++;
PositionOnLine = 0;
}
else if (ch == '\n')
{
CurrentLine++;
PositionOnLine = 0;
}
}
PositionOnLine++;
return ch;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// The implementation for the reduced product of intervals and symbolic weak upper bounds
// This has got the official name of "Pentagons"
// Those two options are really used to run the experiments in the Pentagons paper
// #define EXPENSIVE_JOIN
// #define CARTESIAN
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Research.AbstractDomains.Expressions;
using Microsoft.Research.DataStructures;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Research.CodeAnalysis;
using System.Linq;
namespace Microsoft.Research.AbstractDomains.Numerical
{
/// <summary>
/// The main class for intervals (of rationals) with symbolic upper bounds
/// </summary>
[ContractVerification(true)]
public class Pentagons<Variable, Expression>
: ReducedCartesianAbstractDomain<IIntervalAbstraction<Variable, Expression>, WeakUpperBounds<Variable, Expression>>,
INumericalAbstractDomain<Variable, Expression>
{
#region Invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(expManager != null);
}
#endregion
#region Statistics
static public string Statistics
{
get
{
#if TRACE_PERFORMANCE
string maxSizeforFunctionalDomain = MaxSizesAnalysisFrom(IntervalEnvironment<Variable, Expression>.MaxSizes);
return maxSizeforFunctionalDomain.ToString();
#else
return "Performance tracing is off";
#endif
}
}
private static string MaxSizesAnalysisFrom(IDictionary<int, int> iDictionary)
{
if (iDictionary == null)
return "";
int max = Int32.MinValue;
int sum = 0;
var occurrences = new Dictionary<int, int>();
foreach (int o in iDictionary.Keys)
{
if (iDictionary[o] > max)
{
max = iDictionary[o];
}
sum += iDictionary[o];
// Update the occurrences count
if (occurrences.ContainsKey(iDictionary[o]))
{
occurrences[iDictionary[o]]++;
}
else
{
occurrences[iDictionary[o]] = 1;
}
}
var averageSize = iDictionary.Count != 0 ? ((double)sum) / iDictionary.Count : Double.PositiveInfinity;
return "Max size : " + max + Environment.NewLine + "Average size: " + averageSize;
}
#endregion
#region Private state
private readonly ExpressionManagerWithEncoder<Variable, Expression> expManager;
#endregion
#region (private) Constructor
/// <summary>
/// Please note that the decoder MUST be already be set for the <code>left</code> and <code>right</code> abstract domains
/// </summary>
public Pentagons(
IIntervalAbstraction<Variable, Expression> left,
WeakUpperBounds<Variable, Expression> right,
ExpressionManagerWithEncoder<Variable, Expression> expManager)
: base(left, right)
{
Contract.Requires(left != null);
Contract.Requires(right != null);
Contract.Requires(expManager != null);
this.expManager = expManager;
}
#endregion
#region (protected) Getters
protected ExpressionManagerWithEncoder<Variable, Expression> ExpressionManager
{
get
{
Contract.Ensures(Contract.Result<ExpressionManagerWithEncoder<Variable, Expression>>() != null);
return expManager;
}
}
#endregion
#region Factories
[Pure]
override protected ReducedCartesianAbstractDomain<IIntervalAbstraction<Variable, Expression>, WeakUpperBounds<Variable, Expression>>
Factory(IIntervalAbstraction<Variable, Expression> left, WeakUpperBounds<Variable, Expression> right)
{
return this.FactoryOfPentagons(left, right);
}
[Pure]
private Pentagons<Variable, Expression> FactoryOfPentagons(
IIntervalAbstraction<Variable, Expression> left, WeakUpperBounds<Variable, Expression> right)
{
Contract.Requires(left != null);
Contract.Requires(right != null);
Contract.Ensures(Contract.Result<Pentagons<Variable, Expression>>() != null);
return new Pentagons<Variable, Expression>(left, right, expManager);
}
/// <summary>
/// This reduction considers the pairs (x, y) of intervals and add to the weak upper bounds all those such that x < y
/// </summary>
[Pure]
public override ReducedCartesianAbstractDomain<IIntervalAbstraction<Variable, Expression>, WeakUpperBounds<Variable, Expression>>
Reduce(IIntervalAbstraction<Variable, Expression> left, WeakUpperBounds<Variable, Expression> right)
{
return this.Factory(left, right);
}
#endregion
#region Implementation of the abstract methods
override public bool LessEqual(IAbstractDomain a)
{
bool result;
if (AbstractDomainsHelper.TryTrivialLessEqual(this, a, out result))
{
return result;
}
var r = a as Pentagons<Variable, Expression>;
Contract.Assume(r != null);
if (!this.Left.LessEqual(r.Left))
{
return false;
}
return this.Right.LessEqual(r.Right);
}
/// <summary>
/// This is a version of the join which causes a partial propagation of the information from Intervals to Symbolic upper bounds
/// </summary>
/// <param name="a">The other element</param>
sealed public override IAbstractDomain Join(IAbstractDomain a)
{
if (this.IsBottom)
return a;
if (a.IsBottom)
return this;
if (this.IsTop)
return this;
if (a.IsTop)
return a;
var r = a as Pentagons<Variable, Expression>;
Contract.Assume(r != null);
// These two lines have a weak notion of closure, which essentially avoids dropping "x < y" if it is implied by the intervals abstract domain
// It seems that it is as precise as the expensive join
var joinRightPart = this.Right.Join(r.Right, this.Left, r.Left);
var joinLeftPart = this.Left.Join(r.Left);
return this.Factory(joinLeftPart, joinRightPart);
}
/// <summary>
/// The pairwise widening
/// </summary>
public override IAbstractDomain Widening(IAbstractDomain prev)
{
if (this.IsBottom)
return prev;
if (prev.IsBottom)
return this;
var asIntWSUB = prev as Pentagons<Variable, Expression>;
Contract.Assume(asIntWSUB != null);
var widenLeft = this.Left.Widening(asIntWSUB.Left);
var widenRight = this.Right.Widening(asIntWSUB.Right);
return this.Factory(widenLeft, widenRight);
}
#endregion
#region INumericalAbstractDomain<Variable, Expression>Members
/// <summary>
/// Dispatch the assigment to the underlying abstract domains
/// </summary>
/// <param name="sourcesToTargets"></param>
public void AssignInParallel(Dictionary<Variable, FList<Variable>> sourcesToTargets, Converter<Variable, Expression> convert)
{
// NOTE NOTE that we first assign in the right (so to assign in the pre-state!!!) and then on the left
this.Right.AssignInParallel(sourcesToTargets, convert, this.Left);
this.Left.AssignInParallel(sourcesToTargets, convert);
}
/// <returns>
/// An interval that contains the upper bounds for <code>v</code>
/// </returns>
public DisInterval BoundsFor(Expression v)
{
return this.Left.BoundsFor(v);
}
public DisInterval BoundsFor(Variable v)
{
return this.Left.BoundsFor(v);
}
public List<Pair<Variable, Int32>> IntConstants
{
get
{
return this.Left.IntConstants;
}
}
public IEnumerable<Expression> LowerBoundsFor(Expression v, bool strict)
{
return this.Right.LowerBoundsFor(v, strict).Union(this.Left.LowerBoundsFor(v, strict));
}
public IEnumerable<Expression> UpperBoundsFor(Expression v, bool strict)
{
return this.Right.UpperBoundsFor(v, strict).Union(this.Left.UpperBoundsFor(v, strict));
}
public IEnumerable<Variable> EqualitiesFor(Variable v)
{
return this.Right.EqualitiesFor(v);
}
public IEnumerable<Expression> LowerBoundsFor(Variable v, bool strict)
{
return this.Right.LowerBoundsFor(v, strict).Union(this.Left.LowerBoundsFor(v, strict));
}
public IEnumerable<Expression> UpperBoundsFor(Variable v, bool strict)
{
return this.Right.UpperBoundsFor(v, strict).Union(this.Left.UpperBoundsFor(v, strict));
}
public FlatAbstractDomain<bool> CheckIfGreaterEqualThanZero(Expression exp)
{
return this.Left.CheckIfGreaterEqualThanZero(exp).Meet(Right.CheckIfGreaterEqualThanZero(exp));
}
public FlatAbstractDomain<bool> CheckIfLessThan(Expression e1, Expression e2)
{
var checkOnLeft = this.Left.CheckIfLessThan(e1, e2);
var checkOnRight = this.Right.CheckIfLessThan(e1, e2, this.Left);
return checkOnLeft.Meet(checkOnRight);
}
public FlatAbstractDomain<bool> CheckIfLessThanIncomplete(Expression e1, Expression e2)
{
return this.CheckIfLessThan(e1, e2);
}
public FlatAbstractDomain<bool> CheckIfLessThan_Un(Expression e1, Expression e2)
{
var checkOnLeft = this.Left.CheckIfLessThan_Un(e1, e2);
var checkOnRight = this.Right.CheckIfLessThan_Un(e1, e2);
return checkOnLeft.Meet(checkOnRight);
}
public FlatAbstractDomain<bool> CheckIfLessThan(Variable v1, Variable v2)
{
var checkOnLeft = this.Left.CheckIfLessThan(v1, v2);
var checkOnRight = this.Right.CheckIfLessThan(v1, v2);
return checkOnLeft.Meet(checkOnRight);
}
public FlatAbstractDomain<bool> CheckIfLessEqualThan(Expression e1, Expression e2)
{
var checkOnLeft = this.Left.CheckIfLessEqualThan(e1, e2);
var checkOnRight = this.Right.CheckIfLessEqualThan(e1, e2, this.Left);
return checkOnLeft.Meet(checkOnRight);
}
public FlatAbstractDomain<bool> CheckIfLessEqualThan_Un(Expression e1, Expression e2)
{
var checkOnLeft = this.Left.CheckIfLessEqualThan_Un(e1, e2);
var checkOnRight = this.Right.CheckIfLessEqualThan_Un(e1, e2);
return checkOnLeft.Meet(checkOnRight);
}
public FlatAbstractDomain<bool> CheckIfLessEqualThan(Variable v1, Variable v2)
{
var checkOnLeft = this.Left.CheckIfLessEqualThan(v1, v2);
var checkOnRight = this.Right.CheckIfLessEqualThan(v1, v2);
return checkOnLeft.Meet(checkOnRight);
}
public FlatAbstractDomain<bool> CheckIfEqual(Expression e1, Expression e2)
{
var c1 = CheckIfLessEqualThan(e1, e2);
var c2 = CheckIfLessEqualThan(e2, e1);
if (c1.IsNormal())
{
if (c2.IsNormal())
{
return new FlatAbstractDomain<bool>(c1.BoxedElement && c2.BoxedElement);
}
else
{
var lt = CheckIfLessThan(e1, e2);
if (lt.IsTrue()) // e1 < e2
{
return CheckOutcome.False;
}
else if (lt.IsFalse()) // e1 <= e2 & !(e1 < e2)
{
return CheckOutcome.True;
}
}
}
else if (c2.IsNormal())
{
var gt = CheckIfLessThan(e2, e1);
if (gt.IsTrue()) // e1 > e2
{
return CheckOutcome.False;
}
else if (gt.IsFalse()) // e1 >= e2 & !(e1 > e2)
{
return CheckOutcome.True;
}
}
return CheckOutcome.Top;
}
public FlatAbstractDomain<bool> CheckIfEqualIncomplete(Expression e1, Expression e2)
{
return this.CheckIfEqual(e1, e2);
}
public FlatAbstractDomain<bool> CheckIfNonZero(Expression e)
{
var checkOnLeft = this.Left.CheckIfNonZero(e);
var checkOnRight = this.Right.CheckIfNonZero(e);
return checkOnLeft.Meet(checkOnRight);
}
public Variable ToVariable(Expression exp)
{
return this.ExpressionManager.Decoder.UnderlyingVariable(exp);
}
#endregion
#region IPureExpressionAssignmentsWithForward<Expression> Members
public void AssumeInDisInterval(Variable x, DisInterval value)
{
this.Left.AssumeInDisInterval(x, value);
}
void IPureExpressionTest<Variable, Expression>.AssumeDomainSpecificFact(DomainSpecificFact fact)
{
this.AssumeDomainSpecificFact(fact);
}
public void Assign(Expression x, Expression exp)
{
if (x == null || exp == null)
return;
this.Assign(x, exp, TopNumericalDomain<Variable, Expression>.Singleton);
}
public void Assign(Expression x, Expression exp, INumericalAbstractDomainQuery<Variable, Expression> preState)
{
// Infer some x >= 0 invariants which requires the information from the two domains
// The information should be inferred in the pre-state
List<Expression> geqZero;
// if (this.ExpressionManager.Encoder!= null)
{
geqZero = new GreaterEqualThanZeroConstraints<Variable, Expression>(this.ExpressionManager).InferConstraints(x, exp, preState);
Contract.Assert(Contract.ForAll(geqZero, condition => condition != null));
}
/* else
{
geqZero = new List<Expression>();
// F: we do not decompile ForAll in the case below
Contract.Assume(Contract.ForAll(geqZero, condition => condition != null));
}
*/
Contract.Assert(Contract.ForAll(geqZero, condition => condition != null));
this.Right.Assign(x, exp, preState);
this.Left.Assign(x, exp, preState);
// The information is assumed in the post-state...
foreach (var condition in geqZero)
{
this.TestTrue(condition);
}
}
#endregion
#region IPureExpressionAssignments<Expression> Members
public List<Variable> Variables
{
get
{
return this.Left.Variables.SetUnion(this.Right.Variables);
}
}
public void AddVariable(Variable var)
{
this.Left.AddVariable(var);
this.Right.AddVariable(var);
}
public void ProjectVariable(Variable var)
{
this.Left.ProjectVariable(var);
this.Right.ProjectVariable(var);
}
public void RemoveVariable(Variable var)
{
this.Left.RemoveVariable(var);
this.Right.RemoveVariable(var);
}
public void RenameVariable(Variable OldName, Variable NewName)
{
this.Left.RenameVariable(OldName, NewName);
this.Right.RenameVariable(OldName, NewName);
}
#endregion
#region IPureExpressionTest<Expression> Members
IAbstractDomainForEnvironments<Variable, Expression> IPureExpressionTest<Variable, Expression>.TestTrue(Expression guard)
{
return this.TestTrue(guard);
}
public Pentagons<Variable, Expression> TestTrue(Expression guard)
{
Contract.Requires(guard != null);
Contract.Ensures(Contract.Result<Pentagons<Variable, Expression>>() != null);
var resultLeft = this.Left.TestTrue(guard);
var resultRight = this.Right.TestTrue(guard);
return this.FactoryOfPentagons(resultLeft, resultRight);
}
IAbstractDomainForEnvironments<Variable, Expression> IPureExpressionTest<Variable, Expression>.TestFalse(Expression guard)
{
return this.TestFalse(guard);
}
public Pentagons<Variable, Expression> TestFalse(Expression guard)
{
Contract.Requires(guard != null);
Contract.Ensures(Contract.Result<Pentagons<Variable, Expression>>() != null);
var resultLeft = this.Left.TestFalse(guard);
var resultRight = this.Right.TestFalse(guard);
return this.FactoryOfPentagons(resultLeft, resultRight);
}
INumericalAbstractDomain<Variable, Expression> INumericalAbstractDomain<Variable, Expression>.TestTrueGeqZero(Expression exp)
{
return this.TestTrueGeqZero(exp);
}
public Pentagons<Variable, Expression> TestTrueGeqZero(Expression exp)
{
Contract.Requires(exp != null);
var newLeft = this.Left.TestTrueGeqZero(exp);
var newRight = this.Right; // We abstract them away
return this.FactoryOfPentagons(newLeft, newRight);
}
INumericalAbstractDomain<Variable, Expression> INumericalAbstractDomain<Variable, Expression>.TestTrueLessThan(Expression exp1, Expression exp2)
{
return this.TestTrueLessThan(exp1, exp2);
}
public Pentagons<Variable, Expression> TestTrueLessThan(Expression exp1, Expression exp2)
{
Contract.Requires(exp1 != null);
Contract.Requires(exp2 != null);
Contract.Ensures(Contract.Result<Pentagons<Variable, Expression>>() != null);
var newLeft = this.Left.TestTrueLessThan(exp1, exp2);
var newRight = this.Right.TestTrueLessThan(exp1, exp2);
return this.FactoryOfPentagons(newLeft, newRight);
}
public Pentagons<Variable, Expression> TestTrueLessThan(Variable v1, Variable v2)
{
var newLeft = this.Left.TestTrueLessThan(v1, v2);
var newRight = this.Right.TestTrueLessThan(v1, v2);
return this.FactoryOfPentagons(newLeft, newRight);
}
public Pentagons<Variable, Expression> TestTrueLessThan(Expression exp1, Expression exp2,
WeakUpperBoundsEqual<Variable, Expression> oracleDomain)
{
Contract.Requires(exp1 != null);
Contract.Requires(exp2 != null);
Contract.Requires(oracleDomain != null);
Contract.Ensures(Contract.Result<Pentagons<Variable, Expression>>() != null);
var newLeft = this.Left.TestTrueLessThan(exp1, exp2);
var newRight = this.Right.TestTrueLessThan(exp1, exp2, oracleDomain);
return this.FactoryOfPentagons(newLeft, newRight);
}
INumericalAbstractDomain<Variable, Expression> INumericalAbstractDomain<Variable, Expression>.TestTrueLessEqualThan(Expression exp1, Expression exp2)
{
return this.TestTrueLessEqualThan(exp1, exp2);
}
public Pentagons<Variable, Expression> TestTrueLessEqualThan(Expression exp1, Expression exp2)
{
Contract.Requires(exp1 != null);
Contract.Requires(exp2 != null);
Contract.Ensures(Contract.Result<Pentagons<Variable, Expression>>() != null);
var newLeft = this.Left.TestTrueLessEqualThan(exp1, exp2);
var newRight = this.Right.TestTrueLessEqualThan(exp1, exp2);
return this.FactoryOfPentagons(newLeft, newRight);
}
INumericalAbstractDomain<Variable, Expression> INumericalAbstractDomain<Variable, Expression>.TestTrueEqual(Expression exp1, Expression exp2)
{
return this.TestTrueEqual(exp1, exp2);
}
public INumericalAbstractDomain<Variable, Expression> TestTrueEqual(Expression exp1, Expression exp2)
{
Contract.Assume(exp1 != null);
Contract.Assume(exp2 != null);
var resultLeft = this.Left.TestTrueEqual(exp1, exp2);
var resultRight = this.Right.TestTrueEqual(exp1, exp2);
return this.FactoryOfPentagons(resultLeft, resultRight);
}
public FlatAbstractDomain<bool> CheckIfHolds(Expression exp)
{
if (CommonChecks.CheckTrivialEquality(exp, this.ExpressionManager.Decoder))
{
return CheckOutcome.True;
}
var checkLeft = this.Left.CheckIfHolds(exp);
var checkRight = this.Right.CheckIfHolds(exp, null);
return checkLeft.Meet(checkRight);
}
#endregion
#region Remove redundancies
public Pentagons<Variable, Expression> RemoveRedundanciesWith(INumericalAbstractDomain<Variable, Expression> oracle)
{
Contract.Requires(oracle != null);
var left = this.Left.RemoveRedundanciesWith(oracle);
var right = this.Right.RemoveRedundanciesWith(this.Right).RemoveRedundanciesWith(oracle);
return this.FactoryOfPentagons(left, right);
}
INumericalAbstractDomain<Variable, Expression> INumericalAbstractDomain<Variable, Expression>.RemoveRedundanciesWith(INumericalAbstractDomain<Variable, Expression> oracle)
{
return this.RemoveRedundanciesWith(oracle);
}
#endregion
#region ToString
public string ToString(Expression exp)
{
// if (this.expManager.Decoder != null)
{
return ExpressionPrinter.ToString(exp, expManager.Decoder);
}
/* else
{
return "< missing expression decoder >";
}*/
}
#endregion
#region Floating point types
public void SetFloatType(Variable v, ConcreteFloat f)
{
// does nothing
}
public FlatAbstractDomain<ConcreteFloat> GetFloatType(Variable v)
{
return FloatTypes<Variable, Expression>.Unknown;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using Signum.Utilities;
using System.Data.Common;
using System.Linq;
namespace Signum.Engine
{
/// <summary>
/// Allows easy nesting of transaction by making use of 'using' statement
/// Keeps an implicit stack of Transaction objects over the call stack of the current Thread
/// and an explicit stack of RealTransaction objects on thread variable.
/// Usually, just the first Transaccion creates a RealTransaction, but you can create more using
/// forceNew = true
/// All Transaction can cancel but only the one that created the RealTransaction can Commit
/// </summary>
public class Transaction : IDisposableException
{
static readonly Variable<Dictionary<Connector, ICoreTransaction>?> currents = Statics.ThreadVariable<Dictionary<Connector, ICoreTransaction>?>("transactions", avoidExportImport: true);
bool commited;
ICoreTransaction coreTransaction;
interface ICoreTransaction
{
event Action<Dictionary<string, object>?>? PostRealCommit;
void CallPostRealCommit();
event Action<Dictionary<string, object>?>? PreRealCommit;
DbConnection? Connection { get; }
DbTransaction? Transaction { get; }
bool Started { get; }
Exception? IsRolledback { get; }
void Rollback(Exception ex);
event Action<Dictionary<string, object>?> Rolledback;
void Commit();
void Finish();
void Start();
ICoreTransaction? Parent { get; }
Dictionary<string, object> UserData { get; }
}
class FakedTransaction : ICoreTransaction
{
ICoreTransaction parent;
public FakedTransaction(ICoreTransaction parent)
{
if (parent == null)
throw new ArgumentNullException(nameof(parent));
if (parent.IsRolledback != null)
throw new InvalidOperationException("The transaction can not be created because a parent transaction is rolled back. Exception:\r\n\t" + parent.IsRolledback.Message, parent.IsRolledback);
this.parent = parent;
}
public event Action<Dictionary<string, object>?>? PostRealCommit
{
add { parent.PostRealCommit += value; }
remove { parent.PostRealCommit -= value; }
}
public event Action<Dictionary<string, object>?>? PreRealCommit
{
add { parent.PreRealCommit += value; }
remove { parent.PreRealCommit -= value; }
}
public DbConnection? Connection { get { return parent.Connection; } }
public DbTransaction? Transaction { get { return parent.Transaction; } }
public Exception? IsRolledback { get { return parent.IsRolledback; } }
public bool Started { get { return parent.Started; } }
public void Start() { parent.Start(); }
public void Rollback(Exception ex)
{
parent.Rollback(ex);
}
public void Commit() { }
public void Finish() { }
public Dictionary<string, object> UserData
{
get { return parent.UserData; }
}
public void CallPostRealCommit()
{
}
public ICoreTransaction? Parent
{
get { return parent; }
}
public event Action<Dictionary<string, object>?> Rolledback
{
add { parent.Rolledback += value; }
remove { parent.Rolledback -= value; }
}
}
class RealTransaction : ICoreTransaction
{
ICoreTransaction? parent;
public DbConnection? Connection { get; private set; }
public DbTransaction? Transaction { get; private set; }
public Exception? IsRolledback { get; private set; }
public bool Started { get; private set; }
public event Action<Dictionary<string, object>?>? PostRealCommit;
public event Action<Dictionary<string, object>?>? PreRealCommit;
public event Action<Dictionary<string, object>?>? Rolledback;
IsolationLevel? IsolationLevel;
public RealTransaction(ICoreTransaction? parent, IsolationLevel? isolationLevel)
{
IsolationLevel = isolationLevel;
this.parent = parent;
}
public void Start()
{
if (!Started)
{
Connection = Connector.Current.CreateConnection();
Connection.Open();
Transaction = Connection.BeginTransaction(IsolationLevel ?? Connector.Current.IsolationLevel);
Started = true;
}
}
public virtual void Commit()
{
if (Started)
{
OnPreRealCommit();
Transaction!.Commit();
}
}
internal void OnPreRealCommit()
{
while (PreRealCommit != null)
{
foreach (var item in PreRealCommit.GetInvocationListTyped())
{
item(this.UserData);
PreRealCommit -= item;
}
}
}
public void CallPostRealCommit()
{
if (PostRealCommit != null)
{
foreach (var item in PostRealCommit.GetInvocationListTyped())
{
item(this.UserData);
}
}
}
public void Rollback(Exception ex)
{
if (Started && IsRolledback == null)
{
Transaction!.Rollback();
IsRolledback = ex;
Rolledback?.Invoke(this.userData);
}
}
public virtual void Finish()
{
if (Transaction != null)
{
Transaction.Dispose();
Transaction = null;
}
if (Connection != null)
{
Connection.Dispose();
Connection = null;
}
}
Dictionary<string, object>? userData;
public Dictionary<string, object> UserData
{
get { return userData ?? (userData = new Dictionary<string, object>()); }
}
public ICoreTransaction? Parent
{
get { return parent; }
}
}
class NamedTransaction : ICoreTransaction
{
ICoreTransaction parent;
string savePointName;
public Exception? IsRolledback { get; private set; }
public bool Started { get; private set; }
public event Action<Dictionary<string, object>?>? PostRealCommit;
public event Action<Dictionary<string, object>?>? PreRealCommit;
public event Action<Dictionary<string, object>?>? Rolledback;
public NamedTransaction(ICoreTransaction parent, string savePointName)
{
if (parent == null)
throw new InvalidOperationException("Named transactions should be nested inside another transaction");
if (parent.IsRolledback != null)
throw new InvalidOperationException("The transaction can not be created because a parent transaction is rolled back. Exception:\r\n\t" + parent.IsRolledback.Message, parent.IsRolledback);
this.parent = parent;
this.savePointName = savePointName;
}
public DbConnection? Connection { get { return parent.Connection; } }
public DbTransaction? Transaction { get { return parent.Transaction; } }
public void Start()
{
if (!Started)
{
parent.Start();
Connector.Current.SaveTransactionPoint(Transaction!, savePointName);
Started = true;
}
}
public void Rollback(Exception ex)
{
if (Started && IsRolledback == null)
{
Connector.Current.RollbackTransactionPoint(Transaction!, savePointName);
IsRolledback = ex;
Rolledback?.Invoke(this.UserData);
}
}
public void Commit()
{
}
public void CallPostRealCommit()
{
if (PreRealCommit != null)
foreach (var item in PreRealCommit.GetInvocationListTyped())
parent.PreRealCommit += parentUserData => item(this.UserData);
if (PostRealCommit != null)
foreach (var item in PostRealCommit.GetInvocationListTyped())
parent.PostRealCommit += parentUserData => item(this.UserData);
}
public void Finish() { }
Dictionary<string, object>? userData;
public Dictionary<string, object> UserData
{
get { return userData ?? (userData = new Dictionary<string, object>()); }
}
public ICoreTransaction? Parent
{
get { return parent; }
}
}
class NoneTransaction : ICoreTransaction
{
ICoreTransaction? parent;
public DbConnection? Connection { get; private set; }
public DbTransaction? Transaction { get { return null; } }
public Exception? IsRolledback { get; private set; }
public bool Started { get; private set; }
public event Action<Dictionary<string, object>?>? PostRealCommit;
public event Action<Dictionary<string, object>?>? PreRealCommit;
public event Action<Dictionary<string, object>?>? Rolledback;
public NoneTransaction(ICoreTransaction? parent)
{
this.parent = parent;
}
public void Start()
{
if (!Started)
{
Connection = Connector.Current.CreateConnection();
Connection.Open();
//Transaction = Connection.BeginTransaction(IsolationLevel ?? con.IsolationLevel);
Started = true;
}
}
public void Commit()
{
if (Started)
{
while (PreRealCommit != null)
{
foreach (var item in PreRealCommit.GetInvocationListTyped())
{
item(this.UserData);
PreRealCommit -= item;
}
}
//Transaction.Commit();
}
}
public void CallPostRealCommit()
{
if (PostRealCommit != null)
{
foreach (var item in PostRealCommit.GetInvocationListTyped())
{
item(this.UserData);
}
}
}
public void Rollback(Exception ex)
{
if (Started && IsRolledback == null)
{
//Transaction.Rollback();
IsRolledback = ex;
Rolledback?.Invoke(this.UserData);
}
}
public void Finish()
{
//if (Transaction != null)
//{
// Transaction.Dispose();
// Transaction = null;
//}
if (Connection != null)
{
Connection.Dispose();
Connection = null;
}
}
Dictionary<string, object>? userData;
public Dictionary<string, object> UserData
{
get { return userData ?? (userData = new Dictionary<string, object>()); }
}
public ICoreTransaction? Parent
{
get { return parent; }
}
}
public static bool InTestTransaction
{
get { return inTestTransaction.Value; }
}
static readonly Variable<bool> inTestTransaction = Statics.ThreadVariable<bool>("inTestTransaction");
class TestTransaction : RealTransaction
{
bool oldTestTransaction;
public TestTransaction(ICoreTransaction? parent, IsolationLevel? isolation)
: base(parent, isolation)
{
oldTestTransaction = inTestTransaction.Value;
inTestTransaction.Value = true;
}
public override void Finish()
{
inTestTransaction.Value = oldTestTransaction;
base.Finish();
}
}
public Transaction()
: this(parent => parent == null ?
(ICoreTransaction)new RealTransaction(parent, null) :
(ICoreTransaction)new FakedTransaction(parent))
{
}
Transaction(Func<ICoreTransaction?, ICoreTransaction> factory)
{
var dic = currents.Value ??= new Dictionary<Connector, ICoreTransaction>();
Connector bc = Connector.Current;
if (bc == null)
throw new InvalidOperationException("ConnectionScope.Current not established. Use ConnectionScope.Default to set it.");
ICoreTransaction? parent = dic.TryGetC(bc);
dic[bc] = coreTransaction = factory(parent);
}
public static Transaction None()
{
return new Transaction(parent => new NoneTransaction(parent));
}
public static Transaction NamedSavePoint(string savePointName)
{
return new Transaction(parent => new NamedTransaction(parent!, savePointName));
}
public static T ForceNew<T>(Func<T> func)
{
using (Transaction tr = Transaction.ForceNew())
return tr.Commit(func.Invoke());
}
public static Transaction ForceNew()
{
return new Transaction(parent => inTestTransaction.Value ?
(ICoreTransaction)new FakedTransaction(parent!) :
(ICoreTransaction)new RealTransaction(parent, null));
}
public static Transaction ForceNew(IsolationLevel? isolationLevel)
{
return new Transaction(parent => inTestTransaction.Value ?
(ICoreTransaction)new FakedTransaction(parent!) :
(ICoreTransaction)new RealTransaction(parent, isolationLevel));
}
public static Transaction Test()
{
return new Transaction(parent => new TestTransaction(parent, null));
}
public static Transaction Test(IsolationLevel? isolationLevel)
{
return new Transaction(parent => new TestTransaction(parent, isolationLevel));
}
static ICoreTransaction GetCurrent()
{
return currents.Value!.GetOrThrow(Connector.Current, "No Transaction created yet");
}
public static event Action<Dictionary<string, object>> PostRealCommit
{
add { GetCurrent().PostRealCommit += value; }
remove { GetCurrent().PostRealCommit -= value; }
}
public static event Action<Dictionary<string, object>> PreRealCommit
{
add { GetCurrent().PreRealCommit += value; }
remove { GetCurrent().PreRealCommit -= value; }
}
public static event Action<Dictionary<string, object>> Rolledback
{
add { GetCurrent().Rolledback += value; }
remove { GetCurrent().Rolledback -= value; }
}
public static Dictionary<string, object> UserData
{
get { return GetCurrent().UserData; }
}
public static Dictionary<string, object> TopParentUserData()
{
return GetCurrent().Follow(a => a.Parent).Last().UserData;
}
public static bool HasTransaction
{
get { return currents.Value != null && currents.Value!.ContainsKey(Connector.Current); }
}
public static DbConnection? CurrentConnection
{
get
{
ICoreTransaction tran = GetCurrent();
tran.Start();
return tran.Connection;
}
}
public static DbTransaction? CurrentTransaccion
{
get
{
ICoreTransaction tran = GetCurrent();
tran.Start();
return tran.Transaction;
}
}
public static string CurrentStatus()
{
return GetCurrent().Follow(a => a.Parent).ToString(t => "{0} Started : {1} Rollbacked: {2} Connection: {3} Transaction: {4}".FormatWith(
t.GetType().Name,
t.Started,
t.IsRolledback,
t.Connection == null ? "null" : (t.Connection.State.ToString() + " Hash " + t.Connection.GetHashCode()),
t.Transaction == null ? "null" : (" Hash " + t.Transaction.GetHashCode())), "\r\n");
}
public T Commit<T>(T returnValue)
{
Commit();
return returnValue;
}
public void Commit()
{
if (coreTransaction.IsRolledback != null)
throw new InvalidOperationException("The transation is rolled back and can not be commited.");
coreTransaction.Commit();
commited = true;
}
public void PreRealCommitOnly()
{
if (coreTransaction.IsRolledback != null)
throw new InvalidOperationException("The transation is rolled back and can not be commited.");
var rt = coreTransaction as RealTransaction;
if (rt == null)
throw new InvalidOperationException("This method is meant for testing purposes, and only Real and Test transactions can execute it");
rt.OnPreRealCommit();
}
public void Dispose()
{
try
{
if (!commited)
coreTransaction.Rollback(this.savedException ??
new Exception("Unkwnown exception. Consider 'EndUsing' or 'Using' methods instead of 'using' statement.")); //... sqlTransacion.Rollback()
coreTransaction.Finish(); //... sqlTransaction.Dispose() sqlConnection.Dispose()
}
finally
{
var dic = currents.Value!;
if (coreTransaction.Parent == null)
{
dic.Remove(Connector.Current);
if (dic.Count == 0)
currents.Value = null;
}
else
dic[Connector.Current] = coreTransaction.Parent;
}
if (commited)
coreTransaction.CallPostRealCommit();
}
public static void InvokePreRealCommit(Transaction tr)
{
((RealTransaction)tr.coreTransaction).OnPreRealCommit();
}
Exception? savedException;
public void OnException(Exception ex)
{
this.savedException = ex;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Globalization;
using System.IO;
using System.Runtime;
using System.Runtime.Serialization;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Xml;
namespace System.ServiceModel.Channels
{
public abstract class MessageHeader : MessageHeaderInfo
{
private const bool DefaultRelayValue = false;
private const bool DefaultMustUnderstandValue = false;
private const string DefaultActorValue = "";
public override string Actor
{
get { return ""; }
}
public override bool IsReferenceParameter
{
get { return false; }
}
public override bool MustUnderstand
{
get { return DefaultMustUnderstandValue; }
}
public override bool Relay
{
get { return DefaultRelayValue; }
}
public virtual bool IsMessageVersionSupported(MessageVersion messageVersion)
{
if (messageVersion == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion");
}
return true;
}
public override string ToString()
{
XmlWriterSettings xmlSettings = new XmlWriterSettings() { Indent = true };
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
using (XmlWriter textWriter = XmlWriter.Create(stringWriter, xmlSettings))
{
using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(textWriter))
{
if (IsMessageVersionSupported(MessageVersion.Soap12WSAddressing10))
{
WriteHeader(writer, MessageVersion.Soap12WSAddressing10);
}
else if (IsMessageVersionSupported(MessageVersion.Soap11WSAddressing10))
{
WriteHeader(writer, MessageVersion.Soap11WSAddressing10);
}
else if (IsMessageVersionSupported(MessageVersion.Soap12))
{
WriteHeader(writer, MessageVersion.Soap12);
}
else if (IsMessageVersionSupported(MessageVersion.Soap11))
{
WriteHeader(writer, MessageVersion.Soap11);
}
else
{
WriteHeader(writer, MessageVersion.None);
}
writer.Flush();
return stringWriter.ToString();
}
}
}
}
public void WriteHeader(XmlWriter writer, MessageVersion messageVersion)
{
WriteHeader(XmlDictionaryWriter.CreateDictionaryWriter(writer), messageVersion);
}
public void WriteHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer"));
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion"));
OnWriteStartHeader(writer, messageVersion);
OnWriteHeaderContents(writer, messageVersion);
writer.WriteEndElement();
}
public void WriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer"));
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion"));
OnWriteStartHeader(writer, messageVersion);
}
protected virtual void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteStartElement(this.Name, this.Namespace);
WriteHeaderAttributes(writer, messageVersion);
}
public void WriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer"));
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion"));
OnWriteHeaderContents(writer, messageVersion);
}
protected abstract void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion);
protected void WriteHeaderAttributes(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
string actor = this.Actor;
if (actor.Length > 0)
writer.WriteAttributeString(messageVersion.Envelope.DictionaryActor, messageVersion.Envelope.DictionaryNamespace, actor);
if (this.MustUnderstand)
writer.WriteAttributeString(XD.MessageDictionary.MustUnderstand, messageVersion.Envelope.DictionaryNamespace, "1");
if (this.Relay && messageVersion.Envelope == EnvelopeVersion.Soap12)
writer.WriteAttributeString(XD.Message12Dictionary.Relay, XD.Message12Dictionary.Namespace, "1");
}
public static MessageHeader CreateHeader(string name, string ns, object value)
{
return CreateHeader(name, ns, value, DefaultMustUnderstandValue, DefaultActorValue, DefaultRelayValue);
}
public static MessageHeader CreateHeader(string name, string ns, object value, bool mustUnderstand)
{
return CreateHeader(name, ns, value, mustUnderstand, DefaultActorValue, DefaultRelayValue);
}
public static MessageHeader CreateHeader(string name, string ns, object value, bool mustUnderstand, string actor)
{
return CreateHeader(name, ns, value, mustUnderstand, actor, DefaultRelayValue);
}
public static MessageHeader CreateHeader(string name, string ns, object value, bool mustUnderstand, string actor, bool relay)
{
return new XmlObjectSerializerHeader(name, ns, value, null, mustUnderstand, actor, relay);
}
public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer)
{
return CreateHeader(name, ns, value, serializer, DefaultMustUnderstandValue, DefaultActorValue, DefaultRelayValue);
}
public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand)
{
return CreateHeader(name, ns, value, serializer, mustUnderstand, DefaultActorValue, DefaultRelayValue);
}
public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand, string actor)
{
return CreateHeader(name, ns, value, serializer, mustUnderstand, actor, DefaultRelayValue);
}
public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay)
{
if (serializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer"));
return new XmlObjectSerializerHeader(name, ns, value, serializer, mustUnderstand, actor, relay);
}
internal static void GetHeaderAttributes(XmlDictionaryReader reader, MessageVersion version,
out string actor, out bool mustUnderstand, out bool relay, out bool isReferenceParameter)
{
int attributeCount = reader.AttributeCount;
if (attributeCount == 0)
{
mustUnderstand = false;
actor = string.Empty;
relay = false;
isReferenceParameter = false;
}
else
{
string mustUnderstandString = reader.GetAttribute(XD.MessageDictionary.MustUnderstand, version.Envelope.DictionaryNamespace);
if (mustUnderstandString != null && ToBoolean(mustUnderstandString))
mustUnderstand = true;
else
mustUnderstand = false;
if (mustUnderstand && attributeCount == 1)
{
actor = string.Empty;
relay = false;
}
else
{
actor = reader.GetAttribute(version.Envelope.DictionaryActor, version.Envelope.DictionaryNamespace);
if (actor == null)
actor = "";
if (version.Envelope == EnvelopeVersion.Soap12)
{
string relayString = reader.GetAttribute(XD.Message12Dictionary.Relay, version.Envelope.DictionaryNamespace);
if (relayString != null && ToBoolean(relayString))
relay = true;
else
relay = false;
}
else
{
relay = false;
}
}
isReferenceParameter = false;
if (version.Addressing == AddressingVersion.WSAddressing10)
{
string refParam = reader.GetAttribute(XD.AddressingDictionary.IsReferenceParameter, version.Addressing.DictionaryNamespace);
if (refParam != null)
isReferenceParameter = ToBoolean(refParam);
}
}
}
private static bool ToBoolean(string value)
{
if (value.Length == 1)
{
char ch = value[0];
if (ch == '1')
{
return true;
}
if (ch == '0')
{
return false;
}
}
else
{
if (value == "true")
{
return true;
}
else if (value == "false")
{
return false;
}
}
try
{
return XmlConvert.ToBoolean(value);
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(exception.Message, null));
}
}
}
internal abstract class DictionaryHeader : MessageHeader
{
public override string Name
{
get { return DictionaryName.Value; }
}
public override string Namespace
{
get { return DictionaryNamespace.Value; }
}
public abstract XmlDictionaryString DictionaryName { get; }
public abstract XmlDictionaryString DictionaryNamespace { get; }
protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteStartElement(DictionaryName, DictionaryNamespace);
WriteHeaderAttributes(writer, messageVersion);
}
}
internal class XmlObjectSerializerHeader : MessageHeader
{
private XmlObjectSerializer _serializer;
private bool _mustUnderstand;
private bool _relay;
private bool _isOneTwoSupported;
private bool _isOneOneSupported;
private bool _isNoneSupported;
private object _objectToSerialize;
private string _name;
private string _ns;
private string _actor;
private object _syncRoot = new object();
private XmlObjectSerializerHeader(XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay)
{
if (actor == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("actor");
}
_mustUnderstand = mustUnderstand;
_relay = relay;
_serializer = serializer;
_actor = actor;
if (actor == EnvelopeVersion.Soap12.UltimateDestinationActor)
{
_isOneOneSupported = false;
_isOneTwoSupported = true;
}
else if (actor == EnvelopeVersion.Soap12.NextDestinationActorValue)
{
_isOneOneSupported = false;
_isOneTwoSupported = true;
}
else if (actor == EnvelopeVersion.Soap11.NextDestinationActorValue)
{
_isOneOneSupported = true;
_isOneTwoSupported = false;
}
else
{
_isOneOneSupported = true;
_isOneTwoSupported = true;
_isNoneSupported = true;
}
}
public XmlObjectSerializerHeader(string name, string ns, object objectToSerialize, XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay)
: this(serializer, mustUnderstand, actor, relay)
{
if (null == name)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name"));
}
if (name.Length == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.SFXHeaderNameCannotBeNullOrEmpty, "name"));
}
if (ns == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns");
}
if (ns.Length > 0)
{
NamingHelper.CheckUriParameter(ns, "ns");
}
_objectToSerialize = objectToSerialize;
_name = name;
_ns = ns;
}
public override bool IsMessageVersionSupported(MessageVersion messageVersion)
{
if (messageVersion == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion");
}
if (messageVersion.Envelope == EnvelopeVersion.Soap12)
{
return _isOneTwoSupported;
}
else if (messageVersion.Envelope == EnvelopeVersion.Soap11)
{
return _isOneOneSupported;
}
else if (messageVersion.Envelope == EnvelopeVersion.None)
{
return _isNoneSupported;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.EnvelopeVersionUnknown, messageVersion.Envelope.ToString())));
}
}
public override string Name
{
get { return _name; }
}
public override string Namespace
{
get { return _ns; }
}
public override bool MustUnderstand
{
get { return _mustUnderstand; }
}
public override bool Relay
{
get { return _relay; }
}
public override string Actor
{
get { return _actor; }
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
lock (_syncRoot)
{
if (_serializer == null)
{
_serializer = DataContractSerializerDefaults.CreateSerializer(
(_objectToSerialize == null ? typeof(object) : _objectToSerialize.GetType()), this.Name, this.Namespace, int.MaxValue/*maxItems*/);
}
_serializer.WriteObjectContent(writer, _objectToSerialize);
}
}
}
internal abstract class ReadableMessageHeader : MessageHeader
{
public abstract XmlDictionaryReader GetHeaderReader();
protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
if (!IsMessageVersionSupported(messageVersion))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MessageHeaderVersionNotSupported, this.GetType().FullName, messageVersion.ToString()), "version"));
XmlDictionaryReader reader = GetHeaderReader();
writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
writer.WriteAttributes(reader, false);
reader.Dispose();
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
XmlDictionaryReader reader = GetHeaderReader();
reader.ReadStartElement();
while (reader.NodeType != XmlNodeType.EndElement)
writer.WriteNode(reader, false);
reader.ReadEndElement();
reader.Dispose();
}
}
internal interface IMessageHeaderWithSharedNamespace
{
XmlDictionaryString SharedNamespace { get; }
XmlDictionaryString SharedPrefix { get; }
}
internal class BufferedHeader : ReadableMessageHeader
{
private MessageVersion _version;
private XmlBuffer _buffer;
private int _bufferIndex;
private string _actor;
private bool _relay;
private bool _mustUnderstand;
private string _name;
private string _ns;
private bool _streamed;
private bool _isRefParam;
public BufferedHeader(MessageVersion version, XmlBuffer buffer, int bufferIndex, string name, string ns, bool mustUnderstand, string actor, bool relay, bool isRefParam)
{
_version = version;
_buffer = buffer;
_bufferIndex = bufferIndex;
_name = name;
_ns = ns;
_mustUnderstand = mustUnderstand;
_actor = actor;
_relay = relay;
_isRefParam = isRefParam;
}
public BufferedHeader(MessageVersion version, XmlBuffer buffer, int bufferIndex, MessageHeaderInfo headerInfo)
{
_version = version;
_buffer = buffer;
_bufferIndex = bufferIndex;
_actor = headerInfo.Actor;
_relay = headerInfo.Relay;
_name = headerInfo.Name;
_ns = headerInfo.Namespace;
_isRefParam = headerInfo.IsReferenceParameter;
_mustUnderstand = headerInfo.MustUnderstand;
}
public BufferedHeader(MessageVersion version, XmlBuffer buffer, XmlDictionaryReader reader, XmlAttributeHolder[] envelopeAttributes, XmlAttributeHolder[] headerAttributes)
{
_streamed = true;
_buffer = buffer;
_version = version;
GetHeaderAttributes(reader, version, out _actor, out _mustUnderstand, out _relay, out _isRefParam);
_name = reader.LocalName;
_ns = reader.NamespaceURI;
Fx.Assert(_name != null, "");
Fx.Assert(_ns != null, "");
_bufferIndex = buffer.SectionCount;
XmlDictionaryWriter writer = buffer.OpenSection(reader.Quotas);
// Write an enclosing Envelope tag
writer.WriteStartElement(MessageStrings.Envelope);
if (envelopeAttributes != null)
XmlAttributeHolder.WriteAttributes(envelopeAttributes, writer);
// Write and enclosing Header tag
writer.WriteStartElement(MessageStrings.Header);
if (headerAttributes != null)
XmlAttributeHolder.WriteAttributes(headerAttributes, writer);
writer.WriteNode(reader, false);
writer.WriteEndElement();
writer.WriteEndElement();
buffer.CloseSection();
}
public override string Actor
{
get { return _actor; }
}
public override bool IsReferenceParameter
{
get { return _isRefParam; }
}
public override string Name
{
get { return _name; }
}
public override string Namespace
{
get { return _ns; }
}
public override bool MustUnderstand
{
get { return _mustUnderstand; }
}
public override bool Relay
{
get { return _relay; }
}
public override bool IsMessageVersionSupported(MessageVersion messageVersion)
{
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion"));
return messageVersion == _version;
}
public override XmlDictionaryReader GetHeaderReader()
{
XmlDictionaryReader reader = _buffer.GetReader(_bufferIndex);
// See if we need to move past the enclosing envelope/header
if (_streamed)
{
reader.MoveToContent();
reader.Read(); // Envelope
reader.Read(); // Header
reader.MoveToContent();
}
return reader;
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using System.Xml.Linq;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Project.ImportWizard;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Python;
namespace PythonToolsTests {
[TestClass]
public class ImportWizardTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
private static string CreateRequestedProject(dynamic settings) {
return Task.Run(async () => {
return await await WpfProxy.FromObject((object)settings).InvokeAsync(
async () => await (Task<string>)settings.CreateRequestedProjectAsync()
);
})
.GetAwaiter()
.GetResult();
}
[TestMethod, Priority(1)]
public void ImportWizardSimple() {
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.py;*.pyproj";
settings.SearchPaths = TestData.GetPath("TestData\\SearchPath1\\") + Environment.NewLine + TestData.GetPath("TestData\\SearchPath2\\");
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("4.0", proj.Descendant("Project").Attribute("ToolsVersion").Value);
Assert.AreEqual("..\\..\\HelloWorld\\", proj.Descendant("ProjectHome").Value);
Assert.AreEqual("..\\SearchPath1\\;..\\SearchPath2\\", proj.Descendant("SearchPath").Value);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"Program.py");
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Content")).Select(x => x.Attribute("Include").Value),
"HelloWorld.pyproj");
}
}
[TestMethod, Priority(1)]
public void ImportWizardFiltered() {
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.py";
settings.SearchPaths = TestData.GetPath("TestData\\SearchPath1\\") + Environment.NewLine + TestData.GetPath("TestData\\SearchPath2\\");
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("..\\..\\HelloWorld\\", proj.Descendant("ProjectHome").Value);
Assert.AreEqual("..\\SearchPath1\\;..\\SearchPath2\\", proj.Descendant("SearchPath").Value);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"Program.py");
Assert.AreEqual(0, proj.Descendants(proj.GetName("Content")).Count());
}
}
[TestMethod, Priority(1)]
public void ImportWizardFolders() {
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld2\\");
settings.Filters = "*";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("..\\..\\HelloWorld2\\", proj.Descendant("ProjectHome").Value);
Assert.AreEqual("", proj.Descendant("SearchPath").Value);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"Program.py",
"TestFolder\\SubItem.py",
"TestFolder2\\SubItem.py",
"TestFolder3\\SubItem.py");
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
"TestFolder",
"TestFolder2",
"TestFolder3");
}
}
[TestMethod, Priority(1)]
public void ImportWizardInterpreter() {
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.py;*.pyproj";
var interpreter = new PythonInterpreterView("Test", "Test|Blah", null);
settings.Dispatcher.Invoke((Action)(() => settings.AvailableInterpreters.Add(interpreter)));
//settings.AddAvailableInterpreter(interpreter);
settings.SelectedInterpreter = interpreter;
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual(interpreter.Id, proj.Descendant("InterpreterId").Value);
var interp = proj.Descendant("InterpreterReference");
Assert.AreEqual(string.Format("{0}", interpreter.Id),
interp.Attribute("Include").Value);
}
}
[TestMethod, Priority(1)]
public void ImportWizardStartupFile() {
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.py;*.pyproj";
settings.StartupFile = "Program.py";
settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
Assert.AreEqual("Program.py", proj.Descendant("StartupFile").Value);
}
}
[TestMethod, Priority(1)]
public void ImportWizardSemicolons() {
// https://pytools.codeplex.com/workitem/2022
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
var sourcePath = TestData.GetTempPath(randomSubPath: true);
// Create a fake set of files to import
Directory.CreateDirectory(Path.Combine(sourcePath, "ABC"));
File.WriteAllText(Path.Combine(sourcePath, "ABC", "a;b;c.py"), "");
Directory.CreateDirectory(Path.Combine(sourcePath, "A;B;C"));
File.WriteAllText(Path.Combine(sourcePath, "A;B;C", "abc.py"), "");
settings.SourcePath = sourcePath;
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"ABC\\a%3bb%3bc.py",
"A%3bB%3bC\\abc.py"
);
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
"ABC",
"A%3bB%3bC"
);
}
}
private void ImportWizardVirtualEnvWorker(
PythonVersion python,
string venvModuleName,
string expectedFile,
bool brokenBaseInterpreter
) {
var mockService = new MockInterpreterOptionsService();
mockService.AddProvider(new MockPythonInterpreterFactoryProvider("Test Provider",
new MockPythonInterpreterFactory(
new InterpreterConfiguration(
python.Configuration.Id,
"Test Python",
python.Configuration.PrefixPath,
python.Configuration.InterpreterPath,
python.Configuration.WindowsInterpreterPath,
python.Configuration.LibraryPath,
python.Configuration.PathEnvironmentVariable,
python.Configuration.Architecture,
python.Configuration.Version,
python.Configuration.UIMode
)
)
));
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, mockService));
var sourcePath = TestData.GetTempPath(randomSubPath: true);
// Create a fake set of files to import
File.WriteAllText(Path.Combine(sourcePath, "main.py"), "");
Directory.CreateDirectory(Path.Combine(sourcePath, "A"));
File.WriteAllText(Path.Combine(sourcePath, "A", "__init__.py"), "");
// Create a real virtualenv environment to import
using (var p = ProcessOutput.RunHiddenAndCapture(python.InterpreterPath, "-m", venvModuleName, Path.Combine(sourcePath, "env"))) {
Console.WriteLine(p.Arguments);
p.Wait();
Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines)));
Assert.AreEqual(0, p.ExitCode);
}
if (brokenBaseInterpreter) {
var cfgPath = Path.Combine(sourcePath, "env", "Lib", "orig-prefix.txt");
if (File.Exists(cfgPath)) {
File.WriteAllText(cfgPath, string.Format("C:\\{0:N}", Guid.NewGuid()));
} else if (File.Exists((cfgPath = Path.Combine(sourcePath, "env", "pyvenv.cfg")))) {
File.WriteAllLines(cfgPath, File.ReadAllLines(cfgPath)
.Select(line => {
if (line.StartsWith("home = ")) {
return string.Format("home = C:\\{0:N}", Guid.NewGuid());
}
return line;
})
);
}
}
Console.WriteLine("All files:");
foreach (var f in Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories)) {
Console.WriteLine(PathUtils.GetRelativeFilePath(sourcePath, f));
}
Assert.IsTrue(
File.Exists(Path.Combine(sourcePath, "env", expectedFile)),
"Virtualenv was not created correctly"
);
settings.SourcePath = sourcePath;
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
var proj = XDocument.Load(path);
// Does not include any .py files from the virtualenv
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
"main.py",
"A\\__init__.py"
);
// Does not contain 'env'
AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
"A"
);
var env = proj.Descendant("Interpreter");
Assert.AreEqual("env\\", env.Attribute("Include").Value);
Assert.AreEqual("lib\\", env.Descendant("LibraryPath").Value, true);
if (brokenBaseInterpreter) {
Assert.AreEqual("env", env.Descendant("Description").Value);
Assert.AreEqual("", env.Descendant("InterpreterPath").Value);
Assert.AreEqual("", env.Descendant("WindowsInterpreterPath").Value);
Assert.AreEqual("", env.Descendant("BaseInterpreter").Value);
Assert.AreEqual("", env.Descendant("PathEnvironmentVariable").Value);
} else {
Assert.AreEqual("env (Test Python)", env.Descendant("Description").Value);
Assert.AreEqual("scripts\\python.exe", env.Descendant("InterpreterPath").Value, true);
// The mock configuration uses python.exe for both paths.
Assert.AreEqual("scripts\\python.exe", env.Descendant("WindowsInterpreterPath").Value, true);
Assert.AreEqual(python.Id, env.Descendant("BaseInterpreter").Value, true);
Assert.AreEqual("PYTHONPATH", env.Descendant("PathEnvironmentVariable").Value, true);
}
}
}
[TestMethod, Priority(1)]
public void ImportWizardVirtualEnv() {
var python = PythonPaths.Versions.LastOrDefault(pv =>
pv.IsCPython &&
File.Exists(Path.Combine(pv.LibPath, "site-packages", "virtualenv.py")) &&
// CPython 3.3.4 does not work correctly with virtualenv, so
// skip testing on 3.3 to avoid false failures
pv.Version != PythonLanguageVersion.V33
);
ImportWizardVirtualEnvWorker(python, "virtualenv", "lib\\orig-prefix.txt", false);
}
[TestMethod, Priority(1)]
public void ImportWizardVEnv() {
var python = PythonPaths.Versions.LastOrDefault(pv =>
pv.IsCPython && File.Exists(Path.Combine(pv.LibPath, "venv", "__main__.py"))
);
ImportWizardVirtualEnvWorker(python, "venv", "pyvenv.cfg", false);
}
[TestMethod, Priority(1)]
[TestCategory("10s")]
public void ImportWizardBrokenVirtualEnv() {
var python = PythonPaths.Versions.LastOrDefault(pv =>
pv.IsCPython &&
File.Exists(Path.Combine(pv.LibPath, "site-packages", "virtualenv.py")) &&
// CPython 3.3.4 does not work correctly with virtualenv, so
// skip testing on 3.3 to avoid false failures
pv.Version != PythonLanguageVersion.V33
);
ImportWizardVirtualEnvWorker(python, "virtualenv", "lib\\orig-prefix.txt", true);
}
[TestMethod, Priority(1)]
[TestCategory("10s")]
public void ImportWizardBrokenVEnv() {
var python = PythonPaths.Versions.LastOrDefault(pv =>
pv.IsCPython && File.Exists(Path.Combine(pv.LibPath, "venv", "__main__.py"))
);
ImportWizardVirtualEnvWorker(python, "venv", "pyvenv.cfg", true);
}
private static void ImportWizardCustomizationsWorker(ProjectCustomization customization, Action<XDocument> verify) {
using (var wpf = new WpfProxy()) {
var settings = wpf.Create(() => new ImportSettings(null, null));
settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
settings.Filters = "*.py;*.pyproj";
settings.StartupFile = "Program.py";
settings.UseCustomization = true;
settings.Customization = customization;
settings.ProjectPath = Path.Combine(TestData.GetTempPath("ImportWizardCustomizations_" + customization.GetType().Name), "Project.pyproj");
Directory.CreateDirectory(Path.GetDirectoryName(settings.ProjectPath));
string path = CreateRequestedProject(settings);
Assert.AreEqual(settings.ProjectPath, path);
Console.WriteLine(File.ReadAllText(path));
var proj = XDocument.Load(path);
verify(proj);
}
}
[TestMethod, Priority(1)]
public void ImportWizardCustomizations() {
ImportWizardCustomizationsWorker(DefaultProjectCustomization.Instance, proj => {
Assert.AreEqual("Program.py", proj.Descendant("StartupFile").Value);
Assert.IsTrue(proj.Descendants(proj.GetName("Import")).Any(d => d.Attribute("Project").Value == "$(PtvsTargetsFile)"));
});
ImportWizardCustomizationsWorker(BottleProjectCustomization.Instance, proj => {
Assert.AreNotEqual(-1, proj.Descendant("ProjectTypeGuids").Value.IndexOf("e614c764-6d9e-4607-9337-b7073809a0bd", StringComparison.OrdinalIgnoreCase));
Assert.IsTrue(proj.Descendants(proj.GetName("Import")).Any(d => d.Attribute("Project").Value.Contains("Web.targets")));
Assert.AreEqual("Web launcher", proj.Descendant("LaunchProvider").Value);
});
ImportWizardCustomizationsWorker(DjangoProjectCustomization.Instance, proj => {
Assert.AreNotEqual(-1, proj.Descendant("ProjectTypeGuids").Value.IndexOf("5F0BE9CA-D677-4A4D-8806-6076C0FAAD37", StringComparison.OrdinalIgnoreCase));
Assert.IsTrue(proj.Descendants(proj.GetName("Import")).Any(d => d.Attribute("Project").Value.Contains("Django.targets")));
Assert.AreEqual("Django launcher", proj.Descendant("LaunchProvider").Value);
});
ImportWizardCustomizationsWorker(FlaskProjectCustomization.Instance, proj => {
Assert.AreNotEqual(-1, proj.Descendant("ProjectTypeGuids").Value.IndexOf("789894c7-04a9-4a11-a6b5-3f4435165112", StringComparison.OrdinalIgnoreCase));
Assert.IsTrue(proj.Descendants(proj.GetName("Import")).Any(d => d.Attribute("Project").Value.Contains("Web.targets")));
Assert.AreEqual("Web launcher", proj.Descendant("LaunchProvider").Value);
});
}
static T Wait<T>(System.Threading.Tasks.Task<T> task) {
task.Wait();
return task.Result;
}
[TestMethod, Priority(1)]
public void ImportWizardCandidateStartupFiles() {
var sourcePath = TestData.GetTempPath(randomSubPath: true);
// Create a fake set of files to import
File.WriteAllText(Path.Combine(sourcePath, "a.py"), "");
File.WriteAllText(Path.Combine(sourcePath, "b.py"), "");
File.WriteAllText(Path.Combine(sourcePath, "c.py"), "");
File.WriteAllText(Path.Combine(sourcePath, "a.pyw"), "");
File.WriteAllText(Path.Combine(sourcePath, "b.pyw"), "");
File.WriteAllText(Path.Combine(sourcePath, "c.pyw"), "");
File.WriteAllText(Path.Combine(sourcePath, "a.txt"), "");
File.WriteAllText(Path.Combine(sourcePath, "b.txt"), "");
File.WriteAllText(Path.Combine(sourcePath, "c.txt"), "");
AssertUtil.ContainsExactly(Wait(ImportSettings.GetCandidateStartupFiles(sourcePath, "")),
"a.py",
"b.py",
"c.py"
);
AssertUtil.ContainsExactly(Wait(ImportSettings.GetCandidateStartupFiles(sourcePath, "*.pyw")),
"a.py",
"b.py",
"c.py",
"a.pyw",
"b.pyw",
"c.pyw"
);
AssertUtil.ContainsExactly(Wait(ImportSettings.GetCandidateStartupFiles(sourcePath, "b.pyw")),
"a.py",
"b.py",
"c.py",
"b.pyw"
);
AssertUtil.ContainsExactly(Wait(ImportSettings.GetCandidateStartupFiles(sourcePath, "*.txt")),
"a.py",
"b.py",
"c.py"
);
}
[TestMethod, Priority(1)]
public void ImportWizardDefaultStartupFile() {
var files = new[] { "a.py", "b.py", "c.py" };
var expectedDefault = files[0];
Assert.AreEqual(expectedDefault, ImportSettings.SelectDefaultStartupFile(files, null));
Assert.AreEqual(expectedDefault, ImportSettings.SelectDefaultStartupFile(files, "not in list"));
Assert.AreEqual("b.py", ImportSettings.SelectDefaultStartupFile(files, "b.py"));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype01.gettype01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype01.gettype01;
// <Area>variance</Area>
// <Title> Expression based tests</Title>
// <Description> getType tests</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Tiger>();
iVariance<Animal> v2 = v1;
dynamic v3 = (iVariance<Animal>)v1;
if (typeof(Variance<Tiger>).ToString() != v2.GetType().ToString())
return 1;
if (typeof(Variance<Tiger>).ToString() != v3.GetType().ToString())
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype02.gettype02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype02.gettype02;
// <Area>variance</Area>
// <Title> Expression based tests</Title>
// <Description> getType tests</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<in T>
{
void Boo(T t);
}
public class Variance<T> : iVariance<T>
{
public void Boo(T t)
{
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Animal>();
iVariance<Tiger> v2 = v1;
dynamic v3 = (iVariance<Tiger>)v1;
if (typeof(Variance<Animal>).ToString() != v2.GetType().ToString())
return 1;
if (typeof(Variance<Animal>).ToString() != v3.GetType().ToString())
return 1;
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype03.gettype03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype03.gettype03;
// <Area>variance</Area>
// <Title> Expression based tests</Title>
// <Description> getType tests</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Animal>)((Animal a) =>
{
}
);
Foo<Tiger> f2 = f1;
dynamic f3 = (Foo<Tiger>)f1;
if (typeof(Foo<Animal>).ToString() != f2.GetType().ToString())
return 1;
if (typeof(Foo<Animal>).ToString() != f3.GetType().ToString())
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype04.gettype04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype04.gettype04;
// <Area>variance</Area>
// <Title> Expression based tests</Title>
// <Description> getType tests</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate T Foo<out T>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Tiger>)(() =>
{
return new Tiger();
}
);
Foo<Animal> f2 = f1;
dynamic f3 = (Foo<Animal>)f1;
if (typeof(Foo<Tiger>).ToString() != f2.GetType().ToString())
return 1;
if (typeof(Foo<Tiger>).ToString() != f3.GetType().ToString())
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is01.is01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is01.is01;
// <Area>variance</Area>
// <Title> expressions - Is Keyword</Title>
// <Description> using the is keyword on a covariant public interface </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Tiger>();
iVariance<Animal> v2 = v1;
dynamic v3 = (iVariance<Animal>)v1;
if (!(v2 is iVariance<Animal>))
return 1;
if (!(v3 is iVariance<Animal>))
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is02.is02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is02.is02;
// <Area>variance</Area>
// <Title> expressions - Is Keyword</Title>
// <Description> using the is keyword on a covariant public interface </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Variance<Tiger> v1 = new Variance<Tiger>();
iVariance<Animal> v2 = v1;
dynamic v3 = (iVariance<Animal>)v1;
if (!(v2 is iVariance<Animal>))
return 1;
if (!(v3 is iVariance<Animal>))
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is03.is03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is03.is03;
// <Area>variance</Area>
// <Title> expressions - is keyword</Title>
// <Description> is keyword with contravariant delegates</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Animal>)((Animal a) =>
{
}
);
Foo<Tiger> f2 = f1;
dynamic f3 = (Foo<Tiger>)f1;
if (!(f2 is Foo<Tiger>))
return 1;
if (!(f3 is Foo<Tiger>))
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is04.is04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is04.is04;
// <Area>variance</Area>
// <Title> expressions - is keyword</Title>
// <Description> is keyword with contravariant delegates</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
private delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Foo<Animal> f1 = (Animal a) =>
{
}
;
Foo<Tiger> f2 = f1;
dynamic f3 = (Foo<Tiger>)f1;
if (!(f2 is Foo<Animal>))
return 1;
if (!(f3 is Foo<Animal>))
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is05.is05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is05.is05;
// <Area>variance</Area>
// <Title> expressions - Is Keyword</Title>
// <Description> using the is keyword on a covariant public interface </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Tiger>();
iVariance<Animal> v2 = v1;
if (v1 is iVariance<Animal>)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is06.is06
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is06.is06;
// <Area>variance</Area>
// <Title> expressions - Is Keyword</Title>
// <Description> using the is keyword on a covariant public interface </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Tiger>();
iVariance<Animal> v2 = v1;
if (v1 is iVariance<Tiger>)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is07.is07
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is07.is07;
// <Area>variance</Area>
// <Title> expressions - is keyword</Title>
// <Description> is keyword with contravariant delegates</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Animal>)((Animal a) =>
{
}
);
Foo<Tiger> f2 = f1;
if (f1 is Foo<Tiger>)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is08.is08
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is08.is08;
// <Area>variance</Area>
// <Title> expressions - is keyword</Title>
// <Description> is keyword with contravariant delegates</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Animal>)((Animal a) =>
{
}
);
Foo<Tiger> f2 = f1;
if (f1 is Foo<Animal>)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is09.is09
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is09.is09;
// <Area>variance</Area>
// <Title> expressions - Is Keyword</Title>
// <Description> using the is keyword on a invariant public interface </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Tiger>();
if (v1 is iVariance<Animal>)
return 1;
else
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is10.is10
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is10.is10;
// <Area>variance</Area>
// <Title> expressions - Is Keyword</Title>
// <Description> using the is keyword on a invariant public interface </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Tiger>();
if (v1 is iVariance<Tiger>)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is11.is11
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is11.is11;
// <Area>variance</Area>
// <Title> expressions - is keyword</Title>
// <Description> is keyword with contravariant delegates</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
private delegate void Foo<T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Animal>)((Animal a) =>
{
}
);
if (f1 is Foo<Tiger>)
return 1;
else
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is12.is12
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is12.is12;
// <Area>variance</Area>
// <Title> expressions - is keyword</Title>
// <Description> is keyword with invariant delegates</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
private delegate void Foo<T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Animal>)((Animal a) =>
{
}
);
if (f1 is Foo<Animal>)
return 0;
else
return 1;
}
}
//</Code>
}
| |
// 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.Linq;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Xunit;
namespace TypeSystemTests
{
public class StaticFieldLayoutTests
{
TestTypeSystemContext _context;
ModuleDesc _testModule;
public StaticFieldLayoutTests()
{
_context = new TestTypeSystemContext(TargetArchitecture.X64);
var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly");
_context.SetSystemModule(systemModule);
_testModule = systemModule;
}
[Fact]
public void TestNoPointers()
{
MetadataType t = _testModule.GetType("StaticFieldLayout", "NoPointers");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "int1":
Assert.Equal(0, field.Offset);
break;
case "byte1":
Assert.Equal(4, field.Offset);
break;
case "char1":
Assert.Equal(6, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestStillNoPointers()
{
//
// Test that static offsets ignore instance fields preceeding them
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "StillNoPointers");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "bool1":
Assert.Equal(0, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestClassNoPointers()
{
//
// Ensure classes behave the same as structs when containing statics
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "ClassNoPointers");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "int1":
Assert.Equal(0, field.Offset);
break;
case "byte1":
Assert.Equal(4, field.Offset);
break;
case "char1":
Assert.Equal(6, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestHasPointers()
{
//
// Test a struct containing static types with pointers
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "HasPointers");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "string1":
Assert.Equal(8, field.Offset);
break;
case "class1":
Assert.Equal(16, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestMixPointersAndNonPointers()
{
//
// Test that static fields with GC pointers get separate offsets from non-GC fields
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "MixPointersAndNonPointers");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "string1":
Assert.Equal(8, field.Offset);
break;
case "int1":
Assert.Equal(0, field.Offset);
break;
case "class1":
Assert.Equal(16, field.Offset);
break;
case "int2":
Assert.Equal(4, field.Offset);
break;
case "string2":
Assert.Equal(24, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestEnsureInheritanceResetsStaticOffsets()
{
//
// Test that when inheriting a class with static fields, the derived slice's static fields
// are again offset from 0
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "EnsureInheritanceResetsStaticOffsets");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "int3":
Assert.Equal(0, field.Offset);
break;
case "string3":
Assert.Equal(8, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestLiteralFieldsDontAffectLayout()
{
//
// Test that literal fields are not laid out.
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "LiteralFieldsDontAffectLayout");
Assert.Equal(4, t.GetFields().Count());
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "IntConstant":
case "StringConstant":
Assert.True(field.IsStatic);
Assert.True(field.IsLiteral);
break;
case "Int1":
Assert.Equal(0, field.Offset);
break;
case "String1":
Assert.Equal(8, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestStaticSelfRef()
{
//
// Test that we can load a struct which has a static field referencing itself without
// going into an infinite loop
//
MetadataType t = _testModule.GetType("StaticFieldLayout", "StaticSelfRef");
foreach (var field in t.GetFields())
{
if (!field.IsStatic)
continue;
switch (field.Name)
{
case "selfRef1":
Assert.Equal(0, field.Offset);
break;
default:
throw new Exception(field.Name);
}
}
}
[Fact]
public void TestRvaStatics()
{
//
// Test that an RVA mapped field has the right value for the offset.
//
var ilModule = _context.GetModuleForSimpleName("ILTestAssembly");
var t = ilModule.GetType("StaticFieldLayout", "RvaStatics");
var field = t.GetField("StaticInitedInt");
Assert.True(field.HasRva);
byte[] rvaData = ((EcmaField)field).GetFieldRvaData();
Assert.Equal(4, rvaData.Length);
int value = rvaData[0] |
rvaData[1] << 8 |
rvaData[2] << 16 |
rvaData[3] << 24;
Assert.Equal(0x78563412, value);
}
[Fact]
public void TestFunctionPointer()
{
//
// Test layout with a function pointer typed-field.
//
var ilModule = _context.GetModuleForSimpleName("ILTestAssembly");
var t = ilModule.GetType("StaticFieldLayout", "FunctionPointerType");
var field = t.GetField("StaticMethodField");
Assert.Equal(8, field.Offset);
Assert.False(field.HasGCStaticBase);
}
}
}
| |
// Original source code: https://gitlab.com/kenjiuno/khkh_xldM/blob/master/khkh_xldMii/Mdlxfst.cs
using OpenKh.Common;
using OpenKh.Common.Ps2;
using OpenKh.Common.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xe.BinaryMapper;
namespace OpenKh.Kh2
{
public partial class Mdlx
{
public class SubModelMapHeader
{
[Data] public int Type { get; set; }
[Data] public int Unk04 { get; set; }
[Data] public int Unk08 { get; set; }
[Data] public int NextOffset { get; set; }
[Data] public int DmaChainMapCount { get; set; }
[Data] public short va4 { get; set; }
[Data] public short CountVifPacketRenderingGroup { get; set; }
[Data] public int OffsetVifPacketRenderingGroup { get; set; }
[Data] public int OffsetToOffsetDmaChainIndexRemapTable { get; set; }
}
private class DmaChainMap
{
[Data] public int VifOffset { get; set; }
[Data] public int TextureIndex { get; set; }
[Data] public short Unk08 { get; set; }
[Data] public short IsTransparentFlag { get; set; }
[Data] public int Unk0c { get; set; }
public bool EnableUvsc
{
get => BitsUtil.Int.GetBit(Unk0c, 1);
set => Unk0c = BitsUtil.Int.SetBit(Unk0c, 1, value);
}
public int UvscIndex
{
get => BitsUtil.Int.GetBits(Unk0c, 2, 4);
set => Unk0c = BitsUtil.Int.SetBits(Unk0c, 2, 4, value);
}
}
public class M4
{
public int unk04;
public int unk08;
public int nextOffset;
public short va4;
public List<ushort> DmaChainIndexRemapTable;
public List<ushort[]> vifPacketRenderingGroup;
public List<VifPacketDescriptor> VifPackets;
}
public class VifPacketDescriptor
{
public byte[] VifPacket { get; set; }
public int TextureId { get; set; }
public short Unk08 { get; set; }
public short IsTransparentFlag { get; set; }
public int Unk0c { get; set; }
public ushort[] DmaPerVif { get; set; }
public bool EnableUvsc
{
get => BitsUtil.Int.GetBit(Unk0c, 1);
set => Unk0c = BitsUtil.Int.SetBit(Unk0c, 1, value);
}
public int UvscIndex
{
get => BitsUtil.Int.GetBits(Unk0c, 2, 4);
set => Unk0c = BitsUtil.Int.SetBits(Unk0c, 2, 4, value);
}
}
private static M4 ReadAsMap(Stream stream)
{
var header = BinaryMapping.ReadObject<SubModelMapHeader>(stream);
if (header.Type != Map) throw new NotSupportedException("Type must be 2 for maps");
var dmaChainMaps = For(header.DmaChainMapCount, () => BinaryMapping.ReadObject<DmaChainMap>(stream));
stream.Position = header.OffsetVifPacketRenderingGroup;
// The original game engine ignores header.Count1 for some reason
var count1 = (short)((stream.ReadInt32() - header.OffsetVifPacketRenderingGroup) / 4);
stream.Position -= 4;
var vifPacketRenderingGroup = For(count1, () => stream.ReadInt32())
.Select(offset => ReadUInt16List(stream.SetPosition(offset)).ToArray())
.ToList();
stream.Position = header.OffsetToOffsetDmaChainIndexRemapTable;
var offsetDmaChainIndexRemapTable = stream.ReadInt32();
stream.Position = offsetDmaChainIndexRemapTable;
var dmaChainIndexRemapTable = ReadUInt16List(stream)
.ToList();
var vifPackets = dmaChainMaps
.Select(dmaChain =>
{
var currentVifOffset = dmaChain.VifOffset;
DmaTag dmaTag;
var packet = new List<byte>();
var sizePerDma = new List<ushort>();
do
{
stream.Position = currentVifOffset;
dmaTag = BinaryMapping.ReadObject<DmaTag>(stream);
var packets = stream.ReadBytes(8 + 16 * dmaTag.Qwc);
packet.AddRange(packets);
sizePerDma.Add(dmaTag.Qwc);
currentVifOffset += 16 + 16 * dmaTag.Qwc;
} while (dmaTag.TagId < 2);
return new VifPacketDescriptor
{
VifPacket = packet.ToArray(),
TextureId = dmaChain.TextureIndex,
Unk08 = dmaChain.Unk08,
IsTransparentFlag = dmaChain.IsTransparentFlag,
Unk0c = dmaChain.Unk0c,
DmaPerVif = sizePerDma.ToArray(),
};
})
.ToList();
return new M4
{
unk04 = header.Unk04,
unk08 = header.Unk08,
nextOffset = header.NextOffset,
va4 = header.va4,
vifPacketRenderingGroup = vifPacketRenderingGroup,
DmaChainIndexRemapTable = dmaChainIndexRemapTable,
VifPackets = vifPackets
};
}
private static void WriteAsMap(Stream stream, M4 mapModel)
{
var mapHeader = new SubModelMapHeader
{
Type = Map,
DmaChainMapCount = mapModel.VifPackets.Count,
Unk04 = mapModel.unk04,
Unk08 = mapModel.unk08,
NextOffset = mapModel.nextOffset,
va4 = mapModel.va4,
CountVifPacketRenderingGroup = Convert.ToInt16(mapModel.vifPacketRenderingGroup.Count),
};
BinaryMapping.WriteObject(stream, mapHeader);
var dmaChainMapDescriptorOffset = (int)stream.Position;
stream.Position += mapModel.VifPackets.Count * 0x10;
mapHeader.OffsetVifPacketRenderingGroup = (int)stream.Position;
stream.Position += mapModel.vifPacketRenderingGroup.Count * 4;
var groupOffsets = new List<int>();
foreach (var group in mapModel.vifPacketRenderingGroup)
{
groupOffsets.Add((int)stream.Position);
WriteUInt16List(stream, group);
}
// capture remapTable offset here
var remapTableOffsetToOffset = Helpers.Align((int)stream.Position, 4);
// seek back and fill offsets
stream.Position = mapHeader.OffsetVifPacketRenderingGroup;
foreach (var offset in groupOffsets)
stream.Write(offset);
// write remapTable here
stream.Position = remapTableOffsetToOffset;
mapHeader.OffsetToOffsetDmaChainIndexRemapTable = remapTableOffsetToOffset;
var remapTableOffset = remapTableOffsetToOffset + 4;
stream.Write(remapTableOffset);
WriteUInt16List(stream, mapModel.DmaChainIndexRemapTable);
stream.AlignPosition(0x10);
var dmaChainVifOffsets = new List<int>();
foreach (var dmaChainMap in mapModel.VifPackets)
{
var vifPacketIndex = 0;
dmaChainVifOffsets.Add((int)stream.Position);
foreach (var packetCount in dmaChainMap.DmaPerVif)
{
BinaryMapping.WriteObject(stream, new DmaTag
{
Qwc = packetCount,
Address = 0,
TagId = packetCount > 0 ? 1 : 6,
Irq = false,
});
var packetLength = packetCount * 0x10 + 8;
stream.Write(dmaChainMap.VifPacket, vifPacketIndex, packetLength);
vifPacketIndex += packetLength;
}
}
stream.AlignPosition(0x80);
stream.SetLength(stream.Position);
stream.Position = dmaChainMapDescriptorOffset;
for (var i = 0; i < mapModel.VifPackets.Count; i++)
{
var dmaChainMap = mapModel.VifPackets[i];
BinaryMapping.WriteObject(stream, new DmaChainMap
{
VifOffset = dmaChainVifOffsets[i],
TextureIndex = dmaChainMap.TextureId,
Unk08 = dmaChainMap.Unk08,
IsTransparentFlag = dmaChainMap.IsTransparentFlag,
Unk0c = dmaChainMap.Unk0c,
EnableUvsc = dmaChainMap.EnableUvsc,
UvscIndex = dmaChainMap.UvscIndex,
});
}
stream.Position = 0;
BinaryMapping.WriteObject(stream, mapHeader);
}
private static IEnumerable<ushort> ReadUInt16List(Stream stream)
{
while (true)
{
var data = stream.ReadUInt16();
if (data == 0xFFFF) break;
yield return data;
}
}
private static void WriteUInt16List(Stream stream, IEnumerable<ushort> alb2t2)
{
foreach (var data in alb2t2)
stream.Write(data);
stream.Write((ushort)0xFFFF);
}
}
}
| |
/*
* Naiad ver. 0.5
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using Microsoft.Research.Naiad.DataStructures;
using Microsoft.Research.Naiad;
using Microsoft.Research.Naiad.Dataflow;
namespace Microsoft.Research.Naiad.Frameworks.DifferentialDataflow.Operators
{
#if true
internal class Min<K, V, M, S, T> : OperatorImplementations.ConservativeUnaryStatefulOperator<K, V, S, T, S>
where K : IEquatable<K>
where V : IEquatable<V>
where S : IEquatable<S>
where M : IComparable<M>
where T : Microsoft.Research.Naiad.Time<T>
{
Func<K, V, M> valueSelector;
Func<K, V, S> resultSelector;
protected override void Reduce(K key, UnaryKeyIndices keyIndices, int timeIndex)
{
var minFound = false;
var minValue = default(M);
var minEntry = default(V);
collection.Clear();
inputTrace.EnumerateCollectionAt(keyIndices.processed, timeIndex, collection);
for (int i = 0; i < collection.Count; i++)
{
var element = collection.Array[i];
if (element.weight > 0)
{
var value = valueSelector(key, element.record);
if (minFound == false || minValue.CompareTo(value) > 0)
{
minFound = true;
minValue = value;
minEntry = element.record;
}
}
}
if (minFound)
outputTrace.Introduce(ref outputWorkspace, resultSelector(key, minEntry), 1, timeIndex);
}
public Min(int index, Stage<T> collection, bool inputImmutable, Expression<Func<S, K>> k, Expression<Func<S, V>> e, Expression<Func<K, V, M>> v, Expression<Func<K, V, S>> r)
: base(index, collection, inputImmutable, k, e)
{
valueSelector = v.Compile();
resultSelector = r.Compile();
}
}
#else
internal class Min<K, V, M, S, T> : OperatorImplementations.UnaryStatefulOperator<K, V, S, T, S>
where K : IEquatable<K>
where V : IEquatable<V>
where S : IEquatable<S>
where M : IEquatable<M>, IComparable<M>
where T : Naiad.Time<T>
{
Func<K, V, M> minBySelector;
Func<K, V, S> resultSelector;
protected override void NewOutputMinusOldOutput(K key, UnaryKeyIndices keyIndices, int timeIndex)
{
var oldFound = false;
var oldValue = default(M);
var oldEntry = default(S);
var oldWeight = 0L;
toSend.Clear();
outputTrace.EnumerateCollectionAt(keyIndices.output, timeIndex, toSend);
for (int i = 0; i < toSend.Count; i++)
{
oldFound = true;
oldEntry = toSend.Array[i].record;
oldWeight = toSend.Array[i].weight;
oldValue = minBySelector(key, value(oldEntry)); // something to be non-maxvalue
}
var minFound = false;
var minValue = default(M);
var minEntry = default(V);
var newEntry = default(S);
var minStable = true;
difference.Clear();
inputTrace.EnumerateCollectionAt(keyIndices.unprocessed, timeIndex, difference);
for (int i = 0; i < difference.Count; i++)
{
var entry = difference.Array[i];
if (entry.weight != 0)
{
var value = minBySelector(key, entry.record);
if (((value.CompareTo(oldValue) < 0 || !oldFound) && entry.weight > 0) || (value.Equals(oldValue) && entry.weight <= 0))
minStable = false;
}
}
// only want to do this if we really need to.
if (!minStable)
{
collection.Clear();
inputTrace.EnumerateCollectionAt(keyIndices.processed, timeIndex, collection);
for (int i = 0; i < collection.Count; i++)
{
var element = collection.Array[i];
if (element.weight > 0)
{
var value = minBySelector(key, element.record);
if (minValue.CompareTo(value) > 0 || minFound == false)
{
minFound = true;
minValue = value;
minEntry = element.record;
}
}
}
if (minFound)
newEntry = resultSelector(key, minEntry);
// if they are the same record, and both going to be output, we don't need to produce them.
if (!(newEntry.Equals(oldEntry) && oldFound && minFound))
{
if (oldFound)
outputTrace.Introduce(ref outputWorkspace, oldEntry, -1, timeIndex);
if (minFound)
outputTrace.Introduce(ref outputWorkspace, newEntry, +1, timeIndex);
}
}
}
public Min(int index, Stage<T> collection, bool inputImmutable, Expression<Func<S, K>> k, Expression<Func<S, V>> e, Expression<Func<K, V, M>> v, Expression<Func<K, V, S>> r)
: base(index, collection, inputImmutable, k, e)
{
minBySelector = v.Compile();
resultSelector = r.Compile();
}
}
#endif
internal class MinIntKeyed<V, M, S, T> : OperatorImplementations.UnaryStatefulIntKeyedOperator<V, S, T, S>
where V : IEquatable<V>
where M : IEquatable<M>, IComparable<M>
where S : IEquatable<S>
where T : Time<T>
{
Func<int, V, M> valueSelector;
Func<int, V, S> resultSelector;
#if true
protected override void NewOutputMinusOldOutput(int index, UnaryKeyIndices keyIndices, int timeIndex)
{
var key = index * this.Stage.Placement.Count + this.VertexId;
var oldFound = false;
var oldValue = default(M);
var oldEntry = default(S);
//var oldWeight = 0L;
toSend.Clear();
outputTrace.EnumerateCollectionAt(keyIndices.output, timeIndex, toSend);
for (int i = 0; i < toSend.Count; i++)
{
oldFound = true;
oldEntry = toSend.Array[i].record;
//oldWeight = toSend.Array[i].weight;
oldValue = valueSelector(key, value(oldEntry)); // something to be non-maxvalue
}
var minFound = false;
var minValue = default(M);
var minEntry = default(V);
var newEntry = default(S);
var minStable = true;
difference.Clear();
inputTrace.EnumerateCollectionAt(keyIndices.unprocessed, timeIndex, difference);
for (int i = 0; i < difference.Count; i++)
{
var entry = difference.Array[i];
if (entry.weight != 0)
{
var value = valueSelector(key, entry.record);
if (((value.CompareTo(oldValue) < 0 || !oldFound)&& entry.weight > 0) || (value.Equals(oldValue) && entry.weight <= 0))
minStable = false;
}
}
// only want to do this if we really need to.
if (!minStable)
{
collection.Clear();
inputTrace.EnumerateCollectionAt(keyIndices.processed, timeIndex, collection);
for (int i = 0; i < collection.Count; i++)
{
var element = collection.Array[i];
if (element.weight > 0)
{
var value = valueSelector(key, element.record);
if (minValue.CompareTo(value) > 0 || minFound == false)
{
minFound = true;
minValue = value;
minEntry = element.record;
}
}
}
if (minFound)
newEntry = resultSelector(key, minEntry);
// if they are the same record, and both going to be output, we don't need to produce them.
if (!(newEntry.Equals(oldEntry) && oldFound && minFound))
{
if (oldFound)
outputTrace.Introduce(ref outputWorkspace, oldEntry, -1, timeIndex);
if (minFound)
outputTrace.Introduce(ref outputWorkspace, newEntry, +1, timeIndex);
}
}
}
#endif
public MinIntKeyed(int index, Stage<T> collection, bool inputImmutable, Expression<Func<S, int>> k, Expression<Func<S, V>> e, Expression<Func<int, V, M>> v, Expression<Func<int, V, S>> r)
: base(index, collection, inputImmutable, k, e)
{
valueSelector = v.Compile();
resultSelector = r.Compile();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Xsl.XsltOld
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Xml;
using System.Globalization;
internal class HtmlElementProps
{
private bool _empty;
private bool _abrParent;
private bool _uriParent;
private bool _noEntities;
private bool _blockWS;
private bool _head;
private bool _nameParent;
public static HtmlElementProps Create(bool empty, bool abrParent, bool uriParent, bool noEntities, bool blockWS, bool head, bool nameParent)
{
HtmlElementProps props = new HtmlElementProps();
props._empty = empty;
props._abrParent = abrParent;
props._uriParent = uriParent;
props._noEntities = noEntities;
props._blockWS = blockWS;
props._head = head;
props._nameParent = nameParent;
return props;
}
public bool Empty { get { return _empty; } }
public bool AbrParent { get { return _abrParent; } }
public bool UriParent { get { return _uriParent; } }
public bool NoEntities { get { return _noEntities; } }
public bool BlockWS { get { return _blockWS; } }
public bool Head { get { return _head; } }
public bool NameParent { get { return _nameParent; } }
private static Hashtable s_table = CreatePropsTable();
// private static HtmlElementProps s_otherElements = Create(false, false, false, false, false, false, false);
public static HtmlElementProps GetProps(string name)
{
HtmlElementProps result = (HtmlElementProps)s_table[name];
return result;
// We can do this but in case of Xml/Html mixed output this doesn't have big sence.
// return result != null ? result : s_otherElements;
}
private static Hashtable CreatePropsTable()
{
bool o = false, X = true;
Hashtable table = new Hashtable(71, StringComparer.OrdinalIgnoreCase);
{
// EMPTY ABR URI NO_ENT NO_WS HEAD NAME
table.Add("a", Create(o, o, X, o, o, o, X));
table.Add("address", Create(o, o, o, o, X, o, o));
table.Add("applet", Create(o, o, o, o, X, o, o));
table.Add("area", Create(X, X, X, o, X, o, o));
table.Add("base", Create(X, o, X, o, X, o, o));
table.Add("basefont", Create(X, o, o, o, X, o, o));
table.Add("blockquote", Create(o, o, X, o, X, o, o));
table.Add("body", Create(o, o, o, o, X, o, o));
table.Add("br", Create(X, o, o, o, o, o, o));
table.Add("button", Create(o, X, o, o, o, o, o));
table.Add("caption", Create(o, o, o, o, X, o, o));
table.Add("center", Create(o, o, o, o, X, o, o));
table.Add("col", Create(X, o, o, o, X, o, o));
table.Add("colgroup", Create(o, o, o, o, X, o, o));
table.Add("dd", Create(o, o, o, o, X, o, o));
table.Add("del", Create(o, o, X, o, X, o, o));
table.Add("dir", Create(o, X, o, o, X, o, o));
table.Add("div", Create(o, o, o, o, X, o, o));
table.Add("dl", Create(o, X, o, o, X, o, o));
table.Add("dt", Create(o, o, o, o, X, o, o));
table.Add("fieldset", Create(o, o, o, o, X, o, o));
table.Add("font", Create(o, o, o, o, X, o, o));
table.Add("form", Create(o, o, X, o, X, o, o));
table.Add("frame", Create(X, X, o, o, X, o, o));
table.Add("frameset", Create(o, o, o, o, X, o, o));
table.Add("h1", Create(o, o, o, o, X, o, o));
table.Add("h2", Create(o, o, o, o, X, o, o));
table.Add("h3", Create(o, o, o, o, X, o, o));
table.Add("h4", Create(o, o, o, o, X, o, o));
table.Add("h5", Create(o, o, o, o, X, o, o));
table.Add("h6", Create(o, o, o, o, X, o, o));
table.Add("head", Create(o, o, X, o, X, X, o));
table.Add("hr", Create(X, X, o, o, X, o, o));
table.Add("html", Create(o, o, o, o, X, o, o));
table.Add("iframe", Create(o, o, o, o, X, o, o));
table.Add("img", Create(X, X, X, o, o, o, o));
table.Add("input", Create(X, X, X, o, o, o, o));
table.Add("ins", Create(o, o, X, o, X, o, o));
table.Add("isindex", Create(X, o, o, o, X, o, o));
table.Add("legend", Create(o, o, o, o, X, o, o));
table.Add("li", Create(o, o, o, o, X, o, o));
table.Add("link", Create(X, o, X, o, X, o, o));
table.Add("map", Create(o, o, o, o, X, o, o));
table.Add("menu", Create(o, X, o, o, X, o, o));
table.Add("meta", Create(X, o, o, o, X, o, o));
table.Add("noframes", Create(o, o, o, o, X, o, o));
table.Add("noscript", Create(o, o, o, o, X, o, o));
table.Add("object", Create(o, X, X, o, o, o, o));
table.Add("ol", Create(o, X, o, o, X, o, o));
table.Add("optgroup", Create(o, X, o, o, X, o, o));
table.Add("option", Create(o, X, o, o, X, o, o));
table.Add("p", Create(o, o, o, o, X, o, o));
table.Add("param", Create(X, o, o, o, X, o, o));
table.Add("pre", Create(o, o, o, o, X, o, o));
table.Add("q", Create(o, o, X, o, o, o, o));
table.Add("s", Create(o, o, o, o, X, o, o));
table.Add("script", Create(o, X, X, X, o, o, o));
table.Add("select", Create(o, X, o, o, o, o, o));
table.Add("strike", Create(o, o, o, o, X, o, o));
table.Add("style", Create(o, o, o, X, X, o, o));
table.Add("table", Create(o, o, X, o, X, o, o));
table.Add("tbody", Create(o, o, o, o, X, o, o));
table.Add("td", Create(o, X, o, o, X, o, o));
table.Add("textarea", Create(o, X, o, o, o, o, o));
table.Add("tfoot", Create(o, o, o, o, X, o, o));
table.Add("th", Create(o, X, o, o, X, o, o));
table.Add("thead", Create(o, o, o, o, X, o, o));
table.Add("title", Create(o, o, o, o, X, o, o));
table.Add("tr", Create(o, o, o, o, X, o, o));
table.Add("ul", Create(o, X, o, o, X, o, o));
table.Add("xmp", Create(o, o, o, o, o, o, o));
}
return table;
}
}
internal class HtmlAttributeProps
{
private bool _abr;
private bool _uri;
private bool _name;
public static HtmlAttributeProps Create(bool abr, bool uri, bool name)
{
HtmlAttributeProps props = new HtmlAttributeProps();
props._abr = abr;
props._uri = uri;
props._name = name;
return props;
}
public bool Abr { get { return _abr; } }
public bool Uri { get { return _uri; } }
public bool Name { get { return _name; } }
private static Hashtable s_table = CreatePropsTable();
// private static HtmlElementProps s_otherAttributes = Create(false, false, false);
public static HtmlAttributeProps GetProps(string name)
{
HtmlAttributeProps result = (HtmlAttributeProps)s_table[name];
return result;
// We can do this but in case of Xml/Html mixed output this doesn't have big sence.
// return result != null ? result : s_otherElements;
}
private static Hashtable CreatePropsTable()
{
bool o = false, X = true;
Hashtable table = new Hashtable(26, StringComparer.OrdinalIgnoreCase);
{
// ABR URI NAME
table.Add("action", Create(o, X, o));
table.Add("checked", Create(X, o, o));
table.Add("cite", Create(o, X, o));
table.Add("classid", Create(o, X, o));
table.Add("codebase", Create(o, X, o));
table.Add("compact", Create(X, o, o));
table.Add("data", Create(o, X, o));
table.Add("datasrc", Create(o, X, o));
table.Add("declare", Create(X, o, o));
table.Add("defer", Create(X, o, o));
table.Add("disabled", Create(X, o, o));
table.Add("for", Create(o, X, o));
table.Add("href", Create(o, X, o));
table.Add("ismap", Create(X, o, o));
table.Add("longdesc", Create(o, X, o));
table.Add("multiple", Create(X, o, o));
table.Add("name", Create(o, o, X));
table.Add("nohref", Create(X, o, o));
table.Add("noresize", Create(X, o, o));
table.Add("noshade", Create(X, o, o));
table.Add("nowrap", Create(X, o, o));
table.Add("profile", Create(o, X, o));
table.Add("readonly", Create(X, o, o));
table.Add("selected", Create(X, o, o));
table.Add("src", Create(o, X, o));
table.Add("usemap", Create(o, X, o));
}
return table;
}
}
}
| |
using System;
using System.Reflection;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Xml.Serialization;
using CamBam;
using CamBam.CAD;
using CamBam.CAM;
using CamBam.Geom;
using CamBam.UI;
using CamBam.Values;
using Matmill;
namespace Trochomops
{
[Serializable]
public class MOPTrochopock : Trochomop, IIcon
{
//--- mop properties
protected double _min_stepover_percentage = 0.9;
//--- invisible and non-serializable properties
[XmlIgnore, Browsable(false)]
public override string MOPTypeName
{
get { return "TrochoPock"; }
}
[XmlIgnore, Browsable(false)]
public Image ActiveIconImage
{
get { return resources.cam_trochopock1;}
}
[XmlIgnore, Browsable(false)]
public string ActiveIconKey
{
get { return "cam_trochopock1"; }
}
[XmlIgnore, Browsable(false)]
public Image InactiveIconImage
{
get { return resources.cam_trochopock0;}
}
[XmlIgnore, Browsable(false)]
public string InactiveIconKey
{
get { return "cam_trochopock0"; }
}
//--- our own new parameters. No reason to make them CBValues, since they couldn't be styled anyway
[
CBAdvancedValue,
Category("Step Over"),
DefaultValue(0.9),
Description("Minimum allowed stepover as a percentage of the nominal stepover (0.1 - 0.9).\nLarger values may leave uncut corners"),
DisplayName("Minimum Stepover")
]
public double Min_stepover
{
get { return _min_stepover_percentage; }
set
{
_min_stepover_percentage = value;
if (value < 0.05 || value > 0.95)
{
_min_stepover_percentage = Math.Max(Math.Min(0.95, value), 0.05);
base.redraw_parameters();
}
}
}
private Sliced_path gen_pocket(ShapeListItem shape)
{
Polyline outline;
Polyline[] islands;
if (shape.Shape is Polyline)
{
outline = (Polyline)shape.Shape;
islands = new Polyline[] { };
}
else if (shape.Shape is CamBam.CAD.Region)
{
CamBam.CAD.Region reg = (CamBam.CAD.Region)shape.Shape;
outline = reg.OuterCurve;
islands = reg.HoleCurves;
}
else
{
return null;
}
Pocket_generator gen = new Pocket_generator(outline, islands);
gen.General_tolerance = is_inch_units() ? 0.001 / 25.4 : 0.001;
gen.Tool_d = base.ToolDiameter.Cached;
gen.Max_ted = base.ToolDiameter.Cached * _stepover.Cached;
gen.Min_ted = base.ToolDiameter.Cached * _stepover.Cached * _min_stepover_percentage;
gen.Startpoint = (Point2F)base.StartPoint.Cached;
gen.Margin = base.RoughingClearance.Cached;
if (_milling_direction.Cached == MillingDirectionOptions.Mixed || base.SpindleDirection.Cached == SpindleDirectionOptions.Off)
{
gen.Mill_direction = RotationDirection.Unknown; // means 'mixed' here
gen.Should_smooth_chords = false;
}
else
{
int dir = (int)(base.SpindleDirection.Cached);
if (_milling_direction.Cached == MillingDirectionOptions.Climb)
dir = -dir;
gen.Mill_direction = (RotationDirection)dir;
gen.Should_smooth_chords = _should_smooth_chords;
}
return gen.run();
}
protected override void _GenerateToolpathsWorker()
{
try
{
base.reset_toolpaths();
if (base.ToolDiameter.Cached == 0)
{
Logger.err("tool diameter is zero");
base.MachineOpStatus = MachineOpStatus.Errors;
return;
}
if (_stepover.Cached == 0 || _stepover.Cached > 1)
{
Logger.err("stepover should be > 0 and <= 1");
base.MachineOpStatus = MachineOpStatus.Errors;
return;
}
// XXX: is it needed ?
base.UpdateGeometryExtrema(base._CADFile);
base._CADFile.MachiningOptions.UpdateGeometryExtrema(base._CADFile);
ShapeList shapes = new ShapeList();
shapes.ApplyTransformations = true;
shapes.AddEntities(base._CADFile, base.PrimitiveIds);
shapes = shapes.DetectRegions();
bool found_opened_polylines = false;
for (int i = shapes.Count - 1; i >= 0; i--)
{
if (shapes[i].Shape is Polyline && ! ((Polyline)shapes[i].Shape).Closed)
{
found_opened_polylines = true;
shapes.RemoveAt(i);
}
}
if (found_opened_polylines)
{
Logger.warn("ignoring open polylines");
base.MachineOpStatus = MachineOpStatus.Warnings;
}
List<Sliced_path> trajectories = new List<Sliced_path>();
foreach (ShapeListItem shape in shapes)
{
Sliced_path traj = gen_pocket(shape);
if (traj != null)
trajectories.Add(traj);
}
if (trajectories.Count == 0)
return;
base.insert_toolpaths(trajectories);
if (base.MachineOpStatus == MachineOpStatus.Unknown)
{
base.MachineOpStatus = MachineOpStatus.OK;
}
}
catch (Exception ex)
{
base.MachineOpStatus = MachineOpStatus.Errors;
ThisApplication.HandleException(ex);
}
finally
{
base._GenerateToolpathsFinal();
}
}
public override MachineOp Clone()
{
return new MOPTrochopock(this);
}
public MOPTrochopock(MOPTrochopock src) : base(src)
{
Min_stepover = src.Min_stepover;
}
public MOPTrochopock()
{
}
public MOPTrochopock(CADFile CADFile, ICollection<Entity> plist) : base(CADFile, plist)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class zip_UpdateTests : ZipFileTestBase
{
[Theory]
[InlineData("normal.zip", "normal")]
[InlineData("fake64.zip", "small")]
[InlineData("empty.zip", "empty")]
[InlineData("appended.zip", "small")]
[InlineData("prepended.zip", "small")]
[InlineData("emptydir.zip", "emptydir")]
[InlineData("small.zip", "small")]
[InlineData("unicode.zip", "unicode")]
public static async Task UpdateReadNormal(string zipFile, string zipFolder)
{
IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream(zfile(zipFile)), zfolder(zipFolder), ZipArchiveMode.Update, requireExplicit: true, checkTimes: true);
}
[Fact]
public static async Task UpdateReadTwice()
{
using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(zfile("small.zip")), ZipArchiveMode.Update))
{
ZipArchiveEntry entry = archive.Entries[0];
string contents1, contents2;
using (StreamReader s = new StreamReader(entry.Open()))
{
contents1 = s.ReadToEnd();
}
using (StreamReader s = new StreamReader(entry.Open()))
{
contents2 = s.ReadToEnd();
}
Assert.Equal(contents1, contents2);
}
}
[InlineData("normal")]
[InlineData("empty")]
[InlineData("unicode")]
public static async Task UpdateCreate(string zipFolder)
{
var zs = new LocalMemoryStream();
await CreateFromDir(zfolder(zipFolder), zs, ZipArchiveMode.Update);
IsZipSameAsDir(zs.Clone(), zfolder(zipFolder), ZipArchiveMode.Read, requireExplicit: true, checkTimes: true);
}
[Theory]
[InlineData(ZipArchiveMode.Create)]
[InlineData(ZipArchiveMode.Update)]
public static void EmptyEntryTest(ZipArchiveMode mode)
{
string data1 = "test data written to file.";
string data2 = "more test data written to file.";
DateTimeOffset lastWrite = new DateTimeOffset(1992, 4, 5, 12, 00, 30, new TimeSpan(-5, 0, 0));
var baseline = new LocalMemoryStream();
using (ZipArchive archive = new ZipArchive(baseline, mode))
{
AddEntry(archive, "data1.txt", data1, lastWrite);
ZipArchiveEntry e = archive.CreateEntry("empty.txt");
e.LastWriteTime = lastWrite;
using (Stream s = e.Open()) { }
AddEntry(archive, "data2.txt", data2, lastWrite);
}
var test = new LocalMemoryStream();
using (ZipArchive archive = new ZipArchive(test, mode))
{
AddEntry(archive, "data1.txt", data1, lastWrite);
ZipArchiveEntry e = archive.CreateEntry("empty.txt");
e.LastWriteTime = lastWrite;
AddEntry(archive, "data2.txt", data2, lastWrite);
}
//compare
Assert.True(ArraysEqual(baseline.ToArray(), test.ToArray()), "Arrays didn't match");
//second test, this time empty file at end
baseline = baseline.Clone();
using (ZipArchive archive = new ZipArchive(baseline, mode))
{
AddEntry(archive, "data1.txt", data1, lastWrite);
ZipArchiveEntry e = archive.CreateEntry("empty.txt");
e.LastWriteTime = lastWrite;
using (Stream s = e.Open()) { }
}
test = test.Clone();
using (ZipArchive archive = new ZipArchive(test, mode))
{
AddEntry(archive, "data1.txt", data1, lastWrite);
ZipArchiveEntry e = archive.CreateEntry("empty.txt");
e.LastWriteTime = lastWrite;
}
//compare
Assert.True(ArraysEqual(baseline.ToArray(), test.ToArray()), "Arrays didn't match after update");
}
[Fact]
public static async Task DeleteAndMoveEntries()
{
//delete and move
var testArchive = await StreamHelpers.CreateTempCopyStream(zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
ZipArchiveEntry toBeDeleted = archive.GetEntry("binary.wmv");
toBeDeleted.Delete();
toBeDeleted.Delete(); //delete twice should be okay
ZipArchiveEntry moved = archive.CreateEntry("notempty/secondnewname.txt");
ZipArchiveEntry orig = archive.GetEntry("notempty/second.txt");
using (Stream origMoved = orig.Open(), movedStream = moved.Open())
{
origMoved.CopyTo(movedStream);
}
moved.LastWriteTime = orig.LastWriteTime;
orig.Delete();
}
IsZipSameAsDir(testArchive, zmodified("deleteMove"), ZipArchiveMode.Read, requireExplicit: true, checkTimes: true);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public static async Task AppendToEntry(bool writeWithSpans)
{
//append
Stream testArchive = await StreamHelpers.CreateTempCopyStream(zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
ZipArchiveEntry e = archive.GetEntry("first.txt");
using (Stream s = e.Open())
{
s.Seek(0, SeekOrigin.End);
byte[] data = Encoding.ASCII.GetBytes("\r\n\r\nThe answer my friend, is blowin' in the wind.");
if (writeWithSpans)
{
s.Write(data, 0, data.Length);
}
else
{
s.Write(new ReadOnlySpan<byte>(data));
}
}
var file = FileData.GetFile(zmodified(Path.Combine("append", "first.txt")));
e.LastWriteTime = file.LastModifiedDate;
}
IsZipSameAsDir(testArchive, zmodified("append"), ZipArchiveMode.Read, requireExplicit: true, checkTimes: true);
}
[Fact]
public static async Task OverwriteEntry()
{
//Overwrite file
Stream testArchive = await StreamHelpers.CreateTempCopyStream(zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
string fileName = zmodified(Path.Combine("overwrite", "first.txt"));
ZipArchiveEntry e = archive.GetEntry("first.txt");
var file = FileData.GetFile(fileName);
e.LastWriteTime = file.LastModifiedDate;
using (var stream = await StreamHelpers.CreateTempCopyStream(fileName))
{
using (Stream es = e.Open())
{
es.SetLength(0);
stream.CopyTo(es);
}
}
}
IsZipSameAsDir(testArchive, zmodified("overwrite"), ZipArchiveMode.Read, requireExplicit: true, checkTimes: true);
}
[Fact]
public static async Task AddFileToArchive()
{
//add file
var testArchive = await StreamHelpers.CreateTempCopyStream(zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
await updateArchive(archive, zmodified(Path.Combine("addFile", "added.txt")), "added.txt");
}
IsZipSameAsDir(testArchive, zmodified ("addFile"), ZipArchiveMode.Read, requireExplicit: true, checkTimes: true);
}
[Fact]
public static async Task AddFileToArchive_AfterReading()
{
//add file and read entries before
Stream testArchive = await StreamHelpers.CreateTempCopyStream(zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
var x = archive.Entries;
await updateArchive(archive, zmodified(Path.Combine("addFile", "added.txt")), "added.txt");
}
IsZipSameAsDir(testArchive, zmodified("addFile"), ZipArchiveMode.Read, requireExplicit: true, checkTimes: true);
}
[Fact]
public static async Task AddFileToArchive_ThenReadEntries()
{
//add file and read entries after
Stream testArchive = await StreamHelpers.CreateTempCopyStream(zfile("normal.zip"));
using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true))
{
await updateArchive(archive, zmodified(Path.Combine("addFile", "added.txt")), "added.txt");
var x = archive.Entries;
}
IsZipSameAsDir(testArchive, zmodified("addFile"), ZipArchiveMode.Read, requireExplicit: true, checkTimes: true);
}
private static async Task updateArchive(ZipArchive archive, string installFile, string entryName)
{
ZipArchiveEntry e = archive.CreateEntry(entryName);
var file = FileData.GetFile(installFile);
e.LastWriteTime = file.LastModifiedDate;
Assert.Equal(e.LastWriteTime, file.LastModifiedDate);
using (var stream = await StreamHelpers.CreateTempCopyStream(installFile))
{
using (Stream es = e.Open())
{
es.SetLength(0);
stream.CopyTo(es);
}
}
}
[Fact]
public static async Task UpdateModeInvalidOperations()
{
using (LocalMemoryStream ms = await LocalMemoryStream.readAppFileAsync(zfile("normal.zip")))
{
ZipArchive target = new ZipArchive(ms, ZipArchiveMode.Update, leaveOpen: true);
ZipArchiveEntry edeleted = target.GetEntry("first.txt");
Stream s = edeleted.Open();
//invalid ops while entry open
Assert.Throws<IOException>(() => edeleted.Open());
Assert.Throws<InvalidOperationException>(() => { var x = edeleted.Length; });
Assert.Throws<InvalidOperationException>(() => { var x = edeleted.CompressedLength; });
Assert.Throws<IOException>(() => edeleted.Delete());
s.Dispose();
//invalid ops on stream after entry closed
Assert.Throws<ObjectDisposedException>(() => s.ReadByte());
Assert.Throws<InvalidOperationException>(() => { var x = edeleted.Length; });
Assert.Throws<InvalidOperationException>(() => { var x = edeleted.CompressedLength; });
edeleted.Delete();
//invalid ops while entry deleted
Assert.Throws<InvalidOperationException>(() => edeleted.Open());
Assert.Throws<InvalidOperationException>(() => { edeleted.LastWriteTime = new DateTimeOffset(); });
ZipArchiveEntry e = target.GetEntry("notempty/second.txt");
target.Dispose();
Assert.Throws<ObjectDisposedException>(() => { var x = target.Entries; });
Assert.Throws<ObjectDisposedException>(() => target.CreateEntry("dirka"));
Assert.Throws<ObjectDisposedException>(() => e.Open());
Assert.Throws<ObjectDisposedException>(() => e.Delete());
Assert.Throws<ObjectDisposedException>(() => { e.LastWriteTime = new DateTimeOffset(); });
}
}
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Reflection.Emit.Lightweight.Tests
{
public class DynamicMethodCreateDelegateStaticTests
{
private const string c_DYNAMIC_METHOD_NAME = "TestDynamicMethodA";
private readonly Type _DYNAMIC_METHOD_OWNER_TYPE = typeof(TestCreateDelegateOwner2);
private readonly Type _DYNAMIC_METHOD_OWNER_DERIVED_TYPE = typeof(TestCreateDelegateOwner2Derived);
private const string c_FIELD_NAME = "_id";
public Module CurrentModule
{
get
{
return typeof(DynamicMethodCreateDelegateStaticTests).GetTypeInfo().Assembly.ManifestModule;
}
}
[Fact]
public void PosTest1()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2 target = new TestCreateDelegateOwner2();
int newId = 100;
bool actualResult;
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(_DYNAMIC_METHOD_OWNER_TYPE);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
UseLikeStatic2 staticCallBack = (UseLikeStatic2)testDynMethod.CreateDelegate(typeof(UseLikeStatic2));
actualResult = target.ID == staticCallBack(target, newId);
actualResult = (target.ID == newId) && actualResult;
Assert.True(actualResult, "Failed to create delegate for dynamic method.");
}
[Fact]
public void PosTest2()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2Derived target = new TestCreateDelegateOwner2Derived();
int newId = 100;
bool actualResult;
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(_DYNAMIC_METHOD_OWNER_TYPE);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
UseLikeStatic2 staticCallBack = (UseLikeStatic2)testDynMethod.CreateDelegate(typeof(UseLikeStatic2));
actualResult = target.ID == staticCallBack(target, newId);
actualResult = (target.ID == newId) && actualResult;
Assert.True(actualResult, "Failed to create delegate for dynamic method.");
}
[Fact]
public void PosTest3()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2 target = new TestCreateDelegateOwner2();
int newId = 100;
bool actualResult;
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(this.CurrentModule);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
UseLikeStatic2 staticCallBack = (UseLikeStatic2)testDynMethod.CreateDelegate(typeof(UseLikeStatic2));
actualResult = target.ID == staticCallBack(target, newId);
actualResult = (target.ID == newId) && actualResult;
Assert.True(actualResult, "Failed to create delegate for dynamic method.");
}
[Fact]
public void PosTest4()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2Derived target = new TestCreateDelegateOwner2Derived();
int newId = 100;
bool actualResult;
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(this.CurrentModule);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
UseLikeStatic2 staticCallBack = (UseLikeStatic2)testDynMethod.CreateDelegate(typeof(UseLikeStatic2));
actualResult = target.ID == staticCallBack(target, newId);
actualResult = (target.ID == newId) && actualResult;
Assert.True(actualResult, "Failed to create delegate for dynamic method.");
}
[Fact]
public void NegTest1()
{
DynamicMethod testDynMethod;
TestCreateDelegateOwner2 target = new TestCreateDelegateOwner2();
testDynMethod = this.CreateDynMethod(_DYNAMIC_METHOD_OWNER_TYPE);
Assert.Throws<InvalidOperationException>(() =>
{
UseLikeStatic2 staticCallBack = (UseLikeStatic2)testDynMethod.CreateDelegate(typeof(UseLikeStatic2));
});
}
[Fact]
public void NegTest2()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2 target = new TestCreateDelegateOwner2();
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(_DYNAMIC_METHOD_OWNER_TYPE);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
Assert.Throws<ArgumentException>(() =>
{
InvalidRetType2 invalidCallBack = (InvalidRetType2)testDynMethod.CreateDelegate(typeof(InvalidRetType2));
});
}
[Fact]
public void NegTest3()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2 target = new TestCreateDelegateOwner2();
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(_DYNAMIC_METHOD_OWNER_TYPE);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
Assert.Throws<ArgumentException>(() =>
{
WrongParamNumber2 invalidCallBack = (WrongParamNumber2)testDynMethod.CreateDelegate(typeof(WrongParamNumber2));
});
}
[Fact]
public void NegTest4()
{
DynamicMethod testDynMethod;
FieldInfo fieldInfo;
TestCreateDelegateOwner2 target = new TestCreateDelegateOwner2();
fieldInfo = _DYNAMIC_METHOD_OWNER_TYPE.GetField(
c_FIELD_NAME,
BindingFlags.NonPublic |
BindingFlags.Instance);
testDynMethod = this.CreateDynMethod(_DYNAMIC_METHOD_OWNER_TYPE);
this.EmitDynMethodBody(testDynMethod, fieldInfo);
Assert.Throws<ArgumentException>(() =>
{
InvalidParamType2 invalidCallBack = (InvalidParamType2)testDynMethod.CreateDelegate(typeof(InvalidParamType2));
});
}
private DynamicMethod CreateDynMethod(Type dynMethodOwnerType)
{
Type retType = typeof(int);
Type[] paramTypes = new Type[]
{
_DYNAMIC_METHOD_OWNER_TYPE,
typeof(int)
};
return new DynamicMethod(c_DYNAMIC_METHOD_NAME,
retType,
paramTypes,
dynMethodOwnerType);
}
private DynamicMethod CreateDynMethod(Module mod)
{
Type retType = typeof(int);
Type[] paramTypes = new Type[]
{
_DYNAMIC_METHOD_OWNER_TYPE,
typeof(int)
};
return new DynamicMethod(c_DYNAMIC_METHOD_NAME,
retType,
paramTypes,
mod,
true);
}
private void EmitDynMethodBody(DynamicMethod dynMethod, FieldInfo fld)
{
ILGenerator methodIL = dynMethod.GetILGenerator();
methodIL.Emit(OpCodes.Ldarg_0);
methodIL.Emit(OpCodes.Ldfld, fld);
methodIL.Emit(OpCodes.Ldarg_0);
methodIL.Emit(OpCodes.Ldarg_1);
methodIL.Emit(OpCodes.Stfld, fld);
methodIL.Emit(OpCodes.Ret);
}
}
internal class TestCreateDelegateOwner2
{
private int _id; //c_FIELD_NAME
public TestCreateDelegateOwner2(int id)
{
_id = id;
}
public TestCreateDelegateOwner2() : this(0)
{
}
public int ID
{
get { return _id; }
}
}
internal class TestCreateDelegateOwner2Derived : TestCreateDelegateOwner2
{
public TestCreateDelegateOwner2Derived(int id)
: base(id)
{
}
public TestCreateDelegateOwner2Derived()
: base()
{
}
}
internal delegate int UseLikeStatic2(TestCreateDelegateOwner2 owner, int id);
internal delegate TestCreateDelegateOwner2 InvalidRetType2(TestCreateDelegateOwner2 owner, int id);
internal delegate int WrongParamNumber2(TestCreateDelegateOwner2 owner, int id, int m);
internal delegate int InvalidParamType2(int id, TestCreateDelegateOwner2 owner);
}
| |
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2015 Tim Stair
//
// 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.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace Support.UI
{
public class QueryPanelDialog : QueryPanel
{
private Form m_zForm;
private int m_nMaxDesiredHeight = -1;
private string m_sButtonPressed = string.Empty;
public Form Form => m_zForm;
/// <summary>
/// Constructor
/// </summary>
/// <param name="sTitle">Title of the dialog</param>
/// <param name="nWidth">Width of the dialog</param>
/// <param name="bTabbed">Whether the panel should be tabbed</param>
public QueryPanelDialog(string sTitle, int nWidth, bool bTabbed)
: base(null, bTabbed)
{
InitForm(sTitle, nWidth, null, null);
X_LABEL_SIZE = (int)((float)m_zPanel.Width * 0.25);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="sTitle">Title of the dialog</param>
/// <param name="nWidth">Width of the dialog</param>
/// <param name="nLabelWidth">Width of labels</param>
/// <param name="bTabbed">Flag indicating whether this should support tabs</param>
public QueryPanelDialog(string sTitle, int nWidth, int nLabelWidth, bool bTabbed)
: base(null, nLabelWidth, bTabbed)
{
InitForm(sTitle, nWidth, null, null);
if (0 < nLabelWidth && nLabelWidth < m_zPanel.Width)
{
X_LABEL_SIZE = nLabelWidth;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="sTitle">Title of the dialog</param>
/// <param name="nWidth">Width of the dialog</param>
/// <param name="nLabelWidth">Width of labels</param>
/// <param name="bTabbed">Flag indicating whether this should support tabs</param>
/// <param name="arrayButtons">Array of button names to support</param>
public QueryPanelDialog(string sTitle, int nWidth, int nLabelWidth, bool bTabbed, string[] arrayButtons)
: base(null, nLabelWidth, bTabbed)
{
InitForm(sTitle, nWidth, arrayButtons, null);
if (0 < nLabelWidth && nLabelWidth < m_zPanel.Width)
{
X_LABEL_SIZE = nLabelWidth;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="sTitle">Title of the dialog</param>
/// <param name="nWidth">Width of the dialog</param>
/// <param name="nLabelWidth">Width of labels</param>
/// <param name="bTabbed">Flag indicating whether this should support tabs</param>
/// <param name="arrayButtons">Array of button names to support</param>
/// <param name="arrayHandlers">The handlers to associated with the buttons (order match with buttons, null is allowed for an event handler)</param>
public QueryPanelDialog(string sTitle, int nWidth, int nLabelWidth, bool bTabbed, string[] arrayButtons, EventHandler[] arrayHandlers)
: base(null, nLabelWidth, bTabbed)
{
InitForm(sTitle, nWidth, arrayButtons, arrayHandlers);
if (0 < nLabelWidth && nLabelWidth < m_zPanel.Width)
{
X_LABEL_SIZE = nLabelWidth;
}
}
/// <summary>
/// Initializes the form associated with this QueryDialog
/// </summary>
/// <param name="sTitle">Title of the dialog</param>
/// <param name="nWidth">Width of the dialog</param>
/// <param name="arrayButtons">The names of the buttons to put on the dialog</param>
/// <param name="arrayHandlers">event handlers for the buttons</param>
private void InitForm(string sTitle, int nWidth, string[] arrayButtons, EventHandler[] arrayHandlers)
{
m_zForm = new Form
{
Size = new Size(nWidth, 300)
};
Button btnDefault = null; // used to set the proper height of the internal panel
// setup the buttons
if (null == arrayButtons)
{
var btnCancel = new Button();
var btnOk = new Button();
btnOk.Click += btnOk_Click;
btnCancel.Click += btnCancel_Click;
btnOk.TabIndex = 65001;
btnCancel.TabIndex = 65002;
btnCancel.Text = "Cancel";
btnOk.Text = "OK";
btnCancel.Location = new Point((m_zForm.ClientSize.Width - (3 * X_CONTROL_BUFFER)) - btnCancel.Size.Width, (m_zForm.ClientSize.Height - Y_CONTROL_BUFFER) - btnCancel.Size.Height);
btnOk.Location = new Point((btnCancel.Location.X - X_CONTROL_BUFFER) - btnOk.Size.Width, btnCancel.Location.Y);
btnOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
btnCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
m_zForm.AcceptButton = btnOk;
m_zForm.CancelButton = btnCancel;
m_zForm.Controls.Add(btnOk);
m_zForm.Controls.Add(btnCancel);
btnDefault = btnCancel;
}
else
{
Button btnPrevious = null;
for (int nIdx = arrayButtons.Length - 1; nIdx > -1; nIdx--)
{
btnDefault = new Button();
var bHandlerSet = false;
if (arrayHandlers?[nIdx] != null)
{
btnDefault.Click += arrayHandlers[nIdx];
bHandlerSet = true;
}
if (!bHandlerSet)
{
btnDefault.Click += btnGeneric_Click;
}
btnDefault.TabIndex = 65000 + nIdx;
btnDefault.Text = arrayButtons[nIdx];
btnDefault.Location = null == btnPrevious
? new Point((m_zForm.ClientSize.Width - (3 * X_CONTROL_BUFFER)) - btnDefault.Size.Width, (m_zForm.ClientSize.Height - Y_CONTROL_BUFFER) - btnDefault.Size.Height)
: new Point((btnPrevious.Location.X - X_CONTROL_BUFFER) - btnDefault.Size.Width, btnPrevious.Location.Y);
btnDefault.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
m_zForm.Controls.Add(btnDefault);
btnPrevious = btnDefault;
}
}
// setup the form
m_zForm.FormBorderStyle = FormBorderStyle.FixedSingle;
m_zForm.MaximizeBox = false;
m_zForm.MinimizeBox = false;
m_zForm.Name = "QueryDialog";
m_zForm.ShowInTaskbar = false;
m_zForm.SizeGripStyle = SizeGripStyle.Hide;
m_zForm.StartPosition = FormStartPosition.CenterParent;
m_zForm.Text = sTitle;
m_zForm.Load += QueryDialog_Load;
// setup the panel to contain the controls
m_zPanel.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
if (null != btnDefault)
{
m_zPanel.Size = new Size(m_zForm.ClientSize.Width,
m_zForm.ClientSize.Height - (btnDefault.Size.Height + (2*Y_CONTROL_BUFFER)));
}
m_zPanel.AutoScroll = true;
m_zPanel.Resize += m_zPanel_Resize;
m_zForm.Controls.Add(m_zPanel);
}
void m_zPanel_Resize(object sender, EventArgs e)
{
SetupScrollState(m_zPanel);
}
/// <summary>
/// Sets the title text of the dialog.
/// </summary>
/// <param name="sTitle"></param>
public void SetTitleText(string sTitle)
{
m_zForm.Text = sTitle;
}
/// <summary>
/// Flags the dialog to be shown in the task bar.
/// </summary>
/// <param name="bShow"></param>
public void ShowInTaskBar(bool bShow)
{
m_zForm.ShowInTaskbar = bShow;
}
/// <summary>
/// Allows the form to be resized. This should be used after all of the controls have been added to set the minimum size.
/// </summary>
public void AllowResize()
{
m_zForm.MaximizeBox = true;
m_zForm.FormBorderStyle = FormBorderStyle.Sizable;
}
/// <summary>
/// Sets the icon for the form
/// </summary>
/// <param name="zIcon">The icon to use for the dialog. If null is specified the icon is hidden.</param>
public void SetIcon(Icon zIcon)
{
if (null == zIcon)
{
m_zForm.ShowIcon = false;
}
else
{
m_zForm.Icon = zIcon;
}
}
/// <summary>
/// Shows the dialog (much like the Form.ShowDialog method)
/// </summary>
/// <param name="zParentForm"></param>
/// <returns></returns>
public DialogResult ShowDialog(IWin32Window zParentForm)
{
return m_zForm.ShowDialog(zParentForm);
}
/// <summary>
/// Returns the string on the button pressed on exit.
/// </summary>
/// <returns></returns>
public string GetButtonPressedString()
{
return m_sButtonPressed;
}
#region Events
/// <summary>
/// Handles generic button presses (for those on the bottom of the dialog)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGeneric_Click(object sender, EventArgs e)
{
m_zForm.DialogResult = DialogResult.OK;
m_sButtonPressed = ((Button)sender).Text;
m_zForm.Close();
}
/// <summary>
/// Handles the Ok button press.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOk_Click(object sender, EventArgs e)
{
m_zForm.DialogResult = DialogResult.OK;
m_sButtonPressed = m_zForm.DialogResult.ToString();
}
/// <summary>
/// Handles the Cancel button press.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCancel_Click(object sender, EventArgs e)
{
m_zForm.DialogResult = DialogResult.Cancel;
m_sButtonPressed = m_zForm.DialogResult.ToString();
}
/// <summary>
/// Sets the max desired height for the dialog.
/// </summary>
/// <param name="nMaxHeight"></param>
public void SetMaxHeight(int nMaxHeight)
{
m_nMaxDesiredHeight = nMaxHeight;
}
/// <summary>
/// The dialog load event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void QueryDialog_Load(object sender, EventArgs e)
{
if (null == m_zTabControl)
{
int nHeight = GetYPosition() + m_nButtonHeight + (Y_CONTROL_BUFFER * 2);
if (m_nMaxDesiredHeight > 0)
{
if (nHeight > m_nMaxDesiredHeight)
{
nHeight = m_nMaxDesiredHeight;
}
}
m_zForm.ClientSize = new Size(m_zForm.ClientSize.Width, nHeight);
}
else
{
var nLargestHeight = -1;
foreach(var zPage in m_zTabControl.TabPages.OfType<TabPage>())
{
if(nLargestHeight < (int)zPage.Tag)
{
nLargestHeight = (int)zPage.Tag;
}
}
if (nLargestHeight > 0)
{
nLargestHeight = Math.Min(m_nMaxDesiredHeight, nLargestHeight);
// hard coded extra vertical space
m_zForm.ClientSize = new Size(m_zForm.ClientSize.Width, nLargestHeight + 60);
}
}
if (0 < m_zPanel.Controls.Count)
{
m_zPanel.SelectNextControl(m_zPanel.Controls[m_zPanel.Controls.Count - 1], true, true, true, true);
}
}
#endregion
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// 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.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.6.2. Remove an entity. COMPLETE
/// </summary>
[Serializable]
[XmlRoot]
public partial class RemoveEntityPdu : SimulationManagementFamilyPdu, IEquatable<RemoveEntityPdu>
{
/// <summary>
/// Identifier for the request
/// </summary>
private uint _requestID;
/// <summary>
/// Initializes a new instance of the <see cref="RemoveEntityPdu"/> class.
/// </summary>
public RemoveEntityPdu()
{
PduType = (byte)12;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(RemoveEntityPdu left, RemoveEntityPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(RemoveEntityPdu left, RemoveEntityPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += 4; // this._requestID
return marshalSize;
}
/// <summary>
/// Gets or sets the Identifier for the request
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "requestID")]
public uint RequestID
{
get
{
return this._requestID;
}
set
{
this._requestID = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
dos.WriteUnsignedInt((uint)this._requestID);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._requestID = dis.ReadUnsignedInt();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<RemoveEntityPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>");
sb.AppendLine("</RemoveEntityPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as RemoveEntityPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(RemoveEntityPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (this._requestID != obj._requestID)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._requestID.GetHashCode();
return result;
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.ComponentModel;
using WindowsUtilities;
namespace RebarDotNet
{
/// <summary>
/// Summary description for BandWrapper.
/// </summary>
public enum GripperSettings{Always, Auto, Never};
[ToolboxItem(false)]
public class BandWrapper: Component, IDisposable
{
private BandCollection _bands;
private bool _allowVertical = true;
private Color _backColor;
private string _caption = "";
private bool _created = false;
private Control _child = null;
protected bool _disposed = false;
private bool _embossPicture = true;
private bool _fixedBackground = true;
private bool _fixedSize = false;
private Color _foreColor;
private GripperSettings _gripSettings = GripperSettings.Always;
private int _header = -1;
private int _id = -1;
private int _idealWidth = -1;
private int _image = -1;
private int _integral = 1;
private int _cx = -1;
private string _key = "";
private int _maxHeight = 0;
private int _minHeight = 24;
private int _minWidth = 24;
private bool _newRow = true;
private Bitmap _backgroundImage = null;
private IntPtr _pictureHandle = IntPtr.Zero;
private bool _showCaption = true;
private bool _showIcon = false;
private object _tag = null;
private bool _throwExceptions = true;
private bool _useCoolbarColors = true;
private bool _useCoolbarPicture = true;
private bool _visible = true;
// 2003/08/29
// [email protected]
private bool _useChevron = true;
public event MouseEventHandler MouseDown; //Done
public event MouseEventHandler MouseMove; //Done
public event MouseEventHandler MouseUp; //Done
public event MouseEventHandler MouseWheel; //Done
public event EventHandler Move; //Fix
public event EventHandler Resize; //Done
public event EventHandler VisibleChanged; //Done
public BandWrapper()
{
_foreColor = SystemColors.ControlText;
_backColor = SystemColors.Control;
}
~BandWrapper()
{
Dispose(false);
}
[Browsable(true),
DefaultValue(true),
NotifyParentProperty(true)]
public bool AllowVertical
{
get
{
return _allowVertical;
}
set
{
if(value != _allowVertical)
{
//Code to set the style
_allowVertical = value;
UpdateStyles();
}
}
}
[Browsable(true),
DefaultValue(typeof(Color), "Control"),
NotifyParentProperty(true)]
public Color BackColor
{
get
{
return _backColor;
}
set
{
if(value != _backColor)
{
//Code to set BackColor
_backColor = value;
}
}
}
[Browsable(true)]
[DefaultValue(null)]
[NotifyParentProperty(true)]
public Bitmap BackgroundImage
{
get
{
return _backgroundImage;
}
set
{
if(value != _backgroundImage)
{
if(_pictureHandle != IntPtr.Zero) Gdi32Dll.DeleteObject(_pictureHandle);
_backgroundImage = value;
_pictureHandle = (value == null)?IntPtr.Zero:_backgroundImage.GetHbitmap();
UpdatePicture();
}
}
}
[Browsable(false),
System.ComponentModel.DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
EditorBrowsable(EditorBrowsableState.Always)]
public int BandIndex
{
get
{
if(Created)
{
return (int)User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_IDTOINDEX, (uint)_id, 0U);
}
else
{
return -1;
}
}
}
[Browsable(false),
System.ComponentModel.DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
EditorBrowsable(EditorBrowsableState.Always)]
public BandCollection Bands
{
get
{
return _bands;
}
set
{
if(!Created)
{
_bands = value;
_id = _bands.NextID();
if(_useCoolbarPicture)
BackgroundImage = _bands.Rebar.BackgroundImage;
CreateBand();
}
}
}
[Browsable(false),
System.ComponentModel.DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
EditorBrowsable(EditorBrowsableState.Always)]
public Rectangle Bounds
{
get
{
if(Created)
{
RECT rect = new RECT();
User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_GETRECT, BandIndex ,ref rect);
return new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
}
else
{
return new Rectangle(0,0,0,0);
}
}
}
[Browsable(true),
DefaultValue(""),
NotifyParentProperty(true)]
public string Caption
{
get
{
return _caption;
}
set
{
if(value != _caption)
{
//Code to set Caption
_caption = value;
UpdateCaption();
}
}
}
[Browsable(true),
DefaultValue(null),
NotifyParentProperty(true)]
public Control Child
{
get
{
return _child;
}
set
{
if(value != _child)
{
if(_child != null && Created)
{
_child.HandleCreated -= new EventHandler(OnChildHandleCreated);
_child.SizeChanged -= new EventHandler(OnChildSizeChanged);
_child.Move -= new EventHandler(OnChildMove);
_child.ParentChanged -=new EventHandler(OnChildParentChanged);
_child.Parent = _bands.Rebar.Parent;
}
//Code to set Child
_child = value;
if(_bands !=null)
{
_child.Parent = _bands.Rebar;
_child.HandleCreated += new EventHandler(OnChildHandleCreated);
_child.SizeChanged += new EventHandler(OnChildSizeChanged);
_child.Move += new EventHandler(OnChildMove);
_child.ParentChanged +=new EventHandler(OnChildParentChanged);
}
UpdateChild();
}
}
}
[Browsable(false),
System.ComponentModel.DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
EditorBrowsable(EditorBrowsableState.Always)]
public Rectangle ClientArea
{
get
{
if(Created)
{
RECT rect = new RECT();
User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_GETBANDBORDERS, BandIndex ,ref rect);
return new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
}
else
{
return new Rectangle(0,0,0,0);
}
}
}
internal void CreateBand()
{
if(!Created && _bands != null && _bands.Rebar.Rebar != null)
{
if(_child != null) _child.Parent = _bands.Rebar;
REBARBANDINFO rbBand = new REBARBANDINFO();
rbBand.cbSize = (uint)Marshal.SizeOf(rbBand);
rbBand.fMask = (uint)(
RebarBandInfoConstants.RBBIM_STYLE |
RebarBandInfoConstants.RBBIM_ID |
RebarBandInfoConstants.RBBIM_TEXT |
RebarBandInfoConstants.RBBIM_CHILDSIZE
);
if(!_useCoolbarColors)
rbBand.fMask |= (uint) RebarBandInfoConstants.RBBIM_COLORS;
if(_child != null) //Add ChildSize stuff at some point
rbBand.fMask |= (uint) RebarBandInfoConstants.RBBIM_CHILD;
if(_image >= 0)
rbBand.fMask |= (uint) RebarBandInfoConstants.RBBIM_IMAGE;
if(_backgroundImage != null)
rbBand.fMask |= (uint) RebarBandInfoConstants.RBBIM_BACKGROUND;
if (_cx != -1)
rbBand.fMask |= (uint) RebarBandInfoConstants.RBBIM_SIZE;
if (_idealWidth != -1)
rbBand.fMask |= (uint) RebarBandInfoConstants.RBBIM_IDEALSIZE;
rbBand.clrFore = new COLORREF(ForeColor);
rbBand.clrBack = new COLORREF(BackColor);
rbBand.fStyle = (uint)Style;
rbBand.cx = (uint)_cx;
_cx = -1;
if(_backgroundImage != null)
{
rbBand.hbmBack = _pictureHandle;
}
rbBand.lpText = _caption;
if(_child != null)
{
rbBand.hwndChild = _child.Handle;
rbBand.cxMinChild = (uint)_minWidth;
rbBand.cyMinChild = (uint)_minHeight;
rbBand.cyIntegral = (uint)_integral;//0;
rbBand.cyChild = (uint)_minHeight;
rbBand.cyMaxChild = 40;
rbBand.cxIdeal = (uint)_idealWidth;
}
if(_showIcon)
{
rbBand.iImage = _image;
}
rbBand.wID = (uint)_id;
rbBand.cxHeader = (uint)_header;
if(User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_INSERTBANDA, -1,ref rbBand) == 0)
{
int LastErr = Marshal.GetHRForLastWin32Error();
try
{
Marshal.ThrowExceptionForHR(LastErr);
}
catch (Exception ex)
{
Console.WriteLine(LastErr + " " + ex.Message);
if (_throwExceptions) throw(new Exception("Error Creating Band.", ex));
}
}
else
{
_created = true;
}
}
}
[Browsable(false),
EditorBrowsable(EditorBrowsableState.Always)]
public bool Created
{
get
{
return (_created);
}
}
internal void DestroyBand()
{
if(Created)
{
User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_DELETEBAND, (uint)BandIndex, 0U);
_bands = null;
_created = false;
}
}
protected override void Dispose(bool disposing)
{
DestroyBand();
if(_pictureHandle != IntPtr.Zero) Gdi32Dll.DeleteObject(_pictureHandle);
if(disposing)
{
}
_disposed = true;
}
[Browsable(true),
DefaultValue(true),
NotifyParentProperty(true)]
public bool EmbossPicture
{
get
{
return _embossPicture;
}
set
{
if(value != _embossPicture)
{
//Code to set Style
_embossPicture = value;
UpdateStyles();
}
}
}
[Browsable(true),
DefaultValue(true),
NotifyParentProperty(true)]
public bool FixedBackground
{
get
{
return _fixedBackground;
}
set
{
if(value != _fixedBackground)
{
//Code to set Style
_fixedBackground = value;
UpdateStyles();
}
}
}
[Browsable(true),
DefaultValue(false),
NotifyParentProperty(true)]
public bool FixedSize
{
get
{
return _fixedSize;
}
set
{
if(value != _fixedSize)
{
//Code to set Style
_fixedSize = value;
UpdateStyles();
}
}
}
[Browsable(true),
DefaultValue(typeof(Color), "ControlText"),
NotifyParentProperty(true)]
public Color ForeColor
{
get
{
return _foreColor;
}
set
{
if(value != _foreColor)
{
//Code to set ForeColor
_foreColor = value;
UpdateColors();
}
}
}
[Browsable(true),
DefaultValue(GripperSettings.Auto),
NotifyParentProperty(true)]
public GripperSettings GripSettings
{
get
{
return _gripSettings;
}
set
{
if(value != _gripSettings)
{
//Code to set Caption
_gripSettings = value;
UpdateStyles();
}
}
}
[Browsable(true),
DefaultValue(0),
NotifyParentProperty(true)]
public int Header
{
get
{
return _header;
}
set
{
if(value != _header)
{
//Set Band Header
_header = value;
UpdateMinimums();
}
}
}
[Browsable(false),
EditorBrowsable(EditorBrowsableState.Always)]
public int Height
{
get
{
return Bounds.Height;
}
}
[Browsable(false),
EditorBrowsable(EditorBrowsableState.Always)]
public int ID
{
get
{
if(_bands != null)
return _id;
else
return -1;
}
}
[Browsable(true),
DefaultValue(0),
NotifyParentProperty(true)]
public int IdealWidth
{
get
{
return _idealWidth;
}
set
{
if(value != _idealWidth)
{
_idealWidth = value;
// 2003/09/14
if(Created)
{
REBARBANDINFO rbBand = new REBARBANDINFO();
rbBand.cbSize = (uint)Marshal.SizeOf(rbBand);
if (_idealWidth != -1)
{
rbBand.fMask |= (uint)RebarBandInfoConstants.RBBIM_IDEALSIZE;
rbBand.cxIdeal = (uint)_idealWidth;
}
if(User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_SETBANDINFOA, BandIndex ,ref rbBand) == 0)
{
int LastErr = Marshal.GetHRForLastWin32Error();
try
{
Marshal.ThrowExceptionForHR(LastErr);
}
catch (Exception ex)
{
Console.WriteLine(LastErr + " " + ex.Message);
if (_throwExceptions) throw(new Exception("Error Updating Minimums.", ex));
}
}
}
}
}
}
[Browsable(true),
DefaultValue(-1),
NotifyParentProperty(true)]
public int Image
{
get
{
return _image;
}
set
{
if(value != _image)
{
//Set Image for band
_image = value;
UpdateIcon();
}
}
}
[Browsable(false),
EditorBrowsable(EditorBrowsableState.Always)]
public int Index
{
get
{
if(_bands != null)
return _bands.IndexOf(this);
else
return -1;
}
}
[Browsable(true),
DefaultValue("1")]
public int Integral
{
get
{
return _integral;
}
set
{
if(value != _integral)
{
_integral = value;
UpdateMinimums();
}
}
}
[Browsable(true),
DefaultValue("")]
public string Key
{
get
{
return _key;
}
set
{
if(value != _key)
{
if(_bands != null & value != "")
{
if(_bands[value] != null)
{
if (_throwExceptions) throw(new ArgumentException("The key specified is not unique.", "Key"));
return;
}
}
_key = value;
}
}
}
[Browsable(false),
EditorBrowsable(EditorBrowsableState.Always)]
public int Left
{
get
{
return Bounds.Left;
}
}
[Browsable(false),
EditorBrowsable(EditorBrowsableState.Always)]
public Point Location
{
get
{
return Bounds.Location;
}
}
[Browsable(false),
System.ComponentModel.DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
EditorBrowsable(EditorBrowsableState.Always)]
public MARGINS Margins
{//RB_GETBANDMARGINS
get
{
if(Created)
{
if(OSFeature.Feature.GetVersionPresent(OSFeature.Themes) != null)
{
MARGINS margins = new MARGINS();
User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_GETBANDMARGINS, 0,ref margins);
return margins;
}
return new MARGINS(0,0,0,0);
}
else
{
return new MARGINS(0,0,0,0);
}
}
}
public void Maximize()
{
if(Created)
{
User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_MAXIMIZEBAND, (uint)BandIndex, (uint)_idealWidth);
}
}
[Browsable(true),
DefaultValue(24),
NotifyParentProperty(true)]
public int MaxHeight
{
get
{
return _maxHeight;
}
set
{
if(value != _maxHeight)
{
//Set Band Height
_maxHeight = value;
UpdateMinimums();
}
}
}
public void Minimize()
{
if(Created)
{
User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_MINIMIZEBAND, (uint)BandIndex, (uint)_idealWidth);
}
}
[Browsable(true),
DefaultValue(24),
NotifyParentProperty(true)]
public int MinHeight
{
get
{
return _minHeight;
}
set
{
if(value != _minHeight)
{
//Set Band Height
_minHeight = value;
UpdateMinimums();
}
}
}
[Browsable(true),
DefaultValue(24),
NotifyParentProperty(true)]
public int MinWidth
{
get
{
return _minWidth;
}
set
{
if(value != _minWidth)
{
//Set Band Width
_minWidth = value;
UpdateMinimums();
}
}
}
[Browsable(true),
DefaultValue(true),
NotifyParentProperty(true)]
public bool NewRow
{
get
{
return _newRow;
}
set
{
if(value != _newRow)
{
//Set Style
_newRow = value;
UpdateStyles();
}
}
}
protected void OnChildHandleCreated(object sender, EventArgs e)
{
//UpdateChild();
}
protected void OnChildMove(object sender, EventArgs e)
{
}
protected void OnChildParentChanged(object sender, EventArgs e)
{
UpdateChild();
}
protected void OnChildSizeChanged(object sender, EventArgs e)
{
}
internal void OnMouseDown(MouseEventArgs e)
{
if(MouseDown != null)
{
MouseDown(this, e);
}
}
internal void OnMouseMove(MouseEventArgs e)
{
if(MouseMove != null)
{
MouseMove(this, e);
}
}
internal void OnMouseUp(MouseEventArgs e)
{
if(MouseUp != null)
{
MouseUp(this, e);
}
}
internal void OnMouseWheel(MouseEventArgs e)
{
if(MouseWheel != null)
{
MouseWheel(this, e);
}
}
internal void OnMove(EventArgs e)
{
if(Move != null)
{
Move(this, e);
}
}
internal void OnResize(EventArgs e)
{
if(Resize != null)
{
Resize(this, e);
}
}
internal void OnVisibleChanged(EventArgs e)
{
if(VisibleChanged != null)
{
VisibleChanged(this, e);
}
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Always)]
public int Position
{
get
{
if(Created)
{
return BandIndex;
}
else if(_bands != null)
{
return Index;
}
else
{
return -1;
}
}
}
private bool ShouldSerializeForeColor()
{
return _foreColor != SystemColors.ControlText;
}
[Browsable(true)]
[DefaultValue(true)]
[NotifyParentProperty(true)]
public bool ShowCaption
{
get
{
return _showCaption;
}
set
{
if(value != _showCaption)
{
//Set band style
_showCaption = value;
UpdateStyles();
}
}
}
[Browsable(true)]
[DefaultValue(false)]
[NotifyParentProperty(true)]
public bool ShowIcon
{
get
{
return _showIcon;
}
set
{
if(value != _showIcon)
{
_showIcon = value;
UpdateIcon();
}
}
}
[Browsable(false),
EditorBrowsable(EditorBrowsableState.Always)]
public Size Size
{
get
{
return Bounds.Size;
}
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Always)]
protected int Style
{
get
{
int style = 0;
if(!_allowVertical)
style |= (int)RebarBandStyleConstants.RBBS_NOVERT;
if(_embossPicture)
style |= (int)RebarBandStyleConstants.RBBS_CHILDEDGE;
if(_fixedBackground)
style |= (int)RebarBandStyleConstants.RBBS_FIXEDBMP;
if(_fixedSize)
style |= (int)RebarBandStyleConstants.RBBS_FIXEDSIZE;
if(_newRow)
style |= (int)RebarBandStyleConstants.RBBS_BREAK;
if(!_showCaption)
style |= (int)RebarBandStyleConstants.RBBS_HIDETITLE;
if(!_visible)
style |= (int)RebarBandStyleConstants.RBBS_HIDDEN;
if(_gripSettings == GripperSettings.Always)
style |= (int)RebarBandStyleConstants.RBBS_GRIPPERALWAYS;
else if(_gripSettings == GripperSettings.Never)
style |= (int)RebarBandStyleConstants.RBBS_NOGRIPPER;
// 2003/08/29
// [email protected]
if (_useChevron)
style |= (int)RebarBandStyleConstants.RBBS_USECHEVRON;
return style;
}
set
{
// 2003/08/29
// [email protected]
_useChevron = ((value & (int)RebarBandStyleConstants.RBBS_USECHEVRON)
== (int)RebarBandStyleConstants.RBBS_USECHEVRON);
_allowVertical = !((value & (int)RebarBandStyleConstants.RBBS_NOVERT)
== (int)RebarBandStyleConstants.RBBS_NOVERT);
_embossPicture = (value & (int)RebarBandStyleConstants.RBBS_CHILDEDGE)
== (int)RebarBandStyleConstants.RBBS_CHILDEDGE;
_fixedBackground = (value & (int)RebarBandStyleConstants.RBBS_FIXEDBMP)
== (int)RebarBandStyleConstants.RBBS_FIXEDBMP;
_fixedSize = (value & (int)RebarBandStyleConstants.RBBS_FIXEDSIZE)
== (int)RebarBandStyleConstants.RBBS_FIXEDSIZE;
_newRow = (value & (int)RebarBandStyleConstants.RBBS_BREAK)
== (int)RebarBandStyleConstants.RBBS_BREAK;
_showCaption = !((value & (int)RebarBandStyleConstants.RBBS_HIDETITLE)
== (int)RebarBandStyleConstants.RBBS_HIDETITLE);
_visible = !((value & (int)RebarBandStyleConstants.RBBS_HIDDEN)
== (int)RebarBandStyleConstants.RBBS_HIDDEN);
if((value & (int)RebarBandStyleConstants.RBBS_GRIPPERALWAYS)
== (int)RebarBandStyleConstants.RBBS_GRIPPERALWAYS)
_gripSettings = GripperSettings.Always;
else if ((value & (int)RebarBandStyleConstants.RBBS_NOGRIPPER)
== (int)RebarBandStyleConstants.RBBS_NOGRIPPER)
_gripSettings = GripperSettings.Never;
else
_gripSettings = GripperSettings.Auto;
UpdateStyles();
}
}
[Browsable(true),
DefaultValue(null)]
public object Tag
{
get
{
return _tag;
}
set
{
_tag = value;
}
}
[Category("Behavior"),
Browsable(true),
DefaultValue(true)]
public bool ThrowExceptions
{
get
{
return _throwExceptions;
}
set
{
_throwExceptions = value;
}
}
protected void UpdateCaption()
{
if(Created)
{
REBARBANDINFO rbBand = new REBARBANDINFO();
rbBand.cbSize = (uint)Marshal.SizeOf(rbBand);
rbBand.fMask = (uint)RebarBandInfoConstants.RBBIM_TEXT;
rbBand.lpText = _caption;
if(User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_SETBANDINFOA, BandIndex ,ref rbBand) == 0)
{
int LastErr = Marshal.GetHRForLastWin32Error();
try
{
Marshal.ThrowExceptionForHR(LastErr);
}
catch (Exception ex)
{
Console.WriteLine(LastErr + " " + ex.Message);
if (_throwExceptions) throw(new Exception("Error Updating Caption.", ex));
}
}
}
}
protected void UpdateChild()
{
if(Created)
{
REBARBANDINFO rbBand = new REBARBANDINFO();
rbBand.cbSize = (uint)Marshal.SizeOf(rbBand);
rbBand.fMask = (uint) RebarBandInfoConstants.RBBIM_CHILD;
if(_child == null)
{
rbBand.hwndChild = IntPtr.Zero;
}
else
{
rbBand.hwndChild = _child.Handle;
}
if(User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_SETBANDINFOA, BandIndex ,ref rbBand) == 0)
{
int LastErr = Marshal.GetHRForLastWin32Error();
try
{
Marshal.ThrowExceptionForHR(LastErr);
}
catch (Exception ex)
{
Console.WriteLine(LastErr + " " + ex.Message);
if (_throwExceptions) throw(new Exception("Error Updating Child.", ex));
}
}
UpdateMinimums();
}
}
protected void UpdateColors()
{
if(Created)
{
REBARBANDINFO rbBand = new REBARBANDINFO();
rbBand.cbSize = (uint)Marshal.SizeOf(rbBand);
rbBand.fMask = (uint) RebarBandInfoConstants.RBBIM_COLORS;
if(_useCoolbarColors)
{
rbBand.clrBack = new COLORREF();
rbBand.clrBack._ColorDWORD = (uint) ColorConstants.CLR_DEFAULT;
rbBand.clrFore = new COLORREF();
rbBand.clrFore._ColorDWORD = (uint) ColorConstants.CLR_DEFAULT;
}
else
{
rbBand.clrBack = new COLORREF(_backColor);
rbBand.clrFore = new COLORREF(_foreColor);
}
if(User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_SETBANDINFOA, BandIndex ,ref rbBand) == 0)
{
int LastErr = Marshal.GetHRForLastWin32Error();
try
{
Marshal.ThrowExceptionForHR(LastErr);
}
catch (Exception ex)
{
Console.WriteLine(LastErr + " " + ex.Message);
if (_throwExceptions) throw(new Exception("Error Updating Foreground and Background Colors.", ex));
}
}
}
}
protected void UpdateIcon()
{
if(Created)
{
REBARBANDINFO rbBand = new REBARBANDINFO();
rbBand.cbSize = (uint)Marshal.SizeOf(rbBand);
rbBand.fMask = (uint) RebarBandInfoConstants.RBBIM_IMAGE;
if(_showIcon)
{
rbBand.iImage = _image;
}
else
{
rbBand.iImage = -1;
}
if(User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_SETBANDINFOA, BandIndex ,ref rbBand) == 0)
{
int LastErr = Marshal.GetHRForLastWin32Error();
try
{
Marshal.ThrowExceptionForHR(LastErr);
}
catch (Exception ex)
{
Console.WriteLine(LastErr + " " + ex.Message);
if (_throwExceptions) throw(new Exception("Error Updating Icon.", ex));
}
}
}
}
protected void UpdateMinimums()
{
if(Created)
{
REBARBANDINFO rbBand = new REBARBANDINFO();
rbBand.cbSize = (uint)Marshal.SizeOf(rbBand);
rbBand.fMask = (uint)(RebarBandInfoConstants.RBBIM_CHILDSIZE);
if (_header != -1) rbBand.fMask |= (uint)RebarBandInfoConstants.RBBIM_HEADERSIZE;
rbBand.cxMinChild = (uint)_minWidth;
rbBand.cyMinChild = (uint)_minHeight;
rbBand.cyIntegral = (uint)_integral;//1;
rbBand.cyChild = (uint)_minHeight;
rbBand.cyMaxChild = (uint)_maxHeight;
rbBand.cxHeader = (uint)_header;
if (_idealWidth != -1)
{
rbBand.fMask |= (uint)RebarBandInfoConstants.RBBIM_IDEALSIZE;
rbBand.cxIdeal = (uint)_idealWidth;
}
if (_cx != -1)
{
rbBand.fMask |= (uint) RebarBandInfoConstants.RBBIM_SIZE;
rbBand.cx = (uint)_cx;
_cx = -1;
}
if(User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_SETBANDINFOA, BandIndex ,ref rbBand) == 0)
{
int LastErr = Marshal.GetHRForLastWin32Error();
try
{
Marshal.ThrowExceptionForHR(LastErr);
}
catch (Exception ex)
{
Console.WriteLine(LastErr + " " + ex.Message);
if (_throwExceptions) throw(new Exception("Error Updating Minimums.", ex));
}
}
}
}
protected void UpdatePicture()
{
if(Created)
{
REBARBANDINFO rbBand = new REBARBANDINFO();
rbBand.cbSize = (uint)Marshal.SizeOf(rbBand);
rbBand.fMask = (uint) RebarBandInfoConstants.RBBIM_BACKGROUND;
rbBand.hbmBack = _pictureHandle;
if(User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_SETBANDINFOA, BandIndex ,ref rbBand) == 0)
{
int LastErr = Marshal.GetHRForLastWin32Error();
try
{
Marshal.ThrowExceptionForHR(LastErr);
}
catch (Exception ex)
{
Console.WriteLine(LastErr + " " + ex.Message);
if (_throwExceptions) throw(new Exception("Error Updating Background.", ex));
}
}
}
}
protected void UpdateStyles()
{
if(Created)
{
REBARBANDINFO rbBand = new REBARBANDINFO();
rbBand.cbSize = (uint)Marshal.SizeOf(rbBand);
rbBand.fMask = (uint) RebarBandInfoConstants.RBBIM_STYLE;
rbBand.fStyle = (uint)Style;
if(User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int)WindowsMessages.RB_SETBANDINFOA, BandIndex ,ref rbBand) == 0)
{
int LastErr = Marshal.GetHRForLastWin32Error();
try
{
Marshal.ThrowExceptionForHR(LastErr);
}
catch (Exception ex)
{
Console.WriteLine(LastErr + " " + ex.Message);
if (_throwExceptions) throw(new Exception("Error Updating Styles.", ex));
}
}
}
}
[Browsable(true)]
[DefaultValue(true)]
[NotifyParentProperty(true)]
public bool UseCoolbarColors
{
get
{
return _useCoolbarColors;
}
set
{
if(value != _useCoolbarColors)
{
//Set the Colors
_useCoolbarColors = value;
UpdateColors();
}
}
}
[Browsable(true)]
[DefaultValue(true)]
[NotifyParentProperty(true)]
public bool UseCoolbarPicture
{
get
{
return _useCoolbarPicture;
}
set
{
if(value != _useCoolbarPicture)
{
//Set the Picture
_useCoolbarPicture = value;
UpdatePicture();
}
}
}
// 2003/08/29
// [email protected]
[Browsable(true)]
[DefaultValue(true)]
[NotifyParentProperty(true)]
public bool UseChevron
{
get {
return _useChevron;
}
set {
if (value != _useChevron)
{
_useChevron = value;
//UpdateStyles();
}
}
}
[Browsable(true)]
[DefaultValue(true)]
public bool Visible
{
get
{
return _visible;
}
set
{
if(value != _visible)
{
//Set band style
_visible = value;
if(Created)
{
User32Dll.SendMessage(_bands.Rebar.RebarHwnd, (int) WindowsMessages.RB_SHOWBAND, (uint)BandIndex, (_visible)?1U:0U);
OnVisibleChanged(new System.EventArgs());
}
}
}
}
[Browsable(false),
EditorBrowsable(EditorBrowsableState.Always)]
public int Width
{
set {
_cx = value;
UpdateMinimums();
}
get
{
return Bounds.Width;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Linq.Tests
{
public class ToArrayTests : EnumerableTests
{
[Fact]
public void ToArray_CreateACopyWhenNotEmpty()
{
int[] sourceArray = new int[] { 1, 2, 3, 4, 5 };
int[] resultArray = sourceArray.ToArray();
Assert.NotSame(sourceArray, resultArray);
Assert.Equal(sourceArray, resultArray);
}
[Fact]
public void ToArray_UseArrayEmptyWhenEmpty()
{
int[] emptySourceArray = Array.Empty<int>();
Assert.Same(emptySourceArray.ToArray(), emptySourceArray.ToArray());
Assert.Same(emptySourceArray.Select(i => i).ToArray(), emptySourceArray.Select(i => i).ToArray());
Assert.Same(emptySourceArray.ToList().Select(i => i).ToArray(), emptySourceArray.ToList().Select(i => i).ToArray());
Assert.Same(new Collection<int>(emptySourceArray).Select(i => i).ToArray(), new Collection<int>(emptySourceArray).Select(i => i).ToArray());
Assert.Same(emptySourceArray.OrderBy(i => i).ToArray(), emptySourceArray.OrderBy(i => i).ToArray());
Assert.Same(Enumerable.Range(5, 0).ToArray(), Enumerable.Range(3, 0).ToArray());
Assert.Same(Enumerable.Range(5, 3).Take(0).ToArray(), Enumerable.Range(3, 0).ToArray());
Assert.Same(Enumerable.Range(5, 3).Skip(3).ToArray(), Enumerable.Range(3, 0).ToArray());
Assert.Same(Enumerable.Repeat(42, 0).ToArray(), Enumerable.Range(84, 0).ToArray());
Assert.Same(Enumerable.Repeat(42, 3).Take(0).ToArray(), Enumerable.Range(84, 3).Take(0).ToArray());
Assert.Same(Enumerable.Repeat(42, 3).Skip(3).ToArray(), Enumerable.Range(84, 3).Skip(3).ToArray());
}
private void RunToArrayOnAllCollectionTypes<T>(T[] items, Action<T[]> validation)
{
validation(Enumerable.ToArray(items));
validation(Enumerable.ToArray(new List<T>(items)));
validation(new TestEnumerable<T>(items).ToArray());
validation(new TestReadOnlyCollection<T>(items).ToArray());
validation(new TestCollection<T>(items).ToArray());
}
[Fact]
public void ToArray_WorkWithEmptyCollection()
{
RunToArrayOnAllCollectionTypes(new int[0],
resultArray =>
{
Assert.NotNull(resultArray);
Assert.Equal(0, resultArray.Length);
});
}
[Fact]
public void ToArray_ProduceCorrectArray()
{
int[] sourceArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
RunToArrayOnAllCollectionTypes(sourceArray,
resultArray =>
{
Assert.Equal(sourceArray.Length, resultArray.Length);
Assert.Equal(sourceArray, resultArray);
});
string[] sourceStringArray = new string[] { "1", "2", "3", "4", "5", "6", "7", "8" };
RunToArrayOnAllCollectionTypes(sourceStringArray,
resultStringArray =>
{
Assert.Equal(sourceStringArray.Length, resultStringArray.Length);
for (int i = 0; i < sourceStringArray.Length; i++)
Assert.Same(sourceStringArray[i], resultStringArray[i]);
});
}
[Fact]
public void RunOnce()
{
Assert.Equal(new int[] {1, 2, 3, 4, 5, 6, 7}, Enumerable.Range(1, 7).RunOnce().ToArray());
Assert.Equal(
new string[] {"1", "2", "3", "4", "5", "6", "7", "8"},
Enumerable.Range(1, 8).Select(i => i.ToString()).RunOnce().ToArray());
}
[Fact]
public void ToArray_TouchCountWithICollection()
{
TestCollection<int> source = new TestCollection<int>(new int[] { 1, 2, 3, 4 });
var resultArray = source.ToArray();
Assert.Equal(source, resultArray);
Assert.Equal(1, source.CountTouched);
}
[Fact]
public void ToArray_ThrowArgumentNullExceptionWhenSourceIsNull()
{
int[] source = null;
Assert.Throws<ArgumentNullException>("source", () => source.ToArray());
}
// Generally the optimal approach. Anything that breaks this should be confirmed as not harming performance.
[Fact]
public void ToArray_UseCopyToWithICollection()
{
TestCollection<int> source = new TestCollection<int>(new int[] { 1, 2, 3, 4 });
var resultArray = source.ToArray();
Assert.Equal(source, resultArray);
Assert.Equal(1, source.CopyToTouched);
}
[Fact]
[ActiveIssue("Valid test but too intensive to enable even in OuterLoop")]
public void ToArray_FailOnExtremelyLargeCollection()
{
var largeSeq = new FastInfiniteEnumerator<byte>();
var thrownException = Assert.ThrowsAny<Exception>(() => { largeSeq.ToArray(); });
Assert.True(thrownException.GetType() == typeof(OverflowException) || thrownException.GetType() == typeof(OutOfMemoryException));
}
[Theory]
[InlineData(new int[] { }, new string[] { })]
[InlineData(new int[] { 1 }, new string[] { "1" })]
[InlineData(new int[] { 1, 2, 3 }, new string[] { "1", "2", "3" })]
public void ToArray_ArrayWhereSelect(int[] sourceIntegers, string[] convertedStrings)
{
Assert.Equal(convertedStrings, sourceIntegers.Select(i => i.ToString()).ToArray());
Assert.Equal(sourceIntegers, sourceIntegers.Where(i => true).ToArray());
Assert.Equal(Array.Empty<int>(), sourceIntegers.Where(i => false).ToArray());
Assert.Equal(convertedStrings, sourceIntegers.Where(i => true).Select(i => i.ToString()).ToArray());
Assert.Equal(Array.Empty<string>(), sourceIntegers.Where(i => false).Select(i => i.ToString()).ToArray());
Assert.Equal(convertedStrings, sourceIntegers.Select(i => i.ToString()).Where(s => s != null).ToArray());
Assert.Equal(Array.Empty<string>(), sourceIntegers.Select(i => i.ToString()).Where(s => s == null).ToArray());
}
[Theory]
[InlineData(new int[] { }, new string[] { })]
[InlineData(new int[] { 1 }, new string[] { "1" })]
[InlineData(new int[] { 1, 2, 3 }, new string[] { "1", "2", "3" })]
public void ToArray_ListWhereSelect(int[] sourceIntegers, string[] convertedStrings)
{
var sourceList = new List<int>(sourceIntegers);
Assert.Equal(convertedStrings, sourceList.Select(i => i.ToString()).ToArray());
Assert.Equal(sourceList, sourceList.Where(i => true).ToArray());
Assert.Equal(Array.Empty<int>(), sourceList.Where(i => false).ToArray());
Assert.Equal(convertedStrings, sourceList.Where(i => true).Select(i => i.ToString()).ToArray());
Assert.Equal(Array.Empty<string>(), sourceList.Where(i => false).Select(i => i.ToString()).ToArray());
Assert.Equal(convertedStrings, sourceList.Select(i => i.ToString()).Where(s => s != null).ToArray());
Assert.Equal(Array.Empty<string>(), sourceList.Select(i => i.ToString()).Where(s => s == null).ToArray());
}
[Fact]
public void SameResultsRepeatCallsFromWhereOnIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
Assert.Equal(q.ToArray(), q.ToArray());
}
[Fact]
public void SameResultsRepeatCallsFromWhereOnStringQuery()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x;
Assert.Equal(q.ToArray(), q.ToArray());
}
[Fact]
public void SameResultsButNotSameObject()
{
var qInt = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var qString = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x;
Assert.NotSame(qInt.ToArray(), qInt.ToArray());
Assert.NotSame(qString.ToArray(), qString.ToArray());
}
[Fact]
public void EmptyArraysSameObject()
{
Assert.Same(Enumerable.Empty<int>().ToArray(), Enumerable.Empty<int>().ToArray());
var array = new int[0];
Assert.NotSame(array, array.ToArray());
}
[Fact]
public void SourceIsEmptyICollectionT()
{
int[] source = { };
ICollection<int> collection = source as ICollection<int>;
Assert.Empty(source.ToArray());
Assert.Empty(collection.ToArray());
}
[Fact]
public void SourceIsICollectionTWithFewElements()
{
int?[] source = { -5, null, 0, 10, 3, -1, null, 4, 9 };
int?[] expected = { -5, null, 0, 10, 3, -1, null, 4, 9 };
ICollection<int?> collection = source as ICollection<int?>;
Assert.Equal(expected, source.ToArray());
Assert.Equal(expected, collection.ToArray());
}
[Fact]
public void SourceNotICollectionAndIsEmpty()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-4, 0);
Assert.Null(source as ICollection<int>);
Assert.Empty(source.ToArray());
}
[Fact]
public void SourceNotICollectionAndHasElements()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-4, 10);
int[] expected = { -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 };
Assert.Null(source as ICollection<int>);
Assert.Equal(expected, source.ToArray());
}
[Fact]
public void SourceNotICollectionAndAllNull()
{
IEnumerable<int?> source = RepeatedNullableNumberGuaranteedNotCollectionType(null, 5);
int?[] expected = { null, null, null, null, null };
Assert.Null(source as ICollection<int>);
Assert.Equal(expected, source.ToArray());
}
[Fact]
public void ConstantTimeCountPartitionSelectSameTypeToArray()
{
var source = Enumerable.Range(0, 100).Select(i => i * 2).Skip(1).Take(5);
Assert.Equal(new[] { 2, 4, 6, 8, 10 }, source.ToArray());
}
[Fact]
public void ConstantTimeCountPartitionSelectDiffTypeToArray()
{
var source = Enumerable.Range(0, 100).Select(i => i.ToString()).Skip(1).Take(5);
Assert.Equal(new[] { "1", "2", "3", "4", "5" }, source.ToArray());
}
[Fact]
public void ConstantTimeCountEmptyPartitionSelectSameTypeToArray()
{
var source = Enumerable.Range(0, 100).Select(i => i * 2).Skip(1000);
Assert.Empty(source.ToArray());
}
[Fact]
public void ConstantTimeCountEmptyPartitionSelectDiffTypeToArray()
{
var source = Enumerable.Range(0, 100).Select(i => i.ToString()).Skip(1000);
Assert.Empty(source.ToArray());
}
[Fact]
public void NonConstantTimeCountPartitionSelectSameTypeToArray()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 100).OrderBy(i => i).Select(i => i * 2).Skip(1).Take(5);
Assert.Equal(new[] { 2, 4, 6, 8, 10 }, source.ToArray());
}
[Fact]
public void NonConstantTimeCountPartitionSelectDiffTypeToArray()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 100).OrderBy(i => i).Select(i => i.ToString()).Skip(1).Take(5);
Assert.Equal(new[] { "1", "2", "3", "4", "5" }, source.ToArray());
}
[Fact]
public void NonConstantTimeCountEmptyPartitionSelectSameTypeToArray()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 100).OrderBy(i => i).Select(i => i * 2).Skip(1000);
Assert.Empty(source.ToArray());
}
[Fact]
public void NonConstantTimeCountEmptyPartitionSelectDiffTypeToArray()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 100).OrderBy(i => i).Select(i => i.ToString()).Skip(1000);
Assert.Empty(source.ToArray());
}
[Theory]
[MemberData(nameof(JustBelowPowersOfTwoLengths))]
[MemberData(nameof(PowersOfTwoLengths))]
[MemberData(nameof(JustAbovePowersOfTwoLengths))]
public void ToArrayShouldWorkWithSpecialLengthLazyEnumerables(int length)
{
Debug.Assert(length >= 0);
var range = Enumerable.Range(0, length);
var lazyEnumerable = ForceNotCollection(range); // We won't go down the IIListProvider path
Assert.Equal(range, lazyEnumerable.ToArray());
}
public static IEnumerable<object[]> JustBelowPowersOfTwoLengths()
{
return SmallPowersOfTwo.Select(p => new object[] { p - 1 });
}
public static IEnumerable<object[]> PowersOfTwoLengths()
{
return SmallPowersOfTwo.Select(p => new object[] { p });
}
public static IEnumerable<object[]> JustAbovePowersOfTwoLengths()
{
return SmallPowersOfTwo.Select(p => new object[] { p + 1 });
}
private static IEnumerable<int> SmallPowersOfTwo
{
get
{
// By N being "small" we mean that allocating an array of
// size N doesn't come close to the risk of causing an OOME
const int MaxPower = 18;
for (int i = 0; i <= MaxPower; i++)
{
yield return 1 << i; // equivalent to pow(2, i)
}
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using ElzeKool;
using Microsoft.SPOT;
using NetMf.CommonExtensions;
using netmfazurestorage.Account;
using netmfazurestorage.Http;
namespace netmfazurestorage.Blob
{
public class BlobClient
{
private readonly CloudStorageAccount _account;
public BlobClient(CloudStorageAccount account)
{
_account = account;
DateHeader = DateTime.Now.ToString("R");
}
public bool PutBlockBlob(string containerName, string blobName, string fileNamePath)
{
try
{
string deploymentPath =
StringUtility.Format("{0}/{1}/{2}", _account.UriEndpoints["Blob"], containerName,
blobName);
int contentLength;
HttpVerb = "PUT";
byte[] ms = GetPackageFileBytesAndLength(fileNamePath, out contentLength);
string canResource = StringUtility.Format("/{0}/{1}/{2}", _account.AccountName, containerName, blobName);
string authHeader = CreateAuthorizationHeader(canResource, "\nx-ms-blob-type:BlockBlob", contentLength);
try
{
var blobTypeHeaders = new Hashtable();
blobTypeHeaders.Add("x-ms-blob-type", "BlockBlob");
var response = AzureStorageHttpHelper.SendWebRequest(deploymentPath, authHeader, DateHeader, VersionHeader, ms, contentLength, HttpVerb, true, blobTypeHeaders);
if (response.StatusCode != HttpStatusCode.Created)
{
Debug.Print("Deployment Path was " + deploymentPath);
Debug.Print("Auth Header was " + authHeader);
Debug.Print("Ms was " + ms.Length);
Debug.Print("Length was " + contentLength);
}
else
{
Debug.Print("Success");
Debug.Print("Auth Header was " + authHeader);
}
return response.StatusCode == HttpStatusCode.Created;
}
catch (WebException wex)
{
Debug.Print(wex.ToString());
return false;
}
}
catch(IOException ex)
{
Debug.Print(ex.ToString());
return false;
}
catch(Exception ex)
{
Debug.Print(ex.ToString());
return false;
}
return true;
}
public bool PutBlockBlob(string containerName, string blobName, Byte[] ms)
{
try
{
string deploymentPath =
StringUtility.Format("{0}/{1}/{2}", _account.UriEndpoints["Blob"], containerName,
blobName);
int contentLength = ms.Length;
HttpVerb = "PUT";
string canResource = StringUtility.Format("/{0}/{1}/{2}", _account.AccountName, containerName, blobName);
string authHeader = CreateAuthorizationHeader(canResource, "\nx-ms-blob-type:BlockBlob", contentLength);
try
{
var blobTypeHeaders = new Hashtable();
blobTypeHeaders.Add("x-ms-blob-type", "BlockBlob");
var response = AzureStorageHttpHelper.SendWebRequest(deploymentPath, authHeader, DateHeader, VersionHeader, ms, contentLength, HttpVerb, true, blobTypeHeaders);
if (response.StatusCode != HttpStatusCode.Created)
{
Debug.Print("Deployment Path was " + deploymentPath);
Debug.Print("Auth Header was " + authHeader);
Debug.Print("Ms was " + ms.Length);
Debug.Print("Length was " + contentLength);
}
else
{
Debug.Print("Success");
Debug.Print("Auth Header was " + authHeader);
}
return response.StatusCode == HttpStatusCode.Created;
}
catch (WebException wex)
{
Debug.Print(wex.ToString());
return false;
}
}
catch (IOException ex)
{
Debug.Print(ex.ToString());
return false;
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
return false;
}
return true;
}
public bool DeleteBlob(string containerName, string blobName)
{
try
{
string deploymentPath =
StringUtility.Format("{0}/{1}/{2}", _account.UriEndpoints["Blob"], containerName,
blobName);
HttpVerb = "DELETE";
string canResource = StringUtility.Format("/{0}/{1}/{2}", _account.AccountName, containerName, blobName);
string authHeader = CreateAuthorizationHeader(canResource);
try
{
var response = AzureStorageHttpHelper.SendWebRequest(deploymentPath, authHeader, DateHeader, VersionHeader, null, 0, HttpVerb, true);
if (response.StatusCode != HttpStatusCode.Accepted)
{
Debug.Print("Deployment Path was " + deploymentPath);
Debug.Print("Auth Header was " + authHeader);
Debug.Print("Error Status Code: " + response.StatusCode);
}
else
{
Debug.Print("Success");
Debug.Print("Auth Header was " + authHeader);
}
return response.StatusCode == HttpStatusCode.Accepted;
}
catch (WebException wex)
{
Debug.Print(wex.ToString());
return false;
}
}
catch (IOException ex)
{
Debug.Print(ex.ToString());
return false;
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
return false;
}
}
public bool CreateContainer(string containerName)
{
try
{
string deploymentPath =
StringUtility.Format("{0}/{1}?{2}", _account.UriEndpoints["Blob"], containerName, ContainerString);
HttpVerb = "PUT";
string canResource = StringUtility.Format("/{0}/{1}\nrestype:container", _account.AccountName,
containerName);
string authHeader = CreateAuthorizationHeader(canResource);
try
{
var response = AzureStorageHttpHelper.SendWebRequest(deploymentPath, authHeader, DateHeader, VersionHeader, null, 0, HttpVerb, true);
if (response.StatusCode != HttpStatusCode.Created)
{
Debug.Print("Deployment Path was " + deploymentPath);
Debug.Print("Auth Header was " + authHeader);
Debug.Print("Error Status Code: " + response.StatusCode);
}
else
{
Debug.Print("Success");
Debug.Print("Auth Header was " + authHeader);
}
return response.StatusCode == HttpStatusCode.Created;
}
catch (WebException wex)
{
Debug.Print(wex.ToString());
return false;
}
}
catch (IOException ex)
{
Debug.Print(ex.ToString());
return false;
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
return false;
}
}
public bool DeleteContainer(string containerName)
{
try
{
string deploymentPath =
StringUtility.Format("{0}/{1}?{2}", _account.UriEndpoints["Blob"], containerName, ContainerString);
HttpVerb = "DELETE";
string canResource = StringUtility.Format("/{0}/{1}\nrestype:container", _account.AccountName,
containerName);
string authHeader = CreateAuthorizationHeader(canResource);
try
{
var response = AzureStorageHttpHelper.SendWebRequest(deploymentPath, authHeader, DateHeader, VersionHeader, null, 0, HttpVerb, true);
if (response.StatusCode != HttpStatusCode.Accepted)
{
Debug.Print("Deployment Path was " + deploymentPath);
Debug.Print("Auth Header was " + authHeader);
Debug.Print("Error Status Code: " + response.StatusCode);
}
else
{
Debug.Print("Success");
Debug.Print("Auth Header was " + authHeader);
}
return response.StatusCode == HttpStatusCode.Accepted;
}
catch (WebException wex)
{
Debug.Print(wex.ToString());
return false;
}
}
catch (IOException ex)
{
Debug.Print(ex.ToString());
return false;
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
return false;
}
}
protected byte[] GetPackageFileBytesAndLength(string fileName, out int contentLength)
{
byte[] ms = null;
contentLength = 0;
if (fileName != null)
{
using (StreamReader sr = new StreamReader(File.Open(fileName, FileMode.Open)))
{
string data = sr.ReadToEnd();
ms = Encoding.UTF8.GetBytes(data);
contentLength = ms.Length;
}
}
return ms;
}
protected string CreateAuthorizationHeader(string canResource, string options = "", int contentLength = 0)
{
string toSign = StringUtility.Format("{0}\n\n\n{1}\n\n\n\n\n\n\n\n{5}\nx-ms-date:{2}\nx-ms-version:{3}\n{4}",
HttpVerb, contentLength, DateHeader, VersionHeader, canResource, options);
var hmacBytes = SHA.computeHMAC_SHA256(Convert.FromBase64String(_account.AccountKey), Encoding.UTF8.GetBytes(toSign));
string signature = Convert.ToBase64String(hmacBytes).Replace("!", "+").Replace("*", "/");;
return "SharedKey " + _account.AccountName + ":" + signature;
}
internal const string VersionHeader = "2011-08-18";
private const string ContainerString = "restype=container";
protected string DateHeader { get; set; }
public string HttpVerb { get; set; }
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
// Enables instruction counting and displaying stats at process exit.
// #define STATS
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Management.Automation.Interpreter
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
[DebuggerTypeProxy(typeof(InstructionArray.DebugView))]
internal readonly struct InstructionArray
{
internal readonly int MaxStackDepth;
internal readonly int MaxContinuationDepth;
internal readonly Instruction[] Instructions;
internal readonly object[] Objects;
internal readonly RuntimeLabel[] Labels;
// list of (instruction index, cookie) sorted by instruction index:
internal readonly List<KeyValuePair<int, object>> DebugCookies;
internal InstructionArray(int maxStackDepth, int maxContinuationDepth, Instruction[] instructions,
object[] objects, RuntimeLabel[] labels, List<KeyValuePair<int, object>> debugCookies)
{
MaxStackDepth = maxStackDepth;
MaxContinuationDepth = maxContinuationDepth;
Instructions = instructions;
DebugCookies = debugCookies;
Objects = objects;
Labels = labels;
}
internal int Length
{
get { return Instructions.Length; }
}
#region Debug View
internal sealed class DebugView
{
private readonly InstructionArray _array;
public DebugView(InstructionArray array)
{
_array = array;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public InstructionList.DebugView.InstructionView[] A0
{
get
{
return InstructionList.DebugView.GetInstructionViews(
_array.Instructions,
_array.Objects,
(index) => _array.Labels[index].Index,
_array.DebugCookies
);
}
}
}
#endregion
}
[DebuggerTypeProxy(typeof(InstructionList.DebugView))]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
internal sealed class InstructionList
{
private readonly List<Instruction> _instructions = new List<Instruction>();
private List<object> _objects;
private int _currentStackDepth;
private int _maxStackDepth;
private int _currentContinuationsDepth;
private int _maxContinuationDepth;
private int _runtimeLabelCount;
private List<BranchLabel> _labels;
// list of (instruction index, cookie) sorted by instruction index:
#pragma warning disable IDE0044 // Add readonly modifier
private List<KeyValuePair<int, object>> _debugCookies = null;
#pragma warning restore IDE0044 // Variable is assigned when DEBUG is defined.
#region Debug View
internal sealed class DebugView
{
private readonly InstructionList _list;
public DebugView(InstructionList list)
{
_list = list;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public InstructionView[] A0
{
get
{
return GetInstructionViews(
_list._instructions,
_list._objects,
(index) => _list._labels[index].TargetIndex,
_list._debugCookies
);
}
}
internal static InstructionView[] GetInstructionViews(IList<Instruction> instructions, IList<object> objects,
Func<int, int> labelIndexer, IList<KeyValuePair<int, object>> debugCookies)
{
var result = new List<InstructionView>();
int index = 0;
int stackDepth = 0;
int continuationsDepth = 0;
var cookieEnumerator = (debugCookies ?? Array.Empty<KeyValuePair<int, object>>()).GetEnumerator();
var hasCookie = cookieEnumerator.MoveNext();
for (int i = 0; i < instructions.Count; i++)
{
object cookie = null;
while (hasCookie && cookieEnumerator.Current.Key == i)
{
cookie = cookieEnumerator.Current.Value;
hasCookie = cookieEnumerator.MoveNext();
}
int stackDiff = instructions[i].StackBalance;
int contDiff = instructions[i].ContinuationsBalance;
string name = instructions[i].ToDebugString(i, cookie, labelIndexer, objects);
result.Add(new InstructionView(instructions[i], name, i, stackDepth, continuationsDepth));
index++;
stackDepth += stackDiff;
continuationsDepth += contDiff;
}
return result.ToArray();
}
[DebuggerDisplay("{GetValue(),nq}", Name = "{GetName(),nq}", Type = "{GetDisplayType(), nq}")]
internal readonly struct InstructionView
{
private readonly int _index;
private readonly int _stackDepth;
private readonly int _continuationsDepth;
private readonly string _name;
private readonly Instruction _instruction;
internal string GetName()
{
return _index +
(_continuationsDepth == 0 ? string.Empty : " C(" + _continuationsDepth + ")") +
(_stackDepth == 0 ? string.Empty : " S(" + _stackDepth + ")");
}
internal string GetValue()
{
return _name;
}
internal string GetDisplayType()
{
return _instruction.ContinuationsBalance + "/" + _instruction.StackBalance;
}
public InstructionView(Instruction instruction, string name, int index, int stackDepth, int continuationsDepth)
{
_instruction = instruction;
_name = name;
_index = index;
_stackDepth = stackDepth;
_continuationsDepth = continuationsDepth;
}
}
}
#endregion
#region Core Emit Ops
public void Emit(Instruction instruction)
{
_instructions.Add(instruction);
UpdateStackDepth(instruction);
}
private void UpdateStackDepth(Instruction instruction)
{
Debug.Assert(instruction.ConsumedStack >= 0 && instruction.ProducedStack >= 0 &&
instruction.ConsumedContinuations >= 0 && instruction.ProducedContinuations >= 0);
_currentStackDepth -= instruction.ConsumedStack;
Debug.Assert(_currentStackDepth >= 0);
_currentStackDepth += instruction.ProducedStack;
if (_currentStackDepth > _maxStackDepth)
{
_maxStackDepth = _currentStackDepth;
}
_currentContinuationsDepth -= instruction.ConsumedContinuations;
Debug.Assert(_currentContinuationsDepth >= 0);
_currentContinuationsDepth += instruction.ProducedContinuations;
if (_currentContinuationsDepth > _maxContinuationDepth)
{
_maxContinuationDepth = _currentContinuationsDepth;
}
}
/// <summary>
/// Attaches a cookie to the last emitted instruction.
/// </summary>
[Conditional("DEBUG")]
public void SetDebugCookie(object cookie)
{
#if DEBUG
if (_debugCookies == null)
{
_debugCookies = new List<KeyValuePair<int, object>>();
}
Debug.Assert(Count > 0);
_debugCookies.Add(new KeyValuePair<int, object>(Count - 1, cookie));
#endif
}
public int Count
{
get { return _instructions.Count; }
}
public int CurrentStackDepth
{
get { return _currentStackDepth; }
}
public int CurrentContinuationsDepth
{
get { return _currentContinuationsDepth; }
}
public int MaxStackDepth
{
get { return _maxStackDepth; }
}
internal Instruction GetInstruction(int index)
{
return _instructions[index];
}
#if STATS
private static Dictionary<string, int> _executedInstructions = new Dictionary<string, int>();
private static Dictionary<string, Dictionary<object, bool>> _instances = new Dictionary<string, Dictionary<object, bool>>();
static InstructionList() {
AppDomain.CurrentDomain.ProcessExit += new EventHandler((_, __) => {
PerfTrack.DumpHistogram(_executedInstructions);
Console.WriteLine("-- Total executed: {0}", _executedInstructions.Values.Aggregate(0, static (sum, value) => sum + value));
Console.WriteLine("-----");
var referenced = new Dictionary<string, int>();
int total = 0;
foreach (var entry in _instances) {
referenced[entry.Key] = entry.Value.Count;
total += entry.Value.Count;
}
PerfTrack.DumpHistogram(referenced);
Console.WriteLine("-- Total referenced: {0}", total);
Console.WriteLine("-----");
});
}
#endif
public InstructionArray ToArray()
{
#if STATS
lock (_executedInstructions) {
_instructions.ForEach((instr) => {
int value = 0;
var name = instr.GetType().Name;
_executedInstructions.TryGetValue(name, out value);
_executedInstructions[name] = value + 1;
Dictionary<object, bool> dict;
if (!_instances.TryGetValue(name, out dict)) {
_instances[name] = dict = new Dictionary<object, bool>();
}
dict[instr] = true;
});
}
#endif
return new InstructionArray(
_maxStackDepth,
_maxContinuationDepth,
_instructions.ToArray(),
_objects?.ToArray(),
BuildRuntimeLabels(),
_debugCookies
);
}
#endregion
#region Stack Operations
private const int PushIntMinCachedValue = -100;
private const int PushIntMaxCachedValue = 100;
private const int CachedObjectCount = 256;
private static Instruction s_null;
private static Instruction s_true;
private static Instruction s_false;
private static Instruction[] s_ints;
private static Instruction[] s_loadObjectCached;
public void EmitLoad(object value)
{
EmitLoad(value, null);
}
public void EmitLoad(bool value)
{
if ((bool)value)
{
Emit(s_true ??= new LoadObjectInstruction(value));
}
else
{
Emit(s_false ??= new LoadObjectInstruction(value));
}
}
public void EmitLoad(object value, Type type)
{
if (value == null)
{
Emit(s_null ??= new LoadObjectInstruction(null));
return;
}
if (type == null || type.IsValueType)
{
if (value is bool)
{
EmitLoad((bool)value);
return;
}
if (value is int)
{
int i = (int)value;
if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue)
{
if (s_ints == null)
{
s_ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1];
}
i -= PushIntMinCachedValue;
Emit(s_ints[i] ?? (s_ints[i] = new LoadObjectInstruction(value)));
return;
}
}
}
if (_objects == null)
{
_objects = new List<object>();
if (s_loadObjectCached == null)
{
s_loadObjectCached = new Instruction[CachedObjectCount];
}
}
if (_objects.Count < s_loadObjectCached.Length)
{
uint index = (uint)_objects.Count;
_objects.Add(value);
Emit(s_loadObjectCached[index] ?? (s_loadObjectCached[index] = new LoadCachedObjectInstruction(index)));
}
else
{
Emit(new LoadObjectInstruction(value));
}
}
public void EmitDup()
{
Emit(DupInstruction.Instance);
}
public void EmitPop()
{
Emit(PopInstruction.Instance);
}
#endregion
#region Locals
internal void SwitchToBoxed(int index, int instructionIndex)
{
var instruction = _instructions[instructionIndex] as IBoxableInstruction;
if (instruction != null)
{
var newInstruction = instruction.BoxIfIndexMatches(index);
if (newInstruction != null)
{
_instructions[instructionIndex] = newInstruction;
}
}
}
private const int LocalInstrCacheSize = 64;
private static Instruction[] s_loadLocal;
private static Instruction[] s_loadLocalBoxed;
private static Instruction[] s_loadLocalFromClosure;
private static Instruction[] s_loadLocalFromClosureBoxed;
private static Instruction[] s_assignLocal;
private static Instruction[] s_storeLocal;
private static Instruction[] s_assignLocalBoxed;
private static Instruction[] s_storeLocalBoxed;
private static Instruction[] s_assignLocalToClosure;
private static Instruction[] s_initReference;
private static Instruction[] s_initImmutableRefBox;
private static Instruction[] s_parameterBox;
private static Instruction[] s_parameter;
public void EmitLoadLocal(int index)
{
if (s_loadLocal == null)
{
s_loadLocal = new Instruction[LocalInstrCacheSize];
}
if (index < s_loadLocal.Length)
{
Emit(s_loadLocal[index] ?? (s_loadLocal[index] = new LoadLocalInstruction(index)));
}
else
{
Emit(new LoadLocalInstruction(index));
}
}
public void EmitLoadLocalBoxed(int index)
{
Emit(LoadLocalBoxed(index));
}
internal static Instruction LoadLocalBoxed(int index)
{
if (s_loadLocalBoxed == null)
{
s_loadLocalBoxed = new Instruction[LocalInstrCacheSize];
}
if (index < s_loadLocalBoxed.Length)
{
return s_loadLocalBoxed[index] ?? (s_loadLocalBoxed[index] = new LoadLocalBoxedInstruction(index));
}
else
{
return new LoadLocalBoxedInstruction(index);
}
}
public void EmitLoadLocalFromClosure(int index)
{
if (s_loadLocalFromClosure == null)
{
s_loadLocalFromClosure = new Instruction[LocalInstrCacheSize];
}
if (index < s_loadLocalFromClosure.Length)
{
Emit(s_loadLocalFromClosure[index] ?? (s_loadLocalFromClosure[index] = new LoadLocalFromClosureInstruction(index)));
}
else
{
Emit(new LoadLocalFromClosureInstruction(index));
}
}
public void EmitLoadLocalFromClosureBoxed(int index)
{
if (s_loadLocalFromClosureBoxed == null)
{
s_loadLocalFromClosureBoxed = new Instruction[LocalInstrCacheSize];
}
if (index < s_loadLocalFromClosureBoxed.Length)
{
Emit(s_loadLocalFromClosureBoxed[index] ?? (s_loadLocalFromClosureBoxed[index] = new LoadLocalFromClosureBoxedInstruction(index)));
}
else
{
Emit(new LoadLocalFromClosureBoxedInstruction(index));
}
}
public void EmitAssignLocal(int index)
{
if (s_assignLocal == null)
{
s_assignLocal = new Instruction[LocalInstrCacheSize];
}
if (index < s_assignLocal.Length)
{
Emit(s_assignLocal[index] ?? (s_assignLocal[index] = new AssignLocalInstruction(index)));
}
else
{
Emit(new AssignLocalInstruction(index));
}
}
public void EmitStoreLocal(int index)
{
if (s_storeLocal == null)
{
s_storeLocal = new Instruction[LocalInstrCacheSize];
}
if (index < s_storeLocal.Length)
{
Emit(s_storeLocal[index] ?? (s_storeLocal[index] = new StoreLocalInstruction(index)));
}
else
{
Emit(new StoreLocalInstruction(index));
}
}
public void EmitAssignLocalBoxed(int index)
{
Emit(AssignLocalBoxed(index));
}
internal static Instruction AssignLocalBoxed(int index)
{
if (s_assignLocalBoxed == null)
{
s_assignLocalBoxed = new Instruction[LocalInstrCacheSize];
}
if (index < s_assignLocalBoxed.Length)
{
return s_assignLocalBoxed[index] ?? (s_assignLocalBoxed[index] = new AssignLocalBoxedInstruction(index));
}
else
{
return new AssignLocalBoxedInstruction(index);
}
}
public void EmitStoreLocalBoxed(int index)
{
Emit(StoreLocalBoxed(index));
}
internal static Instruction StoreLocalBoxed(int index)
{
if (s_storeLocalBoxed == null)
{
s_storeLocalBoxed = new Instruction[LocalInstrCacheSize];
}
if (index < s_storeLocalBoxed.Length)
{
return s_storeLocalBoxed[index] ?? (s_storeLocalBoxed[index] = new StoreLocalBoxedInstruction(index));
}
else
{
return new StoreLocalBoxedInstruction(index);
}
}
public void EmitAssignLocalToClosure(int index)
{
if (s_assignLocalToClosure == null)
{
s_assignLocalToClosure = new Instruction[LocalInstrCacheSize];
}
if (index < s_assignLocalToClosure.Length)
{
Emit(s_assignLocalToClosure[index] ?? (s_assignLocalToClosure[index] = new AssignLocalToClosureInstruction(index)));
}
else
{
Emit(new AssignLocalToClosureInstruction(index));
}
}
public void EmitStoreLocalToClosure(int index)
{
EmitAssignLocalToClosure(index);
EmitPop();
}
public void EmitInitializeLocal(int index, Type type)
{
object value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type);
if (value != null)
{
Emit(new InitializeLocalInstruction.ImmutableValue(index, value));
}
else if (type.IsValueType)
{
Emit(new InitializeLocalInstruction.MutableValue(index, type));
}
else
{
Emit(InitReference(index));
}
}
internal void EmitInitializeParameter(int index)
{
Emit(Parameter(index));
}
internal static Instruction Parameter(int index)
{
if (s_parameter == null)
{
s_parameter = new Instruction[LocalInstrCacheSize];
}
if (index < s_parameter.Length)
{
return s_parameter[index] ?? (s_parameter[index] = new InitializeLocalInstruction.Parameter(index));
}
return new InitializeLocalInstruction.Parameter(index);
}
internal static Instruction ParameterBox(int index)
{
if (s_parameterBox == null)
{
s_parameterBox = new Instruction[LocalInstrCacheSize];
}
if (index < s_parameterBox.Length)
{
return s_parameterBox[index] ?? (s_parameterBox[index] = new InitializeLocalInstruction.ParameterBox(index));
}
return new InitializeLocalInstruction.ParameterBox(index);
}
internal static Instruction InitReference(int index)
{
if (s_initReference == null)
{
s_initReference = new Instruction[LocalInstrCacheSize];
}
if (index < s_initReference.Length)
{
return s_initReference[index] ?? (s_initReference[index] = new InitializeLocalInstruction.Reference(index));
}
return new InitializeLocalInstruction.Reference(index);
}
internal static Instruction InitImmutableRefBox(int index)
{
if (s_initImmutableRefBox == null)
{
s_initImmutableRefBox = new Instruction[LocalInstrCacheSize];
}
if (index < s_initImmutableRefBox.Length)
{
return s_initImmutableRefBox[index] ?? (s_initImmutableRefBox[index] = new InitializeLocalInstruction.ImmutableBox(index, null));
}
return new InitializeLocalInstruction.ImmutableBox(index, null);
}
public void EmitNewRuntimeVariables(int count)
{
Emit(new RuntimeVariablesInstruction(count));
}
#endregion
#region Array Operations
public void EmitGetArrayItem(Type arrayType)
{
var elementType = arrayType.GetElementType();
if (elementType.IsClass || elementType.IsInterface)
{
Emit(InstructionFactory<object>.Factory.GetArrayItem());
}
else
{
Emit(InstructionFactory.GetFactory(elementType).GetArrayItem());
}
}
public void EmitSetArrayItem(Type arrayType)
{
var elementType = arrayType.GetElementType();
if (elementType.IsClass || elementType.IsInterface)
{
Emit(InstructionFactory<object>.Factory.SetArrayItem());
}
else
{
Emit(InstructionFactory.GetFactory(elementType).SetArrayItem());
}
}
public void EmitNewArray(Type elementType)
{
Emit(InstructionFactory.GetFactory(elementType).NewArray());
}
public void EmitNewArrayBounds(Type elementType, int rank)
{
Emit(new NewArrayBoundsInstruction(elementType, rank));
}
public void EmitNewArrayInit(Type elementType, int elementCount)
{
// To avoid lock contention in InstructionFactory.GetFactory, we special case the most common
// types of arrays that the compiler creates.
if (elementType == typeof(CommandParameterInternal))
{
Emit(InstructionFactory<CommandParameterInternal>.Factory.NewArrayInit(elementCount));
}
else if (elementType == typeof(CommandParameterInternal[]))
{
Emit(InstructionFactory<CommandParameterInternal[]>.Factory.NewArrayInit(elementCount));
}
else if (elementType == typeof(object))
{
Emit(InstructionFactory<object>.Factory.NewArrayInit(elementCount));
}
else if (elementType == typeof(string))
{
Emit(InstructionFactory<string>.Factory.NewArrayInit(elementCount));
}
else
{
Emit(InstructionFactory.GetFactory(elementType).NewArrayInit(elementCount));
}
}
#endregion
#region Arithmetic Operations
public void EmitAdd(Type type, bool @checked)
{
if (@checked)
{
Emit(AddOvfInstruction.Create(type));
}
else
{
Emit(AddInstruction.Create(type));
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
public void EmitSub(Type type, bool @checked)
{
if (@checked)
{
Emit(SubOvfInstruction.Create(type));
}
else
{
Emit(SubInstruction.Create(type));
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
public void EmitMul(Type type, bool @checked)
{
if (@checked)
{
Emit(MulOvfInstruction.Create(type));
}
else
{
Emit(MulInstruction.Create(type));
}
}
public void EmitDiv(Type type)
{
Emit(DivInstruction.Create(type));
}
#endregion
#region Comparisons
public void EmitEqual(Type type)
{
Emit(EqualInstruction.Create(type));
}
public void EmitNotEqual(Type type)
{
Emit(NotEqualInstruction.Create(type));
}
public void EmitLessThan(Type type)
{
Emit(LessThanInstruction.Create(type));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
public void EmitLessThanOrEqual(Type type)
{
throw new NotSupportedException();
}
public void EmitGreaterThan(Type type)
{
Emit(GreaterThanInstruction.Create(type));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
public void EmitGreaterThanOrEqual(Type type)
{
throw new NotSupportedException();
}
#endregion
#region Conversions
public void EmitNumericConvertChecked(TypeCode from, TypeCode to)
{
Emit(new NumericConvertInstruction.Checked(from, to));
}
public void EmitNumericConvertUnchecked(TypeCode from, TypeCode to)
{
Emit(new NumericConvertInstruction.Unchecked(from, to));
}
#endregion
#region Boolean Operators
public void EmitNot()
{
Emit(NotInstruction.Instance);
}
#endregion
#region Types
public void EmitDefaultValue(Type type)
{
Emit(InstructionFactory.GetFactory(type).DefaultValue());
}
public void EmitNew(ConstructorInfo constructorInfo)
{
Emit(new NewInstruction(constructorInfo));
}
internal void EmitCreateDelegate(LightDelegateCreator creator)
{
Emit(new CreateDelegateInstruction(creator));
}
public void EmitTypeEquals()
{
Emit(TypeEqualsInstruction.Instance);
}
public void EmitTypeIs(Type type)
{
Emit(InstructionFactory.GetFactory(type).TypeIs());
}
public void EmitTypeAs(Type type)
{
Emit(InstructionFactory.GetFactory(type).TypeAs());
}
#endregion
#region Fields and Methods
private static readonly Dictionary<FieldInfo, Instruction> s_loadFields = new Dictionary<FieldInfo, Instruction>();
public void EmitLoadField(FieldInfo field)
{
Emit(GetLoadField(field));
}
private static Instruction GetLoadField(FieldInfo field)
{
lock (s_loadFields)
{
Instruction instruction;
if (!s_loadFields.TryGetValue(field, out instruction))
{
if (field.IsStatic)
{
instruction = new LoadStaticFieldInstruction(field);
}
else
{
instruction = new LoadFieldInstruction(field);
}
s_loadFields.Add(field, instruction);
}
return instruction;
}
}
public void EmitStoreField(FieldInfo field)
{
if (field.IsStatic)
{
Emit(new StoreStaticFieldInstruction(field));
}
else
{
Emit(new StoreFieldInstruction(field));
}
}
public void EmitCall(MethodInfo method)
{
EmitCall(method, method.GetParameters());
}
public void EmitCall(MethodInfo method, ParameterInfo[] parameters)
{
Emit(CallInstruction.Create(method, parameters));
}
#endregion
#region Dynamic
public void EmitDynamic(Type type, CallSiteBinder binder)
{
Emit(CreateDynamicInstruction(type, binder));
}
#region Generated Dynamic InstructionList Factory
// *** BEGIN GENERATED CODE ***
// generated by function: gen_instructionlist_factory from: generate_dynamic_instructions.py
public void EmitDynamic<T0, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, T3, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, T3, T4, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TRet>.Factory(binder));
}
public void EmitDynamic<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TRet>(CallSiteBinder binder)
{
Emit(DynamicInstruction<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TRet>.Factory(binder));
}
// *** END GENERATED CODE ***
#endregion
private static readonly Dictionary<Type, Func<CallSiteBinder, Instruction>> s_factories =
new Dictionary<Type, Func<CallSiteBinder, Instruction>>();
internal static Instruction CreateDynamicInstruction(Type delegateType, CallSiteBinder binder)
{
Func<CallSiteBinder, Instruction> factory;
lock (s_factories)
{
if (!s_factories.TryGetValue(delegateType, out factory))
{
if (delegateType.GetMethod("Invoke").ReturnType == typeof(void))
{
// TODO: We should generally support void returning binders but the only
// ones that exist are delete index/member who's perf isn't that critical.
return new DynamicInstructionN(delegateType, CallSite.Create(delegateType, binder), true);
}
Type instructionType = DynamicInstructionN.GetDynamicInstructionType(delegateType);
if (instructionType == null)
{
return new DynamicInstructionN(delegateType, CallSite.Create(delegateType, binder));
}
factory = (Func<CallSiteBinder, Instruction>)instructionType
.GetMethod("Factory")
.CreateDelegate(typeof(Func<CallSiteBinder, Instruction>));
s_factories[delegateType] = factory;
}
}
return factory(binder);
}
#endregion
#region Control Flow
private static readonly RuntimeLabel[] s_emptyRuntimeLabels = new RuntimeLabel[] { new RuntimeLabel(Interpreter.RethrowOnReturn, 0, 0) };
private RuntimeLabel[] BuildRuntimeLabels()
{
if (_runtimeLabelCount == 0)
{
return s_emptyRuntimeLabels;
}
var result = new RuntimeLabel[_runtimeLabelCount + 1];
foreach (BranchLabel label in _labels)
{
if (label.HasRuntimeLabel)
{
result[label.LabelIndex] = label.ToRuntimeLabel();
}
}
// "return and rethrow" label:
result[result.Length - 1] = new RuntimeLabel(Interpreter.RethrowOnReturn, 0, 0);
return result;
}
public BranchLabel MakeLabel()
{
if (_labels == null)
{
_labels = new List<BranchLabel>();
}
var label = new BranchLabel();
_labels.Add(label);
return label;
}
internal void FixupBranch(int branchIndex, int offset)
{
_instructions[branchIndex] = ((OffsetInstruction)_instructions[branchIndex]).Fixup(offset);
}
private int EnsureLabelIndex(BranchLabel label)
{
if (label.HasRuntimeLabel)
{
return label.LabelIndex;
}
label.LabelIndex = _runtimeLabelCount;
_runtimeLabelCount++;
return label.LabelIndex;
}
public int MarkRuntimeLabel()
{
BranchLabel handlerLabel = MakeLabel();
MarkLabel(handlerLabel);
return EnsureLabelIndex(handlerLabel);
}
public void MarkLabel(BranchLabel label)
{
label.Mark(this);
}
public void EmitGoto(BranchLabel label, bool hasResult, bool hasValue)
{
Emit(GotoInstruction.Create(EnsureLabelIndex(label), hasResult, hasValue));
}
private void EmitBranch(OffsetInstruction instruction, BranchLabel label)
{
Emit(instruction);
label.AddBranch(this, Count - 1);
}
public void EmitBranch(BranchLabel label)
{
EmitBranch(new BranchInstruction(), label);
}
public void EmitBranch(BranchLabel label, bool hasResult, bool hasValue)
{
EmitBranch(new BranchInstruction(hasResult, hasValue), label);
}
public void EmitCoalescingBranch(BranchLabel leftNotNull)
{
EmitBranch(new CoalescingBranchInstruction(), leftNotNull);
}
public void EmitBranchTrue(BranchLabel elseLabel)
{
EmitBranch(new BranchTrueInstruction(), elseLabel);
}
public void EmitBranchFalse(BranchLabel elseLabel)
{
EmitBranch(new BranchFalseInstruction(), elseLabel);
}
public void EmitThrow()
{
Emit(ThrowInstruction.Throw);
}
public void EmitThrowVoid()
{
Emit(ThrowInstruction.VoidThrow);
}
public void EmitRethrow()
{
Emit(ThrowInstruction.Rethrow);
}
public void EmitRethrowVoid()
{
Emit(ThrowInstruction.VoidRethrow);
}
public void EmitEnterTryFinally(BranchLabel finallyStartLabel)
{
Emit(EnterTryCatchFinallyInstruction.CreateTryFinally(EnsureLabelIndex(finallyStartLabel)));
}
public void EmitEnterTryCatch()
{
Emit(EnterTryCatchFinallyInstruction.CreateTryCatch());
}
public void EmitEnterFinally(BranchLabel finallyStartLabel)
{
Emit(EnterFinallyInstruction.Create(EnsureLabelIndex(finallyStartLabel)));
}
public void EmitLeaveFinally()
{
Emit(LeaveFinallyInstruction.Instance);
}
public void EmitLeaveFault(bool hasValue)
{
Emit(hasValue ? LeaveFaultInstruction.NonVoid : LeaveFaultInstruction.Void);
}
public void EmitEnterExceptionHandlerNonVoid()
{
Emit(EnterExceptionHandlerInstruction.NonVoid);
}
public void EmitEnterExceptionHandlerVoid()
{
Emit(EnterExceptionHandlerInstruction.Void);
}
public void EmitLeaveExceptionHandler(bool hasValue, BranchLabel tryExpressionEndLabel)
{
Emit(LeaveExceptionHandlerInstruction.Create(EnsureLabelIndex(tryExpressionEndLabel), hasValue));
}
public void EmitSwitch(Dictionary<int, int> cases)
{
Emit(new SwitchInstruction(cases));
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
** Purpose: A circular-array implementation of a generic queue.
**
**
=============================================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Collections.Generic
{
// A simple Queue of generic objects. Internally it is implemented as a
// circular buffer, so Enqueue can be O(n). Dequeue is O(1).
[DebuggerTypeProxy(typeof(QueueDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class Queue<T> : IEnumerable<T>,
System.Collections.ICollection,
IReadOnlyCollection<T>
{
private T[] _array;
private int _head; // The index from which to dequeue if the queue isn't empty.
private int _tail; // The index at which to enqueue if the queue isn't full.
private int _size; // Number of elements.
private int _version;
private object _syncRoot;
private const int MinimumGrow = 4;
private const int GrowFactor = 200; // double each time
// Creates a queue with room for capacity objects. The default initial
// capacity and grow factor are used.
public Queue()
{
_array = Array.Empty<T>();
}
// Creates a queue with room for capacity objects. The default grow factor
// is used.
public Queue(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
_array = new T[capacity];
}
// Fills a Queue with the elements of an ICollection. Uses the enumerator
// to get each of the elements.
public Queue(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
_array = EnumerableHelpers.ToArray(collection, out _size);
if (_size != _array.Length) _tail = _size;
}
public int Count
{
get { return _size; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the queue.
public void Clear()
{
if (_size != 0)
{
if (_head < _tail)
Array.Clear(_array, _head, _size);
else
{
Array.Clear(_array, _head, _array.Length - _head);
Array.Clear(_array, 0, _tail);
}
_size = 0;
}
_head = 0;
_tail = 0;
_version++;
}
// CopyTo copies a collection into an Array, starting at a particular
// index into the array.
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
int arrayLen = array.Length;
if (arrayLen - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int numToCopy = _size;
if (numToCopy == 0) return;
int firstPart = Math.Min(_array.Length - _head, numToCopy);
Array.Copy(_array, _head, array, arrayIndex, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
{
Array.Copy(_array, 0, array, arrayIndex + _array.Length - _head, numToCopy);
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
int arrayLen = array.Length;
if (index < 0 || index > arrayLen)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
if (arrayLen - index < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int numToCopy = _size;
if (numToCopy == 0) return;
try
{
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, array, index, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
{
Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
// Adds item to the tail of the queue.
public void Enqueue(T item)
{
if (_size == _array.Length)
{
int newcapacity = (int)((long)_array.Length * (long)GrowFactor / 100);
if (newcapacity < _array.Length + MinimumGrow)
{
newcapacity = _array.Length + MinimumGrow;
}
SetCapacity(newcapacity);
}
_array[_tail] = item;
MoveNext(ref _tail);
_size++;
_version++;
}
// GetEnumerator returns an IEnumerator over this Queue. This
// Enumerator will support removing.
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
// Removes the object at the head of the queue and returns it. If the queue
// is empty, this method throws an
// InvalidOperationException.
public T Dequeue()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
T removed = _array[_head];
_array[_head] = default(T);
MoveNext(ref _head);
_size--;
_version++;
return removed;
}
// Returns the object at the head of the queue. The object remains in the
// queue. If the queue is empty, this method throws an
// InvalidOperationException.
public T Peek()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
return _array[_head];
}
// Returns true if the queue contains at least one object equal to item.
// Equality is determined using item.Equals().
public bool Contains(T item)
{
int index = _head;
int count = _size;
EqualityComparer<T> c = EqualityComparer<T>.Default;
while (count-- > 0)
{
if (c.Equals(_array[index], item))
{
return true;
}
MoveNext(ref index);
}
return false;
}
// Iterates over the objects in the queue, returning an array of the
// objects in the Queue, or an empty array if the queue is empty.
// The order of elements in the array is first in to last in, the same
// order produced by successive calls to Dequeue.
public T[] ToArray()
{
if (_size == 0)
{
return Array.Empty<T>();
}
T[] arr = new T[_size];
if (_head < _tail)
{
Array.Copy(_array, _head, arr, 0, _size);
}
else
{
Array.Copy(_array, _head, arr, 0, _array.Length - _head);
Array.Copy(_array, 0, arr, _array.Length - _head, _tail);
}
return arr;
}
// PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity
// must be >= _size.
private void SetCapacity(int capacity)
{
T[] newarray = new T[capacity];
if (_size > 0)
{
if (_head < _tail)
{
Array.Copy(_array, _head, newarray, 0, _size);
}
else
{
Array.Copy(_array, _head, newarray, 0, _array.Length - _head);
Array.Copy(_array, 0, newarray, _array.Length - _head, _tail);
}
}
_array = newarray;
_head = 0;
_tail = (_size == capacity) ? 0 : _size;
_version++;
}
// Increments the index wrapping it if necessary.
private void MoveNext(ref int index)
{
// It is tempting to use the remainder operator here but it is actually much slower
// than a simple comparison and a rarely taken branch.
int tmp = index + 1;
index = (tmp == _array.Length) ? 0 : tmp;
}
public void TrimExcess()
{
int threshold = (int)(((double)_array.Length) * 0.9);
if (_size < threshold)
{
SetCapacity(_size);
}
}
// Implements an enumerator for a Queue. The enumerator uses the
// internal version number of the list to ensure that no modifications are
// made to the list while an enumeration is in progress.
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<T>,
System.Collections.IEnumerator
{
private readonly Queue<T> _q;
private readonly int _version;
private int _index; // -1 = not started, -2 = ended/disposed
private T _currentElement;
internal Enumerator(Queue<T> q)
{
_q = q;
_version = q._version;
_index = -1;
_currentElement = default(T);
}
public void Dispose()
{
_index = -2;
_currentElement = default(T);
}
public bool MoveNext()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index == -2)
return false;
_index++;
if (_index == _q._size)
{
// We've run past the last element
_index = -2;
_currentElement = default(T);
return false;
}
// Cache some fields in locals to decrease code size
T[] array = _q._array;
int capacity = array.Length;
// _index represents the 0-based index into the queue, however the queue
// doesn't have to start from 0 and it may not even be stored contiguously in memory.
int arrayIndex = _q._head + _index; // this is the actual index into the queue's backing array
if (arrayIndex >= capacity)
{
// NOTE: Originally we were using the modulo operator here, however
// on Intel processors it has a very high instruction latency which
// was slowing down the loop quite a bit.
// Replacing it with simple comparison/subtraction operations sped up
// the average foreach loop by 2x.
arrayIndex -= capacity; // wrap around if needed
}
_currentElement = array[arrayIndex];
return true;
}
public T Current
{
get
{
if (_index < 0)
ThrowEnumerationNotStartedOrEnded();
return _currentElement;
}
}
private void ThrowEnumerationNotStartedOrEnded()
{
Debug.Assert(_index == -1 || _index == -2);
throw new InvalidOperationException(_index == -1 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded);
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -1;
_currentElement = default(T);
}
}
}
}
| |
//
// 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.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using DiscUtils.Streams;
namespace DiscUtils.Iso9660
{
/// <summary>
/// Class that creates ISO images.
/// </summary>
/// <example>
/// <code>
/// CDBuilder builder = new CDBuilder();
/// builder.VolumeIdentifier = "MYISO";
/// builder.UseJoliet = true;
/// builder.AddFile("Hello.txt", Encoding.ASCII.GetBytes("hello world!"));
/// builder.Build(@"C:\TEMP\myiso.iso");
/// </code>
/// </example>
public sealed class CDBuilder : StreamBuilder
{
private const long DiskStart = 0x8000;
private BootInitialEntry _bootEntry;
private Stream _bootImage;
private readonly BuildParameters _buildParams;
private readonly List<BuildDirectoryInfo> _dirs;
private readonly List<BuildFileInfo> _files;
private readonly BuildDirectoryInfo _rootDirectory;
/// <summary>
/// Initializes a new instance of the CDBuilder class.
/// </summary>
public CDBuilder()
{
_files = new List<BuildFileInfo>();
_dirs = new List<BuildDirectoryInfo>();
_rootDirectory = new BuildDirectoryInfo("\0", null);
_dirs.Add(_rootDirectory);
_buildParams = new BuildParameters();
_buildParams.UseJoliet = true;
}
/// <summary>
/// Gets or sets a value indicating whether to update the ISOLINUX info table at the
/// start of the boot image. Use with ISOLINUX only.
/// </summary>
/// <remarks>
/// ISOLINUX has an 'information table' at the start of the boot loader that verifies
/// the CD has been loaded correctly by the BIOS. This table needs to be updated
/// to match the actual ISO.
/// </remarks>
public bool UpdateIsolinuxBootTable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether Joliet file-system extensions should be used.
/// </summary>
public bool UseJoliet
{
get { return _buildParams.UseJoliet; }
set { _buildParams.UseJoliet = value; }
}
/// <summary>
/// Gets or sets the Volume Identifier for the ISO file.
/// </summary>
/// <remarks>
/// Must be a valid identifier, i.e. max 32 characters in the range A-Z, 0-9 or _.
/// Lower-case characters are not permitted.
/// </remarks>
public string VolumeIdentifier
{
get { return _buildParams.VolumeIdentifier; }
set
{
if (value.Length > 32)
{
throw new ArgumentException("Not a valid volume identifier");
}
_buildParams.VolumeIdentifier = value;
}
}
/// <summary>
/// Sets the boot image for the ISO image.
/// </summary>
/// <param name="image">Stream containing the boot image.</param>
/// <param name="emulation">The type of emulation requested of the BIOS.</param>
/// <param name="loadSegment">The memory segment to load the image to (0 for default).</param>
public void SetBootImage(Stream image, BootDeviceEmulation emulation, int loadSegment)
{
if (_bootEntry != null)
{
throw new InvalidOperationException("Boot image already set");
}
_bootEntry = new BootInitialEntry();
_bootEntry.BootIndicator = 0x88;
_bootEntry.BootMediaType = emulation;
_bootEntry.LoadSegment = (ushort)loadSegment;
_bootEntry.SystemType = 0;
_bootImage = image;
}
/// <summary>
/// Adds a directory to the ISO image.
/// </summary>
/// <param name="name">The name of the directory on the ISO image.</param>
/// <returns>The object representing this directory.</returns>
/// <remarks>
/// The name is the full path to the directory, for example:
/// <example><code>
/// builder.AddDirectory(@"DIRA\DIRB\DIRC");
/// </code></example>
/// </remarks>
public BuildDirectoryInfo AddDirectory(string name)
{
string[] nameElements = name.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
return GetDirectory(nameElements, nameElements.Length, true);
}
/// <summary>
/// Adds a byte array to the ISO image as a file.
/// </summary>
/// <param name="name">The name of the file on the ISO image.</param>
/// <param name="content">The contents of the file.</param>
/// <returns>The object representing this file.</returns>
/// <remarks>
/// The name is the full path to the file, for example:
/// <example><code>
/// builder.AddFile(@"DIRA\DIRB\FILE.TXT;1", new byte[]{0,1,2});
/// </code></example>
/// <para>Note the version number at the end of the file name is optional, if not
/// specified the default of 1 will be used.</para>
/// </remarks>
public BuildFileInfo AddFile(string name, byte[] content)
{
string[] nameElements = name.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
BuildDirectoryInfo dir = GetDirectory(nameElements, nameElements.Length - 1, true);
BuildDirectoryMember existing;
if (dir.TryGetMember(nameElements[nameElements.Length - 1], out existing))
{
throw new IOException("File already exists");
}
BuildFileInfo fi = new BuildFileInfo(nameElements[nameElements.Length - 1], dir, content);
_files.Add(fi);
dir.Add(fi);
return fi;
}
/// <summary>
/// Adds a disk file to the ISO image as a file.
/// </summary>
/// <param name="name">The name of the file on the ISO image.</param>
/// <param name="sourcePath">The name of the file on disk.</param>
/// <returns>The object representing this file.</returns>
/// <remarks>
/// The name is the full path to the file, for example:
/// <example><code>
/// builder.AddFile(@"DIRA\DIRB\FILE.TXT;1", @"C:\temp\tempfile.bin");
/// </code></example>
/// <para>Note the version number at the end of the file name is optional, if not
/// specified the default of 1 will be used.</para>
/// </remarks>
public BuildFileInfo AddFile(string name, string sourcePath)
{
string[] nameElements = name.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
BuildDirectoryInfo dir = GetDirectory(nameElements, nameElements.Length - 1, true);
BuildDirectoryMember existing;
if (dir.TryGetMember(nameElements[nameElements.Length - 1], out existing))
{
throw new IOException("File already exists");
}
BuildFileInfo fi = new BuildFileInfo(nameElements[nameElements.Length - 1], dir, sourcePath);
_files.Add(fi);
dir.Add(fi);
return fi;
}
/// <summary>
/// Adds a stream to the ISO image as a file.
/// </summary>
/// <param name="name">The name of the file on the ISO image.</param>
/// <param name="source">The contents of the file.</param>
/// <returns>The object representing this file.</returns>
/// <remarks>
/// The name is the full path to the file, for example:
/// <example><code>
/// builder.AddFile(@"DIRA\DIRB\FILE.TXT;1", stream);
/// </code></example>
/// <para>Note the version number at the end of the file name is optional, if not
/// specified the default of 1 will be used.</para>
/// </remarks>
public BuildFileInfo AddFile(string name, Stream source)
{
if (!source.CanSeek)
{
throw new ArgumentException("source doesn't support seeking", nameof(source));
}
string[] nameElements = name.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
BuildDirectoryInfo dir = GetDirectory(nameElements, nameElements.Length - 1, true);
BuildDirectoryMember existing;
if (dir.TryGetMember(nameElements[nameElements.Length - 1], out existing))
{
throw new IOException("File already exists");
}
BuildFileInfo fi = new BuildFileInfo(nameElements[nameElements.Length - 1], dir, source);
_files.Add(fi);
dir.Add(fi);
return fi;
}
protected override List<BuilderExtent> FixExtents(out long totalLength)
{
List<BuilderExtent> fixedRegions = new List<BuilderExtent>();
DateTime buildTime = DateTime.UtcNow;
Encoding suppEncoding = _buildParams.UseJoliet ? Encoding.BigEndianUnicode : Encoding.ASCII;
Dictionary<BuildDirectoryMember, uint> primaryLocationTable = new Dictionary<BuildDirectoryMember, uint>();
Dictionary<BuildDirectoryMember, uint> supplementaryLocationTable =
new Dictionary<BuildDirectoryMember, uint>();
long focus = DiskStart + 3 * IsoUtilities.SectorSize; // Primary, Supplementary, End (fixed at end...)
if (_bootEntry != null)
{
focus += IsoUtilities.SectorSize;
}
// ####################################################################
// # 0. Fix boot image location
// ####################################################################
long bootCatalogPos = 0;
if (_bootEntry != null)
{
long bootImagePos = focus;
Stream realBootImage = PatchBootImage(_bootImage, (uint)(DiskStart / IsoUtilities.SectorSize),
(uint)(bootImagePos / IsoUtilities.SectorSize));
BuilderStreamExtent bootImageExtent = new BuilderStreamExtent(focus, realBootImage);
fixedRegions.Add(bootImageExtent);
focus += MathUtilities.RoundUp(bootImageExtent.Length, IsoUtilities.SectorSize);
bootCatalogPos = focus;
byte[] bootCatalog = new byte[IsoUtilities.SectorSize];
BootValidationEntry bve = new BootValidationEntry();
bve.WriteTo(bootCatalog, 0x00);
_bootEntry.ImageStart = (uint)MathUtilities.Ceil(bootImagePos, IsoUtilities.SectorSize);
_bootEntry.SectorCount = (ushort)MathUtilities.Ceil(_bootImage.Length, Sizes.Sector);
_bootEntry.WriteTo(bootCatalog, 0x20);
fixedRegions.Add(new BuilderBufferExtent(bootCatalogPos, bootCatalog));
focus += IsoUtilities.SectorSize;
}
// ####################################################################
// # 1. Fix file locations
// ####################################################################
// Find end of the file data, fixing the files in place as we go
foreach (BuildFileInfo fi in _files)
{
primaryLocationTable.Add(fi, (uint)(focus / IsoUtilities.SectorSize));
supplementaryLocationTable.Add(fi, (uint)(focus / IsoUtilities.SectorSize));
FileExtent extent = new FileExtent(fi, focus);
// Only remember files of non-zero length (otherwise we'll stomp on a valid file)
if (extent.Length != 0)
{
fixedRegions.Add(extent);
}
focus += MathUtilities.RoundUp(extent.Length, IsoUtilities.SectorSize);
}
// ####################################################################
// # 2. Fix directory locations
// ####################################################################
// There are two directory tables
// 1. Primary (std ISO9660)
// 2. Supplementary (Joliet)
// Find start of the second set of directory data, fixing ASCII directories in place.
long startOfFirstDirData = focus;
foreach (BuildDirectoryInfo di in _dirs)
{
primaryLocationTable.Add(di, (uint)(focus / IsoUtilities.SectorSize));
DirectoryExtent extent = new DirectoryExtent(di, primaryLocationTable, Encoding.ASCII, focus);
fixedRegions.Add(extent);
focus += MathUtilities.RoundUp(extent.Length, IsoUtilities.SectorSize);
}
// Find end of the second directory table, fixing supplementary directories in place.
long startOfSecondDirData = focus;
foreach (BuildDirectoryInfo di in _dirs)
{
supplementaryLocationTable.Add(di, (uint)(focus / IsoUtilities.SectorSize));
DirectoryExtent extent = new DirectoryExtent(di, supplementaryLocationTable, suppEncoding, focus);
fixedRegions.Add(extent);
focus += MathUtilities.RoundUp(extent.Length, IsoUtilities.SectorSize);
}
// ####################################################################
// # 3. Fix path tables
// ####################################################################
// There are four path tables:
// 1. LE, ASCII
// 2. BE, ASCII
// 3. LE, Supp Encoding (Joliet)
// 4. BE, Supp Encoding (Joliet)
// Find end of the path table
long startOfFirstPathTable = focus;
PathTable pathTable = new PathTable(false, Encoding.ASCII, _dirs, primaryLocationTable, focus);
fixedRegions.Add(pathTable);
focus += MathUtilities.RoundUp(pathTable.Length, IsoUtilities.SectorSize);
long primaryPathTableLength = pathTable.Length;
long startOfSecondPathTable = focus;
pathTable = new PathTable(true, Encoding.ASCII, _dirs, primaryLocationTable, focus);
fixedRegions.Add(pathTable);
focus += MathUtilities.RoundUp(pathTable.Length, IsoUtilities.SectorSize);
long startOfThirdPathTable = focus;
pathTable = new PathTable(false, suppEncoding, _dirs, supplementaryLocationTable, focus);
fixedRegions.Add(pathTable);
focus += MathUtilities.RoundUp(pathTable.Length, IsoUtilities.SectorSize);
long supplementaryPathTableLength = pathTable.Length;
long startOfFourthPathTable = focus;
pathTable = new PathTable(true, suppEncoding, _dirs, supplementaryLocationTable, focus);
fixedRegions.Add(pathTable);
focus += MathUtilities.RoundUp(pathTable.Length, IsoUtilities.SectorSize);
// Find the end of the disk
totalLength = focus;
// ####################################################################
// # 4. Prepare volume descriptors now other structures are fixed
// ####################################################################
int regionIdx = 0;
focus = DiskStart;
PrimaryVolumeDescriptor pvDesc = new PrimaryVolumeDescriptor(
(uint)(totalLength / IsoUtilities.SectorSize), // VolumeSpaceSize
(uint)primaryPathTableLength, // PathTableSize
(uint)(startOfFirstPathTable / IsoUtilities.SectorSize), // TypeLPathTableLocation
(uint)(startOfSecondPathTable / IsoUtilities.SectorSize), // TypeMPathTableLocation
(uint)(startOfFirstDirData / IsoUtilities.SectorSize), // RootDirectory.LocationOfExtent
(uint)_rootDirectory.GetDataSize(Encoding.ASCII), // RootDirectory.DataLength
buildTime);
pvDesc.VolumeIdentifier = _buildParams.VolumeIdentifier;
PrimaryVolumeDescriptorRegion pvdr = new PrimaryVolumeDescriptorRegion(pvDesc, focus);
fixedRegions.Insert(regionIdx++, pvdr);
focus += IsoUtilities.SectorSize;
if (_bootEntry != null)
{
BootVolumeDescriptor bvDesc = new BootVolumeDescriptor(
(uint)(bootCatalogPos / IsoUtilities.SectorSize));
BootVolumeDescriptorRegion bvdr = new BootVolumeDescriptorRegion(bvDesc, focus);
fixedRegions.Insert(regionIdx++, bvdr);
focus += IsoUtilities.SectorSize;
}
SupplementaryVolumeDescriptor svDesc = new SupplementaryVolumeDescriptor(
(uint)(totalLength / IsoUtilities.SectorSize), // VolumeSpaceSize
(uint)supplementaryPathTableLength, // PathTableSize
(uint)(startOfThirdPathTable / IsoUtilities.SectorSize), // TypeLPathTableLocation
(uint)(startOfFourthPathTable / IsoUtilities.SectorSize), // TypeMPathTableLocation
(uint)(startOfSecondDirData / IsoUtilities.SectorSize), // RootDirectory.LocationOfExtent
(uint)_rootDirectory.GetDataSize(suppEncoding), // RootDirectory.DataLength
buildTime,
suppEncoding);
svDesc.VolumeIdentifier = _buildParams.VolumeIdentifier;
SupplementaryVolumeDescriptorRegion svdr = new SupplementaryVolumeDescriptorRegion(svDesc, focus);
fixedRegions.Insert(regionIdx++, svdr);
focus += IsoUtilities.SectorSize;
VolumeDescriptorSetTerminator evDesc = new VolumeDescriptorSetTerminator();
VolumeDescriptorSetTerminatorRegion evdr = new VolumeDescriptorSetTerminatorRegion(evDesc, focus);
fixedRegions.Insert(regionIdx++, evdr);
return fixedRegions;
}
/// <summary>
/// Patches a boot image (esp. for ISOLINUX) before it is written to the disk.
/// </summary>
/// <param name="bootImage">The original (master) boot image.</param>
/// <param name="pvdLba">The logical block address of the primary volume descriptor.</param>
/// <param name="bootImageLba">The logical block address of the boot image itself.</param>
/// <returns>A stream containing the patched boot image - does not need to be disposed.</returns>
private Stream PatchBootImage(Stream bootImage, uint pvdLba, uint bootImageLba)
{
// Early-exit if no patching to do...
if (!UpdateIsolinuxBootTable)
{
return bootImage;
}
byte[] bootData = StreamUtilities.ReadExact(bootImage, (int)bootImage.Length);
Array.Clear(bootData, 8, 56);
uint checkSum = 0;
for (int i = 64; i < bootData.Length; i += 4)
{
checkSum += EndianUtilities.ToUInt32LittleEndian(bootData, i);
}
EndianUtilities.WriteBytesLittleEndian(pvdLba, bootData, 8);
EndianUtilities.WriteBytesLittleEndian(bootImageLba, bootData, 12);
EndianUtilities.WriteBytesLittleEndian(bootData.Length, bootData, 16);
EndianUtilities.WriteBytesLittleEndian(checkSum, bootData, 20);
return new MemoryStream(bootData, false);
}
private BuildDirectoryInfo GetDirectory(string[] path, int pathLength, bool createMissing)
{
BuildDirectoryInfo di = TryGetDirectory(path, pathLength, createMissing);
if (di == null)
{
throw new DirectoryNotFoundException("Directory not found");
}
return di;
}
private BuildDirectoryInfo TryGetDirectory(string[] path, int pathLength, bool createMissing)
{
BuildDirectoryInfo focus = _rootDirectory;
for (int i = 0; i < pathLength; ++i)
{
BuildDirectoryMember next;
if (!focus.TryGetMember(path[i], out next))
{
if (createMissing)
{
// This directory doesn't exist, create it...
BuildDirectoryInfo di = new BuildDirectoryInfo(path[i], focus);
focus.Add(di);
_dirs.Add(di);
focus = di;
}
else
{
return null;
}
}
else
{
BuildDirectoryInfo nextAsBuildDirectoryInfo = next as BuildDirectoryInfo;
if (nextAsBuildDirectoryInfo == null)
{
throw new IOException("File with conflicting name exists");
}
focus = nextAsBuildDirectoryInfo;
}
}
return focus;
}
}
}
| |
#region License
/*
* 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.
*/
#endregion
#if !MONO
#region Imports
using System;
using System.Collections;
using System.EnterpriseServices;
using System.Reflection;
using System.Reflection.Emit;
using Spring.Core.TypeResolution;
using Spring.Objects.Factory;
using Spring.Proxy;
#endregion
namespace Spring.EnterpriseServices
{
/// <summary>
/// Encapsulates information necessary to create ServicedComponent
/// wrapper around target class.
/// </summary>
/// <remarks>
/// <para>
/// Instances of this class should be used as elements in the Components
/// list of the <see cref="EnterpriseServicesExporter"/> class, which will
/// register them with COM+ Services. For a full description on how to export
/// and use services with COM+, see the <see cref="EnterpriseServicesExporter"/> reference.
/// </para>
/// </remarks>
/// <seealso cref="EnterpriseServicesExporter"/>
/// <author>Aleksandar Seovic</author>
/// <author>Erich Eichinger</author>
public class ServicedComponentExporter : IInitializingObject, IObjectNameAware
{
#region Fields
private string _objectName;
private string _targetName;
private string[] _interfaces;
private IList _typeAttributes = new ArrayList();
private IDictionary _memberAttributes = new Hashtable();
#endregion
#region Constructor(s) / Destructor
/// <summary>
/// Creates a new instance of the
/// <see cref="ServicedComponentExporter"/> class.
/// </summary>
public ServicedComponentExporter()
{}
#endregion
#region Properties
/// <summary>
/// Gets or sets name of the target object that should be exposed as a serviced component.
/// </summary>
public string TargetName
{
get { return _targetName; }
set { _targetName = value; }
}
/// <summary>
/// Gets or sets the list of interfaces whose methods should be exported.
/// </summary>
/// <remarks>
/// The default value of this property is all the interfaces
/// implemented or inherited by the target type.
/// </remarks>
/// <value>The interfaces to export.</value>
public string[] Interfaces
{
get { return _interfaces; }
set { _interfaces = value; }
}
/// <summary>
/// Gets or sets a list of custom attributes
/// that should be applied to a proxy class.
/// </summary>
public IList TypeAttributes
{
get { return _typeAttributes; }
set { _typeAttributes = value; }
}
/// <summary>
/// Gets or sets a dictionary of custom attributes
/// that should be applied to proxy members.
/// </summary>
/// <remarks>
/// Map key is an expression that members can be matched against. Value is a list
/// of attributes that should be applied to each member that matches expression.
/// </remarks>
public IDictionary MemberAttributes
{
get { return _memberAttributes; }
set { _memberAttributes = value; }
}
#endregion
#region IInitializingObject Members
/// <summary>
/// Validate configuration.
/// </summary>
public void AfterPropertiesSet()
{
ValidateConfiguration();
}
#endregion
#region IObjectNameAware Members
/// <summary>
/// Set the name of the object in the object factory
/// that created this object.
/// </summary>
public string ObjectName
{
set { _objectName = value; }
}
#endregion
#region Methods
private void ValidateConfiguration()
{
if (TargetName == null)
{
throw new ArgumentException("The TargetName property is required.");
}
}
/// <summary>
/// Creates ServicedComponent wrapper around target class.
/// </summary>
/// <param name="module">Dynamic module builder to use</param>
/// <param name="baseType"></param>
/// <param name="targetType">Type of the exported object.</param>
/// <param name="springManagedLifecycle">whether to generate lookups in ContextRegistry for each service method call or use a 'new'ed target instance</param>
/// <remarks>
/// if <paramref name="springManagedLifecycle"/> is <c>true</c>, each ServicedComponent method call will look similar to
/// <code>
/// class MyServicedComponent {
/// void MethodX() {
/// ContextRegistry.GetContext().GetObject("TargetName").MethodX();
/// }
/// }
/// </code>
/// <br/>
/// if <paramref name="springManagedLifecycle"/> is <c>false</c>, the instance will be simply created at component activation using 'new':
/// <code>
/// class MyServicedComponent {
/// TargetType target = new TargetType();
///
/// void MethodX() {
/// target.MethodX();
/// }
/// }
/// </code>
/// <br/>
/// The differences are of course that in the former case, the target lifecycle is entirely managed by Spring, thus avoiding
/// issues with ServiceComponent activation/deactivation as well as removing the need for default constructors.
/// </remarks>
public Type CreateWrapperType(ModuleBuilder module, Type baseType, Type targetType, bool springManagedLifecycle)
{
ValidateConfiguration();
// create wrapper using appropriate proxy builder
IProxyTypeBuilder proxyBuilder;
if (springManagedLifecycle)
{
proxyBuilder = new SpringManagedServicedComponentProxyTypeBuilder(module, baseType, this);
}
else
{
proxyBuilder = new SimpleServicedComponentProxyTypeBuilder(module, baseType);
}
proxyBuilder.Name = _objectName;
proxyBuilder.TargetType = targetType;
if (_interfaces != null && _interfaces.Length > 0)
{
proxyBuilder.Interfaces = TypeResolutionUtils.ResolveInterfaceArray(_interfaces);
}
proxyBuilder.TypeAttributes = TypeAttributes;
proxyBuilder.MemberAttributes = MemberAttributes;
Type componentType = proxyBuilder.BuildProxyType();
// create and register client-side proxy factory for component
return componentType;
}
#endregion
#region ServicedComponentProxyTypeBuilder inner class definition
private class ServicedComponentTargetProxyMethodBuilder : TargetProxyMethodBuilder
{
public ServicedComponentTargetProxyMethodBuilder(TypeBuilder typeBuilder, IProxyTypeGenerator proxyGenerator, bool explicitImplementation) : base(typeBuilder, proxyGenerator, explicitImplementation)
{}
/// <summary>
/// Suppress output to avoid Spring.Core dependency
/// </summary>
protected override void CallAssertUnderstands(ILGenerator il, MethodInfo method, string targetName)
{
// base.CallAssertUnderstands(il, method, targetRef, targetName);
}
}
private class ServicedComponentProxyTypeBuilder : CompositionProxyTypeBuilder
{
/// <summary>
/// Implements default constructor for the proxy class.
/// </summary>
protected override void ImplementConstructors(TypeBuilder builder)
{
MethodAttributes attributes = MethodAttributes.Public |
MethodAttributes.HideBySig | MethodAttributes.SpecialName |
MethodAttributes.RTSpecialName;
ConstructorBuilder cb = builder.DefineConstructor(attributes,
CallingConventions.Standard, Type.EmptyTypes);
ILGenerator il = cb.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, builder.BaseType.GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Ret);
}
protected override IProxyMethodBuilder CreateTargetProxyMethodBuilder(TypeBuilder typeBuilder)
{
return new ServicedComponentTargetProxyMethodBuilder(typeBuilder, this,
this.ExplicitInterfaceImplementation);
}
}
private sealed class SimpleServicedComponentProxyTypeBuilder : ServicedComponentProxyTypeBuilder
{
private readonly ModuleBuilder module;
#region Constructor(s) / Destructor
public SimpleServicedComponentProxyTypeBuilder(ModuleBuilder module, Type baseType)
{
this.module = module;
BaseType = baseType;
}
#endregion
#region Protected Methods
protected override TypeBuilder CreateTypeBuilder(string name, Type baseType)
{
return module.DefineType(name, System.Reflection.TypeAttributes.Public, baseType);
}
#endregion
}
private sealed class SpringManagedServicedComponentProxyTypeBuilder : ServicedComponentProxyTypeBuilder
{
#region Fields
private delegate object GetTargetDelegate(ServicedComponent component, string name);
private static readonly MethodInfo ServicedComponentExporter_GetTarget = new GetTargetDelegate(ServicedComponentHelper.GetObject).Method;
#endregion
#region Fields
private readonly ServicedComponentExporter exporter;
private readonly ModuleBuilder module;
#endregion
#region Constructor(s) / Destructor
public SpringManagedServicedComponentProxyTypeBuilder(ModuleBuilder module, Type baseType, ServicedComponentExporter exporter)
{
this.module = module;
this.exporter = exporter;
BaseType = baseType;
}
#endregion
#region Protected Methods
protected override TypeBuilder CreateTypeBuilder(string name, Type baseType)
{
return module.DefineType(name, System.Reflection.TypeAttributes.Public, baseType);
}
protected override void DeclareTargetInstanceField(TypeBuilder builder)
{
//base.DeclareTargetInstanceField(builder);
}
#endregion
#region IProxyTypeGenerator Members
/// <summary>
/// Generates the IL instructions that pushes
/// the target instance on which calls should be delegated to.
/// </summary>
/// <param name="il">The IL generator to use.</param>
public override void PushTarget( ILGenerator il )
{
FieldInfo getObjectRef = BaseType.GetField("getObject", BindingFlags.NonPublic|BindingFlags.Static);
il.Emit(OpCodes.Ldsfld, getObjectRef);
il.Emit(OpCodes.Ldarg_0);
il.Emit( OpCodes.Ldstr, this.exporter.TargetName );
il.Emit( OpCodes.Callvirt, getObjectRef.FieldType.GetMethod("Invoke"));
}
#endregion
}
#endregion
}
}
#endif // !MONO
| |
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.Cryptography;
using Neo.Cryptography.ECC;
using Neo.IO;
using Neo.IO.Caching;
using Neo.Ledger;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.UnitTests.Extensions;
using Neo.VM;
using System;
using System.Linq;
using System.Numerics;
using static Neo.SmartContract.Native.Tokens.NeoToken;
namespace Neo.UnitTests.SmartContract.Native.Tokens
{
[TestClass]
public class UT_NeoToken
{
[TestInitialize]
public void TestSetup()
{
TestBlockchain.InitializeMockNeoSystem();
}
[TestMethod]
public void Check_Name() => NativeContract.NEO.Name().Should().Be("NEO");
[TestMethod]
public void Check_Symbol() => NativeContract.NEO.Symbol().Should().Be("neo");
[TestMethod]
public void Check_Decimals() => NativeContract.NEO.Decimals().Should().Be(0);
[TestMethod]
public void Check_SupportedStandards() => NativeContract.NEO.SupportedStandards().Should().BeEquivalentTo(new string[] { "NEP-5", "NEP-10" });
[TestMethod]
public void Check_Vote()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
snapshot.PersistingBlock = new Block() { Index = 1000 };
byte[] from = Contract.CreateMultiSigRedeemScript(Blockchain.StandbyValidators.Length / 2 + 1,
Blockchain.StandbyValidators).ToScriptHash().ToArray();
// No signature
var ret = Check_Vote(snapshot, from, new byte[][] { }, false);
ret.Result.Should().BeFalse();
ret.State.Should().BeTrue();
// Wrong address
ret = Check_Vote(snapshot, new byte[19], new byte[][] { }, false);
ret.Result.Should().BeFalse();
ret.State.Should().BeFalse();
// Wrong ec
ret = Check_Vote(snapshot, from, new byte[][] { new byte[19] }, true);
ret.Result.Should().BeFalse();
ret.State.Should().BeFalse();
// no registered
var fakeAddr = new byte[20];
fakeAddr[0] = 0x5F;
fakeAddr[5] = 0xFF;
ret = Check_Vote(snapshot, fakeAddr, new byte[][] { }, true);
ret.Result.Should().BeFalse();
ret.State.Should().BeTrue();
// TODO: More votes tests
}
[TestMethod]
public void Check_UnclaimedGas()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
snapshot.PersistingBlock = new Block() { Index = 1000 };
byte[] from = Contract.CreateMultiSigRedeemScript(Blockchain.StandbyValidators.Length / 2 + 1,
Blockchain.StandbyValidators).ToScriptHash().ToArray();
var unclaim = Check_UnclaimedGas(snapshot, from);
unclaim.Value.Should().Be(new BigInteger(600000000000));
unclaim.State.Should().BeTrue();
unclaim = Check_UnclaimedGas(snapshot, new byte[19]);
unclaim.Value.Should().Be(BigInteger.Zero);
unclaim.State.Should().BeFalse();
}
[TestMethod]
public void Check_RegisterValidator()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
var ret = Check_RegisterValidator(snapshot, new byte[0]);
ret.State.Should().BeFalse();
ret.Result.Should().BeFalse();
ret = Check_RegisterValidator(snapshot, new byte[33]);
ret.State.Should().BeFalse();
ret.Result.Should().BeFalse();
var keyCount = snapshot.Storages.GetChangeSet().Count();
var point = Blockchain.StandbyValidators[0].EncodePoint(true);
ret = Check_RegisterValidator(snapshot, point); // Exists
ret.State.Should().BeTrue();
ret.Result.Should().BeFalse();
snapshot.Storages.GetChangeSet().Count().Should().Be(keyCount); // No changes
point[20]++; // fake point
ret = Check_RegisterValidator(snapshot, point); // New
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
snapshot.Storages.GetChangeSet().Count().Should().Be(keyCount + 1); // New validator
// Check GetRegisteredValidators
var validators = NativeContract.NEO.GetRegisteredValidators(snapshot).OrderBy(u => u.PublicKey).ToArray();
var check = Blockchain.StandbyValidators.Select(u => u.EncodePoint(true)).ToList();
check.Add(point); // Add the new member
for (int x = 0; x < validators.Length; x++)
{
Assert.AreEqual(1, check.RemoveAll(u => u.SequenceEqual(validators[x].PublicKey.EncodePoint(true))));
Assert.AreEqual(0, validators[x].Votes);
}
Assert.AreEqual(0, check.Count);
}
[TestMethod]
public void Check_Transfer()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
snapshot.PersistingBlock = new Block() { Index = 1000 };
byte[] from = Contract.CreateMultiSigRedeemScript(Blockchain.StandbyValidators.Length / 2 + 1,
Blockchain.StandbyValidators).ToScriptHash().ToArray();
byte[] to = new byte[20];
var keyCount = snapshot.Storages.GetChangeSet().Count();
// Check unclaim
var unclaim = Check_UnclaimedGas(snapshot, from);
unclaim.Value.Should().Be(new BigInteger(600000000000));
unclaim.State.Should().BeTrue();
// Transfer
NativeContract.NEO.Transfer(snapshot, from, to, BigInteger.One, false).Should().BeFalse(); // Not signed
NativeContract.NEO.Transfer(snapshot, from, to, BigInteger.One, true).Should().BeTrue();
NativeContract.NEO.BalanceOf(snapshot, from).Should().Be(99_999_999);
NativeContract.NEO.BalanceOf(snapshot, to).Should().Be(1);
// Check unclaim
unclaim = Check_UnclaimedGas(snapshot, from);
unclaim.Value.Should().Be(new BigInteger(0));
unclaim.State.Should().BeTrue();
snapshot.Storages.GetChangeSet().Count().Should().Be(keyCount + 4); // Gas + new balance
// Return balance
keyCount = snapshot.Storages.GetChangeSet().Count();
NativeContract.NEO.Transfer(snapshot, to, from, BigInteger.One, true).Should().BeTrue();
NativeContract.NEO.BalanceOf(snapshot, to).Should().Be(0);
snapshot.Storages.GetChangeSet().Count().Should().Be(keyCount - 1); // Remove neo balance from address two
// Bad inputs
NativeContract.NEO.Transfer(snapshot, from, to, BigInteger.MinusOne, true).Should().BeFalse();
NativeContract.NEO.Transfer(snapshot, new byte[19], to, BigInteger.One, false).Should().BeFalse();
NativeContract.NEO.Transfer(snapshot, from, new byte[19], BigInteger.One, false).Should().BeFalse();
// More than balance
NativeContract.NEO.Transfer(snapshot, to, from, new BigInteger(2), true).Should().BeFalse();
}
[TestMethod]
public void Check_BalanceOf()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
byte[] account = Contract.CreateMultiSigRedeemScript(Blockchain.StandbyValidators.Length / 2 + 1,
Blockchain.StandbyValidators).ToScriptHash().ToArray();
NativeContract.NEO.BalanceOf(snapshot, account).Should().Be(100_000_000);
account[5]++; // Without existing balance
NativeContract.NEO.BalanceOf(snapshot, account).Should().Be(0);
}
[TestMethod]
public void Check_Initialize()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
// StandbyValidators
var validators = Check_GetValidators(snapshot);
for (var x = 0; x < Blockchain.StandbyValidators.Length; x++)
{
validators[x].Equals(Blockchain.StandbyValidators[x]);
}
// Check double call
var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true);
engine.LoadScript(NativeContract.NEO.Script);
var result = NativeContract.NEO.Initialize(engine);
result.Should().Be(false);
}
[TestMethod]
public void Check_BadScript()
{
var engine = new ApplicationEngine(TriggerType.Application, null, Blockchain.Singleton.GetSnapshot(), 0);
var script = new ScriptBuilder();
script.Emit(OpCode.NOP);
engine.LoadScript(script.ToArray());
NativeContract.NEO.Invoke(engine).Should().BeFalse();
}
[TestMethod]
public void TestCalculateBonus()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
StorageKey key = CreateStorageKey(20, UInt160.Zero.ToArray());
snapshot.Storages.Add(key, new StorageItem
{
Value = new AccountState()
{
Balance = -100
}.ToByteArray()
});
Action action = () => NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, 10).Should().Be(new BigInteger(0));
action.Should().Throw<ArgumentOutOfRangeException>();
snapshot.Storages.Delete(key);
snapshot.Storages.GetAndChange(key, () => new StorageItem
{
Value = new AccountState()
{
Balance = 100
}.ToByteArray()
});
NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, 30 * Blockchain.DecrementInterval).Should().Be(new BigInteger(7000000000));
}
[TestMethod]
public void TestGetNextBlockValidators1()
{
using (ApplicationEngine engine = NativeContract.NEO.TestCall("getNextBlockValidators"))
{
var result = engine.ResultStack.Peek();
result.GetType().Should().Be(typeof(VM.Types.Array));
((VM.Types.Array)result).Count.Should().Be(7);
((VM.Types.Array)result)[0].GetSpan().ToHexString().Should().Be("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c");
((VM.Types.Array)result)[1].GetSpan().ToHexString().Should().Be("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093");
((VM.Types.Array)result)[2].GetSpan().ToHexString().Should().Be("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a");
((VM.Types.Array)result)[3].GetSpan().ToHexString().Should().Be("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554");
((VM.Types.Array)result)[4].GetSpan().ToHexString().Should().Be("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d");
((VM.Types.Array)result)[5].GetSpan().ToHexString().Should().Be("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e");
((VM.Types.Array)result)[6].GetSpan().ToHexString().Should().Be("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70");
}
}
[TestMethod]
public void TestGetNextBlockValidators2()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
var result = NativeContract.NEO.GetNextBlockValidators(snapshot);
result.Length.Should().Be(7);
result[0].ToArray().ToHexString().Should().Be("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c");
result[1].ToArray().ToHexString().Should().Be("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093");
result[2].ToArray().ToHexString().Should().Be("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a");
result[3].ToArray().ToHexString().Should().Be("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554");
result[4].ToArray().ToHexString().Should().Be("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d");
result[5].ToArray().ToHexString().Should().Be("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e");
result[6].ToArray().ToHexString().Should().Be("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70");
snapshot.Storages.Add(CreateStorageKey(14), new StorageItem()
{
Value = new ECPoint[] { ECCurve.Secp256r1.G }.ToByteArray()
});
result = NativeContract.NEO.GetNextBlockValidators(snapshot);
result.Length.Should().Be(1);
result[0].ToArray().ToHexString().Should().Be("036b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296");
}
[TestMethod]
public void TestGetRegisteredValidators1()
{
using (ApplicationEngine engine = NativeContract.NEO.TestCall("getRegisteredValidators"))
{
var result = engine.ResultStack.Peek();
result.GetType().Should().Be(typeof(VM.Types.Array));
((VM.Types.Array)result).Count.Should().Be(7);
((VM.Types.Struct)((VM.Types.Array)result)[0])[0].GetSpan().ToHexString().Should().Be("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70");
((VM.Types.Struct)((VM.Types.Array)result)[0])[1].GetBigInteger().Should().Be(new BigInteger(0));
((VM.Types.Struct)((VM.Types.Array)result)[1])[0].GetSpan().ToHexString().Should().Be("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d");
((VM.Types.Struct)((VM.Types.Array)result)[1])[1].GetBigInteger().Should().Be(new BigInteger(0));
((VM.Types.Struct)((VM.Types.Array)result)[2])[0].GetSpan().ToHexString().Should().Be("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e");
((VM.Types.Struct)((VM.Types.Array)result)[2])[1].GetBigInteger().Should().Be(new BigInteger(0));
((VM.Types.Struct)((VM.Types.Array)result)[3])[0].GetSpan().ToHexString().Should().Be("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554");
((VM.Types.Struct)((VM.Types.Array)result)[3])[1].GetBigInteger().Should().Be(new BigInteger(0));
((VM.Types.Struct)((VM.Types.Array)result)[4])[0].GetSpan().ToHexString().Should().Be("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093");
((VM.Types.Struct)((VM.Types.Array)result)[4])[1].GetBigInteger().Should().Be(new BigInteger(0));
((VM.Types.Struct)((VM.Types.Array)result)[5])[0].GetSpan().ToHexString().Should().Be("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c");
((VM.Types.Struct)((VM.Types.Array)result)[5])[1].GetBigInteger().Should().Be(new BigInteger(0));
((VM.Types.Struct)((VM.Types.Array)result)[6])[0].GetSpan().ToHexString().Should().Be("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a");
((VM.Types.Struct)((VM.Types.Array)result)[6])[1].GetBigInteger().Should().Be(new BigInteger(0));
}
}
[TestMethod]
public void TestGetRegisteredValidators2()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
var result = NativeContract.NEO.GetRegisteredValidators(snapshot).ToArray();
result.Length.Should().Be(7);
result[0].PublicKey.ToArray().ToHexString().Should().Be("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70");
result[0].Votes.Should().Be(new BigInteger(0));
result[1].PublicKey.ToArray().ToHexString().Should().Be("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d");
result[1].Votes.Should().Be(new BigInteger(0));
result[2].PublicKey.ToArray().ToHexString().Should().Be("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e");
result[2].Votes.Should().Be(new BigInteger(0));
result[3].PublicKey.ToArray().ToHexString().Should().Be("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554");
result[3].Votes.Should().Be(new BigInteger(0));
result[4].PublicKey.ToArray().ToHexString().Should().Be("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093");
result[4].Votes.Should().Be(new BigInteger(0));
result[5].PublicKey.ToArray().ToHexString().Should().Be("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c");
result[5].Votes.Should().Be(new BigInteger(0));
result[6].PublicKey.ToArray().ToHexString().Should().Be("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a");
result[6].Votes.Should().Be(new BigInteger(0));
StorageKey key = NativeContract.NEO.CreateStorageKey(33, ECCurve.Secp256r1.G);
snapshot.Storages.Add(key, new StorageItem
{
Value = new ValidatorState().ToByteArray()
});
NativeContract.NEO.GetRegisteredValidators(snapshot).ToArray().Length.Should().Be(8);
}
[TestMethod]
public void TestGetValidators1()
{
using (ApplicationEngine engine = NativeContract.NEO.TestCall("getValidators"))
{
var result = engine.ResultStack.Peek();
result.GetType().Should().Be(typeof(VM.Types.Array));
((VM.Types.Array)result).Count.Should().Be(7);
((VM.Types.Array)result)[0].GetSpan().ToHexString().Should().Be("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c");
((VM.Types.Array)result)[1].GetSpan().ToHexString().Should().Be("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093");
((VM.Types.Array)result)[2].GetSpan().ToHexString().Should().Be("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a");
((VM.Types.Array)result)[3].GetSpan().ToHexString().Should().Be("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554");
((VM.Types.Array)result)[4].GetSpan().ToHexString().Should().Be("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d");
((VM.Types.Array)result)[5].GetSpan().ToHexString().Should().Be("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e");
((VM.Types.Array)result)[6].GetSpan().ToHexString().Should().Be("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70");
}
}
[TestMethod]
public void TestGetValidators2()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
var result = NativeContract.NEO.GetValidators(snapshot);
result[0].ToArray().ToHexString().Should().Be("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c");
result[1].ToArray().ToHexString().Should().Be("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093");
result[2].ToArray().ToHexString().Should().Be("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a");
result[3].ToArray().ToHexString().Should().Be("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554");
result[4].ToArray().ToHexString().Should().Be("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d");
result[5].ToArray().ToHexString().Should().Be("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e");
result[6].ToArray().ToHexString().Should().Be("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70");
StorageKey key = CreateStorageKey(15);
ValidatorsCountState state = new ValidatorsCountState();
for (int i = 0; i < 100; i++)
{
state.Votes[i] = new BigInteger(i + 1);
}
snapshot.Storages.Add(key, new StorageItem()
{
Value = state.ToByteArray()
});
NativeContract.NEO.GetValidators(snapshot).ToArray().Length.Should().Be(7);
}
[TestMethod]
public void TestInitialize()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
var engine = new ApplicationEngine(TriggerType.System, null, snapshot, 0, true);
Action action = () => NativeContract.NEO.Initialize(engine);
action.Should().Throw<InvalidOperationException>();
engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true);
NativeContract.NEO.Initialize(engine).Should().BeFalse();
snapshot.Storages.Delete(CreateStorageKey(11));
snapshot.PersistingBlock = Blockchain.GenesisBlock;
engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true);
NativeContract.NEO.Initialize(engine).Should().BeTrue();
}
[TestMethod]
public void TestOnBalanceChanging()
{
var ret = Transfer4TesingOnBalanceChanging(new BigInteger(0), false);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
ret = Transfer4TesingOnBalanceChanging(new BigInteger(1), false);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
ret = Transfer4TesingOnBalanceChanging(new BigInteger(1), true);
ret.Result.Should().BeTrue();
ret.State.Should().BeTrue();
}
[TestMethod]
public void TestTotalSupply()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
NativeContract.NEO.TotalSupply(snapshot).Should().Be(new BigInteger(100000000));
}
[TestMethod]
public void TestUnclaimedGas()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, 10).Should().Be(new BigInteger(0));
snapshot.Storages.Add(CreateStorageKey(20, UInt160.Zero.ToArray()), new StorageItem
{
Value = new AccountState().ToByteArray()
});
NativeContract.NEO.UnclaimedGas(snapshot, UInt160.Zero, 10).Should().Be(new BigInteger(0));
}
[TestMethod]
public void TestVote()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
UInt160 account = UInt160.Parse("01ff00ff00ff00ff00ff00ff00ff00ff00ff00a4");
StorageKey keyAccount = CreateStorageKey(20, account.ToArray());
StorageKey keyValidator = CreateStorageKey(33, ECCurve.Secp256r1.G.ToArray());
var ret = Check_Vote(snapshot, account.ToArray(), new byte[][] { ECCurve.Secp256r1.G.ToArray() }, false);
ret.State.Should().BeTrue();
ret.Result.Should().BeFalse();
ret = Check_Vote(snapshot, account.ToArray(), new byte[][] { ECCurve.Secp256r1.G.ToArray() }, true);
ret.State.Should().BeTrue();
ret.Result.Should().BeFalse();
snapshot.Storages.Add(keyAccount, new StorageItem
{
Value = new AccountState().ToByteArray()
});
ret = Check_Vote(snapshot, account.ToArray(), new byte[][] { ECCurve.Secp256r1.G.ToArray() }, true);
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
snapshot.Storages.Delete(keyAccount);
snapshot.Storages.GetAndChange(keyAccount, () => new StorageItem
{
Value = new AccountState()
{
Votes = new ECPoint[] { ECCurve.Secp256r1.G }
}.ToByteArray()
});
snapshot.Storages.Add(keyValidator, new StorageItem
{
Value = new ValidatorState().ToByteArray()
});
ret = Check_Vote(snapshot, account.ToArray(), new byte[][] { ECCurve.Secp256r1.G.ToArray() }, true);
ret.State.Should().BeTrue();
ret.Result.Should().BeTrue();
}
[TestMethod]
public void TestValidatorsCountState_FromByteArray()
{
ValidatorsCountState input = new ValidatorsCountState { Votes = new BigInteger[] { new BigInteger(1000) } };
ValidatorsCountState output = ValidatorsCountState.FromByteArray(input.ToByteArray());
output.Should().BeEquivalentTo(input);
}
[TestMethod]
public void TestValidatorState_FromByteArray()
{
ValidatorState input = new ValidatorState { Votes = new BigInteger(1000) };
ValidatorState output = ValidatorState.FromByteArray(input.ToByteArray());
output.Should().BeEquivalentTo(input);
}
[TestMethod]
public void TestValidatorState_ToByteArray()
{
ValidatorState input = new ValidatorState { Votes = new BigInteger(1000) };
input.ToByteArray().ToHexString().Should().Be("e803");
}
internal (bool State, bool Result) Transfer4TesingOnBalanceChanging(BigInteger amount, bool addVotes)
{
var snapshot = Blockchain.Singleton.GetSnapshot();
snapshot.PersistingBlock = Blockchain.GenesisBlock;
var engine = new ApplicationEngine(TriggerType.Application, Blockchain.GenesisBlock, snapshot, 0, true);
ScriptBuilder sb = new ScriptBuilder();
var tmp = engine.ScriptContainer.GetScriptHashesForVerifying(engine.Snapshot);
UInt160 from = engine.ScriptContainer.GetScriptHashesForVerifying(engine.Snapshot)[0];
if (addVotes)
{
snapshot.Storages.Add(CreateStorageKey(20, from.ToArray()), new StorageItem
{
Value = new AccountState()
{
Votes = new ECPoint[] { ECCurve.Secp256r1.G },
Balance = new BigInteger(1000)
}.ToByteArray()
});
snapshot.Storages.Add(NativeContract.NEO.CreateStorageKey(33, ECCurve.Secp256r1.G), new StorageItem
{
Value = new ValidatorState().ToByteArray()
});
ValidatorsCountState state = new ValidatorsCountState();
for (int i = 0; i < 100; i++)
{
state.Votes[i] = new BigInteger(i + 1);
}
snapshot.Storages.Add(CreateStorageKey(15), new StorageItem()
{
Value = state.ToByteArray()
});
}
else
{
snapshot.Storages.Add(CreateStorageKey(20, from.ToArray()), new StorageItem
{
Value = new AccountState()
{
Balance = new BigInteger(1000)
}.ToByteArray()
});
}
sb.EmitAppCall(NativeContract.NEO.Hash, "transfer", from, UInt160.Zero, amount);
engine.LoadScript(sb.ToArray());
engine.Execute();
var result = engine.ResultStack.Peek();
result.GetType().Should().Be(typeof(VM.Types.Boolean));
return (true, result.ToBoolean());
}
internal static (bool State, bool Result) Check_Vote(StoreView snapshot, byte[] account, byte[][] pubkeys, bool signAccount)
{
var engine = new ApplicationEngine(TriggerType.Application,
new Nep5NativeContractExtensions.ManualWitness(signAccount ? new UInt160(account) : UInt160.Zero), snapshot, 0, true);
engine.LoadScript(NativeContract.NEO.Script);
var script = new ScriptBuilder();
foreach (var ec in pubkeys) script.EmitPush(ec);
script.EmitPush(pubkeys.Length);
script.Emit(OpCode.PACK);
script.EmitPush(account.ToArray());
script.EmitPush(2);
script.Emit(OpCode.PACK);
script.EmitPush("vote");
engine.LoadScript(script.ToArray());
if (engine.Execute() == VMState.FAULT)
{
return (false, false);
}
var result = engine.ResultStack.Pop();
result.Should().BeOfType(typeof(VM.Types.Boolean));
return (true, result.ToBoolean());
}
internal static (bool State, bool Result) Check_RegisterValidator(StoreView snapshot, byte[] pubkey)
{
var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true);
engine.LoadScript(NativeContract.NEO.Script);
var script = new ScriptBuilder();
script.EmitPush(pubkey);
script.EmitPush(1);
script.Emit(OpCode.PACK);
script.EmitPush("registerValidator");
engine.LoadScript(script.ToArray());
if (engine.Execute() == VMState.FAULT)
{
return (false, false);
}
var result = engine.ResultStack.Pop();
result.Should().BeOfType(typeof(VM.Types.Boolean));
return (true, result.ToBoolean());
}
internal static ECPoint[] Check_GetValidators(StoreView snapshot)
{
var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true);
engine.LoadScript(NativeContract.NEO.Script);
var script = new ScriptBuilder();
script.EmitPush(0);
script.Emit(OpCode.PACK);
script.EmitPush("getValidators");
engine.LoadScript(script.ToArray());
engine.Execute().Should().Be(VMState.HALT);
var result = engine.ResultStack.Pop();
result.Should().BeOfType(typeof(VM.Types.Array));
return (result as VM.Types.Array).Select(u => u.GetSpan().AsSerializable<ECPoint>()).ToArray();
}
internal static (BigInteger Value, bool State) Check_UnclaimedGas(StoreView snapshot, byte[] address)
{
var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true);
engine.LoadScript(NativeContract.NEO.Script);
var script = new ScriptBuilder();
script.EmitPush(snapshot.PersistingBlock.Index);
script.EmitPush(address);
script.EmitPush(2);
script.Emit(OpCode.PACK);
script.EmitPush("unclaimedGas");
engine.LoadScript(script.ToArray());
if (engine.Execute() == VMState.FAULT)
{
return (BigInteger.Zero, false);
}
var result = engine.ResultStack.Pop();
result.Should().BeOfType(typeof(VM.Types.Integer));
return ((result as VM.Types.Integer).GetBigInteger(), true);
}
internal static void CheckValidator(ECPoint eCPoint, DataCache<StorageKey, StorageItem>.Trackable trackable)
{
var st = new BigInteger(trackable.Item.Value);
st.Should().Be(0);
trackable.Key.Key.Should().BeEquivalentTo(new byte[] { 33 }.Concat(eCPoint.EncodePoint(true)));
trackable.Item.IsConstant.Should().Be(false);
}
internal static void CheckBalance(byte[] account, DataCache<StorageKey, StorageItem>.Trackable trackable, BigInteger balance, BigInteger height, ECPoint[] votes)
{
var st = (VM.Types.Struct)trackable.Item.Value.DeserializeStackItem(3, 32);
st.Count.Should().Be(3);
st.Select(u => u.GetType()).ToArray().Should().BeEquivalentTo(new Type[] { typeof(VM.Types.Integer), typeof(VM.Types.Integer), typeof(VM.Types.ByteArray) }); // Balance
st[0].GetBigInteger().Should().Be(balance); // Balance
st[1].GetBigInteger().Should().Be(height); // BalanceHeight
(st[2].GetSpan().AsSerializableArray<ECPoint>(Blockchain.MaxValidators)).Should().BeEquivalentTo(votes); // Votes
trackable.Key.Key.Should().BeEquivalentTo(new byte[] { 20 }.Concat(account));
trackable.Item.IsConstant.Should().Be(false);
}
internal static StorageKey CreateStorageKey(byte prefix, byte[] key = null)
{
StorageKey storageKey = new StorageKey
{
ScriptHash = NativeContract.NEO.Hash,
Key = new byte[sizeof(byte) + (key?.Length ?? 0)]
};
storageKey.Key[0] = prefix;
if (key != null)
Buffer.BlockCopy(key, 0, storageKey.Key, 1, key.Length);
return storageKey;
}
}
}
| |
namespace Azure.AI.FormRecognizer
{
public enum FormContentType
{
Json = 0,
Pdf = 1,
Png = 2,
Jpeg = 3,
Tiff = 4,
}
public partial class FormRecognizerClient
{
protected FormRecognizerClient() { }
public FormRecognizerClient(System.Uri endpoint, Azure.AzureKeyCredential credential) { }
public FormRecognizerClient(System.Uri endpoint, Azure.AzureKeyCredential credential, Azure.AI.FormRecognizer.FormRecognizerClientOptions options) { }
public FormRecognizerClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { }
public FormRecognizerClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.AI.FormRecognizer.FormRecognizerClientOptions options) { }
public virtual Azure.AI.FormRecognizer.Models.RecognizeBusinessCardsOperation StartRecognizeBusinessCards(System.IO.Stream businessCard, Azure.AI.FormRecognizer.RecognizeBusinessCardsOptions recognizeBusinessCardsOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Models.RecognizeBusinessCardsOperation> StartRecognizeBusinessCardsAsync(System.IO.Stream businessCard, Azure.AI.FormRecognizer.RecognizeBusinessCardsOptions recognizeBusinessCardsOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AI.FormRecognizer.Models.RecognizeBusinessCardsOperation StartRecognizeBusinessCardsFromUri(System.Uri businessCardUri, Azure.AI.FormRecognizer.RecognizeBusinessCardsOptions recognizeBusinessCardsOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Models.RecognizeBusinessCardsOperation> StartRecognizeBusinessCardsFromUriAsync(System.Uri businessCardUri, Azure.AI.FormRecognizer.RecognizeBusinessCardsOptions recognizeBusinessCardsOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AI.FormRecognizer.Models.RecognizeContentOperation StartRecognizeContent(System.IO.Stream form, Azure.AI.FormRecognizer.RecognizeContentOptions recognizeContentOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Models.RecognizeContentOperation> StartRecognizeContentAsync(System.IO.Stream form, Azure.AI.FormRecognizer.RecognizeContentOptions recognizeContentOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AI.FormRecognizer.Models.RecognizeContentOperation StartRecognizeContentFromUri(System.Uri formUri, Azure.AI.FormRecognizer.RecognizeContentOptions recognizeContentOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Models.RecognizeContentOperation> StartRecognizeContentFromUriAsync(System.Uri formUri, Azure.AI.FormRecognizer.RecognizeContentOptions recognizeContentOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AI.FormRecognizer.Models.RecognizeCustomFormsOperation StartRecognizeCustomForms(string modelId, System.IO.Stream form, Azure.AI.FormRecognizer.RecognizeCustomFormsOptions recognizeCustomFormsOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Models.RecognizeCustomFormsOperation> StartRecognizeCustomFormsAsync(string modelId, System.IO.Stream form, Azure.AI.FormRecognizer.RecognizeCustomFormsOptions recognizeCustomFormsOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AI.FormRecognizer.Models.RecognizeCustomFormsOperation StartRecognizeCustomFormsFromUri(string modelId, System.Uri formUri, Azure.AI.FormRecognizer.RecognizeCustomFormsOptions recognizeCustomFormsOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Models.RecognizeCustomFormsOperation> StartRecognizeCustomFormsFromUriAsync(string modelId, System.Uri formUri, Azure.AI.FormRecognizer.RecognizeCustomFormsOptions recognizeCustomFormsOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AI.FormRecognizer.Models.RecognizeReceiptsOperation StartRecognizeReceipts(System.IO.Stream receipt, Azure.AI.FormRecognizer.RecognizeReceiptsOptions recognizeReceiptsOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Models.RecognizeReceiptsOperation> StartRecognizeReceiptsAsync(System.IO.Stream receipt, Azure.AI.FormRecognizer.RecognizeReceiptsOptions recognizeReceiptsOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AI.FormRecognizer.Models.RecognizeReceiptsOperation StartRecognizeReceiptsFromUri(System.Uri receiptUri, Azure.AI.FormRecognizer.RecognizeReceiptsOptions recognizeReceiptsOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Models.RecognizeReceiptsOperation> StartRecognizeReceiptsFromUriAsync(System.Uri receiptUri, Azure.AI.FormRecognizer.RecognizeReceiptsOptions recognizeReceiptsOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class FormRecognizerClientOptions : Azure.Core.ClientOptions
{
public FormRecognizerClientOptions(Azure.AI.FormRecognizer.FormRecognizerClientOptions.ServiceVersion version = Azure.AI.FormRecognizer.FormRecognizerClientOptions.ServiceVersion.V2_0) { }
public Azure.AI.FormRecognizer.FormRecognizerClientOptions.ServiceVersion Version { get { throw null; } }
public enum ServiceVersion
{
V2_0 = 1,
}
}
public static partial class OperationExtensions
{
public static System.Threading.Tasks.Task<Azure.Response<Azure.AI.FormRecognizer.Models.RecognizedFormCollection>> WaitForCompletionAsync(this System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Models.RecognizeBusinessCardsOperation> operation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Threading.Tasks.Task<Azure.Response<Azure.AI.FormRecognizer.Models.FormPageCollection>> WaitForCompletionAsync(this System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Models.RecognizeContentOperation> operation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Threading.Tasks.Task<Azure.Response<Azure.AI.FormRecognizer.Models.RecognizedFormCollection>> WaitForCompletionAsync(this System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Models.RecognizeCustomFormsOperation> operation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Threading.Tasks.Task<Azure.Response<Azure.AI.FormRecognizer.Models.RecognizedFormCollection>> WaitForCompletionAsync(this System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Models.RecognizeReceiptsOperation> operation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Threading.Tasks.Task<Azure.Response<Azure.AI.FormRecognizer.Training.CustomFormModelInfo>> WaitForCompletionAsync(this System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Training.CopyModelOperation> operation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Threading.Tasks.Task<Azure.Response<Azure.AI.FormRecognizer.Training.CustomFormModel>> WaitForCompletionAsync(this System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Training.CreateComposedModelOperation> operation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Threading.Tasks.Task<Azure.Response<Azure.AI.FormRecognizer.Training.CustomFormModel>> WaitForCompletionAsync(this System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Training.TrainingOperation> operation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class RecognizeBusinessCardsOptions
{
public RecognizeBusinessCardsOptions() { }
public Azure.AI.FormRecognizer.FormContentType? ContentType { get { throw null; } set { } }
public bool IncludeFieldElements { get { throw null; } set { } }
public string Locale { get { throw null; } set { } }
}
public partial class RecognizeContentOptions
{
public RecognizeContentOptions() { }
public Azure.AI.FormRecognizer.FormContentType? ContentType { get { throw null; } set { } }
}
public partial class RecognizeCustomFormsOptions
{
public RecognizeCustomFormsOptions() { }
public Azure.AI.FormRecognizer.FormContentType? ContentType { get { throw null; } set { } }
public bool IncludeFieldElements { get { throw null; } set { } }
}
public partial class RecognizeReceiptsOptions
{
public RecognizeReceiptsOptions() { }
public Azure.AI.FormRecognizer.FormContentType? ContentType { get { throw null; } set { } }
public bool IncludeFieldElements { get { throw null; } set { } }
public string Locale { get { throw null; } set { } }
}
}
namespace Azure.AI.FormRecognizer.Models
{
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct FieldBoundingBox
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public System.Drawing.PointF this[int index] { get { throw null; } }
public override string ToString() { throw null; }
}
public partial class FieldData : Azure.AI.FormRecognizer.Models.FormElement
{
internal FieldData() { }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormElement> FieldElements { get { throw null; } }
public static implicit operator string (Azure.AI.FormRecognizer.Models.FieldData text) { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct FieldValue
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public Azure.AI.FormRecognizer.Models.FieldValueType ValueType { get { throw null; } }
public System.DateTime AsDate() { throw null; }
public System.Collections.Generic.IReadOnlyDictionary<string, Azure.AI.FormRecognizer.Models.FormField> AsDictionary() { throw null; }
public float AsFloat() { throw null; }
public Azure.AI.FormRecognizer.Models.FormSelectionMarkState AsFormSelectionMarkState() { throw null; }
public long AsInt64() { throw null; }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormField> AsList() { throw null; }
public string AsPhoneNumber() { throw null; }
public string AsString() { throw null; }
public System.TimeSpan AsTime() { throw null; }
}
public enum FieldValueType
{
String = 0,
Date = 1,
Time = 2,
PhoneNumber = 3,
Float = 4,
Int64 = 5,
List = 6,
Dictionary = 7,
SelectionMark = 8,
}
public abstract partial class FormElement
{
internal FormElement() { }
public Azure.AI.FormRecognizer.Models.FieldBoundingBox BoundingBox { get { throw null; } }
public int PageNumber { get { throw null; } }
public string Text { get { throw null; } }
}
public partial class FormField
{
internal FormField() { }
public float Confidence { get { throw null; } }
public Azure.AI.FormRecognizer.Models.FieldData LabelData { get { throw null; } }
public string Name { get { throw null; } }
public Azure.AI.FormRecognizer.Models.FieldValue Value { get { throw null; } }
public Azure.AI.FormRecognizer.Models.FieldData ValueData { get { throw null; } }
}
public partial class FormField<T>
{
public FormField(Azure.AI.FormRecognizer.Models.FormField field, T value) { }
public float Confidence { get { throw null; } }
public Azure.AI.FormRecognizer.Models.FieldData LabelData { get { throw null; } }
public string Name { get { throw null; } }
public T Value { get { throw null; } }
public Azure.AI.FormRecognizer.Models.FieldData ValueData { get { throw null; } }
public static implicit operator T (Azure.AI.FormRecognizer.Models.FormField<T> field) { throw null; }
}
public partial class FormLine : Azure.AI.FormRecognizer.Models.FormElement
{
internal FormLine() { }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormWord> Words { get { throw null; } }
}
public partial class FormPage
{
internal FormPage() { }
public float Height { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormLine> Lines { get { throw null; } }
public int PageNumber { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormSelectionMark> SelectionMarks { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormTable> Tables { get { throw null; } }
public float TextAngle { get { throw null; } }
public Azure.AI.FormRecognizer.Models.LengthUnit Unit { get { throw null; } }
public float Width { get { throw null; } }
}
public partial class FormPageCollection : System.Collections.ObjectModel.ReadOnlyCollection<Azure.AI.FormRecognizer.Models.FormPage>
{
internal FormPageCollection() : base (default(System.Collections.Generic.IList<Azure.AI.FormRecognizer.Models.FormPage>)) { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct FormPageRange
{
private int _dummyPrimitive;
public int FirstPageNumber { get { throw null; } }
public int LastPageNumber { get { throw null; } }
}
public partial class FormRecognizerError
{
internal FormRecognizerError() { }
public string ErrorCode { get { throw null; } }
public string Message { get { throw null; } }
}
public static partial class FormRecognizerModelFactory
{
public static Azure.AI.FormRecognizer.Training.AccountProperties AccountProperties(int customModelCount, int customModelLimit) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static Azure.AI.FormRecognizer.Training.CustomFormModel CustomFormModel(string modelId, Azure.AI.FormRecognizer.Training.CustomFormModelStatus status, System.DateTimeOffset trainingStartedOn, System.DateTimeOffset trainingCompletedOn, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Training.CustomFormSubmodel> submodels, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Training.TrainingDocumentInfo> trainingDocuments, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormRecognizerError> errors) { throw null; }
public static Azure.AI.FormRecognizer.Training.CustomFormModel CustomFormModel(string modelId, Azure.AI.FormRecognizer.Training.CustomFormModelStatus status, System.DateTimeOffset trainingStartedOn, System.DateTimeOffset trainingCompletedOn, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Training.CustomFormSubmodel> submodels, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Training.TrainingDocumentInfo> trainingDocuments, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormRecognizerError> errors, string modelName, Azure.AI.FormRecognizer.Training.CustomFormModelProperties properties) { throw null; }
public static Azure.AI.FormRecognizer.Training.CustomFormModelField CustomFormModelField(string name, string label, float? accuracy) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static Azure.AI.FormRecognizer.Training.CustomFormModelInfo CustomFormModelInfo(string modelId, System.DateTimeOffset trainingStartedOn, System.DateTimeOffset trainingCompletedOn, Azure.AI.FormRecognizer.Training.CustomFormModelStatus status) { throw null; }
public static Azure.AI.FormRecognizer.Training.CustomFormModelInfo CustomFormModelInfo(string modelId, System.DateTimeOffset trainingStartedOn, System.DateTimeOffset trainingCompletedOn, Azure.AI.FormRecognizer.Training.CustomFormModelStatus status, string modelName, Azure.AI.FormRecognizer.Training.CustomFormModelProperties properties) { throw null; }
public static Azure.AI.FormRecognizer.Training.CustomFormModelProperties CustomFormModelProperties(bool isComposedModel) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static Azure.AI.FormRecognizer.Training.CustomFormSubmodel CustomFormSubmodel(string formType, float? accuracy, System.Collections.Generic.IReadOnlyDictionary<string, Azure.AI.FormRecognizer.Training.CustomFormModelField> fields) { throw null; }
public static Azure.AI.FormRecognizer.Training.CustomFormSubmodel CustomFormSubmodel(string formType, float? accuracy, System.Collections.Generic.IReadOnlyDictionary<string, Azure.AI.FormRecognizer.Training.CustomFormModelField> fields, string modelId) { throw null; }
public static Azure.AI.FormRecognizer.Models.FieldBoundingBox FieldBoundingBox(System.Collections.Generic.IReadOnlyList<System.Drawing.PointF> points) { throw null; }
public static Azure.AI.FormRecognizer.Models.FieldData FieldData(Azure.AI.FormRecognizer.Models.FieldBoundingBox boundingBox, int pageNumber, string text, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormElement> fieldElements) { throw null; }
public static Azure.AI.FormRecognizer.Models.FieldValue FieldValueWithDateValueType(System.DateTime value) { throw null; }
public static Azure.AI.FormRecognizer.Models.FieldValue FieldValueWithDictionaryValueType(System.Collections.Generic.IReadOnlyDictionary<string, Azure.AI.FormRecognizer.Models.FormField> value) { throw null; }
public static Azure.AI.FormRecognizer.Models.FieldValue FieldValueWithFloatValueType(float value) { throw null; }
public static Azure.AI.FormRecognizer.Models.FieldValue FieldValueWithInt64ValueType(long value) { throw null; }
public static Azure.AI.FormRecognizer.Models.FieldValue FieldValueWithListValueType(System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormField> value) { throw null; }
public static Azure.AI.FormRecognizer.Models.FieldValue FieldValueWithPhoneNumberValueType(string value) { throw null; }
public static Azure.AI.FormRecognizer.Models.FieldValue FieldValueWithSelectionMarkValueType(Azure.AI.FormRecognizer.Models.FormSelectionMarkState value) { throw null; }
public static Azure.AI.FormRecognizer.Models.FieldValue FieldValueWithStringValueType(string value) { throw null; }
public static Azure.AI.FormRecognizer.Models.FieldValue FieldValueWithTimeValueType(System.TimeSpan value) { throw null; }
public static Azure.AI.FormRecognizer.Models.FormField FormField(string name, Azure.AI.FormRecognizer.Models.FieldData labelData, Azure.AI.FormRecognizer.Models.FieldData valueData, Azure.AI.FormRecognizer.Models.FieldValue value, float confidence) { throw null; }
public static Azure.AI.FormRecognizer.Models.FormLine FormLine(Azure.AI.FormRecognizer.Models.FieldBoundingBox boundingBox, int pageNumber, string text, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormWord> words) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static Azure.AI.FormRecognizer.Models.FormPage FormPage(int pageNumber, float width, float height, float textAngle, Azure.AI.FormRecognizer.Models.LengthUnit unit, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormLine> lines, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormTable> tables) { throw null; }
public static Azure.AI.FormRecognizer.Models.FormPage FormPage(int pageNumber, float width, float height, float textAngle, Azure.AI.FormRecognizer.Models.LengthUnit unit, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormLine> lines, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormTable> tables, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormSelectionMark> selectionMarks) { throw null; }
public static Azure.AI.FormRecognizer.Models.FormPageCollection FormPageCollection(System.Collections.Generic.IList<Azure.AI.FormRecognizer.Models.FormPage> list) { throw null; }
public static Azure.AI.FormRecognizer.Models.FormPageRange FormPageRange(int firstPageNumber, int lastPageNumber) { throw null; }
public static Azure.AI.FormRecognizer.Models.FormRecognizerError FormRecognizerError(string errorCode, string message) { throw null; }
public static Azure.AI.FormRecognizer.Models.FormSelectionMark FormSelectionMark(Azure.AI.FormRecognizer.Models.FieldBoundingBox boundingBox, int pageNumber, string text, float confidence, Azure.AI.FormRecognizer.Models.FormSelectionMarkState state) { throw null; }
public static Azure.AI.FormRecognizer.Models.FormTable FormTable(int pageNumber, int columnCount, int rowCount, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormTableCell> cells) { throw null; }
public static Azure.AI.FormRecognizer.Models.FormTableCell FormTableCell(Azure.AI.FormRecognizer.Models.FieldBoundingBox boundingBox, int pageNumber, string text, int columnIndex, int rowIndex, int columnSpan, int rowSpan, bool isHeader, bool isFooter, float confidence, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormElement> fieldElements) { throw null; }
public static Azure.AI.FormRecognizer.Models.FormWord FormWord(Azure.AI.FormRecognizer.Models.FieldBoundingBox boundingBox, int pageNumber, string text, float confidence) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static Azure.AI.FormRecognizer.Models.RecognizedForm RecognizedForm(string formType, Azure.AI.FormRecognizer.Models.FormPageRange pageRange, System.Collections.Generic.IReadOnlyDictionary<string, Azure.AI.FormRecognizer.Models.FormField> fields, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormPage> pages) { throw null; }
public static Azure.AI.FormRecognizer.Models.RecognizedForm RecognizedForm(string formType, Azure.AI.FormRecognizer.Models.FormPageRange pageRange, System.Collections.Generic.IReadOnlyDictionary<string, Azure.AI.FormRecognizer.Models.FormField> fields, System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormPage> pages, string modelId, float? formTypeConfidence) { throw null; }
public static Azure.AI.FormRecognizer.Models.RecognizedFormCollection RecognizedFormCollection(System.Collections.Generic.IList<Azure.AI.FormRecognizer.Models.RecognizedForm> list) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static Azure.AI.FormRecognizer.Training.TrainingDocumentInfo TrainingDocumentInfo(string name, int pageCount, System.Collections.Generic.IEnumerable<Azure.AI.FormRecognizer.Models.FormRecognizerError> errors, Azure.AI.FormRecognizer.Training.TrainingStatus status) { throw null; }
public static Azure.AI.FormRecognizer.Training.TrainingDocumentInfo TrainingDocumentInfo(string name, int pageCount, System.Collections.Generic.IEnumerable<Azure.AI.FormRecognizer.Models.FormRecognizerError> errors, Azure.AI.FormRecognizer.Training.TrainingStatus status, string modelId) { throw null; }
}
public partial class FormSelectionMark : Azure.AI.FormRecognizer.Models.FormElement
{
internal FormSelectionMark() { }
public float Confidence { get { throw null; } }
public Azure.AI.FormRecognizer.Models.FormSelectionMarkState State { get { throw null; } }
}
public enum FormSelectionMarkState
{
Selected = 0,
Unselected = 1,
}
public partial class FormTable
{
internal FormTable() { }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormTableCell> Cells { get { throw null; } }
public int ColumnCount { get { throw null; } }
public int PageNumber { get { throw null; } }
public int RowCount { get { throw null; } }
}
public partial class FormTableCell : Azure.AI.FormRecognizer.Models.FormElement
{
internal FormTableCell() { }
public int ColumnIndex { get { throw null; } }
public int ColumnSpan { get { throw null; } }
public float Confidence { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormElement> FieldElements { get { throw null; } }
public bool IsFooter { get { throw null; } }
public bool IsHeader { get { throw null; } }
public int RowIndex { get { throw null; } }
public int RowSpan { get { throw null; } }
}
public partial class FormWord : Azure.AI.FormRecognizer.Models.FormElement
{
internal FormWord() { }
public float Confidence { get { throw null; } }
}
public enum LengthUnit
{
Pixel = 0,
Inch = 1,
}
public partial class RecognizeBusinessCardsOperation : Azure.Operation<Azure.AI.FormRecognizer.Models.RecognizedFormCollection>
{
public RecognizeBusinessCardsOperation(string operationId, Azure.AI.FormRecognizer.FormRecognizerClient client) { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.AI.FormRecognizer.Models.RecognizedFormCollection Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AI.FormRecognizer.Models.RecognizedFormCollection>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AI.FormRecognizer.Models.RecognizedFormCollection>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class RecognizeContentOperation : Azure.Operation<Azure.AI.FormRecognizer.Models.FormPageCollection>
{
public RecognizeContentOperation(string operationId, Azure.AI.FormRecognizer.FormRecognizerClient client) { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.AI.FormRecognizer.Models.FormPageCollection Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AI.FormRecognizer.Models.FormPageCollection>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AI.FormRecognizer.Models.FormPageCollection>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class RecognizeCustomFormsOperation : Azure.Operation<Azure.AI.FormRecognizer.Models.RecognizedFormCollection>
{
public RecognizeCustomFormsOperation(string operationId, Azure.AI.FormRecognizer.FormRecognizerClient client) { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.AI.FormRecognizer.Models.RecognizedFormCollection Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AI.FormRecognizer.Models.RecognizedFormCollection>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AI.FormRecognizer.Models.RecognizedFormCollection>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class RecognizedForm
{
internal RecognizedForm() { }
public System.Collections.Generic.IReadOnlyDictionary<string, Azure.AI.FormRecognizer.Models.FormField> Fields { get { throw null; } }
public string FormType { get { throw null; } }
public float? FormTypeConfidence { get { throw null; } }
public string ModelId { get { throw null; } }
public Azure.AI.FormRecognizer.Models.FormPageRange PageRange { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormPage> Pages { get { throw null; } }
}
public partial class RecognizedFormCollection : System.Collections.ObjectModel.ReadOnlyCollection<Azure.AI.FormRecognizer.Models.RecognizedForm>
{
internal RecognizedFormCollection() : base (default(System.Collections.Generic.IList<Azure.AI.FormRecognizer.Models.RecognizedForm>)) { }
}
public partial class RecognizeReceiptsOperation : Azure.Operation<Azure.AI.FormRecognizer.Models.RecognizedFormCollection>
{
public RecognizeReceiptsOperation(string operationId, Azure.AI.FormRecognizer.FormRecognizerClient client) { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.AI.FormRecognizer.Models.RecognizedFormCollection Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AI.FormRecognizer.Models.RecognizedFormCollection>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AI.FormRecognizer.Models.RecognizedFormCollection>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
}
namespace Azure.AI.FormRecognizer.Training
{
public partial class AccountProperties
{
internal AccountProperties() { }
public int CustomModelCount { get { throw null; } }
public int CustomModelLimit { get { throw null; } }
}
public partial class CopyAuthorization
{
internal CopyAuthorization() { }
public System.DateTimeOffset ExpiresOn { get { throw null; } }
public string ModelId { get { throw null; } }
public static Azure.AI.FormRecognizer.Training.CopyAuthorization FromJson(string copyAuthorization) { throw null; }
public string ToJson() { throw null; }
}
public partial class CopyModelOperation : Azure.Operation<Azure.AI.FormRecognizer.Training.CustomFormModelInfo>
{
public CopyModelOperation(string operationId, string targetModelId, Azure.AI.FormRecognizer.Training.FormTrainingClient client) { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.AI.FormRecognizer.Training.CustomFormModelInfo Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AI.FormRecognizer.Training.CustomFormModelInfo>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AI.FormRecognizer.Training.CustomFormModelInfo>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class CreateComposedModelOperation : Azure.AI.FormRecognizer.Training.CreateCustomFormModelOperation
{
public CreateComposedModelOperation(string operationId, Azure.AI.FormRecognizer.Training.FormTrainingClient client) : base (default(string), default(Azure.AI.FormRecognizer.Training.FormTrainingClient)) { }
}
public partial class CreateComposedModelOptions
{
public CreateComposedModelOptions() { }
public string ModelName { get { throw null; } set { } }
}
public partial class CreateCustomFormModelOperation : Azure.Operation<Azure.AI.FormRecognizer.Training.CustomFormModel>
{
public CreateCustomFormModelOperation(string operationId, Azure.AI.FormRecognizer.Training.FormTrainingClient client) { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.AI.FormRecognizer.Training.CustomFormModel Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AI.FormRecognizer.Training.CustomFormModel>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AI.FormRecognizer.Training.CustomFormModel>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class CustomFormModel
{
internal CustomFormModel() { }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormRecognizerError> Errors { get { throw null; } }
public string ModelId { get { throw null; } }
public string ModelName { get { throw null; } }
public Azure.AI.FormRecognizer.Training.CustomFormModelProperties Properties { get { throw null; } }
public Azure.AI.FormRecognizer.Training.CustomFormModelStatus Status { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Training.CustomFormSubmodel> Submodels { get { throw null; } }
public System.DateTimeOffset TrainingCompletedOn { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Training.TrainingDocumentInfo> TrainingDocuments { get { throw null; } }
public System.DateTimeOffset TrainingStartedOn { get { throw null; } }
}
public partial class CustomFormModelField
{
internal CustomFormModelField() { }
public float? Accuracy { get { throw null; } }
public string Label { get { throw null; } }
public string Name { get { throw null; } }
}
public partial class CustomFormModelInfo
{
internal CustomFormModelInfo() { }
public string ModelId { get { throw null; } }
public string ModelName { get { throw null; } }
public Azure.AI.FormRecognizer.Training.CustomFormModelProperties Properties { get { throw null; } }
public Azure.AI.FormRecognizer.Training.CustomFormModelStatus Status { get { throw null; } }
public System.DateTimeOffset TrainingCompletedOn { get { throw null; } }
public System.DateTimeOffset TrainingStartedOn { get { throw null; } }
}
public partial class CustomFormModelProperties
{
internal CustomFormModelProperties() { }
public bool IsComposedModel { get { throw null; } }
}
public enum CustomFormModelStatus
{
Invalid = 0,
Ready = 1,
Creating = 2,
}
public partial class CustomFormSubmodel
{
internal CustomFormSubmodel() { }
public float? Accuracy { get { throw null; } }
public System.Collections.Generic.IReadOnlyDictionary<string, Azure.AI.FormRecognizer.Training.CustomFormModelField> Fields { get { throw null; } }
public string FormType { get { throw null; } }
public string ModelId { get { throw null; } }
}
public partial class FormTrainingClient
{
protected FormTrainingClient() { }
public FormTrainingClient(System.Uri endpoint, Azure.AzureKeyCredential credential) { }
public FormTrainingClient(System.Uri endpoint, Azure.AzureKeyCredential credential, Azure.AI.FormRecognizer.FormRecognizerClientOptions options) { }
public FormTrainingClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { }
public FormTrainingClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.AI.FormRecognizer.FormRecognizerClientOptions options) { }
public virtual Azure.Response DeleteModel(string modelId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteModelAsync(string modelId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.AI.FormRecognizer.Training.AccountProperties> GetAccountProperties(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.AI.FormRecognizer.Training.AccountProperties>> GetAccountPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.AI.FormRecognizer.Training.CopyAuthorization> GetCopyAuthorization(string resourceId, string resourceRegion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.AI.FormRecognizer.Training.CopyAuthorization>> GetCopyAuthorizationAsync(string resourceId, string resourceRegion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.AI.FormRecognizer.Training.CustomFormModel> GetCustomModel(string modelId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.AI.FormRecognizer.Training.CustomFormModel>> GetCustomModelAsync(string modelId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.AI.FormRecognizer.Training.CustomFormModelInfo> GetCustomModels(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.AI.FormRecognizer.Training.CustomFormModelInfo> GetCustomModelsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AI.FormRecognizer.FormRecognizerClient GetFormRecognizerClient() { throw null; }
public virtual Azure.AI.FormRecognizer.Training.CopyModelOperation StartCopyModel(string modelId, Azure.AI.FormRecognizer.Training.CopyAuthorization target, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Training.CopyModelOperation> StartCopyModelAsync(string modelId, Azure.AI.FormRecognizer.Training.CopyAuthorization target, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AI.FormRecognizer.Training.CreateComposedModelOperation StartCreateComposedModel(System.Collections.Generic.IEnumerable<string> modelIds, Azure.AI.FormRecognizer.Training.CreateComposedModelOptions createComposedModelOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Training.CreateComposedModelOperation> StartCreateComposedModelAsync(System.Collections.Generic.IEnumerable<string> modelIds, Azure.AI.FormRecognizer.Training.CreateComposedModelOptions createComposedModelOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AI.FormRecognizer.Training.TrainingOperation StartTraining(System.Uri trainingFilesUri, bool useTrainingLabels, Azure.AI.FormRecognizer.Training.TrainingOptions trainingOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.AI.FormRecognizer.Training.TrainingOperation> StartTrainingAsync(System.Uri trainingFilesUri, bool useTrainingLabels, Azure.AI.FormRecognizer.Training.TrainingOptions trainingOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class TrainingDocumentInfo
{
internal TrainingDocumentInfo() { }
public System.Collections.Generic.IReadOnlyList<Azure.AI.FormRecognizer.Models.FormRecognizerError> Errors { get { throw null; } }
public string ModelId { get { throw null; } }
public string Name { get { throw null; } }
public int PageCount { get { throw null; } }
public Azure.AI.FormRecognizer.Training.TrainingStatus Status { get { throw null; } }
}
public partial class TrainingFileFilter
{
public TrainingFileFilter() { }
public bool IncludeSubfolders { get { throw null; } set { } }
public string Prefix { get { throw null; } set { } }
}
public partial class TrainingOperation : Azure.AI.FormRecognizer.Training.CreateCustomFormModelOperation
{
public TrainingOperation(string operationId, Azure.AI.FormRecognizer.Training.FormTrainingClient client) : base (default(string), default(Azure.AI.FormRecognizer.Training.FormTrainingClient)) { }
}
public partial class TrainingOptions
{
public TrainingOptions() { }
public string ModelName { get { throw null; } set { } }
public Azure.AI.FormRecognizer.Training.TrainingFileFilter TrainingFileFilter { get { throw null; } set { } }
}
public enum TrainingStatus
{
Succeeded = 0,
PartiallySucceeded = 1,
Failed = 2,
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.TextToSpeech.V1
{
/// <summary>Settings for <see cref="TextToSpeechClient"/> instances.</summary>
public sealed partial class TextToSpeechSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="TextToSpeechSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="TextToSpeechSettings"/>.</returns>
public static TextToSpeechSettings GetDefault() => new TextToSpeechSettings();
/// <summary>Constructs a new <see cref="TextToSpeechSettings"/> object with default settings.</summary>
public TextToSpeechSettings()
{
}
private TextToSpeechSettings(TextToSpeechSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListVoicesSettings = existing.ListVoicesSettings;
SynthesizeSpeechSettings = existing.SynthesizeSpeechSettings;
OnCopy(existing);
}
partial void OnCopy(TextToSpeechSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TextToSpeechClient.ListVoices</c> and <c>TextToSpeechClient.ListVoicesAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 300 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListVoicesSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(300000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>TextToSpeechClient.SynthesizeSpeech</c> and <c>TextToSpeechClient.SynthesizeSpeechAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 300 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings SynthesizeSpeechSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(300000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="TextToSpeechSettings"/> object.</returns>
public TextToSpeechSettings Clone() => new TextToSpeechSettings(this);
}
/// <summary>
/// Builder class for <see cref="TextToSpeechClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class TextToSpeechClientBuilder : gaxgrpc::ClientBuilderBase<TextToSpeechClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public TextToSpeechSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public TextToSpeechClientBuilder()
{
UseJwtAccessWithScopes = TextToSpeechClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref TextToSpeechClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<TextToSpeechClient> task);
/// <summary>Builds the resulting client.</summary>
public override TextToSpeechClient Build()
{
TextToSpeechClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<TextToSpeechClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<TextToSpeechClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private TextToSpeechClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return TextToSpeechClient.Create(callInvoker, Settings);
}
private async stt::Task<TextToSpeechClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return TextToSpeechClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => TextToSpeechClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => TextToSpeechClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => TextToSpeechClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>TextToSpeech client wrapper, for convenient use.</summary>
/// <remarks>
/// Service that implements Google Cloud Text-to-Speech API.
/// </remarks>
public abstract partial class TextToSpeechClient
{
/// <summary>
/// The default endpoint for the TextToSpeech service, which is a host of "texttospeech.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "texttospeech.googleapis.com:443";
/// <summary>The default TextToSpeech scopes.</summary>
/// <remarks>
/// The default TextToSpeech scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="TextToSpeechClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="TextToSpeechClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="TextToSpeechClient"/>.</returns>
public static stt::Task<TextToSpeechClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new TextToSpeechClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="TextToSpeechClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="TextToSpeechClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="TextToSpeechClient"/>.</returns>
public static TextToSpeechClient Create() => new TextToSpeechClientBuilder().Build();
/// <summary>
/// Creates a <see cref="TextToSpeechClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="TextToSpeechSettings"/>.</param>
/// <returns>The created <see cref="TextToSpeechClient"/>.</returns>
internal static TextToSpeechClient Create(grpccore::CallInvoker callInvoker, TextToSpeechSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
TextToSpeech.TextToSpeechClient grpcClient = new TextToSpeech.TextToSpeechClient(callInvoker);
return new TextToSpeechClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC TextToSpeech client</summary>
public virtual TextToSpeech.TextToSpeechClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ListVoicesResponse ListVoices(ListVoicesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListVoicesResponse> ListVoicesAsync(ListVoicesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListVoicesResponse> ListVoicesAsync(ListVoicesRequest request, st::CancellationToken cancellationToken) =>
ListVoicesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="languageCode">
/// Optional. Recommended.
/// [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
/// If not specified, the API will return all supported voices.
/// If specified, the ListVoices call will only return voices that can be used
/// to synthesize this language_code. For example, if you specify `"en-NZ"`,
/// all `"en-NZ"` voices will be returned. If you specify `"no"`, both
/// `"no-\*"` (Norwegian) and `"nb-\*"` (Norwegian Bokmal) voices will be
/// returned.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ListVoicesResponse ListVoices(string languageCode, gaxgrpc::CallSettings callSettings = null) =>
ListVoices(new ListVoicesRequest
{
LanguageCode = languageCode ?? "",
}, callSettings);
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="languageCode">
/// Optional. Recommended.
/// [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
/// If not specified, the API will return all supported voices.
/// If specified, the ListVoices call will only return voices that can be used
/// to synthesize this language_code. For example, if you specify `"en-NZ"`,
/// all `"en-NZ"` voices will be returned. If you specify `"no"`, both
/// `"no-\*"` (Norwegian) and `"nb-\*"` (Norwegian Bokmal) voices will be
/// returned.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListVoicesResponse> ListVoicesAsync(string languageCode, gaxgrpc::CallSettings callSettings = null) =>
ListVoicesAsync(new ListVoicesRequest
{
LanguageCode = languageCode ?? "",
}, callSettings);
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="languageCode">
/// Optional. Recommended.
/// [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
/// If not specified, the API will return all supported voices.
/// If specified, the ListVoices call will only return voices that can be used
/// to synthesize this language_code. For example, if you specify `"en-NZ"`,
/// all `"en-NZ"` voices will be returned. If you specify `"no"`, both
/// `"no-\*"` (Norwegian) and `"nb-\*"` (Norwegian Bokmal) voices will be
/// returned.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListVoicesResponse> ListVoicesAsync(string languageCode, st::CancellationToken cancellationToken) =>
ListVoicesAsync(languageCode, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual SynthesizeSpeechResponse SynthesizeSpeech(SynthesizeSpeechRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<SynthesizeSpeechResponse> SynthesizeSpeechAsync(SynthesizeSpeechRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<SynthesizeSpeechResponse> SynthesizeSpeechAsync(SynthesizeSpeechRequest request, st::CancellationToken cancellationToken) =>
SynthesizeSpeechAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="input">
/// Required. The Synthesizer requires either plain text or SSML as input.
/// </param>
/// <param name="voice">
/// Required. The desired voice of the synthesized audio.
/// </param>
/// <param name="audioConfig">
/// Required. The configuration of the synthesized audio.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual SynthesizeSpeechResponse SynthesizeSpeech(SynthesisInput input, VoiceSelectionParams voice, AudioConfig audioConfig, gaxgrpc::CallSettings callSettings = null) =>
SynthesizeSpeech(new SynthesizeSpeechRequest
{
Input = gax::GaxPreconditions.CheckNotNull(input, nameof(input)),
Voice = gax::GaxPreconditions.CheckNotNull(voice, nameof(voice)),
AudioConfig = gax::GaxPreconditions.CheckNotNull(audioConfig, nameof(audioConfig)),
}, callSettings);
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="input">
/// Required. The Synthesizer requires either plain text or SSML as input.
/// </param>
/// <param name="voice">
/// Required. The desired voice of the synthesized audio.
/// </param>
/// <param name="audioConfig">
/// Required. The configuration of the synthesized audio.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<SynthesizeSpeechResponse> SynthesizeSpeechAsync(SynthesisInput input, VoiceSelectionParams voice, AudioConfig audioConfig, gaxgrpc::CallSettings callSettings = null) =>
SynthesizeSpeechAsync(new SynthesizeSpeechRequest
{
Input = gax::GaxPreconditions.CheckNotNull(input, nameof(input)),
Voice = gax::GaxPreconditions.CheckNotNull(voice, nameof(voice)),
AudioConfig = gax::GaxPreconditions.CheckNotNull(audioConfig, nameof(audioConfig)),
}, callSettings);
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="input">
/// Required. The Synthesizer requires either plain text or SSML as input.
/// </param>
/// <param name="voice">
/// Required. The desired voice of the synthesized audio.
/// </param>
/// <param name="audioConfig">
/// Required. The configuration of the synthesized audio.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<SynthesizeSpeechResponse> SynthesizeSpeechAsync(SynthesisInput input, VoiceSelectionParams voice, AudioConfig audioConfig, st::CancellationToken cancellationToken) =>
SynthesizeSpeechAsync(input, voice, audioConfig, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>TextToSpeech client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service that implements Google Cloud Text-to-Speech API.
/// </remarks>
public sealed partial class TextToSpeechClientImpl : TextToSpeechClient
{
private readonly gaxgrpc::ApiCall<ListVoicesRequest, ListVoicesResponse> _callListVoices;
private readonly gaxgrpc::ApiCall<SynthesizeSpeechRequest, SynthesizeSpeechResponse> _callSynthesizeSpeech;
/// <summary>
/// Constructs a client wrapper for the TextToSpeech service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="TextToSpeechSettings"/> used within this client.</param>
public TextToSpeechClientImpl(TextToSpeech.TextToSpeechClient grpcClient, TextToSpeechSettings settings)
{
GrpcClient = grpcClient;
TextToSpeechSettings effectiveSettings = settings ?? TextToSpeechSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callListVoices = clientHelper.BuildApiCall<ListVoicesRequest, ListVoicesResponse>(grpcClient.ListVoicesAsync, grpcClient.ListVoices, effectiveSettings.ListVoicesSettings);
Modify_ApiCall(ref _callListVoices);
Modify_ListVoicesApiCall(ref _callListVoices);
_callSynthesizeSpeech = clientHelper.BuildApiCall<SynthesizeSpeechRequest, SynthesizeSpeechResponse>(grpcClient.SynthesizeSpeechAsync, grpcClient.SynthesizeSpeech, effectiveSettings.SynthesizeSpeechSettings);
Modify_ApiCall(ref _callSynthesizeSpeech);
Modify_SynthesizeSpeechApiCall(ref _callSynthesizeSpeech);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ListVoicesApiCall(ref gaxgrpc::ApiCall<ListVoicesRequest, ListVoicesResponse> call);
partial void Modify_SynthesizeSpeechApiCall(ref gaxgrpc::ApiCall<SynthesizeSpeechRequest, SynthesizeSpeechResponse> call);
partial void OnConstruction(TextToSpeech.TextToSpeechClient grpcClient, TextToSpeechSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC TextToSpeech client</summary>
public override TextToSpeech.TextToSpeechClient GrpcClient { get; }
partial void Modify_ListVoicesRequest(ref ListVoicesRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_SynthesizeSpeechRequest(ref SynthesizeSpeechRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ListVoicesResponse ListVoices(ListVoicesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListVoicesRequest(ref request, ref callSettings);
return _callListVoices.Sync(request, callSettings);
}
/// <summary>
/// Returns a list of Voice supported for synthesis.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ListVoicesResponse> ListVoicesAsync(ListVoicesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListVoicesRequest(ref request, ref callSettings);
return _callListVoices.Async(request, callSettings);
}
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override SynthesizeSpeechResponse SynthesizeSpeech(SynthesizeSpeechRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SynthesizeSpeechRequest(ref request, ref callSettings);
return _callSynthesizeSpeech.Sync(request, callSettings);
}
/// <summary>
/// Synthesizes speech synchronously: receive results after all text input
/// has been processed.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<SynthesizeSpeechResponse> SynthesizeSpeechAsync(SynthesizeSpeechRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SynthesizeSpeechRequest(ref request, ref callSettings);
return _callSynthesizeSpeech.Async(request, callSettings);
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
public static class TestDriver
{
private const string ReferenceDirRoot = @"Microsoft.Research\Imported\ReferenceAssemblies\";
private const string ContractReferenceDirRoot = @"Microsoft.Research\Contracts\bin\Debug\";
private const string ClousotExe = @"Microsoft.Research\Clousot\bin\debug\clousot.exe";
private const string Clousot2Exe = @"Microsoft.Research\Clousot2\bin\debug\clousot2.exe";
private const string Clousot2SExe = @"Microsoft.Research\Clousot2S\bin\debug\clousot2s.exe";
private const string Clousot2SlicingExe = @"Microsoft.Research\Clousot2_Queue\bin\debug\Clousot2_Queue.exe";
private const string ClousotServiceHostExe = @"Microsoft.Research\Clousot2_WCFServiceHost\bin\debug\Cloudot.exe";
private const string ToolsRoot = @"Microsoft.Research\Imported\Tools\";
private static readonly Random randGenerator = new Random();
internal static void Clousot(string absoluteSourceDir, string absoluteBinary, Options options, Output output)
{
var referencedir = options.MakeAbsolute(Path.Combine(ReferenceDirRoot, options.BuildFramework));
var contractreferencedir = options.MakeAbsolute(Path.Combine(ContractReferenceDirRoot, options.ContractFramework));
var absoluteBinaryDir = Path.GetDirectoryName(absoluteBinary);
var absoluteSource = absoluteBinary;
var libPathsString = FormLibPaths(contractreferencedir, options);
var args = String.Format("{0} /regression /define:cci1only;clousot1 -framework:{4} -libpaths:{2} {3} {1}", options.ClousotOptions, absoluteSource, referencedir, libPathsString, options.Framework);
WriteRSPFile(absoluteBinaryDir, options, args);
if (options.Fast || System.Diagnostics.Debugger.IsAttached)
{
output.WriteLine("Calling CCI1Driver.Main with: {0}", args);
// Use output to avoid Clousot from closing the Console
Assert.AreEqual(0, Microsoft.Research.CodeAnalysis.CCI1Driver.Main(args.Split(' '), output));
}
else
RunProcess(absoluteBinaryDir, options.GetFullExecutablePath(ClousotExe), args, output, options.TestName);
}
internal static void Clousot2(string absoluteSourceDir, string absoluteBinary, Options options, Output output)
{
var referencedir = options.MakeAbsolute(Path.Combine(ReferenceDirRoot, options.BuildFramework));
var contractreferencedir = options.MakeAbsolute(Path.Combine(ContractReferenceDirRoot, options.ContractFramework));
var absoluteBinaryDir = Path.GetDirectoryName(absoluteBinary);
var absoluteSource = absoluteBinary;
var libPathsString = FormLibPaths(contractreferencedir, options) + " /libpaths:.";
var args = String.Format("{0} /show progress /regression /define:cci2only;clousot2 -libpaths:{2} {3} {1}", options.ClousotOptions, absoluteSource, referencedir, libPathsString);
WriteRSPFile(absoluteBinaryDir, options, args);
if (options.Fast || System.Diagnostics.Debugger.IsAttached)
{
output.WriteLine("Calling CCI2Driver.Main with: {0}", args);
// Use output to avoid Clousot2 from closing the Console
Assert.AreEqual(0, Microsoft.Research.CodeAnalysis.CCI2Driver.Main(args.Split(' '), output));
}
else
RunProcess(absoluteBinaryDir, options.GetFullExecutablePath(Clousot2Exe), args, output);
}
private static void WriteRSPFile(string dir, Options options, string args)
{
using (var file = new StreamWriter(Path.Combine(dir, options.TestName + ".rsp")))
{
file.WriteLine(args);
file.Close();
}
}
internal static void Clousot1Slicing(string absoluteSourceDir, string absoluteBinary, Options options, Output output)
{
var referencedir = options.MakeAbsolute(Path.Combine(ReferenceDirRoot, options.BuildFramework));
var contractreferencedir = options.MakeAbsolute(Path.Combine(ContractReferenceDirRoot, options.ContractFramework));
var absoluteBinaryDir = Path.GetDirectoryName(absoluteBinary);
var absoluteSource = absoluteBinary;
var libPathsString = FormLibPaths(contractreferencedir, options) + " /libpaths:.";
var args = String.Format("{0} -cci1 /regression /define:cci1only;clousot1 -framework:{4} -libpaths:{2} {3} {1}", options.ClousotOptions, absoluteSource, referencedir, libPathsString, options.Framework);
if (options.Fast || System.Diagnostics.Debugger.IsAttached)
{
output.WriteLine("Calling NewCCI2Driver.Main with: {0}", args);
// Use output to avoid Clousot from closing the Console
Assert.AreEqual(0, Microsoft.Research.CodeAnalysis.NewCCI2Driver.Main(args.Split(' '), output));
}
else
RunProcess(absoluteBinaryDir, options.GetFullExecutablePath(Clousot2SlicingExe), args, output);
}
internal static void Clousot2Slicing(string absoluteSourceDir, string absoluteBinary, Options options, Output output)
{
var referencedir = options.MakeAbsolute(Path.Combine(ReferenceDirRoot, options.BuildFramework));
var contractreferencedir = options.MakeAbsolute(Path.Combine(ContractReferenceDirRoot, options.ContractFramework));
var absoluteBinaryDir = Path.GetDirectoryName(absoluteBinary);
var absoluteSource = absoluteBinary;
var libPathsString = FormLibPaths(contractreferencedir, options) + " /libpaths:.";
var args = String.Format("{0} /show progress /regression /define:cci2only;clousot2 -libpaths:{2} {3} {1}", options.ClousotOptions, absoluteSource, referencedir, libPathsString);
if (options.Fast || System.Diagnostics.Debugger.IsAttached)
{
output.WriteLine("Calling NewCCI2Driver.Main with: {0}", args);
// Use output to avoid Clousot2 from closing the Console
Assert.AreEqual(0, Microsoft.Research.CodeAnalysis.NewCCI2Driver.Main(args.Split(' '), output));
}
else
RunProcess(absoluteBinaryDir, options.GetFullExecutablePath(Clousot2SlicingExe), args, output);
}
internal static void Clousot2S(string absoluteSourceDir, string absoluteBinary, Options options, Output output)
{
EnsureService(options);
var referencedir = options.MakeAbsolute(Path.Combine(ReferenceDirRoot, options.BuildFramework));
var contractreferencedir = options.MakeAbsolute(Path.Combine(ContractReferenceDirRoot, options.ContractFramework));
var absoluteBinaryDir = Path.GetDirectoryName(absoluteBinary);
var absoluteSource = absoluteBinary;
var libPathsString = FormLibPaths(contractreferencedir, options) + " /libpaths:.";
var args = String.Format("{0} /show progress /regression /define:cci2only;clousot2 -libpaths:{2} {3} {1}", options.ClousotOptions, absoluteSource, referencedir, libPathsString);
if (options.Fast || System.Diagnostics.Debugger.IsAttached)
{
output.WriteLine("Calling SDriver.Main with: {0}", args);
// Use output to avoid Clousot2S from closing the Console
Assert.AreEqual(0, Microsoft.Research.CodeAnalysis.SDriver.Main(args.Split(' '), output));
}
else
RunProcess(absoluteBinaryDir, options.GetFullExecutablePath(Clousot2SExe), args, output);
}
private static int RunProcess(string cwd, string tool, string arguments, Output output, string writeBatchFile = null)
{
ProcessStartInfo i = new ProcessStartInfo(tool, arguments);
output.WriteLine("Running '{0}'", i.FileName);
output.WriteLine(" {0}", i.Arguments);
i.RedirectStandardOutput = true;
i.RedirectStandardError = true;
i.UseShellExecute = false;
i.CreateNoWindow = true;
i.WorkingDirectory = cwd;
i.ErrorDialog = false;
if (writeBatchFile != null)
{
var file = new StreamWriter(Path.Combine(cwd, writeBatchFile + ".bat"));
file.WriteLine("\"{0}\" {1} %1 %2 %3 %4 %5", i.FileName, i.Arguments);
file.Close();
}
using (Process p = Process.Start(i))
{
p.OutputDataReceived += output.OutputDataReceivedEventHandler;
p.ErrorDataReceived += output.ErrDataReceivedEventHandler;
p.BeginOutputReadLine();
p.BeginErrorReadLine();
Assert.IsTrue(p.WaitForExit(200000), "{0} timed out", i.FileName);
if (p.ExitCode != 0)
{
Assert.AreEqual(0, p.ExitCode, "{0} returned an errorcode of {1}.", i.FileName, p.ExitCode);
}
return p.ExitCode;
}
}
private static string FormLibPaths(string contractReferenceDir, Options options)
{
// MB: do not change CurrentDirectory because it makes parallel tests fail
if (options.LibPaths == null)
return "";
StringBuilder sb = null;
if (options.UseContractReferenceAssemblies)
sb = new StringBuilder("/libpaths:").Append(contractReferenceDir);
foreach (var path in options.LibPaths)
{
if (sb == null)
sb = new StringBuilder("/libpaths:");
else
sb.Append(';');
sb.Append(options.MakeAbsolute(Path.Combine(path, options.ContractFramework)));
}
if (sb == null)
return "";
return sb.ToString();
}
internal static string Build(Options options, string extraCompilerOptions, Output output, out string absoluteSourceDir)
{
var sourceFile = options.MakeAbsolute(options.SourceFile);
var compilerpath = options.MakeAbsolute(Path.Combine(ToolsRoot, options.BuildFramework, options.Compiler));
var contractreferencedir = options.MakeAbsolute(Path.Combine(ContractReferenceDirRoot, options.BuildFramework));
var sourcedir = absoluteSourceDir = Path.GetDirectoryName(sourceFile);
var outputdir = Path.Combine(sourcedir, "bin", options.BuildFramework);
var extension = options.UseExe ? ".exe" : ".dll";
var targetKind = options.UseExe ? "exe" : "library";
var suffix = "_" + options.TestInstance;
if (options.GenerateUniqueOutputName)
suffix += "." + randGenerator.Next(0x10000).ToString("X4"); // enables concurrent tests on the same source file
var targetfile = Path.Combine(outputdir, Path.GetFileNameWithoutExtension(sourceFile) + suffix + extension);
// add Microsoft.Contracts reference if needed
if (!options.BuildFramework.Contains("v4."))
{
options.References.Add("Microsoft.Contracts.dll");
}
// MB: do not modify the CurrentDirectory, that could cause parallel tests to fail
var resolvedReferences = ResolveReferences(options);
var referenceString = ReferenceOptions(resolvedReferences);
if (!Directory.Exists(outputdir))
{
Directory.CreateDirectory(outputdir);
}
var args = String.Format("/debug /t:{4} /out:{0} {5} {3} {2} {1}", targetfile, sourceFile, referenceString, options.CompilerOptions(resolvedReferences), targetKind, extraCompilerOptions);
var exitCode = RunProcess(sourcedir, compilerpath, args, output);
if (exitCode != 0)
{
return null;
}
//CopyReferenceAssemblies(resolvedReferences, outputdir);
return targetfile;
}
private static void CopyReferenceAssemblies(List<string> resolvedReferences, string outputdir)
{
foreach (var r in resolvedReferences)
{
try
{
var fileName = Path.Combine(outputdir, Path.GetFileName(r));
if (File.Exists(fileName))
{
try
{
File.SetAttributes(fileName, FileAttributes.Normal);
}
catch { }
}
File.Copy(r, fileName, true);
}
catch { }
}
}
private static List<string> ResolveReferences(Options options)
{
var result = new List<string>();
foreach (var r in options.References)
{
foreach (var root in options.LibPaths)
{
var dir = options.MakeAbsolute(Path.Combine(root, options.BuildFramework));
var path = Path.Combine(dir, r);
if (File.Exists(path))
{
result.Add(path);
break;
}
}
foreach (var root in new[] { ReferenceDirRoot, ContractReferenceDirRoot })
{
var dir = options.MakeAbsolute(Path.Combine(root, options.BuildFramework));
var path = Path.Combine(dir, r);
if (File.Exists(path))
{
result.Add(path);
break;
}
}
}
return result;
}
private static string ReferenceOptions(List<string> references)
{
var sb = new StringBuilder();
foreach (var r in references)
{
sb.Append(String.Format(@"/r:{0} ", r));
}
return sb.ToString();
}
public static void BuildAndAnalyze(Options options)
{
var output = Output.ConsoleOutputFor(options.TestName);
string absoluteSourceDir;
var target = Build(options, "/d:CLOUSOT1", output, out absoluteSourceDir);
if (target != null)
{
Clousot(absoluteSourceDir, target, options, output);
}
}
public static void BuildAndAnalyze2(Options options)
{
if (options.SkipForCCI2)
return;
BuildAndAnalyze2(options, Output.ConsoleOutputFor(options.TestName));
}
private static void BuildAndAnalyze2(Options options, Output output)
{
string absoluteSourceDir;
var target = Build(options, "/d:CLOUSOT2", output, out absoluteSourceDir);
if (target != null)
Clousot2(absoluteSourceDir, target, options, output);
}
public static void BuildAndAnalyze2S(Options options)
{
if (options.SkipForCCI2)
return;
BuildAndAnalyze2S(options, Output.ConsoleOutputFor(options.TestName));
}
private static void BuildAndAnalyze2S(Options options, Output output)
{
string absoluteSourceDir;
var target = Build(options, "/d:CLOUSOT2", output, out absoluteSourceDir);
if (target != null)
Clousot2S(absoluteSourceDir, target, options, output);
}
public static void BuildAndAnalyze1Slicing(Options options)
{
BuildAndAnalyze1Slicing(options, Output.ConsoleOutputFor(options.TestName));
}
private static void BuildAndAnalyze1Slicing(Options options, Output output)
{
string absoluteSourceDir;
var target = Build(options, "/d:CLOUSOT1", output, out absoluteSourceDir);
if (target != null)
Clousot1Slicing(absoluteSourceDir, target, options, output);
}
public static void BuildAndAnalyze2Slicing(Options options)
{
if (options.SkipForCCI2)
return;
if (options.SkipSlicing)
return;
BuildAndAnalyze2Slicing(options, Output.ConsoleOutputFor(options.TestName));
}
private static void BuildAndAnalyze2Slicing(Options options, Output output)
{
string absoluteSourceDir;
var target = Build(options, "/d:CLOUSOT2 /d:SLICING", output, out absoluteSourceDir);
if (target != null)
Clousot2Slicing(absoluteSourceDir, target, options, output);
}
#region Parallel tests
private const string DefaultBeginMessage = "Build and analysis launched. Look at End results.";
private static bool SkipForCCI2(Options options) { return options.SkipForCCI2; }
public static readonly AsyncTestDriver AsyncFast2 = new AsyncTestDriver(BuildAndAnalyze2, SkipForCCI2, AsyncTestDriver.MaxWaitHandles_AllButOne) { BeginMessage = DefaultBeginMessage };
public static readonly AsyncTestDriver Async2S = new AsyncTestDriver(BuildAndAnalyze2S, SkipForCCI2) { BeginMessage = DefaultBeginMessage };
#endregion
#region Service actions
private static Process serviceProcess;
private static Object serviceProcessLock = new Object();
private static void EnsureService(Options options)
{
lock (serviceProcessLock) // prevent the service to be run twice at the same time
{
if (serviceProcess == null)
StartService(options);
Assert.IsFalse(serviceProcess.HasExited, "Service needed but service process already exited");
}
}
private static void StartService(Options options)
{
if (serviceProcess != null)
StopService();
// First make sure another instance is not already running (because we don't know which version is running)
foreach (var process in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(ClousotServiceHostExe)))
{
process.CloseMainWindow();
if (!process.WaitForExit(1000))
process.Kill();
}
var serviceHostDir = options.MakeAbsolute(Path.GetDirectoryName(ClousotServiceHostExe));
// note: we do not want to use ClousotServiceHostExe from the deployment directory because the app.config will be missing
serviceProcess = StartServiceProcess(serviceHostDir, options.MakeAbsolute(ClousotServiceHostExe), "", Output.Ignore);
}
public static void Cleanup()
{
KillRemainingClients();
StopService();
}
private static void KillRemainingClients()
{
foreach (var process in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Clousot2SExe)))
{
process.CloseMainWindow();
if (!process.WaitForExit(1000))
process.Kill();
}
}
private static void StopService()
{
lock (serviceProcessLock)
{
if (serviceProcess == null)
return;
serviceProcess.StandardInput.WriteLine();
if (!serviceProcess.WaitForExit(2000))
{
serviceProcess.Close();
if (!serviceProcess.WaitForExit(2000))
{
serviceProcess.Kill();
Assert.IsTrue(serviceProcess.WaitForExit(2000), "{0} did not want to exit");
}
}
Assert.AreEqual(0, serviceProcess.ExitCode, "{0} returned an errorcode of {1}.", serviceProcess.StartInfo.FileName, serviceProcess.ExitCode);
serviceProcess.Dispose();
serviceProcess = null;
}
}
private static Process StartServiceProcess(string cwd, string tool, string arguments, Output output, string writeBatchFile = null)
{
ProcessStartInfo i = new ProcessStartInfo(tool, arguments);
output.WriteLine("Running '{0}'", i.FileName);
output.WriteLine(" {0}", i.Arguments);
i.RedirectStandardInput = true;
i.RedirectStandardOutput = true;
i.RedirectStandardError = true;
i.UseShellExecute = false;
i.CreateNoWindow = true;
i.WorkingDirectory = cwd;
i.ErrorDialog = false;
if (writeBatchFile != null)
{
var file = new StreamWriter(Path.Combine(cwd, writeBatchFile + ".bat"));
file.WriteLine("\"{0}\" {1} %1 %2 %3 %4 %5", i.FileName, i.Arguments);
file.Close();
}
var p = Process.Start(i);
p.OutputDataReceived += output.OutputDataReceivedEventHandler;
p.ErrorDataReceived += output.ErrDataReceivedEventHandler;
p.BeginOutputReadLine();
p.BeginErrorReadLine();
Assert.IsFalse(p.WaitForExit(1000), "{0} exited too quickly", i.FileName);
return p;
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERLevel
{
/// <summary>
/// A11Level111111ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="A11Level111111ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="A10Level11111"/> collection.
/// </remarks>
[Serializable]
public partial class A11Level111111ReChild : BusinessBase<A11Level111111ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int cQarentID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_1_1_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_1_Child_Name, "Level_1_1_1_1_1_1 Child Name");
/// <summary>
/// Gets or sets the Level_1_1_1_1_1_1 Child Name.
/// </summary>
/// <value>The Level_1_1_1_1_1_1 Child Name.</value>
public string Level_1_1_1_1_1_1_Child_Name
{
get { return GetProperty(Level_1_1_1_1_1_1_Child_NameProperty); }
set { SetProperty(Level_1_1_1_1_1_1_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="A11Level111111ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="A11Level111111ReChild"/> object.</returns>
internal static A11Level111111ReChild NewA11Level111111ReChild()
{
return DataPortal.CreateChild<A11Level111111ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="A11Level111111ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="A11Level111111ReChild"/> object.</returns>
internal static A11Level111111ReChild GetA11Level111111ReChild(SafeDataReader dr)
{
A11Level111111ReChild obj = new A11Level111111ReChild();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="A11Level111111ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private A11Level111111ReChild()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="A11Level111111ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="A11Level111111ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_1_1_Child_Name"));
cQarentID2 = dr.GetInt32("CQarentID2");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="A11Level111111ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(A10Level11111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddA11Level111111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="A11Level111111ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(A10Level11111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateA11Level111111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="A11Level111111ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(A10Level11111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteA11Level111111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
namespace System.Xml
{
internal class XmlLoader
{
private XmlDocument _doc;
private XmlReader _reader;
private bool _preserveWhitespace;
public XmlLoader()
{
}
internal void Load(XmlDocument doc, XmlReader reader, bool preserveWhitespace)
{
_doc = doc;
_reader = reader;
_preserveWhitespace = preserveWhitespace;
if (doc == null)
throw new ArgumentException(SR.Xdom_Load_NoDocument);
if (reader == null)
throw new ArgumentException(SR.Xdom_Load_NoReader);
doc.SetBaseURI(reader.BaseURI);
if (_reader.ReadState != ReadState.Interactive)
{
if (!_reader.Read())
return;
}
LoadDocSequence(doc);
}
//The function will start loading the document from where current XmlReader is pointing at.
private void LoadDocSequence(XmlDocument parentDoc)
{
Debug.Assert(_reader != null);
Debug.Assert(parentDoc != null);
XmlNode node = null;
while ((node = LoadNode(true)) != null)
{
parentDoc.AppendChildForLoad(node, parentDoc);
if (!_reader.Read())
return;
}
}
internal XmlNode ReadCurrentNode(XmlDocument doc, XmlReader reader)
{
_doc = doc;
_reader = reader;
// WS are optional only for loading (see XmlDocument.PreserveWhitespace)
_preserveWhitespace = true;
if (doc == null)
throw new ArgumentException(SR.Xdom_Load_NoDocument);
if (reader == null)
throw new ArgumentException(SR.Xdom_Load_NoReader);
if (reader.ReadState == ReadState.Initial)
{
reader.Read();
}
if (reader.ReadState == ReadState.Interactive)
{
XmlNode n = LoadNode(true);
// Move to the next node
if (n.NodeType != XmlNodeType.Attribute)
reader.Read();
return n;
}
return null;
}
private XmlNode LoadNode(bool skipOverWhitespace)
{
XmlReader r = _reader;
XmlNode parent = null;
XmlElement element;
do
{
XmlNode node = null;
switch (r.NodeType)
{
case XmlNodeType.Element:
bool fEmptyElement = r.IsEmptyElement;
element = _doc.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI);
element.IsEmpty = fEmptyElement;
if (r.MoveToFirstAttribute())
{
XmlAttributeCollection attributes = element.Attributes;
do
{
XmlAttribute attr = LoadAttributeNode();
attributes.Append(attr); // special case for load
}
while (r.MoveToNextAttribute());
r.MoveToElement();
}
// recursively load all children.
if (!fEmptyElement)
{
if (parent != null)
{
parent.AppendChildForLoad(element, _doc);
}
parent = element;
continue;
}
else
{
node = element;
break;
}
case XmlNodeType.EndElement:
if (parent == null)
{
return null;
}
Debug.Assert(parent.NodeType == XmlNodeType.Element);
if (parent.ParentNode == null)
{
return parent;
}
parent = parent.ParentNode;
continue;
case XmlNodeType.EntityReference:
node = LoadEntityReferenceNode(false);
break;
case XmlNodeType.EndEntity:
Debug.Assert(parent == null);
return null;
case XmlNodeType.Attribute:
node = LoadAttributeNode();
break;
case XmlNodeType.Text:
node = _doc.CreateTextNode(r.Value);
break;
case XmlNodeType.SignificantWhitespace:
node = _doc.CreateSignificantWhitespace(r.Value);
break;
case XmlNodeType.Whitespace:
if (_preserveWhitespace)
{
node = _doc.CreateWhitespace(r.Value);
break;
}
else if (parent == null && !skipOverWhitespace)
{
// if called from LoadEntityReferenceNode, just return null
return null;
}
else
{
continue;
}
case XmlNodeType.CDATA:
node = _doc.CreateCDataSection(r.Value);
break;
case XmlNodeType.XmlDeclaration:
node = LoadDeclarationNode();
break;
case XmlNodeType.ProcessingInstruction:
node = _doc.CreateProcessingInstruction(r.Name, r.Value);
break;
case XmlNodeType.Comment:
node = _doc.CreateComment(r.Value);
break;
case XmlNodeType.DocumentType:
node = LoadDocumentTypeNode();
break;
default:
throw UnexpectedNodeType(r.NodeType);
}
Debug.Assert(node != null);
if (parent != null)
{
parent.AppendChildForLoad(node, _doc);
}
else
{
return node;
}
}
while (r.Read());
// when the reader ended before full subtree is read, return whatever we have created so far
if (parent != null)
{
while (parent.ParentNode != null)
{
parent = parent.ParentNode;
}
}
return parent;
}
private XmlAttribute LoadAttributeNode()
{
Debug.Assert(_reader.NodeType == XmlNodeType.Attribute);
XmlReader r = _reader;
if (r.IsDefault)
{
return LoadDefaultAttribute();
}
XmlAttribute attr = _doc.CreateAttribute(r.Prefix, r.LocalName, r.NamespaceURI);
while (r.ReadAttributeValue())
{
XmlNode node;
switch (r.NodeType)
{
case XmlNodeType.Text:
node = _doc.CreateTextNode(r.Value);
break;
case XmlNodeType.EntityReference:
node = _doc.CreateEntityReference(r.LocalName);
if (r.CanResolveEntity)
{
r.ResolveEntity();
LoadAttributeValue(node, false);
// Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true,
// if the reader does not present any children for the ent-ref
if (node.FirstChild == null)
{
node.AppendChildForLoad(_doc.CreateTextNode(string.Empty), _doc);
}
}
break;
default:
throw UnexpectedNodeType(r.NodeType);
}
Debug.Assert(node != null);
attr.AppendChildForLoad(node, _doc);
}
return attr;
}
private XmlAttribute LoadDefaultAttribute()
{
Debug.Assert(_reader.IsDefault);
XmlReader r = _reader;
XmlAttribute attr = _doc.CreateDefaultAttribute(r.Prefix, r.LocalName, r.NamespaceURI);
LoadAttributeValue(attr, false);
XmlUnspecifiedAttribute defAttr = attr as XmlUnspecifiedAttribute;
// If user overrides CreateDefaultAttribute, then attr will NOT be a XmlUnspecifiedAttribute instance.
if (defAttr != null)
defAttr.SetSpecified(false);
return attr;
}
private void LoadAttributeValue(XmlNode parent, bool direct)
{
XmlReader r = _reader;
while (r.ReadAttributeValue())
{
XmlNode node;
switch (r.NodeType)
{
case XmlNodeType.Text:
node = direct ? new XmlText(r.Value, _doc) : _doc.CreateTextNode(r.Value);
break;
case XmlNodeType.EndEntity:
return;
case XmlNodeType.EntityReference:
node = direct ? new XmlEntityReference(_reader.LocalName, _doc) : _doc.CreateEntityReference(_reader.LocalName);
if (r.CanResolveEntity)
{
r.ResolveEntity();
LoadAttributeValue(node, direct);
// Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true,
// if the reader does not present any children for the ent-ref
if (node.FirstChild == null)
{
node.AppendChildForLoad(direct ? new XmlText(string.Empty) : _doc.CreateTextNode(string.Empty), _doc);
}
}
break;
default:
throw UnexpectedNodeType(r.NodeType);
}
Debug.Assert(node != null);
parent.AppendChildForLoad(node, _doc);
}
return;
}
private XmlEntityReference LoadEntityReferenceNode(bool direct)
{
Debug.Assert(_reader.NodeType == XmlNodeType.EntityReference);
XmlEntityReference eref = direct ? new XmlEntityReference(_reader.Name, _doc) : _doc.CreateEntityReference(_reader.Name);
if (_reader.CanResolveEntity)
{
_reader.ResolveEntity();
while (_reader.Read() && _reader.NodeType != XmlNodeType.EndEntity)
{
XmlNode node = direct ? LoadNodeDirect() : LoadNode(false);
if (node != null)
{
eref.AppendChildForLoad(node, _doc);
}
}
// Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true,
// if the reader does not present any children for the ent-ref
if (eref.LastChild == null)
eref.AppendChildForLoad(_doc.CreateTextNode(string.Empty), _doc);
}
return eref;
}
private XmlDeclaration LoadDeclarationNode()
{
Debug.Assert(_reader.NodeType == XmlNodeType.XmlDeclaration);
//parse data
string version = null;
string encoding = null;
string standalone = null;
// Try first to use the reader to get the xml decl "attributes". Since not all readers are required to support this, it is possible to have
// implementations that do nothing
while (_reader.MoveToNextAttribute())
{
switch (_reader.Name)
{
case "version":
version = _reader.Value;
break;
case "encoding":
encoding = _reader.Value;
break;
case "standalone":
standalone = _reader.Value;
break;
default:
Debug.Fail("Unknown reader name");
break;
}
}
// For readers that do not break xml decl into attributes, we must parse the xml decl ourselves. We use version attr, b/c xml decl MUST contain
// at least version attr, so if the reader implements them as attr, then version must be present
if (version == null)
XmlParsingHelper.ParseXmlDeclarationValue(_reader.Value, out version, out encoding, out standalone);
return _doc.CreateXmlDeclaration(version, encoding, standalone);
}
private XmlDocumentType LoadDocumentTypeNode()
{
Debug.Assert(_reader.NodeType == XmlNodeType.DocumentType);
String publicId = null;
String systemId = null;
String internalSubset = _reader.Value;
String localName = _reader.LocalName;
while (_reader.MoveToNextAttribute())
{
switch (_reader.Name)
{
case "PUBLIC":
publicId = _reader.Value;
break;
case "SYSTEM":
systemId = _reader.Value;
break;
}
}
XmlDocumentType dtNode = _doc.CreateDocumentType(localName, publicId, systemId, internalSubset);
return dtNode;
}
// LoadNodeDirect does not use creator functions on XmlDocument. It is used loading nodes that are children of entity nodes,
// because we do not want to let users extend these (if we would allow this, XmlDataDocument would have a problem, because
// they do not know that those nodes should not be mapped). It can be also used for an optimized load path when if the
// XmlDocument is not extended if XmlDocumentType and XmlDeclaration handling is added.
private XmlNode LoadNodeDirect()
{
XmlReader r = _reader;
XmlNode parent = null;
do
{
XmlNode node = null;
switch (r.NodeType)
{
case XmlNodeType.Element:
bool fEmptyElement = _reader.IsEmptyElement;
XmlElement element = new XmlElement(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI, _doc);
element.IsEmpty = fEmptyElement;
if (_reader.MoveToFirstAttribute())
{
XmlAttributeCollection attributes = element.Attributes;
do
{
XmlAttribute attr = LoadAttributeNodeDirect();
attributes.Append(attr); // special case for load
} while (r.MoveToNextAttribute());
}
// recursively load all children.
if (!fEmptyElement)
{
parent.AppendChildForLoad(element, _doc);
parent = element;
continue;
}
else
{
node = element;
break;
}
case XmlNodeType.EndElement:
Debug.Assert(parent.NodeType == XmlNodeType.Element);
if (parent.ParentNode == null)
{
return parent;
}
parent = parent.ParentNode;
continue;
case XmlNodeType.EntityReference:
node = LoadEntityReferenceNode(true);
break;
case XmlNodeType.EndEntity:
continue;
case XmlNodeType.Attribute:
node = LoadAttributeNodeDirect();
break;
case XmlNodeType.SignificantWhitespace:
node = new XmlSignificantWhitespace(_reader.Value, _doc);
break;
case XmlNodeType.Whitespace:
if (_preserveWhitespace)
{
node = new XmlWhitespace(_reader.Value, _doc);
}
else
{
continue;
}
break;
case XmlNodeType.Text:
node = new XmlText(_reader.Value, _doc);
break;
case XmlNodeType.CDATA:
node = new XmlCDataSection(_reader.Value, _doc);
break;
case XmlNodeType.ProcessingInstruction:
node = new XmlProcessingInstruction(_reader.Name, _reader.Value, _doc);
break;
case XmlNodeType.Comment:
node = new XmlComment(_reader.Value, _doc);
break;
default:
throw UnexpectedNodeType(_reader.NodeType);
}
Debug.Assert(node != null);
if (parent != null)
{
parent.AppendChildForLoad(node, _doc);
}
else
{
return node;
}
}
while (r.Read());
return null;
}
private XmlAttribute LoadAttributeNodeDirect()
{
XmlReader r = _reader;
XmlAttribute attr;
if (r.IsDefault)
{
XmlUnspecifiedAttribute defattr = new XmlUnspecifiedAttribute(r.Prefix, r.LocalName, r.NamespaceURI, _doc);
LoadAttributeValue(defattr, true);
defattr.SetSpecified(false);
return defattr;
}
else
{
attr = new XmlAttribute(r.Prefix, r.LocalName, r.NamespaceURI, _doc);
LoadAttributeValue(attr, true);
return attr;
}
}
#pragma warning restore 618
private XmlParserContext GetContext(XmlNode node)
{
String lang = null;
XmlSpace spaceMode = XmlSpace.None;
XmlDocumentType docType = _doc.DocumentType;
String baseURI = _doc.BaseURI;
//constructing xmlnamespace
HashSet<string> prefixes = new HashSet<string>();
XmlNameTable nt = _doc.NameTable;
XmlNamespaceManager mgr = new XmlNamespaceManager(nt);
bool bHasDefXmlnsAttr = false;
// Process all xmlns, xmlns:prefix, xml:space and xml:lang attributes
while (node != null && node != _doc)
{
XmlElement element = node as XmlElement;
if (element != null && element.HasAttributes)
{
mgr.PushScope();
foreach (XmlAttribute attr in element.Attributes)
{
if (attr.Prefix == _doc.strXmlns && !prefixes.Contains(attr.LocalName))
{
// Make sure the next time we will not add this prefix
prefixes.Add(attr.LocalName);
mgr.AddNamespace(attr.LocalName, attr.Value);
}
else if (!bHasDefXmlnsAttr && attr.Prefix.Length == 0 && attr.LocalName == _doc.strXmlns)
{
// Save the case xmlns="..." where xmlns is the LocalName
mgr.AddNamespace(String.Empty, attr.Value);
bHasDefXmlnsAttr = true;
}
else if (spaceMode == XmlSpace.None && attr.Prefix == _doc.strXml && attr.LocalName == _doc.strSpace)
{
// Save xml:space context
if (attr.Value == "default")
spaceMode = XmlSpace.Default;
else if (attr.Value == "preserve")
spaceMode = XmlSpace.Preserve;
}
else if (lang == null && attr.Prefix == _doc.strXml && attr.LocalName == _doc.strLang)
{
// Save xml:lag context
lang = attr.Value;
}
}
}
node = node.ParentNode;
}
return new XmlParserContext(
nt,
mgr,
(docType == null) ? null : docType.Name,
(docType == null) ? null : docType.PublicId,
(docType == null) ? null : docType.SystemId,
(docType == null) ? null : docType.InternalSubset,
baseURI,
lang,
spaceMode
);
}
internal XmlNamespaceManager ParsePartialContent(XmlNode parentNode, string innerxmltext, XmlNodeType nt)
{
//the function shouldn't be used to set innerxml for XmlDocument node
Debug.Assert(parentNode.NodeType != XmlNodeType.Document);
_doc = parentNode.OwnerDocument;
Debug.Assert(_doc != null);
XmlParserContext pc = GetContext(parentNode);
_reader = CreateInnerXmlReader(innerxmltext, nt, pc, _doc);
try
{
_preserveWhitespace = true;
bool bOrigLoading = _doc.IsLoading;
_doc.IsLoading = true;
if (nt == XmlNodeType.Entity)
{
XmlNode node = null;
while (_reader.Read() && (node = LoadNodeDirect()) != null)
{
parentNode.AppendChildForLoad(node, _doc);
}
}
else
{
XmlNode node = null;
while (_reader.Read() && (node = LoadNode(true)) != null)
{
parentNode.AppendChildForLoad(node, _doc);
}
}
_doc.IsLoading = bOrigLoading;
}
finally
{
_reader.Dispose();
}
return pc.NamespaceManager;
}
internal void LoadInnerXmlElement(XmlElement node, string innerxmltext)
{
//construct a tree underneath the node
XmlNamespaceManager mgr = ParsePartialContent(node, innerxmltext, XmlNodeType.Element);
//remove the duplicate namesapce
if (node.ChildNodes.Count > 0)
RemoveDuplicateNamespace((XmlElement)node, mgr, false);
}
internal void LoadInnerXmlAttribute(XmlAttribute node, string innerxmltext)
{
ParsePartialContent(node, innerxmltext, XmlNodeType.Attribute);
}
private void RemoveDuplicateNamespace(XmlElement elem, XmlNamespaceManager mgr, bool fCheckElemAttrs)
{
//remove the duplicate attributes on current node first
mgr.PushScope();
XmlAttributeCollection attrs = elem.Attributes;
int cAttrs = attrs.Count;
if (fCheckElemAttrs && cAttrs > 0)
{
for (int i = cAttrs - 1; i >= 0; --i)
{
XmlAttribute attr = attrs[i];
if (attr.Prefix == _doc.strXmlns)
{
string nsUri = mgr.LookupNamespace(attr.LocalName);
if (nsUri != null)
{
if (attr.Value == nsUri)
elem.Attributes.RemoveNodeAt(i);
}
else
{
// Add this namespace, so it we will behave correctly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as
// InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>"
// If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for
// the subsequent InnerXml_set or setting an EntRef inside.
mgr.AddNamespace(attr.LocalName, attr.Value);
}
}
else if (attr.Prefix.Length == 0 && attr.LocalName == _doc.strXmlns)
{
string nsUri = mgr.DefaultNamespace;
if (nsUri != null)
{
if (attr.Value == nsUri)
elem.Attributes.RemoveNodeAt(i);
}
else
{
// Add this namespace, so it we will behave corectly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as
// InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>"
// If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for
// the subsequent InnerXml_set or setting an EntRef inside.
mgr.AddNamespace(attr.LocalName, attr.Value);
}
}
}
}
//now recursively remove the duplicate attributes on the children
XmlNode child = elem.FirstChild;
while (child != null)
{
XmlElement childElem = child as XmlElement;
if (childElem != null)
RemoveDuplicateNamespace(childElem, mgr, true);
child = child.NextSibling;
}
mgr.PopScope();
}
private String EntitizeName(String name)
{
return "&" + name + ";";
}
//The function is called when expanding the entity when its children being asked
internal void ExpandEntity(XmlEntity ent)
{
ParsePartialContent(ent, EntitizeName(ent.Name), XmlNodeType.Entity);
}
//The function is called when expanding the entity ref. ( inside XmlEntityReference.SetParent )
internal void ExpandEntityReference(XmlEntityReference eref)
{
//when the ent ref is not associated w/ an entity, append an empty string text node as child
_doc = eref.OwnerDocument;
bool bOrigLoadingState = _doc.IsLoading;
_doc.IsLoading = true;
switch (eref.Name)
{
case "lt":
eref.AppendChildForLoad(_doc.CreateTextNode("<"), _doc);
_doc.IsLoading = bOrigLoadingState;
return;
case "gt":
eref.AppendChildForLoad(_doc.CreateTextNode(">"), _doc);
_doc.IsLoading = bOrigLoadingState;
return;
case "amp":
eref.AppendChildForLoad(_doc.CreateTextNode("&"), _doc);
_doc.IsLoading = bOrigLoadingState;
return;
case "apos":
eref.AppendChildForLoad(_doc.CreateTextNode("'"), _doc);
_doc.IsLoading = bOrigLoadingState;
return;
case "quot":
eref.AppendChildForLoad(_doc.CreateTextNode("\""), _doc);
_doc.IsLoading = bOrigLoadingState;
return;
}
XmlNamedNodeMap entities = _doc.Entities;
foreach (XmlEntity ent in entities)
{
if (Ref.Equal(ent.Name, eref.Name))
{
ParsePartialContent(eref, EntitizeName(eref.Name), XmlNodeType.EntityReference);
return;
}
}
//no fit so far
if (!(_doc.ActualLoadingStatus))
{
eref.AppendChildForLoad(_doc.CreateTextNode(""), _doc);
_doc.IsLoading = bOrigLoadingState;
}
else
{
_doc.IsLoading = bOrigLoadingState;
throw new XmlException(SR.Format(SR.Xml_UndeclaredParEntity, eref.Name));
}
}
#pragma warning disable 618
// Creates a XmlValidatingReader suitable for parsing InnerXml strings
private XmlReader CreateInnerXmlReader(String xmlFragment, XmlNodeType nt, XmlParserContext context, XmlDocument doc)
{
XmlNodeType contentNT = nt;
if (contentNT == XmlNodeType.Entity || contentNT == XmlNodeType.EntityReference)
contentNT = XmlNodeType.Element;
TextReader fragmentReader = new StringReader(xmlFragment);
XmlReaderSettings settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
XmlReader tr = XmlReader.Create(fragmentReader, settings, context);
if (nt == XmlNodeType.Entity || nt == XmlNodeType.EntityReference)
{
tr.Read(); //this will skip the first element "wrapper"
tr.ResolveEntity();
}
return tr;
}
#pragma warning restore 618
static internal Exception UnexpectedNodeType(XmlNodeType nodetype)
{
return new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.Xml_UnexpectedNodeType, nodetype.ToString()));
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.OpsWorks.Model
{
/// <summary>
/// <para>Describes a time-based instance's auto scaling schedule. The schedule consists of a set of key-value pairs.</para>
/// <ul>
/// <li>The key is the time period (a UTC hour) and must be an integer from 0 - 23.</li>
/// <li>The value indicates whether the instance should be online or offline for the specified period, and must be set to "on" or "off"</li>
///
/// </ul>
/// <para>The default setting for all time periods is off, so you use the following parameters primarily to specify the online periods. You
/// don't have to explicitly specify offline periods unless you want to change an online period to an offline period. </para> <para>The
/// following example specifies that the instance should be online for four hours, from UTC 1200 - 1600. It will be off for the remainder of the
/// day.</para> <c> {
/// "12":"on", "13":"on", "14":"on", "15":"on" }
/// </c>
/// </summary>
public class WeeklyAutoScalingSchedule
{
private Dictionary<string,string> monday = new Dictionary<string,string>();
private Dictionary<string,string> tuesday = new Dictionary<string,string>();
private Dictionary<string,string> wednesday = new Dictionary<string,string>();
private Dictionary<string,string> thursday = new Dictionary<string,string>();
private Dictionary<string,string> friday = new Dictionary<string,string>();
private Dictionary<string,string> saturday = new Dictionary<string,string>();
private Dictionary<string,string> sunday = new Dictionary<string,string>();
/// <summary>
/// The schedule for Monday.
///
/// </summary>
public Dictionary<string,string> Monday
{
get { return this.monday; }
set { this.monday = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Monday dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Monday dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public WeeklyAutoScalingSchedule WithMonday(params KeyValuePair<string, string>[] pairs)
{
foreach (KeyValuePair<string, string> pair in pairs)
{
this.Monday[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Monday property is set
internal bool IsSetMonday()
{
return this.monday != null;
}
/// <summary>
/// The schedule for Tuesday.
///
/// </summary>
public Dictionary<string,string> Tuesday
{
get { return this.tuesday; }
set { this.tuesday = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Tuesday dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Tuesday dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public WeeklyAutoScalingSchedule WithTuesday(params KeyValuePair<string, string>[] pairs)
{
foreach (KeyValuePair<string, string> pair in pairs)
{
this.Tuesday[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Tuesday property is set
internal bool IsSetTuesday()
{
return this.tuesday != null;
}
/// <summary>
/// The schedule for Wednesday.
///
/// </summary>
public Dictionary<string,string> Wednesday
{
get { return this.wednesday; }
set { this.wednesday = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Wednesday dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Wednesday dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public WeeklyAutoScalingSchedule WithWednesday(params KeyValuePair<string, string>[] pairs)
{
foreach (KeyValuePair<string, string> pair in pairs)
{
this.Wednesday[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Wednesday property is set
internal bool IsSetWednesday()
{
return this.wednesday != null;
}
/// <summary>
/// The schedule for Thursday.
///
/// </summary>
public Dictionary<string,string> Thursday
{
get { return this.thursday; }
set { this.thursday = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Thursday dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Thursday dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public WeeklyAutoScalingSchedule WithThursday(params KeyValuePair<string, string>[] pairs)
{
foreach (KeyValuePair<string, string> pair in pairs)
{
this.Thursday[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Thursday property is set
internal bool IsSetThursday()
{
return this.thursday != null;
}
/// <summary>
/// The schedule for Friday.
///
/// </summary>
public Dictionary<string,string> Friday
{
get { return this.friday; }
set { this.friday = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Friday dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Friday dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public WeeklyAutoScalingSchedule WithFriday(params KeyValuePair<string, string>[] pairs)
{
foreach (KeyValuePair<string, string> pair in pairs)
{
this.Friday[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Friday property is set
internal bool IsSetFriday()
{
return this.friday != null;
}
/// <summary>
/// The schedule for Saturday.
///
/// </summary>
public Dictionary<string,string> Saturday
{
get { return this.saturday; }
set { this.saturday = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Saturday dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Saturday dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public WeeklyAutoScalingSchedule WithSaturday(params KeyValuePair<string, string>[] pairs)
{
foreach (KeyValuePair<string, string> pair in pairs)
{
this.Saturday[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Saturday property is set
internal bool IsSetSaturday()
{
return this.saturday != null;
}
/// <summary>
/// The schedule for Sunday.
///
/// </summary>
public Dictionary<string,string> Sunday
{
get { return this.sunday; }
set { this.sunday = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Sunday dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Sunday dictionary.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public WeeklyAutoScalingSchedule WithSunday(params KeyValuePair<string, string>[] pairs)
{
foreach (KeyValuePair<string, string> pair in pairs)
{
this.Sunday[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Sunday property is set
internal bool IsSetSunday()
{
return this.sunday != null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.Customers;
using Nop.Services.Events;
namespace Nop.Services.Customers
{
/// <summary>
/// Customer attribute service
/// </summary>
public partial class CustomerAttributeService : ICustomerAttributeService
{
#region Constants
/// <summary>
/// Key for caching
/// </summary>
private const string CUSTOMERATTRIBUTES_ALL_KEY = "Nop.customerattribute.all";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : customer attribute ID
/// </remarks>
private const string CUSTOMERATTRIBUTES_BY_ID_KEY = "Nop.customerattribute.id-{0}";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : customer attribute ID
/// </remarks>
private const string CUSTOMERATTRIBUTEVALUES_ALL_KEY = "Nop.customerattributevalue.all-{0}";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : customer attribute value ID
/// </remarks>
private const string CUSTOMERATTRIBUTEVALUES_BY_ID_KEY = "Nop.customerattributevalue.id-{0}";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string CUSTOMERATTRIBUTES_PATTERN_KEY = "Nop.customerattribute.";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string CUSTOMERATTRIBUTEVALUES_PATTERN_KEY = "Nop.customerattributevalue.";
#endregion
#region Fields
private readonly IRepository<CustomerAttribute> _customerAttributeRepository;
private readonly IRepository<CustomerAttributeValue> _customerAttributeValueRepository;
private readonly IEventPublisher _eventPublisher;
private readonly ICacheManager _cacheManager;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="cacheManager">Cache manager</param>
/// <param name="customerAttributeRepository">Customer attribute repository</param>
/// <param name="customerAttributeValueRepository">Customer attribute value repository</param>
/// <param name="eventPublisher">Event published</param>
public CustomerAttributeService(ICacheManager cacheManager,
IRepository<CustomerAttribute> customerAttributeRepository,
IRepository<CustomerAttributeValue> customerAttributeValueRepository,
IEventPublisher eventPublisher)
{
this._cacheManager = cacheManager;
this._customerAttributeRepository = customerAttributeRepository;
this._customerAttributeValueRepository = customerAttributeValueRepository;
this._eventPublisher = eventPublisher;
}
#endregion
#region Methods
/// <summary>
/// Deletes a customer attribute
/// </summary>
/// <param name="customerAttribute">Customer attribute</param>
public virtual void DeleteCustomerAttribute(CustomerAttribute customerAttribute)
{
if (customerAttribute == null)
throw new ArgumentNullException("customerAttribute");
_customerAttributeRepository.Delete(customerAttribute);
_cacheManager.RemoveByPattern(CUSTOMERATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(customerAttribute);
}
/// <summary>
/// Gets all customer attributes
/// </summary>
/// <returns>Customer attributes</returns>
public virtual IList<CustomerAttribute> GetAllCustomerAttributes()
{
string key = CUSTOMERATTRIBUTES_ALL_KEY;
return _cacheManager.Get(key, () =>
{
var query = from ca in _customerAttributeRepository.Table
orderby ca.DisplayOrder
select ca;
return query.ToList();
});
}
/// <summary>
/// Gets a customer attribute
/// </summary>
/// <param name="customerAttributeId">Customer attribute identifier</param>
/// <returns>Customer attribute</returns>
public virtual CustomerAttribute GetCustomerAttributeById(int customerAttributeId)
{
if (customerAttributeId == 0)
return null;
string key = string.Format(CUSTOMERATTRIBUTES_BY_ID_KEY, customerAttributeId);
return _cacheManager.Get(key, () => _customerAttributeRepository.GetById(customerAttributeId));
}
/// <summary>
/// Inserts a customer attribute
/// </summary>
/// <param name="customerAttribute">Customer attribute</param>
public virtual void InsertCustomerAttribute(CustomerAttribute customerAttribute)
{
if (customerAttribute == null)
throw new ArgumentNullException("customerAttribute");
_customerAttributeRepository.Insert(customerAttribute);
_cacheManager.RemoveByPattern(CUSTOMERATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(customerAttribute);
}
/// <summary>
/// Updates the customer attribute
/// </summary>
/// <param name="customerAttribute">Customer attribute</param>
public virtual void UpdateCustomerAttribute(CustomerAttribute customerAttribute)
{
if (customerAttribute == null)
throw new ArgumentNullException("customerAttribute");
_customerAttributeRepository.Update(customerAttribute);
_cacheManager.RemoveByPattern(CUSTOMERATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(customerAttribute);
}
/// <summary>
/// Deletes a customer attribute value
/// </summary>
/// <param name="customerAttributeValue">Customer attribute value</param>
public virtual void DeleteCustomerAttributeValue(CustomerAttributeValue customerAttributeValue)
{
if (customerAttributeValue == null)
throw new ArgumentNullException("customerAttributeValue");
_customerAttributeValueRepository.Delete(customerAttributeValue);
_cacheManager.RemoveByPattern(CUSTOMERATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(customerAttributeValue);
}
/// <summary>
/// Gets customer attribute values by customer attribute identifier
/// </summary>
/// <param name="customerAttributeId">The customer attribute identifier</param>
/// <returns>Customer attribute values</returns>
public virtual IList<CustomerAttributeValue> GetCustomerAttributeValues(int customerAttributeId)
{
string key = string.Format(CUSTOMERATTRIBUTEVALUES_ALL_KEY, customerAttributeId);
return _cacheManager.Get(key, () =>
{
var query = from cav in _customerAttributeValueRepository.Table
orderby cav.DisplayOrder
where cav.CustomerAttributeId == customerAttributeId
select cav;
var customerAttributeValues = query.ToList();
return customerAttributeValues;
});
}
/// <summary>
/// Gets a customer attribute value
/// </summary>
/// <param name="customerAttributeValueId">Customer attribute value identifier</param>
/// <returns>Customer attribute value</returns>
public virtual CustomerAttributeValue GetCustomerAttributeValueById(int customerAttributeValueId)
{
if (customerAttributeValueId == 0)
return null;
string key = string.Format(CUSTOMERATTRIBUTEVALUES_BY_ID_KEY, customerAttributeValueId);
return _cacheManager.Get(key, () => _customerAttributeValueRepository.GetById(customerAttributeValueId));
}
/// <summary>
/// Inserts a customer attribute value
/// </summary>
/// <param name="customerAttributeValue">Customer attribute value</param>
public virtual void InsertCustomerAttributeValue(CustomerAttributeValue customerAttributeValue)
{
if (customerAttributeValue == null)
throw new ArgumentNullException("customerAttributeValue");
_customerAttributeValueRepository.Insert(customerAttributeValue);
_cacheManager.RemoveByPattern(CUSTOMERATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(customerAttributeValue);
}
/// <summary>
/// Updates the customer attribute value
/// </summary>
/// <param name="customerAttributeValue">Customer attribute value</param>
public virtual void UpdateCustomerAttributeValue(CustomerAttributeValue customerAttributeValue)
{
if (customerAttributeValue == null)
throw new ArgumentNullException("customerAttributeValue");
_customerAttributeValueRepository.Update(customerAttributeValue);
_cacheManager.RemoveByPattern(CUSTOMERATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(CUSTOMERATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(customerAttributeValue);
}
#endregion
}
}
| |
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 DemoSimpleApi.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>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <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 factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private 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 to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified 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) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), 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="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <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.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
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,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[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;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using fNbt;
using Ionic.Zlib;
using Craft.Net.Common;
namespace Craft.Net.Anvil
{
/// <summary>
/// Represents a 32x32 area of <see cref="Chunk"/> objects.
/// Not all of these chunks are represented at any given time, and
/// will be loaded from disk or generated when the need arises.
/// </summary>
public class Region : IDisposable
{
// In chunks
public const int Width = 32, Depth = 32;
/// <summary>
/// The currently loaded chunk list.
/// </summary>
public Dictionary<Coordinates2D, Chunk> Chunks { get; set; }
/// <summary>
/// The location of this region in the overworld.
/// </summary>
public Coordinates2D Position { get; set; }
public World World { get; set; }
private Stream regionFile { get; set; }
/// <summary>
/// Creates a new Region for server-side use at the given position using
/// the provided terrain generator.
/// </summary>
public Region(Coordinates2D position, World world)
{
Chunks = new Dictionary<Coordinates2D, Chunk>();
Position = position;
World = world;
}
/// <summary>
/// Creates a region from the given region file.
/// </summary>
public Region(Coordinates2D position, World world, string file) : this(position, world)
{
if (File.Exists(file))
regionFile = File.Open(file, FileMode.OpenOrCreate);
else
{
regionFile = File.Open(file, FileMode.OpenOrCreate);
CreateRegionHeader();
}
}
/// <summary>
/// Retrieves the requested chunk from the region, or
/// generates it if a world generator is provided.
/// </summary>
/// <param name="position">The position of the requested local chunk coordinates.</param>
public Chunk GetChunk(Coordinates2D position)
{
// TODO: This could use some refactoring
lock (Chunks)
{
if (!Chunks.ContainsKey(position))
{
if (regionFile != null)
{
// Search the stream for that region
lock (regionFile)
{
var chunkData = GetChunkFromTable(position);
if (chunkData == null)
{
if (World.WorldGenerator == null)
throw new ArgumentException("The requested chunk is not loaded.", "position");
GenerateChunk(position);
return Chunks[position];
}
regionFile.Seek(chunkData.Item1, SeekOrigin.Begin);
/*int length = */new MinecraftStream(regionFile).ReadInt32(); // TODO: Avoid making new objects here, and in the WriteInt32
int compressionMode = regionFile.ReadByte();
switch (compressionMode)
{
case 1: // gzip
break;
case 2: // zlib
var nbt = new NbtFile();
nbt.LoadFromStream(regionFile, NbtCompression.ZLib, null);
var chunk = Chunk.FromNbt(nbt);
Chunks.Add(position, chunk);
break;
default:
throw new InvalidDataException("Invalid compression scheme provided by region file.");
}
}
}
else if (World.WorldGenerator == null)
throw new ArgumentException("The requested chunk is not loaded.", "position");
else
GenerateChunk(position);
}
return Chunks[position];
}
}
/// <summary>
/// Retrieves the requested chunk from the region, without using the
/// world generator if it does not exist.
/// </summary>
/// <param name="position">The position of the requested local chunk coordinates.</param>
public Chunk GetChunkWithoutGeneration(Coordinates2D position)
{
// TODO: This could use some refactoring
lock (Chunks)
{
if (!Chunks.ContainsKey(position))
{
if (regionFile != null)
{
// Search the stream for that region
lock (regionFile)
{
var chunkData = GetChunkFromTable(position);
if (chunkData == null)
return null;
regionFile.Seek(chunkData.Item1, SeekOrigin.Begin);
/*int length = */new MinecraftStream(regionFile).ReadInt32(); // TODO: Avoid making new objects here, and in the WriteInt32
int compressionMode = regionFile.ReadByte();
switch (compressionMode)
{
case 1: // gzip
break;
case 2: // zlib
var nbt = new NbtFile();
nbt.LoadFromStream(regionFile, NbtCompression.ZLib, null);
var chunk = Chunk.FromNbt(nbt);
Chunks.Add(position, chunk);
break;
default:
throw new InvalidDataException("Invalid compression scheme provided by region file.");
}
}
}
else if (World.WorldGenerator == null)
throw new ArgumentException("The requested chunk is not loaded.", "position");
else
GenerateChunk(position);
}
return Chunks[position];
}
}
public void GenerateChunk(Coordinates2D position)
{
var globalPosition = (Position * new Coordinates2D(Width, Depth)) + position;
var chunk = World.WorldGenerator.GenerateChunk(globalPosition);
chunk.IsModified = true;
chunk.X = globalPosition.X;
chunk.Z = globalPosition.Z;
Chunks.Add(position, chunk);
}
/// <summary>
/// Sets the chunk at the specified local position to the given value.
/// </summary>
public void SetChunk(Coordinates2D position, Chunk chunk)
{
if (!Chunks.ContainsKey(position))
Chunks.Add(position, chunk);
chunk.IsModified = true;
chunk.X = position.X;
chunk.Z = position.Z;
chunk.LastAccessed = DateTime.Now;
Chunks[position] = chunk;
}
/// <summary>
/// Saves this region to the specified file.
/// </summary>
public void Save(string file)
{
if(File.Exists(file))
regionFile = regionFile ?? File.Open(file, FileMode.OpenOrCreate);
else
{
regionFile = regionFile ?? File.Open(file, FileMode.OpenOrCreate);
CreateRegionHeader();
}
Save();
}
/// <summary>
/// Saves this region to the open region file.
/// </summary>
public void Save()
{
lock (Chunks)
{
lock (regionFile)
{
var toRemove = new List<Coordinates2D>();
foreach (var kvp in Chunks)
{
var chunk = kvp.Value;
if (chunk.IsModified)
{
var data = chunk.ToNbt();
byte[] raw = data.SaveToBuffer(NbtCompression.ZLib);
var header = GetChunkFromTable(kvp.Key);
if (header == null || header.Item2 > raw.Length)
header = AllocateNewChunks(kvp.Key, raw.Length);
regionFile.Seek(header.Item1, SeekOrigin.Begin);
new MinecraftStream(regionFile).WriteInt32(raw.Length);
regionFile.WriteByte(2); // Compressed with zlib
regionFile.Write(raw, 0, raw.Length);
chunk.IsModified = false;
}
if ((DateTime.Now - chunk.LastAccessed).TotalMinutes > 5)
toRemove.Add(kvp.Key);
}
regionFile.Flush();
// Unload idle chunks
foreach (var chunk in toRemove)
Chunks.Remove(chunk);
}
}
}
#region Stream Helpers
private const int ChunkSizeMultiplier = 4096;
private Tuple<int, int> GetChunkFromTable(Coordinates2D position) // <offset, length>
{
int tableOffset = ((position.X % Width) + (position.Z % Depth) * Width) * 4;
regionFile.Seek(tableOffset, SeekOrigin.Begin);
byte[] offsetBuffer = new byte[4];
regionFile.Read(offsetBuffer, 0, 3);
Array.Reverse(offsetBuffer);
int length = regionFile.ReadByte();
int offset = BitConverter.ToInt32(offsetBuffer, 0) << 4;
if (offset == 0 || length == 0)
return null;
return new Tuple<int, int>(offset,
length * ChunkSizeMultiplier);
}
private void CreateRegionHeader()
{
regionFile.Write(new byte[8192], 0, 8192);
regionFile.Flush();
}
private Tuple<int, int> AllocateNewChunks(Coordinates2D position, int length)
{
// Expand region file
regionFile.Seek(0, SeekOrigin.End);
int dataOffset = (int)regionFile.Position;
length /= ChunkSizeMultiplier;
length++;
regionFile.Write(new byte[length * ChunkSizeMultiplier], 0, length * ChunkSizeMultiplier);
// Write table entry
int tableOffset = ((position.X % Width) + (position.Z % Depth) * Width) * 4;
regionFile.Seek(tableOffset, SeekOrigin.Begin);
byte[] entry = BitConverter.GetBytes(dataOffset >> 4);
entry[0] = (byte)length;
Array.Reverse(entry);
regionFile.Write(entry, 0, entry.Length);
return new Tuple<int, int>(dataOffset, length * ChunkSizeMultiplier);
}
#endregion
public static string GetRegionFileName(Coordinates2D position)
{
return string.Format("r.{0}.{1}.mca", position.X, position.Z);
}
public void UnloadChunk(Coordinates2D position)
{
Chunks.Remove(position);
}
public void Dispose()
{
if (regionFile == null)
return;
lock (regionFile)
{
regionFile.Flush();
regionFile.Close();
}
}
}
}
| |
namespace Newq
{
using System;
/// <summary>
///
/// </summary>
public class Condition : ICustomItem<Filter>
{
/// <summary>
/// Initializes a new instance of the <see cref="Condition"/> class.
/// </summary>
public Condition()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Condition"/> class.
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <param name="logicalOperator"></param>
public Condition(Comparison source, Comparison target, LogicalOperator logicalOperator = LogicalOperator.And)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (target == null)
{
throw new ArgumentNullException(nameof(target));
}
Source = source;
Target = target;
Operator = logicalOperator;
}
/// <summary>
/// Initializes a new instance of the <see cref="Condition"/> class.
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <param name="logicalOperator"></param>
public Condition(Condition source, Condition target, LogicalOperator logicalOperator = LogicalOperator.And)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (target == null)
{
throw new ArgumentNullException(nameof(target));
}
Source = source;
Target = target;
Operator = logicalOperator;
}
/// <summary>
/// Gets or sets <see cref="Source"/>.
/// </summary>
public object Source { get; set; }
/// <summary>
/// Gets or sets <see cref="Target"/>.
/// </summary>
public object Target { get; set; }
/// <summary>
/// Gets or sets <see cref="Operator"/>.
/// </summary>
public LogicalOperator Operator { get; set; }
/// <summary>
///
/// </summary>
/// <param name="customization"></param>
public void AppendTo(Filter customization)
{
customization.Items.Add(this);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public string GetIdentifier()
{
return ToString();
}
/// <summary>
///
/// </summary>
/// <param name="logicalOperator"></param>
/// <returns></returns>
protected string GetOperator(LogicalOperator logicalOperator)
{
return logicalOperator == LogicalOperator.And ? "AND" : "OR";
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns></returns>
public override string ToString()
{
var condition = string.Empty;
if (Source == null || Target == null)
{
return string.Empty;
}
var source = Source.ToString();
var target = Target.ToString();
if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(target))
{
return source + target;
}
if (ReferenceEquals(Source, Target))
{
condition = Source.ToString();
}
else
{
condition = string.Format("({0} {1} {2})", Source, GetOperator(Operator), Target);
}
return condition;
}
/// <summary>
/// Returns a <see cref="Condition"/> that 'and' with a comparison.
/// </summary>
/// <param name="comparison"></param>
/// <returns></returns>
public Condition And(Comparison comparison)
{
return And(new Condition(comparison, comparison));
}
/// <summary>
/// Returns a <see cref="Condition"/> that 'and' with another condition.
/// </summary>
/// <param name="condition"></param>
/// <returns></returns>
public Condition And(Condition condition)
{
return new Condition(this, condition);
}
/// <summary>
/// Returns a <see cref="Condition"/> that 'or' with a comparison.
/// </summary>
/// <param name="comparison"></param>
/// <returns></returns>
public Condition Or(Comparison comparison)
{
return Or(new Condition(comparison, comparison));
}
/// <summary>
/// Returns a <see cref="Condition"/> that 'or' with another condition.
/// </summary>
/// <param name="condition"></param>
/// <returns></returns>
public Condition Or(Condition condition)
{
return new Condition(this, condition, LogicalOperator.Or);
}
/// <summary>
/// <see cref="And(Comparison)"/>
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <returns></returns>
public static Condition operator &(Condition source, Comparison target)
{
return source.And(target);
}
/// <summary>
/// <see cref="And(Condition)"/>
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <returns></returns>
public static Condition operator &(Condition source, Condition target)
{
return source.And(target);
}
/// <summary>
/// <see cref="Or(Comparison)"/>
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <returns></returns>
public static Condition operator |(Condition source, Comparison target)
{
return source.Or(target);
}
/// <summary>
/// <see cref="Or(Condition)"/>
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <returns></returns>
public static Condition operator |(Condition source, Condition target)
{
return source.Or(target);
}
/// <summary>
///
/// </summary>
/// <param name="subquery"></param>
/// <returns></returns>
public static Condition Exists(QueryBuilder subquery)
{
var condition = new Syntax("EXISTS", subquery, false);
return new Condition
{
Source = condition,
Target = condition,
Operator = LogicalOperator.And,
};
}
/// <summary>
///
/// </summary>
/// <param name="subquery"></param>
/// <returns></returns>
public static Condition NotExists(QueryBuilder subquery)
{
var condition = new Syntax("NOT EXISTS", subquery, false);
return new Condition
{
Source = condition,
Target = condition,
Operator = LogicalOperator.And,
};
}
}
/// <summary>
///
/// </summary>
public enum LogicalOperator
{
/// <summary>
/// The AND operator displays a record
/// if both the first condition AND the second condition are true.
/// </summary>
And,
/// <summary>
/// The OR operator displays a record
/// if either the first condition OR the second condition is true.
/// </summary>
Or,
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.Runtime.Utilities;
namespace Orleans.Runtime.MembershipService
{
/// <summary>
/// Responsible for ensuring that this silo monitors other silos in the cluster.
/// </summary>
internal class ClusterHealthMonitor : IHealthCheckParticipant, ILifecycleParticipant<ISiloLifecycle>, ClusterHealthMonitor.ITestAccessor
{
private readonly CancellationTokenSource shutdownCancellation = new CancellationTokenSource();
private readonly ILocalSiloDetails localSiloDetails;
private readonly MembershipTableManager tableManager;
private readonly ILogger<ClusterHealthMonitor> log;
private readonly IFatalErrorHandler fatalErrorHandler;
private readonly ClusterMembershipOptions clusterMembershipOptions;
private readonly IAsyncTimer monitorClusterHealthTimer;
private ImmutableDictionary<SiloAddress, SiloHealthMonitor> monitoredSilos = ImmutableDictionary<SiloAddress, SiloHealthMonitor>.Empty;
private MembershipVersion observedMembershipVersion;
private Func<SiloAddress, SiloHealthMonitor> createMonitor;
private int probeNumber;
/// <summary>
/// Exposes private members of <see cref="ClusterHealthMonitor"/> for test purposes.
/// </summary>
internal interface ITestAccessor
{
ImmutableDictionary<SiloAddress, SiloHealthMonitor> MonitoredSilos { get; set; }
Func<SiloAddress, SiloHealthMonitor> CreateMonitor { get; set; }
MembershipVersion ObservedVersion { get; }
}
public ClusterHealthMonitor(
ILocalSiloDetails localSiloDetails,
MembershipTableManager tableManager,
ILogger<ClusterHealthMonitor> log,
IOptions<ClusterMembershipOptions> clusterMembershipOptions,
IFatalErrorHandler fatalErrorHandler,
IServiceProvider serviceProvider,
IAsyncTimerFactory timerFactory)
{
this.localSiloDetails = localSiloDetails;
this.tableManager = tableManager;
this.log = log;
this.fatalErrorHandler = fatalErrorHandler;
this.clusterMembershipOptions = clusterMembershipOptions.Value;
this.monitorClusterHealthTimer = timerFactory.Create(
this.clusterMembershipOptions.ProbeTimeout,
nameof(MonitorClusterHealth));
this.createMonitor = silo => ActivatorUtilities.CreateInstance<SiloHealthMonitor>(serviceProvider, silo);
}
ImmutableDictionary<SiloAddress, SiloHealthMonitor> ITestAccessor.MonitoredSilos { get => this.monitoredSilos; set => this.monitoredSilos = value; }
Func<SiloAddress, SiloHealthMonitor> ITestAccessor.CreateMonitor { get => this.createMonitor; set => this.createMonitor = value; }
MembershipVersion ITestAccessor.ObservedVersion => this.observedMembershipVersion;
/// <summary>
/// Attempts to probe all active silos in the cluster, returning a list of silos with which connectivity could not be verified.
/// </summary>
/// <returns>A list of silos with which connectivity could not be verified.</returns>
public async Task<List<SiloAddress>> CheckClusterConnectivity(SiloAddress[] members)
{
if (members.Length == 0) return new List<SiloAddress>();
var tasks = new List<Task<int>>(members.Length);
this.log.LogInformation(
(int)ErrorCode.MembershipSendingPreJoinPing,
"About to send pings to {Count} nodes in order to validate communication in the Joining state. Pinged nodes = {Nodes}",
members.Length,
Utils.EnumerableToString(members));
foreach (var silo in members)
{
tasks.Add(this.createMonitor(silo).Probe(Interlocked.Increment(ref this.probeNumber), CancellationToken.None));
}
try
{
await Task.WhenAll(tasks);
}
catch
{
// Ignore exceptions for now.
}
var failed = new List<SiloAddress>();
for (var i = 0; i < tasks.Count; i++)
{
if (tasks[i].Status != TaskStatus.RanToCompletion || tasks[i].GetAwaiter().GetResult() > 0)
{
failed.Add(members[i]);
}
}
return failed;
}
private async Task ProcessMembershipUpdates()
{
IAsyncEnumerator<MembershipTableSnapshot> enumerator = default;
try
{
if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Starting to process membership updates");
enumerator = this.tableManager.MembershipTableUpdates.GetAsyncEnumerator(this.shutdownCancellation.Token);
while (await enumerator.MoveNextAsync())
{
var current = enumerator.Current;
var newMonitoredSilos = this.UpdateMonitoredSilos(current, this.monitoredSilos, DateTime.UtcNow);
foreach (var pair in this.monitoredSilos)
{
if (!newMonitoredSilos.ContainsKey(pair.Key))
{
pair.Value.Cancel();
}
}
this.monitoredSilos = newMonitoredSilos;
this.observedMembershipVersion = current.Version;
}
}
catch (Exception exception) when (this.fatalErrorHandler.IsUnexpected(exception))
{
this.fatalErrorHandler.OnFatalException(this, nameof(ProcessMembershipUpdates), exception);
}
finally
{
if (enumerator is object) await enumerator.DisposeAsync();
if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Stopped processing membership updates");
}
}
private async Task MonitorClusterHealth()
{
if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Starting cluster health monitor");
try
{
// Randomize the initial wait time before initiating probes.
var random = new SafeRandom();
TimeSpan? onceOffDelay = random.NextTimeSpan(this.clusterMembershipOptions.ProbeTimeout);
while (await this.monitorClusterHealthTimer.NextTick(onceOffDelay))
{
if (onceOffDelay != default) onceOffDelay = default;
_ = this.ProbeMonitoredSilos();
}
}
catch (Exception exception) when (this.fatalErrorHandler.IsUnexpected(exception))
{
this.fatalErrorHandler.OnFatalException(this, nameof(ProcessMembershipUpdates), exception);
}
finally
{
if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Stopped cluster health monitor");
}
}
private async Task ProbeMonitoredSilos()
{
try
{
using var cancellation = new CancellationTokenSource(this.clusterMembershipOptions.ProbeTimeout);
var tasks = new List<Task>(this.monitoredSilos.Count);
foreach (var pair in this.monitoredSilos)
{
var monitor = pair.Value;
tasks.Add(PingSilo(monitor, cancellation.Token));
}
await Task.WhenAll(tasks);
}
catch (Exception exception)
{
this.log.LogError(
(int)ErrorCode.MembershipUpdateIAmAliveFailure,
"Exception while monitoring cluster members: {Exception}",
exception);
}
async Task PingSilo(SiloHealthMonitor monitor, CancellationToken pingCancellation)
{
var failedProbes = await monitor.Probe(Interlocked.Increment(ref this.probeNumber), pingCancellation);
if (this.shutdownCancellation.IsCancellationRequested)
{
return;
}
if (failedProbes < this.clusterMembershipOptions.NumMissedProbesLimit)
{
return;
}
if (monitor.IsCanceled || !this.monitoredSilos.ContainsKey(monitor.SiloAddress))
{
if (this.log.IsEnabled(LogLevel.Debug))
{
this.log.LogDebug(
(int)ErrorCode.MembershipPingedSiloNotInWatchList,
"Ignoring probe failure from silo {Silo} since it is no longer being monitored.",
monitor.SiloAddress,
failedProbes);
}
return;
}
this.log.LogWarning("Silo {Silo} failed {FailedProbes} probes and is suspected of being dead. Publishing a death vote.", monitor.SiloAddress, failedProbes);
try
{
await this.tableManager.TryToSuspectOrKill(monitor.SiloAddress);
}
catch (Exception exception)
{
this.log.LogError((int)ErrorCode.MembershipFailedToSuspect, "Failed to register death vote for silo {Silo}: {Exception}", monitor.SiloAddress, exception);
}
}
}
[Pure]
private ImmutableDictionary<SiloAddress, SiloHealthMonitor> UpdateMonitoredSilos(
MembershipTableSnapshot membership,
ImmutableDictionary<SiloAddress, SiloHealthMonitor> monitoredSilos,
DateTime now)
{
// If I am still not fully functional, I should not be probing others.
if (!membership.Entries.TryGetValue(this.localSiloDetails.SiloAddress, out var self) || !IsFunctionalForMembership(self.Status))
{
return ImmutableDictionary<SiloAddress, SiloHealthMonitor>.Empty;
}
// keep watching shutting-down silos as well, so we can properly ensure they are dead.
var tmpList = new List<SiloAddress>();
foreach (var member in membership.Entries)
{
if (IsFunctionalForMembership(member.Value.Status))
{
tmpList.Add(member.Key);
}
}
tmpList.Sort((x, y) => x.GetConsistentHashCode().CompareTo(y.GetConsistentHashCode()));
int myIndex = tmpList.FindIndex(el => el.Equals(self.SiloAddress));
if (myIndex < 0)
{
// this should not happen ...
var error = string.Format("This silo {0} status {1} is not in its own local silo list! This is a bug!", self.SiloAddress.ToLongString(), self.Status);
log.Error(ErrorCode.Runtime_Error_100305, error);
throw new OrleansMissingMembershipEntryException(error);
}
// Go over every node excluding me,
// Find up to NumProbedSilos silos after me, which are not suspected by anyone and add them to the probedSilos,
// In addition, every suspected silo you encounter on the way, add him to the probedSilos.
var silosToWatch = new List<SiloAddress>();
var additionalSilos = new List<SiloAddress>();
for (int i = 0; i < tmpList.Count - 1 && silosToWatch.Count < this.clusterMembershipOptions.NumProbedSilos; i++)
{
var candidate = tmpList[(myIndex + i + 1) % tmpList.Count];
var candidateEntry = membership.Entries[candidate];
if (candidate.IsSameLogicalSilo(this.localSiloDetails.SiloAddress)) continue;
bool isSuspected = candidateEntry.GetFreshVotes(now, this.clusterMembershipOptions.DeathVoteExpirationTimeout).Count > 0;
if (isSuspected)
{
additionalSilos.Add(candidate);
}
else
{
silosToWatch.Add(candidate);
}
}
// take new watched silos, but leave the probe counters for the old ones.
var newProbedSilos = ImmutableDictionary.CreateBuilder<SiloAddress, SiloHealthMonitor>();
foreach (var silo in silosToWatch.Union(additionalSilos))
{
SiloHealthMonitor monitor;
if (!monitoredSilos.TryGetValue(silo, out monitor))
{
monitor = this.createMonitor(silo);
}
newProbedSilos[silo] = monitor;
}
var result = newProbedSilos.ToImmutable();
if (!AreTheSame(monitoredSilos, result))
{
log.Info(ErrorCode.MembershipWatchList, "Will watch (actively ping) {0} silos: {1}",
newProbedSilos.Count, Utils.EnumerableToString(newProbedSilos.Keys, silo => silo.ToLongString()));
}
return result;
bool AreTheSame<T>(ImmutableDictionary<SiloAddress, T> first, ImmutableDictionary<SiloAddress, T> second)
{
return first.Count == second.Count && first.Count == first.Keys.Intersect(second.Keys).Count();
}
bool IsFunctionalForMembership(SiloStatus status)
{
return status == SiloStatus.Active || status == SiloStatus.ShuttingDown || status == SiloStatus.Stopping;
}
}
void ILifecycleParticipant<ISiloLifecycle>.Participate(ISiloLifecycle lifecycle)
{
var tasks = new List<Task>();
lifecycle.Subscribe(nameof(ClusterHealthMonitor), ServiceLifecycleStage.Active, OnActiveStart, OnActiveStop);
Task OnActiveStart(CancellationToken ct)
{
tasks.Add(Task.Run(() => this.ProcessMembershipUpdates()));
tasks.Add(Task.Run(() => this.MonitorClusterHealth()));
return Task.CompletedTask;
}
Task OnActiveStop(CancellationToken ct)
{
this.monitorClusterHealthTimer.Dispose();
this.shutdownCancellation.Cancel(throwOnFirstException: false);
foreach (var monitor in this.monitoredSilos.Values)
{
monitor.Cancel();
}
this.monitoredSilos = this.monitoredSilos.Clear();
// Stop waiting for graceful shutdown when the provided cancellation token is cancelled
return Task.WhenAny(ct.WhenCancelled(), Task.WhenAll(tasks));
}
}
bool IHealthCheckable.CheckHealth(DateTime lastCheckTime)
{
var ok = this.monitorClusterHealthTimer.CheckHealth(lastCheckTime);
return ok;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using Internal.Runtime.CompilerServices;
#if CORERT
using CorElementType = System.Runtime.RuntimeImports.RhCorElementType;
using RuntimeType = System.Type;
using EnumInfo = Internal.Runtime.Augments.EnumInfo;
#endif
// The code below includes partial support for float/double and
// pointer sized enums.
//
// The type loader does not prohibit such enums, and older versions of
// the ECMA spec include them as possible enum types.
//
// However there are many things broken throughout the stack for
// float/double/intptr/uintptr enums. There was a conscious decision
// made to not fix the whole stack to work well for them because of
// the right behavior is often unclear, and it is hard to test and
// very low value because of such enums cannot be expressed in C#.
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract partial class Enum : ValueType, IComparable, IFormattable, IConvertible
{
#region Private Constants
private const char EnumSeparatorChar = ',';
#endregion
#region Private Static Methods
private string ValueToString()
{
ref byte data = ref this.GetRawData();
return (InternalGetCorElementType()) switch
{
CorElementType.ELEMENT_TYPE_I1 => Unsafe.As<byte, sbyte>(ref data).ToString(),
CorElementType.ELEMENT_TYPE_U1 => data.ToString(),
CorElementType.ELEMENT_TYPE_BOOLEAN => Unsafe.As<byte, bool>(ref data).ToString(),
CorElementType.ELEMENT_TYPE_I2 => Unsafe.As<byte, short>(ref data).ToString(),
CorElementType.ELEMENT_TYPE_U2 => Unsafe.As<byte, ushort>(ref data).ToString(),
CorElementType.ELEMENT_TYPE_CHAR => Unsafe.As<byte, char>(ref data).ToString(),
CorElementType.ELEMENT_TYPE_I4 => Unsafe.As<byte, int>(ref data).ToString(),
CorElementType.ELEMENT_TYPE_U4 => Unsafe.As<byte, uint>(ref data).ToString(),
CorElementType.ELEMENT_TYPE_R4 => Unsafe.As<byte, float>(ref data).ToString(),
CorElementType.ELEMENT_TYPE_I8 => Unsafe.As<byte, long>(ref data).ToString(),
CorElementType.ELEMENT_TYPE_U8 => Unsafe.As<byte, ulong>(ref data).ToString(),
CorElementType.ELEMENT_TYPE_R8 => Unsafe.As<byte, double>(ref data).ToString(),
CorElementType.ELEMENT_TYPE_I => Unsafe.As<byte, IntPtr>(ref data).ToString(),
CorElementType.ELEMENT_TYPE_U => Unsafe.As<byte, UIntPtr>(ref data).ToString(),
_ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
};
}
private string ValueToHexString()
{
ref byte data = ref this.GetRawData();
switch (InternalGetCorElementType())
{
case CorElementType.ELEMENT_TYPE_I1:
case CorElementType.ELEMENT_TYPE_U1:
return data.ToString("X2", null);
case CorElementType.ELEMENT_TYPE_BOOLEAN:
return Convert.ToByte(Unsafe.As<byte, bool>(ref data)).ToString("X2", null);
case CorElementType.ELEMENT_TYPE_I2:
case CorElementType.ELEMENT_TYPE_U2:
case CorElementType.ELEMENT_TYPE_CHAR:
return Unsafe.As<byte, ushort>(ref data).ToString("X4", null);
case CorElementType.ELEMENT_TYPE_I4:
case CorElementType.ELEMENT_TYPE_U4:
return Unsafe.As<byte, uint>(ref data).ToString("X8", null);
case CorElementType.ELEMENT_TYPE_I8:
case CorElementType.ELEMENT_TYPE_U8:
return Unsafe.As<byte, ulong>(ref data).ToString("X16", null);
default:
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
private static string ValueToHexString(object value)
{
return (Convert.GetTypeCode(value)) switch
{
TypeCode.SByte => ((byte)(sbyte)value).ToString("X2", null),
TypeCode.Byte => ((byte)value).ToString("X2", null),
TypeCode.Boolean => Convert.ToByte((bool)value).ToString("X2", null), // direct cast from bool to byte is not allowed
TypeCode.Int16 => ((ushort)(short)value).ToString("X4", null),
TypeCode.UInt16 => ((ushort)value).ToString("X4", null),
TypeCode.Char => ((ushort)(char)value).ToString("X4", null),
TypeCode.UInt32 => ((uint)value).ToString("X8", null),
TypeCode.Int32 => ((uint)(int)value).ToString("X8", null),
TypeCode.UInt64 => ((ulong)value).ToString("X16", null),
TypeCode.Int64 => ((ulong)(long)value).ToString("X16", null),
_ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
};
}
internal static string? GetEnumName(RuntimeType enumType, ulong ulValue)
{
return GetEnumName(GetEnumInfo(enumType), ulValue);
}
private static string? GetEnumName(EnumInfo enumInfo, ulong ulValue)
{
int index = Array.BinarySearch(enumInfo.Values, ulValue);
if (index >= 0)
{
return enumInfo.Names[index];
}
return null; // return null so the caller knows to .ToString() the input
}
private static string? InternalFormat(RuntimeType enumType, ulong value)
{
EnumInfo enumInfo = GetEnumInfo(enumType);
if (!enumInfo.HasFlagsAttribute)
{
return GetEnumName(enumInfo, value);
}
else // These are flags OR'ed together (We treat everything as unsigned types)
{
return InternalFlagsFormat(enumType, enumInfo, value);
}
}
private static string? InternalFlagsFormat(RuntimeType enumType, ulong result)
{
return InternalFlagsFormat(enumType, GetEnumInfo(enumType), result);
}
private static string? InternalFlagsFormat(RuntimeType enumType, EnumInfo enumInfo, ulong resultValue)
{
Debug.Assert(enumType != null);
string[] names = enumInfo.Names;
ulong[] values = enumInfo.Values;
Debug.Assert(names.Length == values.Length);
// Values are sorted, so if the incoming value is 0, we can check to see whether
// the first entry matches it, in which case we can return its name; otherwise,
// we can just return "0".
if (resultValue == 0)
{
return values.Length > 0 && values[0] == 0 ?
names[0] :
"0";
}
// With a ulong result value, regardless of the enum's base type, the maximum
// possible number of consistent name/values we could have is 64, since every
// value is made up of one or more bits, and when we see values and incorporate
// their names, we effectively switch off those bits.
Span<int> foundItems = stackalloc int[64];
// Walk from largest to smallest. It's common to have a flags enum with a single
// value that matches a single entry, in which case we can just return the existing
// name string.
int index = values.Length - 1;
while (index >= 0)
{
if (values[index] == resultValue)
{
return names[index];
}
if (values[index] < resultValue)
{
break;
}
index--;
}
// Now look for multiple matches, storing the indices of the values
// into our span.
int resultLength = 0, foundItemsCount = 0;
while (index >= 0)
{
ulong currentValue = values[index];
if (index == 0 && currentValue == 0)
{
break;
}
if ((resultValue & currentValue) == currentValue)
{
resultValue -= currentValue;
foundItems[foundItemsCount++] = index;
resultLength = checked(resultLength + names[index].Length);
}
index--;
}
// If we exhausted looking through all the values and we still have
// a non-zero result, we couldn't match the result to only named values.
// In that case, we return null and let the call site just generate
// a string for the integral value.
if (resultValue != 0)
{
return null;
}
// We know what strings to concatenate. Do so.
Debug.Assert(foundItemsCount > 0);
const int SeparatorStringLength = 2; // ", "
string result = string.FastAllocateString(checked(resultLength + (SeparatorStringLength * (foundItemsCount - 1))));
Span<char> resultSpan = new Span<char>(ref result.GetRawStringData(), result.Length);
string name = names[foundItems[--foundItemsCount]];
name.AsSpan().CopyTo(resultSpan);
resultSpan = resultSpan.Slice(name.Length);
while (--foundItemsCount >= 0)
{
resultSpan[0] = EnumSeparatorChar;
resultSpan[1] = ' ';
resultSpan = resultSpan.Slice(2);
name = names[foundItems[foundItemsCount]];
name.AsSpan().CopyTo(resultSpan);
resultSpan = resultSpan.Slice(name.Length);
}
Debug.Assert(resultSpan.IsEmpty);
return result;
}
internal static ulong ToUInt64(object value)
{
// Helper function to silently convert the value to UInt64 from the other base types for enum without throwing an exception.
// This is need since the Convert functions do overflow checks.
TypeCode typeCode = Convert.GetTypeCode(value);
ulong result = typeCode switch
{
TypeCode.SByte => (ulong)(sbyte)value,
TypeCode.Byte => (byte)value,
TypeCode.Boolean => Convert.ToByte((bool)value), // direct cast from bool to byte is not allowed
TypeCode.Int16 => (ulong)(short)value,
TypeCode.UInt16 => (ushort)value,
TypeCode.Char => (ushort)(char)value,
TypeCode.UInt32 => (uint)value,
TypeCode.Int32 => (ulong)(int)value,
TypeCode.UInt64 => (ulong)value,
TypeCode.Int64 => (ulong)(long)value,
_ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
};
return result;
}
#endregion
#region Public Static Methods
public static object Parse(Type enumType, string value) =>
Parse(enumType, value, ignoreCase: false);
public static object Parse(Type enumType, string value, bool ignoreCase)
{
bool success = TryParse(enumType, value, ignoreCase, throwOnFailure: true, out object? result);
Debug.Assert(success);
return result!;
}
public static TEnum Parse<TEnum>(string value) where TEnum : struct =>
Parse<TEnum>(value, ignoreCase: false);
public static TEnum Parse<TEnum>(string value, bool ignoreCase) where TEnum : struct
{
bool success = TryParse<TEnum>(value, ignoreCase, throwOnFailure: true, out TEnum result);
Debug.Assert(success);
return result;
}
public static bool TryParse(Type enumType, string? value, out object? result) =>
TryParse(enumType, value, ignoreCase: false, out result);
public static bool TryParse(Type enumType, string? value, bool ignoreCase, out object? result) =>
TryParse(enumType, value, ignoreCase, throwOnFailure: false, out result);
private static bool TryParse(Type enumType, string? value, bool ignoreCase, bool throwOnFailure, out object? result)
{
// Validation on the enum type itself. Failures here are considered non-parsing failures
// and thus always throw rather than returning false.
RuntimeType rt = ValidateRuntimeType(enumType);
ReadOnlySpan<char> valueSpan = value.AsSpan().TrimStart();
if (valueSpan.Length == 0)
{
if (throwOnFailure)
{
throw value == null ?
new ArgumentNullException(nameof(value)) :
new ArgumentException(SR.Arg_MustContainEnumInfo, nameof(value));
}
result = null;
return false;
}
int intResult;
uint uintResult;
bool parsed;
switch (Type.GetTypeCode(rt))
{
case TypeCode.SByte:
parsed = TryParseInt32Enum(rt, value, valueSpan, sbyte.MinValue, sbyte.MaxValue, ignoreCase, throwOnFailure, TypeCode.SByte, out intResult);
result = parsed ? InternalBoxEnum(rt, intResult) : null;
return parsed;
case TypeCode.Int16:
parsed = TryParseInt32Enum(rt, value, valueSpan, short.MinValue, short.MaxValue, ignoreCase, throwOnFailure, TypeCode.Int16, out intResult);
result = parsed ? InternalBoxEnum(rt, intResult) : null;
return parsed;
case TypeCode.Int32:
parsed = TryParseInt32Enum(rt, value, valueSpan, int.MinValue, int.MaxValue, ignoreCase, throwOnFailure, TypeCode.Int32, out intResult);
result = parsed ? InternalBoxEnum(rt, intResult) : null;
return parsed;
case TypeCode.Byte:
parsed = TryParseUInt32Enum(rt, value, valueSpan, byte.MaxValue, ignoreCase, throwOnFailure, TypeCode.Byte, out uintResult);
result = parsed ? InternalBoxEnum(rt, uintResult) : null;
return parsed;
case TypeCode.UInt16:
parsed = TryParseUInt32Enum(rt, value, valueSpan, ushort.MaxValue, ignoreCase, throwOnFailure, TypeCode.UInt16, out uintResult);
result = parsed ? InternalBoxEnum(rt, uintResult) : null;
return parsed;
case TypeCode.UInt32:
parsed = TryParseUInt32Enum(rt, value, valueSpan, uint.MaxValue, ignoreCase, throwOnFailure, TypeCode.UInt32, out uintResult);
result = parsed ? InternalBoxEnum(rt, uintResult) : null;
return parsed;
case TypeCode.Int64:
parsed = TryParseInt64Enum(rt, value, valueSpan, ignoreCase, throwOnFailure, out long longResult);
result = parsed ? InternalBoxEnum(rt, longResult) : null;
return parsed;
case TypeCode.UInt64:
parsed = TryParseUInt64Enum(rt, value, valueSpan, ignoreCase, throwOnFailure, out ulong ulongResult);
result = parsed ? InternalBoxEnum(rt, (long)ulongResult) : null;
return parsed;
default:
return TryParseRareEnum(rt, value, valueSpan, ignoreCase, throwOnFailure, out result);
}
}
public static bool TryParse<TEnum>(string? value, out TEnum result) where TEnum : struct =>
TryParse<TEnum>(value, ignoreCase: false, out result);
public static bool TryParse<TEnum>(string? value, bool ignoreCase, out TEnum result) where TEnum : struct =>
TryParse<TEnum>(value, ignoreCase, throwOnFailure: false, out result);
private static bool TryParse<TEnum>(string? value, bool ignoreCase, bool throwOnFailure, out TEnum result) where TEnum : struct
{
// Validation on the enum type itself. Failures here are considered non-parsing failures
// and thus always throw rather than returning false.
if (!typeof(TEnum).IsEnum)
{
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(TEnum));
}
ReadOnlySpan<char> valueSpan = value.AsSpan().TrimStart();
if (valueSpan.Length == 0)
{
if (throwOnFailure)
{
throw value == null ?
new ArgumentNullException(nameof(value)) :
new ArgumentException(SR.Arg_MustContainEnumInfo, nameof(value));
}
result = default;
return false;
}
int intResult;
uint uintResult;
bool parsed;
RuntimeType rt = (RuntimeType)typeof(TEnum);
switch (Type.GetTypeCode(typeof(TEnum)))
{
case TypeCode.SByte:
parsed = TryParseInt32Enum(rt, value, valueSpan, sbyte.MinValue, sbyte.MaxValue, ignoreCase, throwOnFailure, TypeCode.SByte, out intResult);
sbyte sbyteResult = (sbyte)intResult;
result = Unsafe.As<sbyte, TEnum>(ref sbyteResult);
return parsed;
case TypeCode.Int16:
parsed = TryParseInt32Enum(rt, value, valueSpan, short.MinValue, short.MaxValue, ignoreCase, throwOnFailure, TypeCode.Int16, out intResult);
short shortResult = (short)intResult;
result = Unsafe.As<short, TEnum>(ref shortResult);
return parsed;
case TypeCode.Int32:
parsed = TryParseInt32Enum(rt, value, valueSpan, int.MinValue, int.MaxValue, ignoreCase, throwOnFailure, TypeCode.Int32, out intResult);
result = Unsafe.As<int, TEnum>(ref intResult);
return parsed;
case TypeCode.Byte:
parsed = TryParseUInt32Enum(rt, value, valueSpan, byte.MaxValue, ignoreCase, throwOnFailure, TypeCode.Byte, out uintResult);
byte byteResult = (byte)uintResult;
result = Unsafe.As<byte, TEnum>(ref byteResult);
return parsed;
case TypeCode.UInt16:
parsed = TryParseUInt32Enum(rt, value, valueSpan, ushort.MaxValue, ignoreCase, throwOnFailure, TypeCode.UInt16, out uintResult);
ushort ushortResult = (ushort)uintResult;
result = Unsafe.As<ushort, TEnum>(ref ushortResult);
return parsed;
case TypeCode.UInt32:
parsed = TryParseUInt32Enum(rt, value, valueSpan, uint.MaxValue, ignoreCase, throwOnFailure, TypeCode.UInt32, out uintResult);
result = Unsafe.As<uint, TEnum>(ref uintResult);
return parsed;
case TypeCode.Int64:
parsed = TryParseInt64Enum(rt, value, valueSpan, ignoreCase, throwOnFailure, out long longResult);
result = Unsafe.As<long, TEnum>(ref longResult);
return parsed;
case TypeCode.UInt64:
parsed = TryParseUInt64Enum(rt, value, valueSpan, ignoreCase, throwOnFailure, out ulong ulongResult);
result = Unsafe.As<ulong, TEnum>(ref ulongResult);
return parsed;
default:
parsed = TryParseRareEnum(rt, value, valueSpan, ignoreCase, throwOnFailure, out object? objectResult);
result = parsed ? (TEnum)objectResult! : default;
return parsed;
}
}
/// <summary>Tries to parse the value of an enum with known underlying types that fit in an Int32 (Int32, Int16, and SByte).</summary>
private static bool TryParseInt32Enum(
RuntimeType enumType, string? originalValueString, ReadOnlySpan<char> value, int minInclusive, int maxInclusive, bool ignoreCase, bool throwOnFailure, TypeCode type, out int result)
{
Debug.Assert(
enumType.GetEnumUnderlyingType() == typeof(sbyte) ||
enumType.GetEnumUnderlyingType() == typeof(short) ||
enumType.GetEnumUnderlyingType() == typeof(int));
Number.ParsingStatus status = default;
if (StartsNumber(value[0]))
{
status = Number.TryParseInt32IntegerStyle(value, NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture.NumberFormat, out result);
if (status == Number.ParsingStatus.OK)
{
if ((uint)(result - minInclusive) <= (uint)(maxInclusive - minInclusive))
{
return true;
}
status = Number.ParsingStatus.Overflow;
}
}
if (status == Number.ParsingStatus.Overflow)
{
if (throwOnFailure)
{
Number.ThrowOverflowException(type);
}
}
else if (TryParseByName(enumType, originalValueString, value, ignoreCase, throwOnFailure, out ulong ulongResult))
{
result = (int)ulongResult;
Debug.Assert(result >= minInclusive && result <= maxInclusive);
return true;
}
result = 0;
return false;
}
/// <summary>Tries to parse the value of an enum with known underlying types that fit in a UInt32 (UInt32, UInt16, and Byte).</summary>
private static bool TryParseUInt32Enum(RuntimeType enumType, string? originalValueString, ReadOnlySpan<char> value, uint maxInclusive, bool ignoreCase, bool throwOnFailure, TypeCode type, out uint result)
{
Debug.Assert(
enumType.GetEnumUnderlyingType() == typeof(byte) ||
enumType.GetEnumUnderlyingType() == typeof(ushort) ||
enumType.GetEnumUnderlyingType() == typeof(uint));
Number.ParsingStatus status = default;
if (StartsNumber(value[0]))
{
status = Number.TryParseUInt32IntegerStyle(value, NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture.NumberFormat, out result);
if (status == Number.ParsingStatus.OK)
{
if (result <= maxInclusive)
{
return true;
}
status = Number.ParsingStatus.Overflow;
}
}
if (status == Number.ParsingStatus.Overflow)
{
if (throwOnFailure)
{
Number.ThrowOverflowException(type);
}
}
else if (TryParseByName(enumType, originalValueString, value, ignoreCase, throwOnFailure, out ulong ulongResult))
{
result = (uint)ulongResult;
Debug.Assert(result <= maxInclusive);
return true;
}
result = 0;
return false;
}
/// <summary>Tries to parse the value of an enum with Int64 as the underlying type.</summary>
private static bool TryParseInt64Enum(RuntimeType enumType, string? originalValueString, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, out long result)
{
Debug.Assert(enumType.GetEnumUnderlyingType() == typeof(long));
Number.ParsingStatus status = default;
if (StartsNumber(value[0]))
{
status = Number.TryParseInt64IntegerStyle(value, NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture.NumberFormat, out result);
if (status == Number.ParsingStatus.OK)
{
return true;
}
}
if (status == Number.ParsingStatus.Overflow)
{
if (throwOnFailure)
{
Number.ThrowOverflowException(TypeCode.Int64);
}
}
else if (TryParseByName(enumType, originalValueString, value, ignoreCase, throwOnFailure, out ulong ulongResult))
{
result = (long)ulongResult;
return true;
}
result = 0;
return false;
}
/// <summary>Tries to parse the value of an enum with UInt64 as the underlying type.</summary>
private static bool TryParseUInt64Enum(RuntimeType enumType, string? originalValueString, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, out ulong result)
{
Debug.Assert(enumType.GetEnumUnderlyingType() == typeof(ulong));
Number.ParsingStatus status = default;
if (StartsNumber(value[0]))
{
status = Number.TryParseUInt64IntegerStyle(value, NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture.NumberFormat, out result);
if (status == Number.ParsingStatus.OK)
{
return true;
}
}
if (status == Number.ParsingStatus.Overflow)
{
if (throwOnFailure)
{
Number.ThrowOverflowException(TypeCode.UInt64);
}
}
else if (TryParseByName(enumType, originalValueString, value, ignoreCase, throwOnFailure, out result))
{
return true;
}
result = 0;
return false;
}
/// <summary>Tries to parse the value of an enum with an underlying type that can't be expressed in C# (e.g. char, bool, double, etc.)</summary>
private static bool TryParseRareEnum(RuntimeType enumType, string? originalValueString, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, [NotNullWhen(true)] out object? result)
{
Debug.Assert(
enumType.GetEnumUnderlyingType() != typeof(sbyte) &&
enumType.GetEnumUnderlyingType() != typeof(byte) &&
enumType.GetEnumUnderlyingType() != typeof(short) &&
enumType.GetEnumUnderlyingType() != typeof(ushort) &&
enumType.GetEnumUnderlyingType() != typeof(int) &&
enumType.GetEnumUnderlyingType() != typeof(uint) &&
enumType.GetEnumUnderlyingType() != typeof(long) &&
enumType.GetEnumUnderlyingType() != typeof(ulong),
"Should only be used when parsing enums with rare underlying types, those that can't be expressed in C#.");
if (StartsNumber(value[0]))
{
Type underlyingType = GetUnderlyingType(enumType);
try
{
result = ToObject(enumType, Convert.ChangeType(value.ToString(), underlyingType, CultureInfo.InvariantCulture)!);
return true;
}
catch (FormatException)
{
// We need to Parse this as a String instead. There are cases
// when you tlbimp enums that can have values of the form "3D".
}
catch when (!throwOnFailure)
{
result = null;
return false;
}
}
if (TryParseByName(enumType, originalValueString, value, ignoreCase, throwOnFailure, out ulong ulongResult))
{
try
{
result = ToObject(enumType, ulongResult);
return true;
}
catch when (!throwOnFailure) { }
}
result = null;
return false;
}
private static bool TryParseByName(RuntimeType enumType, string? originalValueString, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, out ulong result)
{
// Find the field. Let's assume that these are always static classes because the class is an enum.
EnumInfo enumInfo = GetEnumInfo(enumType);
string[] enumNames = enumInfo.Names;
ulong[] enumValues = enumInfo.Values;
bool parsed = true;
ulong localResult = 0;
while (value.Length > 0)
{
// Find the next separator.
ReadOnlySpan<char> subvalue;
int endIndex = value.IndexOf(EnumSeparatorChar);
if (endIndex == -1)
{
// No next separator; use the remainder as the next value.
subvalue = value.Trim();
value = default;
}
else if (endIndex != value.Length - 1)
{
// Found a separator before the last char.
subvalue = value.Slice(0, endIndex).Trim();
value = value.Slice(endIndex + 1);
}
else
{
// Last char was a separator, which is invalid.
parsed = false;
break;
}
// Try to match this substring against each enum name
bool success = false;
if (ignoreCase)
{
for (int i = 0; i < enumNames.Length; i++)
{
if (subvalue.EqualsOrdinalIgnoreCase(enumNames[i]))
{
localResult |= enumValues[i];
success = true;
break;
}
}
}
else
{
for (int i = 0; i < enumNames.Length; i++)
{
if (subvalue.EqualsOrdinal(enumNames[i]))
{
localResult |= enumValues[i];
success = true;
break;
}
}
}
if (!success)
{
parsed = false;
break;
}
}
if (parsed)
{
result = localResult;
return true;
}
if (throwOnFailure)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumValueNotFound, originalValueString));
}
result = 0;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool StartsNumber(char c) => char.IsInRange(c, '0', '9') || c == '-' || c == '+';
public static object ToObject(Type enumType, object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
// Delegate rest of error checking to the other functions
TypeCode typeCode = Convert.GetTypeCode(value);
return typeCode switch
{
TypeCode.Int32 => ToObject(enumType, (int)value),
TypeCode.SByte => ToObject(enumType, (sbyte)value),
TypeCode.Int16 => ToObject(enumType, (short)value),
TypeCode.Int64 => ToObject(enumType, (long)value),
TypeCode.UInt32 => ToObject(enumType, (uint)value),
TypeCode.Byte => ToObject(enumType, (byte)value),
TypeCode.UInt16 => ToObject(enumType, (ushort)value),
TypeCode.UInt64 => ToObject(enumType, (ulong)value),
TypeCode.Char => ToObject(enumType, (char)value),
TypeCode.Boolean => ToObject(enumType, (bool)value),
_ => throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value)),
};
}
public static string Format(Type enumType, object value, string format)
{
RuntimeType rtType = ValidateRuntimeType(enumType);
if (value == null)
throw new ArgumentNullException(nameof(value));
if (format == null)
throw new ArgumentNullException(nameof(format));
// If the value is an Enum then we need to extract the underlying value from it
Type valueType = value.GetType();
if (valueType.IsEnum)
{
if (!valueType.IsEquivalentTo(enumType))
throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, valueType, enumType));
if (format.Length != 1)
{
// all acceptable format string are of length 1
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
return ((Enum)value).ToString(format);
}
// The value must be of the same type as the Underlying type of the Enum
Type underlyingType = GetUnderlyingType(enumType);
if (valueType != underlyingType)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, valueType, underlyingType));
}
if (format.Length == 1)
{
switch (format[0])
{
case 'G':
case 'g':
return GetEnumName(rtType, ToUInt64(value)) ?? value.ToString()!;
case 'D':
case 'd':
return value.ToString()!;
case 'X':
case 'x':
return ValueToHexString(value);
case 'F':
case 'f':
return InternalFlagsFormat(rtType, ToUInt64(value)) ?? value.ToString()!;
}
}
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
#endregion
#region Private Methods
internal object GetValue()
{
ref byte data = ref this.GetRawData();
return (InternalGetCorElementType()) switch
{
CorElementType.ELEMENT_TYPE_I1 => Unsafe.As<byte, sbyte>(ref data),
CorElementType.ELEMENT_TYPE_U1 => data,
CorElementType.ELEMENT_TYPE_BOOLEAN => Unsafe.As<byte, bool>(ref data),
CorElementType.ELEMENT_TYPE_I2 => Unsafe.As<byte, short>(ref data),
CorElementType.ELEMENT_TYPE_U2 => Unsafe.As<byte, ushort>(ref data),
CorElementType.ELEMENT_TYPE_CHAR => Unsafe.As<byte, char>(ref data),
CorElementType.ELEMENT_TYPE_I4 => Unsafe.As<byte, int>(ref data),
CorElementType.ELEMENT_TYPE_U4 => Unsafe.As<byte, uint>(ref data),
CorElementType.ELEMENT_TYPE_R4 => Unsafe.As<byte, float>(ref data),
CorElementType.ELEMENT_TYPE_I8 => Unsafe.As<byte, long>(ref data),
CorElementType.ELEMENT_TYPE_U8 => Unsafe.As<byte, ulong>(ref data),
CorElementType.ELEMENT_TYPE_R8 => Unsafe.As<byte, double>(ref data),
CorElementType.ELEMENT_TYPE_I => Unsafe.As<byte, IntPtr>(ref data),
CorElementType.ELEMENT_TYPE_U => Unsafe.As<byte, UIntPtr>(ref data),
_ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
};
}
private ulong ToUInt64()
{
ref byte data = ref this.GetRawData();
switch (InternalGetCorElementType())
{
case CorElementType.ELEMENT_TYPE_I1:
return (ulong)Unsafe.As<byte, sbyte>(ref data);
case CorElementType.ELEMENT_TYPE_U1:
return data;
case CorElementType.ELEMENT_TYPE_BOOLEAN:
return Convert.ToUInt64(Unsafe.As<byte, bool>(ref data), CultureInfo.InvariantCulture);
case CorElementType.ELEMENT_TYPE_I2:
return (ulong)Unsafe.As<byte, short>(ref data);
case CorElementType.ELEMENT_TYPE_U2:
case CorElementType.ELEMENT_TYPE_CHAR:
return Unsafe.As<byte, ushort>(ref data);
case CorElementType.ELEMENT_TYPE_I4:
return (ulong)Unsafe.As<byte, int>(ref data);
case CorElementType.ELEMENT_TYPE_U4:
case CorElementType.ELEMENT_TYPE_R4:
return Unsafe.As<byte, uint>(ref data);
case CorElementType.ELEMENT_TYPE_I8:
return (ulong)Unsafe.As<byte, long>(ref data);
case CorElementType.ELEMENT_TYPE_U8:
case CorElementType.ELEMENT_TYPE_R8:
return Unsafe.As<byte, ulong>(ref data);
case CorElementType.ELEMENT_TYPE_I:
return (ulong)Unsafe.As<byte, IntPtr>(ref data);
case CorElementType.ELEMENT_TYPE_U:
return (ulong)Unsafe.As<byte, UIntPtr>(ref data);
default:
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
#endregion
#region Object Overrides
public override int GetHashCode()
{
// CONTRACT with the runtime: GetHashCode of enum types is implemented as GetHashCode of the underlying type.
// The runtime can bypass calls to Enum::GetHashCode and call the underlying type's GetHashCode directly
// to avoid boxing the enum.
ref byte data = ref this.GetRawData();
return (InternalGetCorElementType()) switch
{
CorElementType.ELEMENT_TYPE_I1 => Unsafe.As<byte, sbyte>(ref data).GetHashCode(),
CorElementType.ELEMENT_TYPE_U1 => data.GetHashCode(),
CorElementType.ELEMENT_TYPE_BOOLEAN => Unsafe.As<byte, bool>(ref data).GetHashCode(),
CorElementType.ELEMENT_TYPE_I2 => Unsafe.As<byte, short>(ref data).GetHashCode(),
CorElementType.ELEMENT_TYPE_U2 => Unsafe.As<byte, ushort>(ref data).GetHashCode(),
CorElementType.ELEMENT_TYPE_CHAR => Unsafe.As<byte, char>(ref data).GetHashCode(),
CorElementType.ELEMENT_TYPE_I4 => Unsafe.As<byte, int>(ref data).GetHashCode(),
CorElementType.ELEMENT_TYPE_U4 => Unsafe.As<byte, uint>(ref data).GetHashCode(),
CorElementType.ELEMENT_TYPE_R4 => Unsafe.As<byte, float>(ref data).GetHashCode(),
CorElementType.ELEMENT_TYPE_I8 => Unsafe.As<byte, long>(ref data).GetHashCode(),
CorElementType.ELEMENT_TYPE_U8 => Unsafe.As<byte, ulong>(ref data).GetHashCode(),
CorElementType.ELEMENT_TYPE_R8 => Unsafe.As<byte, double>(ref data).GetHashCode(),
CorElementType.ELEMENT_TYPE_I => Unsafe.As<byte, IntPtr>(ref data).GetHashCode(),
CorElementType.ELEMENT_TYPE_U => Unsafe.As<byte, UIntPtr>(ref data).GetHashCode(),
_ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
};
}
public override string ToString()
{
// Returns the value in a human readable format. For PASCAL style enums who's value maps directly the name of the field is returned.
// For PASCAL style enums who's values do not map directly the decimal value of the field is returned.
// For BitFlags (indicated by the Flags custom attribute): If for each bit that is set in the value there is a corresponding constant
// (a pure power of 2), then the OR string (ie "Red, Yellow") is returned. Otherwise, if the value is zero or if you can't create a string that consists of
// pure powers of 2 OR-ed together, you return a hex value
// Try to see if its one of the enum values, then we return a String back else the value
return InternalFormat((RuntimeType)GetType(), ToUInt64()) ?? ValueToString();
}
#endregion
#region IFormattable
[Obsolete("The provider argument is not used. Please use ToString(String).")]
public string ToString(string? format, IFormatProvider? provider)
{
return ToString(format);
}
#endregion
#region Public Methods
public string ToString(string? format)
{
if (string.IsNullOrEmpty(format))
{
return ToString();
}
if (format.Length == 1)
{
switch (format[0])
{
case 'G':
case 'g':
return ToString();
case 'D':
case 'd':
return ValueToString();
case 'X':
case 'x':
return ValueToHexString();
case 'F':
case 'f':
return InternalFlagsFormat((RuntimeType)GetType(), ToUInt64()) ?? ValueToString();
}
}
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
[Obsolete("The provider argument is not used. Please use ToString().")]
public string ToString(IFormatProvider? provider)
{
return ToString();
}
#endregion
#region IConvertible
public TypeCode GetTypeCode()
{
return (InternalGetCorElementType()) switch
{
CorElementType.ELEMENT_TYPE_I1 => TypeCode.SByte,
CorElementType.ELEMENT_TYPE_U1 => TypeCode.Byte,
CorElementType.ELEMENT_TYPE_BOOLEAN => TypeCode.Boolean,
CorElementType.ELEMENT_TYPE_I2 => TypeCode.Int16,
CorElementType.ELEMENT_TYPE_U2 => TypeCode.UInt16,
CorElementType.ELEMENT_TYPE_CHAR => TypeCode.Char,
CorElementType.ELEMENT_TYPE_I4 => TypeCode.Int32,
CorElementType.ELEMENT_TYPE_U4 => TypeCode.UInt32,
CorElementType.ELEMENT_TYPE_I8 => TypeCode.Int64,
CorElementType.ELEMENT_TYPE_U8 => TypeCode.UInt64,
_ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
};
}
bool IConvertible.ToBoolean(IFormatProvider? provider)
{
return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture);
}
char IConvertible.ToChar(IFormatProvider? provider)
{
return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture);
}
sbyte IConvertible.ToSByte(IFormatProvider? provider)
{
return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture);
}
byte IConvertible.ToByte(IFormatProvider? provider)
{
return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture);
}
short IConvertible.ToInt16(IFormatProvider? provider)
{
return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture);
}
ushort IConvertible.ToUInt16(IFormatProvider? provider)
{
return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture);
}
int IConvertible.ToInt32(IFormatProvider? provider)
{
return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture);
}
uint IConvertible.ToUInt32(IFormatProvider? provider)
{
return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture);
}
long IConvertible.ToInt64(IFormatProvider? provider)
{
return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture);
}
ulong IConvertible.ToUInt64(IFormatProvider? provider)
{
return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture);
}
float IConvertible.ToSingle(IFormatProvider? provider)
{
return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture);
}
double IConvertible.ToDouble(IFormatProvider? provider)
{
return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture);
}
decimal IConvertible.ToDecimal(IFormatProvider? provider)
{
return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture);
}
DateTime IConvertible.ToDateTime(IFormatProvider? provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Enum", "DateTime"));
}
object IConvertible.ToType(Type type, IFormatProvider? provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
#endregion
#region ToObject
[CLSCompliant(false)]
public static object ToObject(Type enumType, sbyte value) =>
InternalBoxEnum(ValidateRuntimeType(enumType), value);
public static object ToObject(Type enumType, short value) =>
InternalBoxEnum(ValidateRuntimeType(enumType), value);
public static object ToObject(Type enumType, int value) =>
InternalBoxEnum(ValidateRuntimeType(enumType), value);
public static object ToObject(Type enumType, byte value) =>
InternalBoxEnum(ValidateRuntimeType(enumType), value);
[CLSCompliant(false)]
public static object ToObject(Type enumType, ushort value) =>
InternalBoxEnum(ValidateRuntimeType(enumType), value);
[CLSCompliant(false)]
public static object ToObject(Type enumType, uint value) =>
InternalBoxEnum(ValidateRuntimeType(enumType), value);
public static object ToObject(Type enumType, long value) =>
InternalBoxEnum(ValidateRuntimeType(enumType), value);
[CLSCompliant(false)]
public static object ToObject(Type enumType, ulong value) =>
InternalBoxEnum(ValidateRuntimeType(enumType), unchecked((long)value));
private static object ToObject(Type enumType, char value) =>
InternalBoxEnum(ValidateRuntimeType(enumType), value);
private static object ToObject(Type enumType, bool value) =>
InternalBoxEnum(ValidateRuntimeType(enumType), value ? 1 : 0);
#endregion
}
}
| |
namespace org.xmlpull.v1
{
[global::MonoJavaBridge.JavaInterface(typeof(global::org.xmlpull.v1.XmlSerializer_))]
public interface XmlSerializer : global::MonoJavaBridge.IJavaObject
{
void setProperty(java.lang.String arg0, java.lang.Object arg1);
global::java.lang.Object getProperty(java.lang.String arg0);
global::java.lang.String getName();
void flush();
void comment(java.lang.String arg0);
global::java.lang.String getPrefix(java.lang.String arg0, bool arg1);
global::org.xmlpull.v1.XmlSerializer text(char[] arg0, int arg1, int arg2);
global::org.xmlpull.v1.XmlSerializer text(java.lang.String arg0);
void startDocument(java.lang.String arg0, java.lang.Boolean arg1);
void endDocument();
void ignorableWhitespace(java.lang.String arg0);
void processingInstruction(java.lang.String arg0);
void setFeature(java.lang.String arg0, bool arg1);
bool getFeature(java.lang.String arg0);
global::java.lang.String getNamespace();
int getDepth();
void setOutput(java.io.OutputStream arg0, java.lang.String arg1);
void setOutput(java.io.Writer arg0);
void setPrefix(java.lang.String arg0, java.lang.String arg1);
global::org.xmlpull.v1.XmlSerializer startTag(java.lang.String arg0, java.lang.String arg1);
global::org.xmlpull.v1.XmlSerializer attribute(java.lang.String arg0, java.lang.String arg1, java.lang.String arg2);
global::org.xmlpull.v1.XmlSerializer endTag(java.lang.String arg0, java.lang.String arg1);
void cdsect(java.lang.String arg0);
void entityRef(java.lang.String arg0);
void docdecl(java.lang.String arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::org.xmlpull.v1.XmlSerializer))]
public sealed partial class XmlSerializer_ : java.lang.Object, XmlSerializer
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static XmlSerializer_()
{
InitJNI();
}
internal XmlSerializer_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _setProperty16590;
void org.xmlpull.v1.XmlSerializer.setProperty(java.lang.String arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._setProperty16590, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._setProperty16590, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getProperty16591;
global::java.lang.Object org.xmlpull.v1.XmlSerializer.getProperty(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._getProperty16591, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._getProperty16591, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object;
}
internal static global::MonoJavaBridge.MethodId _getName16592;
global::java.lang.String org.xmlpull.v1.XmlSerializer.getName()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._getName16592)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._getName16592)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _flush16593;
void org.xmlpull.v1.XmlSerializer.flush()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._flush16593);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._flush16593);
}
internal static global::MonoJavaBridge.MethodId _comment16594;
void org.xmlpull.v1.XmlSerializer.comment(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._comment16594, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._comment16594, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getPrefix16595;
global::java.lang.String org.xmlpull.v1.XmlSerializer.getPrefix(java.lang.String arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._getPrefix16595, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._getPrefix16595, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _text16596;
global::org.xmlpull.v1.XmlSerializer org.xmlpull.v1.XmlSerializer.text(char[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.xmlpull.v1.XmlSerializer>(@__env.CallObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._text16596, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as org.xmlpull.v1.XmlSerializer;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.xmlpull.v1.XmlSerializer>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._text16596, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as org.xmlpull.v1.XmlSerializer;
}
internal static global::MonoJavaBridge.MethodId _text16597;
global::org.xmlpull.v1.XmlSerializer org.xmlpull.v1.XmlSerializer.text(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.xmlpull.v1.XmlSerializer>(@__env.CallObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._text16597, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.xmlpull.v1.XmlSerializer;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.xmlpull.v1.XmlSerializer>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._text16597, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.xmlpull.v1.XmlSerializer;
}
internal static global::MonoJavaBridge.MethodId _startDocument16598;
void org.xmlpull.v1.XmlSerializer.startDocument(java.lang.String arg0, java.lang.Boolean arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._startDocument16598, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._startDocument16598, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _endDocument16599;
void org.xmlpull.v1.XmlSerializer.endDocument()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._endDocument16599);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._endDocument16599);
}
internal static global::MonoJavaBridge.MethodId _ignorableWhitespace16600;
void org.xmlpull.v1.XmlSerializer.ignorableWhitespace(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._ignorableWhitespace16600, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._ignorableWhitespace16600, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _processingInstruction16601;
void org.xmlpull.v1.XmlSerializer.processingInstruction(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._processingInstruction16601, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._processingInstruction16601, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setFeature16602;
void org.xmlpull.v1.XmlSerializer.setFeature(java.lang.String arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._setFeature16602, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._setFeature16602, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getFeature16603;
bool org.xmlpull.v1.XmlSerializer.getFeature(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._getFeature16603, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._getFeature16603, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getNamespace16604;
global::java.lang.String org.xmlpull.v1.XmlSerializer.getNamespace()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._getNamespace16604)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._getNamespace16604)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getDepth16605;
int org.xmlpull.v1.XmlSerializer.getDepth()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._getDepth16605);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._getDepth16605);
}
internal static global::MonoJavaBridge.MethodId _setOutput16606;
void org.xmlpull.v1.XmlSerializer.setOutput(java.io.OutputStream arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._setOutput16606, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._setOutput16606, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setOutput16607;
void org.xmlpull.v1.XmlSerializer.setOutput(java.io.Writer arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._setOutput16607, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._setOutput16607, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setPrefix16608;
void org.xmlpull.v1.XmlSerializer.setPrefix(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._setPrefix16608, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._setPrefix16608, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _startTag16609;
global::org.xmlpull.v1.XmlSerializer org.xmlpull.v1.XmlSerializer.startTag(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.xmlpull.v1.XmlSerializer>(@__env.CallObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._startTag16609, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as org.xmlpull.v1.XmlSerializer;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.xmlpull.v1.XmlSerializer>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._startTag16609, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as org.xmlpull.v1.XmlSerializer;
}
internal static global::MonoJavaBridge.MethodId _attribute16610;
global::org.xmlpull.v1.XmlSerializer org.xmlpull.v1.XmlSerializer.attribute(java.lang.String arg0, java.lang.String arg1, java.lang.String arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.xmlpull.v1.XmlSerializer>(@__env.CallObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._attribute16610, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as org.xmlpull.v1.XmlSerializer;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.xmlpull.v1.XmlSerializer>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._attribute16610, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as org.xmlpull.v1.XmlSerializer;
}
internal static global::MonoJavaBridge.MethodId _endTag16611;
global::org.xmlpull.v1.XmlSerializer org.xmlpull.v1.XmlSerializer.endTag(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.xmlpull.v1.XmlSerializer>(@__env.CallObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._endTag16611, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as org.xmlpull.v1.XmlSerializer;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.xmlpull.v1.XmlSerializer>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._endTag16611, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as org.xmlpull.v1.XmlSerializer;
}
internal static global::MonoJavaBridge.MethodId _cdsect16612;
void org.xmlpull.v1.XmlSerializer.cdsect(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._cdsect16612, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._cdsect16612, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _entityRef16613;
void org.xmlpull.v1.XmlSerializer.entityRef(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._entityRef16613, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._entityRef16613, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _docdecl16614;
void org.xmlpull.v1.XmlSerializer.docdecl(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_._docdecl16614, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.xmlpull.v1.XmlSerializer_.staticClass, global::org.xmlpull.v1.XmlSerializer_._docdecl16614, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::org.xmlpull.v1.XmlSerializer_.staticClass = @__env.NewGlobalRef(@__env.FindClass("org/xmlpull/v1/XmlSerializer"));
global::org.xmlpull.v1.XmlSerializer_._setProperty16590 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "setProperty", "(Ljava/lang/String;Ljava/lang/Object;)V");
global::org.xmlpull.v1.XmlSerializer_._getProperty16591 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "getProperty", "(Ljava/lang/String;)Ljava/lang/Object;");
global::org.xmlpull.v1.XmlSerializer_._getName16592 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "getName", "()Ljava/lang/String;");
global::org.xmlpull.v1.XmlSerializer_._flush16593 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "flush", "()V");
global::org.xmlpull.v1.XmlSerializer_._comment16594 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "comment", "(Ljava/lang/String;)V");
global::org.xmlpull.v1.XmlSerializer_._getPrefix16595 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "getPrefix", "(Ljava/lang/String;Z)Ljava/lang/String;");
global::org.xmlpull.v1.XmlSerializer_._text16596 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "text", "([CII)Lorg/xmlpull/v1/XmlSerializer;");
global::org.xmlpull.v1.XmlSerializer_._text16597 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "text", "(Ljava/lang/String;)Lorg/xmlpull/v1/XmlSerializer;");
global::org.xmlpull.v1.XmlSerializer_._startDocument16598 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "startDocument", "(Ljava/lang/String;Ljava/lang/Boolean;)V");
global::org.xmlpull.v1.XmlSerializer_._endDocument16599 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "endDocument", "()V");
global::org.xmlpull.v1.XmlSerializer_._ignorableWhitespace16600 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "ignorableWhitespace", "(Ljava/lang/String;)V");
global::org.xmlpull.v1.XmlSerializer_._processingInstruction16601 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "processingInstruction", "(Ljava/lang/String;)V");
global::org.xmlpull.v1.XmlSerializer_._setFeature16602 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "setFeature", "(Ljava/lang/String;Z)V");
global::org.xmlpull.v1.XmlSerializer_._getFeature16603 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "getFeature", "(Ljava/lang/String;)Z");
global::org.xmlpull.v1.XmlSerializer_._getNamespace16604 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "getNamespace", "()Ljava/lang/String;");
global::org.xmlpull.v1.XmlSerializer_._getDepth16605 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "getDepth", "()I");
global::org.xmlpull.v1.XmlSerializer_._setOutput16606 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "setOutput", "(Ljava/io/OutputStream;Ljava/lang/String;)V");
global::org.xmlpull.v1.XmlSerializer_._setOutput16607 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "setOutput", "(Ljava/io/Writer;)V");
global::org.xmlpull.v1.XmlSerializer_._setPrefix16608 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "setPrefix", "(Ljava/lang/String;Ljava/lang/String;)V");
global::org.xmlpull.v1.XmlSerializer_._startTag16609 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "startTag", "(Ljava/lang/String;Ljava/lang/String;)Lorg/xmlpull/v1/XmlSerializer;");
global::org.xmlpull.v1.XmlSerializer_._attribute16610 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "attribute", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/xmlpull/v1/XmlSerializer;");
global::org.xmlpull.v1.XmlSerializer_._endTag16611 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "endTag", "(Ljava/lang/String;Ljava/lang/String;)Lorg/xmlpull/v1/XmlSerializer;");
global::org.xmlpull.v1.XmlSerializer_._cdsect16612 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "cdsect", "(Ljava/lang/String;)V");
global::org.xmlpull.v1.XmlSerializer_._entityRef16613 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "entityRef", "(Ljava/lang/String;)V");
global::org.xmlpull.v1.XmlSerializer_._docdecl16614 = @__env.GetMethodIDNoThrow(global::org.xmlpull.v1.XmlSerializer_.staticClass, "docdecl", "(Ljava/lang/String;)V");
}
}
}
| |
using System;
using System.Windows.Input;
using Avalonia.Input;
using Avalonia.Media.Imaging;
using Avalonia.Metadata;
using Avalonia.Utilities;
namespace Avalonia.Controls
{
public class NativeMenuItem : NativeMenuItemBase, INativeMenuItemExporterEventsImplBridge
{
private string? _header;
private KeyGesture? _gesture;
private bool _isEnabled = true;
private ICommand? _command;
private bool _isChecked = false;
private NativeMenuItemToggleType _toggleType;
private IBitmap? _icon;
private readonly CanExecuteChangedSubscriber _canExecuteChangedSubscriber;
private NativeMenu? _menu;
static NativeMenuItem()
{
MenuProperty.Changed.Subscribe(args =>
{
var item = (NativeMenuItem)args.Sender;
var value = args.NewValue.GetValueOrDefault()!;
if (value.Parent != null && value.Parent != item)
throw new InvalidOperationException("NativeMenu already has a parent");
value.Parent = item;
});
}
class CanExecuteChangedSubscriber : IWeakEventSubscriber<EventArgs>
{
private readonly NativeMenuItem _parent;
public CanExecuteChangedSubscriber(NativeMenuItem parent)
{
_parent = parent;
}
public void OnEvent(object? sender, WeakEvent ev, EventArgs e)
{
_parent.CanExecuteChanged();
}
}
public NativeMenuItem()
{
_canExecuteChangedSubscriber = new CanExecuteChangedSubscriber(this);
}
public NativeMenuItem(string header) : this()
{
Header = header;
}
public static readonly DirectProperty<NativeMenuItem, NativeMenu?> MenuProperty =
AvaloniaProperty.RegisterDirect<NativeMenuItem, NativeMenu?>(nameof(Menu), o => o.Menu, (o, v) => o.Menu = v);
[Content]
public NativeMenu? Menu
{
get => _menu;
set
{
if (value != null && value.Parent != null && value.Parent != this)
throw new InvalidOperationException("NativeMenu already has a parent");
SetAndRaise(MenuProperty, ref _menu, value);
}
}
public static readonly DirectProperty<NativeMenuItem, IBitmap?> IconProperty =
AvaloniaProperty.RegisterDirect<NativeMenuItem, IBitmap?>(nameof(Icon), o => o.Icon, (o, v) => o.Icon = v);
public IBitmap? Icon
{
get => _icon;
set => SetAndRaise(IconProperty, ref _icon, value);
}
public static readonly DirectProperty<NativeMenuItem, string?> HeaderProperty =
AvaloniaProperty.RegisterDirect<NativeMenuItem, string?>(nameof(Header), o => o.Header, (o, v) => o.Header = v);
public string? Header
{
get => _header;
set => SetAndRaise(HeaderProperty, ref _header, value);
}
public static readonly DirectProperty<NativeMenuItem, KeyGesture?> GestureProperty =
AvaloniaProperty.RegisterDirect<NativeMenuItem, KeyGesture?>(nameof(Gesture), o => o.Gesture, (o, v) => o.Gesture = v);
public KeyGesture? Gesture
{
get => _gesture;
set => SetAndRaise(GestureProperty, ref _gesture, value);
}
public static readonly DirectProperty<NativeMenuItem, bool> IsCheckedProperty =
AvaloniaProperty.RegisterDirect<NativeMenuItem, bool>(
nameof(IsChecked),
o => o.IsChecked,
(o, v) => o.IsChecked = v);
public bool IsChecked
{
get => _isChecked;
set => SetAndRaise(IsCheckedProperty, ref _isChecked, value);
}
public static readonly DirectProperty<NativeMenuItem, NativeMenuItemToggleType> ToggleTypeProperty =
AvaloniaProperty.RegisterDirect<NativeMenuItem, NativeMenuItemToggleType>(
nameof(ToggleType),
o => o.ToggleType,
(o, v) => o.ToggleType = v);
public NativeMenuItemToggleType ToggleType
{
get => _toggleType;
set => SetAndRaise(ToggleTypeProperty, ref _toggleType, value);
}
public static readonly DirectProperty<NativeMenuItem, ICommand?> CommandProperty =
Button.CommandProperty.AddOwner<NativeMenuItem>(
menuItem => menuItem.Command,
(menuItem, command) => menuItem.Command = command,
enableDataValidation: true);
/// <summary>
/// Defines the <see cref="CommandParameter"/> property.
/// </summary>
public static readonly StyledProperty<object?> CommandParameterProperty =
Button.CommandParameterProperty.AddOwner<MenuItem>();
public static readonly DirectProperty<NativeMenuItem, bool> IsEnabledProperty =
AvaloniaProperty.RegisterDirect<NativeMenuItem, bool>(nameof(IsEnabled), o => o.IsEnabled, (o, v) => o.IsEnabled = v, true);
public bool IsEnabled
{
get => _isEnabled;
set => SetAndRaise(IsEnabledProperty, ref _isEnabled, value);
}
void CanExecuteChanged()
{
IsEnabled = _command?.CanExecute(CommandParameter) ?? true;
}
public bool HasClickHandlers => Click != null;
public ICommand? Command
{
get => _command;
set
{
if (_command != null)
WeakEvents.CommandCanExecuteChanged.Unsubscribe(_command, _canExecuteChangedSubscriber);
SetAndRaise(CommandProperty, ref _command, value);
if (_command != null)
WeakEvents.CommandCanExecuteChanged.Subscribe(_command, _canExecuteChangedSubscriber);
CanExecuteChanged();
}
}
/// <summary>
/// Gets or sets the parameter to pass to the <see cref="Command"/> property of a
/// <see cref="NativeMenuItem"/>.
/// </summary>
public object? CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
/// <summary>
/// Occurs when a <see cref="NativeMenuItem"/> is clicked.
/// </summary>
public event EventHandler? Click;
[Obsolete("Use Click event.")]
public event EventHandler Clicked
{
add => Click += value;
remove => Click -= value;
}
void INativeMenuItemExporterEventsImplBridge.RaiseClicked()
{
Click?.Invoke(this, new EventArgs());
if (Command?.CanExecute(CommandParameter) == true)
{
Command.Execute(CommandParameter);
}
}
}
public enum NativeMenuItemToggleType
{
None,
CheckBox,
Radio
}
}
| |
#define SQLITE_ASCII
#define SQLITE_DISABLE_LFS
#define SQLITE_ENABLE_OVERSIZE_CELL_CHECK
#define SQLITE_MUTEX_OMIT
#define SQLITE_OMIT_AUTHORIZATION
#define SQLITE_OMIT_DEPRECATED
#define SQLITE_OMIT_GET_TABLE
#define SQLITE_OMIT_INCRBLOB
#define SQLITE_OMIT_LOOKASIDE
#define SQLITE_OMIT_SHARED_CACHE
#define SQLITE_OMIT_UTF16
#define SQLITE_OMIT_WAL
#define SQLITE_OS_WIN
#define SQLITE_SYSTEM_MALLOC
#define VDBE_PROFILE_OFF
#define WINDOWS_MOBILE
#define NDEBUG
#define _MSC_VER
#define YYFALLBACK
using System;
using System.Diagnostics;
using i64 = System.Int64;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the sqlite3_get_table() and //sqlite3_free_table()
** interface routines. These are just wrappers around the main
** interface routine of sqlite3_exec().
**
** These routines are in a separate files so that they will not be linked
** if they are not used.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include <stdlib.h>
//#include <string.h>
#if !SQLITE_OMIT_GET_TABLE
/*
** This structure is used to pass data from sqlite3_get_table() through
** to the callback function is uses to build the result.
*/
class TabResult {
public string[] azResult;
public string zErrMsg;
public int nResult;
public int nAlloc;
public int nRow;
public int nColumn;
public int nData;
public int rc;
};
/*
** This routine is called once for each row in the result table. Its job
** is to fill in the TabResult structure appropriately, allocating new
** memory as necessary.
*/
static public int sqlite3_get_table_cb( object pArg, i64 nCol, object Oargv, object Ocolv )
{
string[] argv = (string[])Oargv;
string[]colv = (string[])Ocolv;
TabResult p = (TabResult)pArg;
int need;
int i;
string z;
/* Make sure there is enough space in p.azResult to hold everything
** we need to remember from this invocation of the callback.
*/
if( p.nRow==0 && argv!=null ){
need = (int)nCol*2;
}else{
need = (int)nCol;
}
if( p.nData + need >= p.nAlloc ){
string[] azNew;
p.nAlloc = p.nAlloc*2 + need + 1;
azNew = new string[p.nAlloc];//sqlite3_realloc( p.azResult, sizeof(char*)*p.nAlloc );
if( azNew==null ) goto malloc_failed;
p.azResult = azNew;
}
/* If this is the first row, then generate an extra row containing
** the names of all columns.
*/
if( p.nRow==0 ){
p.nColumn = (int)nCol;
for(i=0; i<nCol; i++){
z = sqlite3_mprintf("%s", colv[i]);
if( z==null ) goto malloc_failed;
p.azResult[p.nData++ -1] = z;
}
}else if( p.nColumn!=nCol ){
//sqlite3_free(ref p.zErrMsg);
p.zErrMsg = sqlite3_mprintf(
"sqlite3_get_table() called with two or more incompatible queries"
);
p.rc = SQLITE_ERROR;
return 1;
}
/* Copy over the row data
*/
if( argv!=null ){
for(i=0; i<nCol; i++){
if( argv[i]==null ){
z = null;
}else{
int n = sqlite3Strlen30(argv[i])+1;
//z = sqlite3_malloc( n );
//if( z==0 ) goto malloc_failed;
z= argv[i];//memcpy(z, argv[i], n);
}
p.azResult[p.nData++ -1] = z;
}
p.nRow++;
}
return 0;
malloc_failed:
p.rc = SQLITE_NOMEM;
return 1;
}
/*
** Query the database. But instead of invoking a callback for each row,
** malloc() for space to hold the result and return the entire results
** at the conclusion of the call.
**
** The result that is written to ***pazResult is held in memory obtained
** from malloc(). But the caller cannot free this memory directly.
** Instead, the entire table should be passed to //sqlite3_free_table() when
** the calling procedure is finished using it.
*/
static public int sqlite3_get_table(
sqlite3 db, /* The database on which the SQL executes */
string zSql, /* The SQL to be executed */
ref string[] pazResult, /* Write the result table here */
ref int pnRow, /* Write the number of rows in the result here */
ref int pnColumn, /* Write the number of columns of result here */
ref string pzErrMsg /* Write error messages here */
){
int rc;
TabResult res = new TabResult();
pazResult = null;
pnColumn = 0;
pnRow = 0;
pzErrMsg = "";
res.zErrMsg = "";
res.nResult = 0;
res.nRow = 0;
res.nColumn = 0;
res.nData = 1;
res.nAlloc = 20;
res.rc = SQLITE_OK;
res.azResult = new string[res.nAlloc];// sqlite3_malloc( sizeof( char* ) * res.nAlloc );
if( res.azResult==null ){
db.errCode = SQLITE_NOMEM;
return SQLITE_NOMEM;
}
res.azResult[0] = null;
rc = sqlite3_exec(db, zSql, (dxCallback) sqlite3_get_table_cb, res, ref pzErrMsg);
//Debug.Assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
//res.azResult = SQLITE_INT_TO_PTR( res.nData );
if( (rc&0xff)==SQLITE_ABORT ){
//sqlite3_free_table(ref res.azResult[1] );
if( res.zErrMsg !=""){
if( pzErrMsg !=null ){
//sqlite3_free(ref pzErrMsg);
pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
}
//sqlite3_free(ref res.zErrMsg);
}
db.errCode = res.rc; /* Assume 32-bit assignment is atomic */
return res.rc;
}
//sqlite3_free(ref res.zErrMsg);
if( rc!=SQLITE_OK ){
//sqlite3_free_table(ref res.azResult[1]);
return rc;
}
if( res.nAlloc>res.nData ){
string[] azNew;
Array.Resize(ref res.azResult, res.nData-1);//sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
//if( azNew==null ){
// //sqlite3_free_table(ref res.azResult[1]);
// db.errCode = SQLITE_NOMEM;
// return SQLITE_NOMEM;
//}
res.nAlloc = res.nData+1;
//res.azResult = azNew;
}
pazResult = res.azResult;
pnColumn = res.nColumn;
pnRow = res.nRow;
return rc;
}
/*
** This routine frees the space the sqlite3_get_table() malloced.
*/
static void //sqlite3_free_table(
ref string azResult /* Result returned from from sqlite3_get_table() */
){
if( azResult !=null){
int i, n;
//azResult--;
//Debug.Assert( azResult!=0 );
//n = SQLITE_PTR_TO_INT(azResult[0]);
//for(i=1; i<n; i++){ if( azResult[i] ) //sqlite3_free(azResult[i]); }
//sqlite3_free(ref azResult);
}
}
#endif //* SQLITE_OMIT_GET_TABLE */
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Xml;
using System.Diagnostics;
using System.Collections.Generic;
namespace System.Xml.Schema
{
#if !SILVERLIGHT
internal enum AttributeMatchState
{
AttributeFound,
AnyIdAttributeFound,
UndeclaredElementAndAttribute,
UndeclaredAttribute,
AnyAttributeLax,
AnyAttributeSkip,
ProhibitedAnyAttribute,
ProhibitedAttribute,
AttributeNameMismatch,
ValidateAttributeInvalidCall,
}
#endif
internal class SchemaInfo : IDtdInfo
{
private Dictionary<XmlQualifiedName, SchemaElementDecl> _elementDecls = new Dictionary<XmlQualifiedName, SchemaElementDecl>();
private Dictionary<XmlQualifiedName, SchemaElementDecl> _undeclaredElementDecls = new Dictionary<XmlQualifiedName, SchemaElementDecl>();
private Dictionary<XmlQualifiedName, SchemaEntity> _generalEntities;
private Dictionary<XmlQualifiedName, SchemaEntity> _parameterEntities;
private XmlQualifiedName _docTypeName = XmlQualifiedName.Empty;
private string _internalDtdSubset = string.Empty;
private bool _hasNonCDataAttributes = false;
private bool _hasDefaultAttributes = false;
#if !SILVERLIGHT
private Dictionary<string, bool> _targetNamespaces = new Dictionary<string, bool>();
private Dictionary<XmlQualifiedName, SchemaAttDef> _attributeDecls = new Dictionary<XmlQualifiedName, SchemaAttDef>();
private int _errorCount;
private SchemaType _schemaType;
private Dictionary<XmlQualifiedName, SchemaElementDecl> _elementDeclsByType = new Dictionary<XmlQualifiedName, SchemaElementDecl>();
private Dictionary<string, SchemaNotation> _notations;
#endif
internal SchemaInfo()
{
#if !SILVERLIGHT
_schemaType = SchemaType.None;
#endif
}
public XmlQualifiedName DocTypeName
{
get { return _docTypeName; }
set { _docTypeName = value; }
}
internal string InternalDtdSubset
{
get { return _internalDtdSubset; }
set { _internalDtdSubset = value; }
}
internal Dictionary<XmlQualifiedName, SchemaElementDecl> ElementDecls
{
get { return _elementDecls; }
}
internal Dictionary<XmlQualifiedName, SchemaElementDecl> UndeclaredElementDecls
{
get { return _undeclaredElementDecls; }
}
internal Dictionary<XmlQualifiedName, SchemaEntity> GeneralEntities
{
get
{
if (_generalEntities == null)
{
_generalEntities = new Dictionary<XmlQualifiedName, SchemaEntity>();
}
return _generalEntities;
}
}
internal Dictionary<XmlQualifiedName, SchemaEntity> ParameterEntities
{
get
{
if (_parameterEntities == null)
{
_parameterEntities = new Dictionary<XmlQualifiedName, SchemaEntity>();
}
return _parameterEntities;
}
}
#if !SILVERLIGHT
internal SchemaType SchemaType
{
get { return _schemaType; }
set { _schemaType = value; }
}
internal Dictionary<string, bool> TargetNamespaces
{
get { return _targetNamespaces; }
}
internal Dictionary<XmlQualifiedName, SchemaElementDecl> ElementDeclsByType
{
get { return _elementDeclsByType; }
}
internal Dictionary<XmlQualifiedName, SchemaAttDef> AttributeDecls
{
get { return _attributeDecls; }
}
internal Dictionary<string, SchemaNotation> Notations
{
get
{
if (_notations == null)
{
_notations = new Dictionary<string, SchemaNotation>();
}
return _notations;
}
}
internal int ErrorCount
{
get { return _errorCount; }
set { _errorCount = value; }
}
internal SchemaElementDecl GetElementDecl(XmlQualifiedName qname)
{
SchemaElementDecl elemDecl;
if (_elementDecls.TryGetValue(qname, out elemDecl))
{
return elemDecl;
}
return null;
}
internal SchemaElementDecl GetTypeDecl(XmlQualifiedName qname)
{
SchemaElementDecl elemDecl;
if (_elementDeclsByType.TryGetValue(qname, out elemDecl))
{
return elemDecl;
}
return null;
}
internal XmlSchemaElement GetElement(XmlQualifiedName qname)
{
SchemaElementDecl ed = GetElementDecl(qname);
if (ed != null)
{
return ed.SchemaElement;
}
return null;
}
internal XmlSchemaAttribute GetAttribute(XmlQualifiedName qname)
{
SchemaAttDef attdef = (SchemaAttDef)_attributeDecls[qname];
if (attdef != null)
{
return attdef.SchemaAttribute;
}
return null;
}
internal XmlSchemaElement GetType(XmlQualifiedName qname)
{
SchemaElementDecl ed = GetElementDecl(qname);
if (ed != null)
{
return ed.SchemaElement;
}
return null;
}
internal bool HasSchema(string ns)
{
return _targetNamespaces.ContainsKey(ns);
}
internal bool Contains(string ns)
{
return _targetNamespaces.ContainsKey(ns);
}
internal SchemaAttDef GetAttributeXdr(SchemaElementDecl ed, XmlQualifiedName qname)
{
SchemaAttDef attdef = null;
if (ed != null)
{
attdef = ed.GetAttDef(qname); ;
if (attdef == null)
{
if (!ed.ContentValidator.IsOpen || qname.Namespace.Length == 0)
{
throw new XmlSchemaException(SR.Sch_UndeclaredAttribute, qname.ToString());
}
if (!_attributeDecls.TryGetValue(qname, out attdef) && _targetNamespaces.ContainsKey(qname.Namespace))
{
throw new XmlSchemaException(SR.Sch_UndeclaredAttribute, qname.ToString());
}
}
}
return attdef;
}
internal SchemaAttDef GetAttributeXsd(SchemaElementDecl ed, XmlQualifiedName qname, XmlSchemaObject partialValidationType, out AttributeMatchState attributeMatchState)
{
SchemaAttDef attdef = null;
attributeMatchState = AttributeMatchState.UndeclaredAttribute;
if (ed != null)
{
attdef = ed.GetAttDef(qname);
if (attdef != null)
{
attributeMatchState = AttributeMatchState.AttributeFound;
return attdef;
}
XmlSchemaAnyAttribute any = ed.AnyAttribute;
if (any != null)
{
if (!any.NamespaceList.Allows(qname))
{
attributeMatchState = AttributeMatchState.ProhibitedAnyAttribute;
}
else if (any.ProcessContentsCorrect != XmlSchemaContentProcessing.Skip)
{
if (_attributeDecls.TryGetValue(qname, out attdef))
{
if (attdef.Datatype.TypeCode == XmlTypeCode.Id)
{ //anyAttribute match whose type is ID
attributeMatchState = AttributeMatchState.AnyIdAttributeFound;
}
else
{
attributeMatchState = AttributeMatchState.AttributeFound;
}
}
else if (any.ProcessContentsCorrect == XmlSchemaContentProcessing.Lax)
{
attributeMatchState = AttributeMatchState.AnyAttributeLax;
}
}
else
{
attributeMatchState = AttributeMatchState.AnyAttributeSkip;
}
}
else if (ed.ProhibitedAttributes.ContainsKey(qname))
{
attributeMatchState = AttributeMatchState.ProhibitedAttribute;
}
}
else if (partialValidationType != null)
{
XmlSchemaAttribute attr = partialValidationType as XmlSchemaAttribute;
if (attr != null)
{
if (qname.Equals(attr.QualifiedName))
{
attdef = attr.AttDef;
attributeMatchState = AttributeMatchState.AttributeFound;
}
else
{
attributeMatchState = AttributeMatchState.AttributeNameMismatch;
}
}
else
{
attributeMatchState = AttributeMatchState.ValidateAttributeInvalidCall;
}
}
else
{
if (_attributeDecls.TryGetValue(qname, out attdef))
{
attributeMatchState = AttributeMatchState.AttributeFound;
}
else
{
attributeMatchState = AttributeMatchState.UndeclaredElementAndAttribute;
}
}
return attdef;
}
internal SchemaAttDef GetAttributeXsd(SchemaElementDecl ed, XmlQualifiedName qname, ref bool skip)
{
AttributeMatchState attributeMatchState;
SchemaAttDef attDef = GetAttributeXsd(ed, qname, null, out attributeMatchState);
switch (attributeMatchState)
{
case AttributeMatchState.UndeclaredAttribute:
throw new XmlSchemaException(SR.Sch_UndeclaredAttribute, qname.ToString());
case AttributeMatchState.ProhibitedAnyAttribute:
case AttributeMatchState.ProhibitedAttribute:
throw new XmlSchemaException(SR.Sch_ProhibitedAttribute, qname.ToString());
case AttributeMatchState.AttributeFound:
case AttributeMatchState.AnyIdAttributeFound:
case AttributeMatchState.AnyAttributeLax:
case AttributeMatchState.UndeclaredElementAndAttribute:
break;
case AttributeMatchState.AnyAttributeSkip:
skip = true;
break;
default:
Debug.Assert(false);
break;
}
return attDef;
}
internal void Add(SchemaInfo sinfo, ValidationEventHandler eventhandler)
{
if (_schemaType == SchemaType.None)
{
_schemaType = sinfo.SchemaType;
}
else if (_schemaType != sinfo.SchemaType)
{
if (eventhandler != null)
{
eventhandler(this, new ValidationEventArgs(new XmlSchemaException(SR.Sch_MixSchemaTypes, string.Empty)));
}
return;
}
foreach (string tns in sinfo.TargetNamespaces.Keys)
{
if (!_targetNamespaces.ContainsKey(tns))
{
_targetNamespaces.Add(tns, true);
}
}
foreach (KeyValuePair<XmlQualifiedName, SchemaElementDecl> entry in sinfo._elementDecls)
{
if (!_elementDecls.ContainsKey(entry.Key))
{
_elementDecls.Add(entry.Key, entry.Value);
}
}
foreach (KeyValuePair<XmlQualifiedName, SchemaElementDecl> entry in sinfo._elementDeclsByType)
{
if (!_elementDeclsByType.ContainsKey(entry.Key))
{
_elementDeclsByType.Add(entry.Key, entry.Value);
}
}
foreach (SchemaAttDef attdef in sinfo.AttributeDecls.Values)
{
if (!_attributeDecls.ContainsKey(attdef.Name))
{
_attributeDecls.Add(attdef.Name, attdef);
}
}
foreach (SchemaNotation notation in sinfo.Notations.Values)
{
if (!Notations.ContainsKey(notation.Name.Name))
{
Notations.Add(notation.Name.Name, notation);
}
}
}
#endif
internal void Finish()
{
Dictionary<XmlQualifiedName, SchemaElementDecl> elements = _elementDecls;
for (int i = 0; i < 2; i++)
{
foreach (SchemaElementDecl e in elements.Values)
{
if (e.HasNonCDataAttribute)
{
_hasNonCDataAttributes = true;
}
if (e.DefaultAttDefs != null)
{
_hasDefaultAttributes = true;
}
}
elements = _undeclaredElementDecls;
}
}
//
// IDtdInfo interface
//
#region IDtdInfo Members
bool IDtdInfo.HasDefaultAttributes
{
get
{
return _hasDefaultAttributes;
}
}
bool IDtdInfo.HasNonCDataAttributes
{
get
{
return _hasNonCDataAttributes;
}
}
IDtdAttributeListInfo IDtdInfo.LookupAttributeList(string prefix, string localName)
{
XmlQualifiedName qname = new XmlQualifiedName(prefix, localName);
SchemaElementDecl elementDecl;
if (!_elementDecls.TryGetValue(qname, out elementDecl))
{
_undeclaredElementDecls.TryGetValue(qname, out elementDecl);
}
return elementDecl;
}
IEnumerable<IDtdAttributeListInfo> IDtdInfo.GetAttributeLists()
{
foreach (SchemaElementDecl elemDecl in _elementDecls.Values)
{
IDtdAttributeListInfo eleDeclAsAttList = (IDtdAttributeListInfo)elemDecl;
yield return eleDeclAsAttList;
}
}
IDtdEntityInfo IDtdInfo.LookupEntity(string name)
{
if (_generalEntities == null)
{
return null;
}
XmlQualifiedName qname = new XmlQualifiedName(name);
SchemaEntity entity;
if (_generalEntities.TryGetValue(qname, out entity))
{
return entity;
}
return null;
}
XmlQualifiedName IDtdInfo.Name
{
get { return _docTypeName; }
}
string IDtdInfo.InternalDtdSubset
{
get { return _internalDtdSubset; }
}
#endregion
}
}
| |
/*
* HashAlgorithm.cs - Implementation of the
* "System.Security.Cryptography.HashAlgorithm" class.
*
* Copyright (C) 2002, 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Security.Cryptography
{
#if CONFIG_CRYPTO
using System;
using System.IO;
public abstract class HashAlgorithm : ICryptoTransform, IDisposable
{
// Internal state which is set by subclasses.
protected int HashSizeValue;
protected byte[] HashValue;
protected int State;
// Create an instance of the default hash algorithm.
public static HashAlgorithm Create()
{
return (HashAlgorithm)
(CryptoConfig.CreateFromName
(CryptoConfig.HashDefault, null));
}
// Create an instance of a specific hash algorithm.
public static HashAlgorithm Create(String hashName)
{
return (HashAlgorithm)
(CryptoConfig.CreateFromName(hashName, null));
}
// Determine if we can reuse this transform object.
public virtual bool CanReuseTransform
{
get
{
return true;
}
}
// Determine if multiple blocks can be transformed.
public virtual bool CanTransformMultipleBlocks
{
get
{
return true;
}
}
// Get the value of the computed hash code.
public virtual byte[] Hash
{
get
{
if(HashValue != null)
{
return HashValue;
}
throw new CryptographicUnexpectedOperationException
(_("Crypto_HashNotComputed"));
}
}
// Get the size of the computed hash value.
public virtual int HashSize
{
get
{
return HashSizeValue;
}
}
// Get the input block size.
public virtual int InputBlockSize
{
get
{
return 1;
}
}
// Get the output block size.
public virtual int OutputBlockSize
{
get
{
return 1;
}
}
// Clear the state within this object.
public void Clear()
{
((IDisposable)this).Dispose();
}
// Dispose the state within this object.
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(HashValue != null)
{
Array.Clear(HashValue, 0, HashValue.Length);
HashValue = null;
}
State = 0;
}
// Compute the hash value for a specified byte array.
public byte[] ComputeHash(byte[] buffer)
{
HashCore(buffer, 0, buffer.Length);
HashValue = HashFinal();
Initialize();
return HashValue;
}
// Compute the hash value for a region within a byte array.
public byte[] ComputeHash(byte[] buffer, int offset, int count)
{
HashCore(buffer, offset, count);
HashValue = HashFinal();
Initialize();
return HashValue;
}
// Compute the hash value for a specified input stream.
public byte[] ComputeHash(Stream inputStream)
{
byte[] buf = new byte [512];
int len;
while((len = inputStream.Read(buf, 0, 512)) > 0)
{
HashCore(buf, 0, len);
}
HashValue = HashFinal();
Initialize();
return HashValue;
}
// Transform an input block into an output block.
public int TransformBlock(byte[] inputBuffer, int inputOffset,
int inputCount, byte[] outputBuffer,
int outputOffset)
{
State = 1;
HashCore(inputBuffer, inputOffset, inputCount);
Array.Copy(inputBuffer, inputOffset,
outputBuffer, outputOffset, inputCount);
return inputCount;
}
// Transform the final input block into a hash value.
public byte[] TransformFinalBlock(byte[] inputBuffer,
int inputOffset,
int inputCount)
{
HashCore(inputBuffer, inputOffset, inputCount);
HashValue = HashFinal();
Initialize();
byte[] outbuf = new byte [inputCount];
Array.Copy(inputBuffer, inputOffset, outbuf, 0, inputCount);
State = 0;
return outbuf;
}
// Initialize the hash algorithm.
public abstract void Initialize();
// Write data to the underlying hash algorithm.
protected abstract void HashCore(byte[] array, int ibStart, int cbSize);
// Finalize the hash and return the final hash value.
protected abstract byte[] HashFinal();
// Access "HashCore" from elsewhere in this library.
internal void InternalHashCore(byte[] array, int ibStart, int cbSize)
{
HashCore(array, ibStart, cbSize);
}
// Access "HashFinal" from elsewhere in this library.
internal byte[] InternalHashFinal()
{
return HashFinal();
}
}; // class HashAlgorithm
#endif // CONFIG_CRYPTO
}; // namespace System.Security.Cryptography
| |
using System;
using System.IO;
using NUnit.Framework;
using SolidGui.Engine;
using SolidGui.Model;
namespace SolidGui.Tests.Engine
{
[TestFixture]
public class SfmReader_Read_Test
{
[TestFixtureSetUp]
public void Init()
{
}
public static string InputProduces (string input)
{
string result = "";
using (var e = new EnvironmentForTest())
{
// parse the input
var reader = SfmRecordReader.CreateFromText(input);
var dict = new SfmDictionary();
SfmLexEntry lexEntry;
while (true)
{
if (!reader.ReadRecord()) break;
lexEntry = SfmLexEntry.CreateFromReaderFields(reader.Fields);
dict.AddRecord(lexEntry, null);
}
dict.SfmHeader = reader.HeaderLinux;
// save it to a file
dict.SaveAs(e.TempFilePath, null);
// read it back in
using (var r = new StreamReader(e.TempFilePath))
{
result = r.ReadToEnd();
r.Close();
}
}
return result;
}
[Test]
public void ReadTabAsSpace_Correct()
{
const string sfm = "header\t header\r\n" +
"\\lx\ta\tb\t \tc\t\r\n" +
"\\ge d\t\r\n\t" +
"\\lx e";
const string sfm2 = "header header\r\n" +
"\\lx a b c \r\n" +
"\\ge d \r\n " +
"\\lx e\r\n";
var result = InputProduces(sfm);
Assert.AreEqual(sfm2, result);
}
[Test]
// I'm not sure how important this is, but without this behavior lines like those last two will take three saves to "settle down". -JMC
public void ReadPreserveSeparatorBeforeEmpty_Correct()
{
string sfm = "hh\r\n" +
"\\lx a\r\n" +
"\\ge b\r\n\r\n" +
"\\ge c \r\n\r\n" +
"\\lx \r\n" +
"\\sn\r\n" +
"\\ge \r\n" +
"\\ge \r\n\r\n" +
"\\lx\r\n \r\n";
var result = InputProduces(sfm);
var result2 = InputProduces(result); // chain it
Assert.AreEqual(sfm, result);
Assert.AreEqual(result2, result);
}
[Test]
public void CreateFromFilePath_ExistingFile_ReadsOk()
{
using (var e = new EnvironmentForTest())
{
const string input = @"
\lx test1
\cc fire
\sn
\cc foo
\sn
\cc bar
\lx test2
\lx test3";
using (var writer = new StreamWriter(e.TempFilePath))
{
writer.Write(input);
writer.Close();
}
using (var reader = new StreamReader(e.TempFilePath))
{
var output = reader.ReadToEnd();
reader.Close();
Assert.AreEqual(input, output);
}
}
}
[Test]
public void EmptySFM_HeaderCount_0()
{
const string sfm = @"";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.AreEqual(false, result);
Assert.AreEqual("", r.HeaderLinux);
// Assert.AreEqual(0, r.Header.Count);
}
[Test]
public void HeaderOnly_Header_Correct()
{
const string sfm = "\\_sh v3.0 269 MDF 4.0 (alternate hierarchy)\r\n" +
"\\_DateStampHasFourDigitYear\r\n";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.AreEqual(false, result);
Assert.AreEqual(sfm, r.HeaderLinux);
/*
Assert.AreEqual(2, r.Header.Count);
Assert.AreEqual("_sh", r.Header[0].Marker);
Assert.AreEqual("v3.0 269 MDF 4.0 (alternate hierarchy)", r.Header[0].Value);
Assert.AreEqual("_DateStampHasFourDigitYear", r.Header[1].Marker);
Assert.AreEqual("", r.Header[1].Value);
*/
}
[Test]
public void EmptySFMRecordRead_False()
{
const string sfm = @"";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.AreEqual(false, result);
}
[Test]
public void HeaderOnlySFMRecordRead_False()
{
const string sfm = "\\_sh v3.0 269 MDF 4.0 (alternate hierarchy)\n" +
"\\_DateStampHasFourDigitYear\n";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.AreEqual(false, result);
}
[Test]
public void ReadTinyRecord_Correct()
{
const string sfm = "\\lx";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.IsTrue(result);
Assert.AreEqual("", r.HeaderLinux);
Assert.AreEqual(1, r.FieldCount);
Assert.AreEqual("", r.Value("lx"));
result = r.ReadRecord();
Assert.IsFalse(result);
}
[Test]
public void ReadNoHeader_Correct()
{
const string sfm = "\\lx a\n" +
"\\ge b\n";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.IsTrue(result);
Assert.AreEqual("", r.HeaderLinux);
/*
Assert.AreEqual(0, r.Header.Count);
Assert.AreEqual(2, r.FieldCount);
Assert.AreEqual("a", r.Value("lx"));
Assert.AreEqual("b", r.Value("ge"));
*/
}
[Test]
public void ReadHeaderConfusing_Correct()
{
const string header = "\\lxh\r\n" +
" \\lx not \\lx\r\n" +
"\\lxHaha\r\n";
const string sfm = header + "\\lx finally!";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.IsTrue(result);
Assert.AreEqual(header, r.HeaderLinux);
}
[Test]
public void ReadNoHeaderTabDelimited_Correct()
{
const string sfm = "\\lx\ta\n" +
"\\ge\tb\n";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.IsTrue(result);
Assert.AreEqual("", r.HeaderLinux);
Assert.AreEqual(2, r.FieldCount);
Assert.AreEqual("a", r.Value("lx"));
Assert.AreEqual("b", r.Value("ge"));
}
[Test]
public void ReadEmptyValue_Correct()
{
const string sfm = "\\lx a\r\n" +
"\\ge\n" +
"\\de\r\n \r\n" +
"\\dt";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.IsTrue(result);
Assert.AreEqual("", r.HeaderLinux);
Assert.AreEqual(4, r.FieldCount);
Assert.AreEqual("a", r.Value("lx"));
Assert.AreEqual("", r.Value("ge"));
Assert.AreEqual("", r.Value("de"));
}
[Test]
public void ReadEmptyKey_Correct()
{
const string sfm = "\\lx a\n" +
"\\\n" +
"\\ge b\n" +
"\\\n" +
"\\\n";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.IsTrue(result);
Assert.AreEqual("", r.HeaderLinux);
Assert.AreEqual(5, r.FieldCount);
Assert.AreEqual("a", r.Value("lx"));
Assert.AreEqual("b", r.Value("ge"));
Assert.AreEqual("", r.Key(1));
Assert.AreEqual("", r.Key(3));
Assert.AreEqual("", r.Key(4));
}
[Test]
public void ReadEmptyLxEmptyKey_Correct()
{
const string sfm = "head\r\n" +
"\\lx\n" +
"\\\n" +
"\\ge b\n" +
"\\lx"
;
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.IsTrue(result);
Assert.AreEqual("head\r\n", r.HeaderLinux);
Assert.AreEqual(3, r.FieldCount);
Assert.AreEqual("", r.Value("lx"));
Assert.AreEqual("b", r.Value("ge"));
Assert.AreEqual("lx", r.Key(0));
Assert.AreEqual("", r.Key(1));
Assert.AreEqual("ge", r.Key(2));
result = r.ReadRecord();
Assert.IsTrue(result);
Assert.AreEqual("head\r\n", r.HeaderLinux);
Assert.AreEqual(1, r.FieldCount);
Assert.AreEqual("", r.Value("lx"));
}
[Test]
[Ignore("but re-implement??")] // JMC:! maybe this choice I made was wrong: "No longer the job of the main parser; will handle with regex in the UI. -JMC 2013-09"
public void ReadIndentedMarker_Correct()
{
const string sfm = "\\lx a\n" +
" \\ge b\n";
var r = SfmRecordReader.CreateFromText(sfm);
r.AllowLeadingWhiteSpace = true;
bool result = r.ReadRecord();
Assert.IsTrue(result);
Assert.AreEqual("", r.HeaderLinux);
Assert.AreEqual(2, r.FieldCount);
Assert.AreEqual("a", r.Value("lx"));
Assert.AreEqual("b", r.Value("ge"));
}
[Test]
public void ReadBackslashInValue_Correct()
{
const string sfm = "\\lx a\n" +
"\\ge \\b \\zblah\\z\n";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.IsTrue(result);
Assert.AreEqual("", r.HeaderLinux);
Assert.AreEqual(2, r.FieldCount);
Assert.AreEqual("a", r.Value("lx"));
Assert.AreEqual("\\b \\zblah\\z", r.Value("ge"));
}
[Test]
public void ReadWrappedText_Correct ()
{
const string sfm = "\\lx a\n" +
"\\ge b\nc";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord ();
Assert.IsTrue (result);
Assert.AreEqual("", r.HeaderLinux);
Assert.AreEqual(2, r.FieldCount);
Assert.AreEqual ("a", r.Value ("lx"));
Assert.AreEqual ("b\r\nc", r.Value ("ge"));
}
[Test]
public void ReadNewlinesPreserved_Correct()
{
string sfm = "\\lx a\n" +
"b\n\n\r" +
"\\ge c\n\n" +
"\\rf\nd\n\n" +
"\\dt\n\n" +
"\\lx f"; //note that \dt is both final and empty, plus extra trailing
//string sfm = "\\lx a\n\\dt\n\n\\lx f";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.IsTrue(result);
Assert.AreEqual("", r.HeaderLinux);
Assert.AreEqual(4, r.FieldCount);
Assert.AreEqual("a\r\nb", r.Value("lx"));
Assert.AreEqual("\r\n\r\n\r\n", r.Trailing("lx"));
Assert.AreEqual("\r\n\r\n", r.Trailing("ge"));
Assert.AreEqual("\r\n\r\n", r.Trailing("rf"));
var tmp = r.Trailing("dt");
Assert.IsTrue("\r\n\r\n" == tmp);
// Assert.IsTrue( ("\r\n\r\n" == tmp || " \r\n\r\n" == tmp) ); // either is acceptable
r.ReadRecord();
Assert.AreEqual(1, r.FieldCount);
Assert.AreEqual("\r\n", r.Trailing("lx"));
}
private SfmRecordReader ReadOneRecordData()
{
const string sfm = "\\_sh v3.0 269 MDF 4.0 (alternate hierarchy)\n" +
"\\_DateStampHasFourDigitYear\n" +
"\\lx a\n" +
"\\ge b\n";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.AreEqual(true, result);
return r;
}
private SfmRecordReader ReadTwoRecordData()
{
const string sfm = "\\_sh v3.0 269 MDF 4.0 (alternate hierarchy)\n" +
"\\_DateStampHasFourDigitYear\n" +
"\\lx a\n" +
"\\ge b\n" +
"\\lx c\n" +
"\\gn d\n";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.AreEqual(true, result);
return r;
}
[Test]
public void EqualizeNewlines()
{
string sfm = "header Windows 1\r\nLinux 2\n\nOldMac 2\r\rCombo \r\r\n\n\r";
string h = "header Windows 1\r\nLinux 2\r\n\r\nOldMac 2\r\n\r\nCombo \r\n\r\n\r\n\r\n";
sfm += "\\lx Windows 1\r\nLinux 2\n\nOldMac 2\r\rCombo \r\r\n\n\r";
string val = " Windows 1\r\nLinux 2\r\n\r\nOldMac 2\r\n\r\nCombo";
string trail = " \r\n\r\n\r\n\r\n";
var r = SfmRecordReader.CreateFromText(sfm);
bool result = r.ReadRecord();
Assert.AreEqual(true, result);
Assert.AreEqual(h, r.HeaderLinux);
Assert.AreEqual(val, r.Value("lx"));
Assert.AreEqual(trail, r.Field(0).Trailing);
}
[Test]
public void OneSFMRecordReadToEOF_Correct()
{
var r = ReadOneRecordData();
Assert.AreEqual(2, r.FieldCount);
Assert.AreEqual("lx", r.Key(0));
}
[Test]
public void SplitTrailingSpaceSimple()
{
string val = "value\r\n";
var f = new SfmField();
f.SetSplitValue(val);
Assert.AreEqual(f.Value, "value");
Assert.AreEqual(f.Trailing, "\r\n");
}
[Test]
public void SplitTrailingSpaceLots()
{
string val = "long long \r\n wrapped field. . .";
string val2 = " \r \r\n\r\n\t\r\n";
var f = new SfmField();
f.SetSplitValue(val + val2);
Assert.AreEqual(f.Value, val);
Assert.AreEqual(f.Trailing, val2);
}
[Test]
public void SplitTrailingEmptyData()
{
string val = " \r \r\n\r\n\t\r\n";
var f = new SfmField();
f.SetSplitValue(val);
Assert.AreEqual(f.Value, "");
Assert.AreEqual(f.Trailing, " " + val);
f.SetSplitValue(val, "\n");
Assert.AreEqual(f.Value, "");
Assert.AreEqual(f.Trailing, "\r\n" + val);
}
[Test]
public void OneSFMRecordReadToNextMarker_Correct()
{
var r = ReadTwoRecordData();
Assert.AreEqual(2, r.FieldCount);
Assert.AreEqual("ge", r.Key(1));
r.ReadRecord();
Assert.AreEqual(2, r.FieldCount);
Assert.AreEqual("gn", r.Key(1));
}
[Test]
public void OneSFMRecordRead_Key0_Correct()
{
var r = ReadTwoRecordData();
Assert.AreEqual("lx", r.Key(0));
}
[Test]
public void OneSFMRecordRead_Key1_Correct()
{
var r = ReadTwoRecordData();
Assert.AreEqual("ge", r.Key(1));
}
[Test]
public void RecordStartLine_Correct()
{
var r = ReadTwoRecordData();
Assert.AreEqual(3, r.RecordStartLine);
r.ReadRecord();
Assert.AreEqual(5, r.RecordStartLine);
}
[Test]
public void RecordEndLine_Correct()
{
var r = ReadTwoRecordData();
Assert.AreEqual(4, r.RecordEndLine);
r.ReadRecord();
Assert.AreEqual(7, r.RecordEndLine);
}
[Test]
public void Record_EOF_Correct()
{
var r = ReadTwoRecordData(); // Reads the first record for us.
bool result = r.ReadRecord();
Assert.IsTrue(result);
result = r.ReadRecord();
Assert.IsFalse(result);
}
[Test]
public void RecordID_Correct()
{
var r = ReadTwoRecordData();
Assert.AreEqual(0, r.RecordID);
bool result = r.ReadRecord();
Assert.IsTrue(result); // Should be for two records.
Assert.AreEqual(1, r.RecordID);
}
public class EnvironmentForTest : IDisposable
{
public EnvironmentForTest()
{
TempFilePath = Path.GetTempFileName();
}
public string TempFilePath { get; private set; }
public void Dispose()
{
File.Delete(TempFilePath);
}
}
}
}
| |
//
// GtkExtensions.cs
//
// Author:
// Vsevolod Kukol <[email protected]>
//
// Copyright (c) 2014 Vsevolod Kukol
//
// 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 Gdk;
namespace Xwt.GtkBackend
{
public static class Gtk2Extensions
{
public static void SetHasWindow (this Gtk.Widget widget, bool value)
{
if (value)
widget.WidgetFlags &= ~Gtk.WidgetFlags.NoWindow;
else
widget.WidgetFlags |= Gtk.WidgetFlags.NoWindow;
}
public static bool GetHasWindow (this Gtk.Widget widget)
{
return !widget.IsNoWindow;
}
public static void SetAppPaintable (this Gtk.Widget widget, bool value)
{
if (value)
widget.WidgetFlags |= Gtk.WidgetFlags.AppPaintable;
else
widget.WidgetFlags &= ~Gtk.WidgetFlags.AppPaintable;
}
public static void SetStateActive(this Gtk.Widget widget)
{
widget.State = Gtk.StateType.Active;
}
public static void SetStateNormal(this Gtk.Widget widget)
{
widget.State = Gtk.StateType.Normal;
}
public static void AddSignalHandler (this Gtk.Widget widget, string name, Delegate handler, Type args_type)
{
var signal = GLib.Signal.Lookup (widget, name, args_type);
signal.AddDelegate (handler);
}
public static void RemoveSignalHandler (this Gtk.Widget widget, string name, Delegate handler)
{
var signal = GLib.Signal.Lookup (widget, name);
signal.RemoveDelegate (handler);
}
public static Gdk.Pixbuf ToPixbuf (this Gdk.Window window, int src_x, int src_y, int width, int height)
{
return Gdk.Pixbuf.FromDrawable (window, Gdk.Colormap.System, src_x, src_y, 0, 0, width, height);
}
public static Gtk.CellRenderer[] GetCellRenderers (this Gtk.TreeViewColumn column)
{
return column.CellRenderers;
}
public static Gdk.DragAction GetSelectedAction (this Gdk.DragContext context)
{
return context.Action;
}
public static Gdk.Atom[] ListTargets (this Gdk.DragContext context)
{
return context.Targets;
}
public static void AddContent (this Gtk.Dialog dialog, Gtk.Widget widget, bool expand = true, bool fill = true, uint padding = 0)
{
dialog.VBox.PackStart (widget, expand, fill, padding);
}
public static void AddContent (this Gtk.MessageDialog dialog, Gtk.Widget widget, bool expand = true, bool fill = true, uint padding = 0)
{
dialog.GetMessageArea().PackStart (widget, expand, fill, padding);
}
public static void SetContentSpacing (this Gtk.Dialog dialog, int spacing)
{
dialog.VBox.Spacing = spacing;
}
public static void SetTextColumn (this Gtk.ComboBox comboBox, int column)
{
((Gtk.ComboBoxEntry)comboBox).TextColumn = column;
}
public static void FixContainerLeak (this Gtk.Container c)
{
GtkWorkarounds.FixContainerLeak (c);
}
public static Xwt.Drawing.Color GetBackgroundColor (this Gtk.Widget widget)
{
return widget.GetBackgroundColor (Gtk.StateType.Normal);
}
public static Xwt.Drawing.Color GetBackgroundColor (this Gtk.Widget widget, Gtk.StateType state)
{
return widget.Style.Background (state).ToXwtValue ();
}
public static void SetBackgroundColor (this Gtk.Widget widget, Xwt.Drawing.Color color)
{
widget.SetBackgroundColor (Gtk.StateType.Normal, color);
}
public static void SetBackgroundColor (this Gtk.Widget widget, Gtk.StateType state, Xwt.Drawing.Color color)
{
widget.ModifyBg (state, color.ToGtkValue ());
}
public static void SetChildBackgroundColor (this Gtk.Container container, Xwt.Drawing.Color color)
{
foreach (var widget in container.Children)
widget.ModifyBg (Gtk.StateType.Normal, color.ToGtkValue ());
}
public static string GetText (this Gtk.TextInsertedArgs args)
{
return args.Text;
}
public static void RenderPlaceholderText (this Gtk.Entry entry, Gtk.ExposeEventArgs args, string placeHolderText, ref Pango.Layout layout)
{
// The Entry's GdkWindow is the top level window onto which
// the frame is drawn; the actual text entry is drawn into a
// separate window, so we can ensure that for themes that don't
// respect HasFrame, we never ever allow the base frame drawing
// to happen
if (args.Event.Window == entry.GdkWindow)
return;
if (entry.Text.Length > 0)
return;
RenderPlaceholderText_internal (entry, args, placeHolderText, ref layout, entry.Xalign, 0.5f, 1, 0);
}
public static void RenderPlaceholderText (this Gtk.TextView textView, Gtk.ExposeEventArgs args, string placeHolderText, ref Pango.Layout layout)
{
if (args.Event.Window != textView.GetWindow (Gtk.TextWindowType.Text))
return;
if (textView.Buffer.Text.Length > 0)
return;
float xalign = 0;
switch (textView.Justification) {
case Gtk.Justification.Center: xalign = 0.5f; break;
case Gtk.Justification.Right: xalign = 1; break;
}
RenderPlaceholderText_internal (textView, args, placeHolderText, ref layout, xalign, 0.0f, 3, 0);
}
static void RenderPlaceholderText_internal (Gtk.Widget widget, Gtk.ExposeEventArgs args, string placeHolderText, ref Pango.Layout layout, float xalign, float yalign, int xpad, int ypad)
{
if (layout == null) {
layout = new Pango.Layout (widget.PangoContext);
layout.FontDescription = widget.PangoContext.FontDescription.Copy ();
}
int wh, ww;
args.Event.Window.GetSize (out ww, out wh);
int width, height;
layout.SetText (placeHolderText);
layout.GetPixelSize (out width, out height);
int x = xpad + (int)((ww - width) * xalign);
int y = ypad + (int)((wh - height) * yalign);
using (var gc = new Gdk.GC (args.Event.Window)) {
gc.Copy (widget.Style.TextGC (Gtk.StateType.Normal));
Xwt.Drawing.Color color_a = widget.Style.Base (Gtk.StateType.Normal).ToXwtValue ();
Xwt.Drawing.Color color_b = widget.Style.Text (Gtk.StateType.Normal).ToXwtValue ();
gc.RgbFgColor = color_b.BlendWith (color_a, 0.5).ToGtkValue ();
args.Event.Window.DrawLayout (gc, x, y, layout);
}
}
public static double GetSliderPosition (this Gtk.Scale scale)
{
Gtk.Orientation orientation;
if (scale is Gtk.HScale)
orientation = Gtk.Orientation.Horizontal;
else if (scale is Gtk.VScale)
orientation = Gtk.Orientation.Vertical;
else
throw new InvalidOperationException ("Can not obtain slider position from " + scale.GetType ());
var padding = (int)scale.StyleGetProperty ("focus-padding");
var slwidth = Convert.ToDouble (scale.StyleGetProperty ("slider-width"));
int orientationSize;
if (orientation == Gtk.Orientation.Horizontal)
orientationSize = scale.Allocation.Width - (2 * padding);
else
orientationSize = scale.Allocation.Height - (2 * padding);
double prct = 0;
if (scale.Adjustment.Lower >= 0) {
prct = (scale.Value / (scale.Adjustment.Upper - scale.Adjustment.Lower));
} else if (scale.Adjustment.Upper <= 0) {
prct = (Math.Abs (scale.Value) / Math.Abs (scale.Adjustment.Lower - scale.Adjustment.Upper));
} else if (scale.Adjustment.Lower < 0) {
if (scale.Value >= 0)
prct = 0.5 + ((scale.Value / 2) / scale.Adjustment.Upper);
else
prct = 0.5 - Math.Abs ((scale.Value / 2) / scale.Adjustment.Lower);
}
if (orientation == Gtk.Orientation.Vertical || scale.Inverted)
prct = 1 - prct;
return (int)(((orientationSize - (slwidth)) * prct) + (slwidth / 2));
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
public enum MegaIntegrator
{
Euler,
Verlet,
VerletTimeCorrected,
MidPoint,
}
public class BaryVert2D
{
public int gx; // Grid position
public int gy;
public Vector2 bary;
}
[System.Serializable]
public class Constraint2D
{
public bool active;
public int p1;
public int p2;
public float length;
public Vector2 pos;
public int contype = 0;
public Transform obj;
public static Constraint2D CreatePointTargetCon(int _p1, Transform trans)
{
Constraint2D con = new Constraint2D();
con.p1 = _p1;
con.active = true;
con.contype = 2;
con.obj = trans;
return con;
}
public static Constraint2D CreateLenCon(int _p1, int _p2, float _len)
{
Constraint2D con = new Constraint2D();
con.p1 = _p1;
con.p2 = _p2;
con.length = _len;
con.active = true;
con.contype = 0;
return con;
}
public static Constraint2D CreatePointCon(int _p1, Vector2 _pos)
{
Constraint2D con = new Constraint2D();
con.p1 = _p1;
con.pos = _pos;
con.active = true;
con.contype = 1;
return con;
}
public void Apply(MegaSoft2D soft)
{
switch ( contype )
{
case 0: ApplyLengthConstraint2D(soft); break;
case 1: ApplyPointConstraint2D(soft); break;
//case 2: ApplyPointTargetConstraint2D(soft); break;
}
}
// Can have a one that has a range to keep in
public void ApplyLengthConstraint2D(MegaSoft2D soft)
{
if ( active && soft.applyConstraints )
{
//calculate direction
Vector2 direction = soft.masses[p2].pos - soft.masses[p1].pos;
//calculate current length
float currentLength = direction.magnitude;
//check for zero vector
if ( currentLength != 0.0f ) //direction.x != 0.0f || direction.y != 0.0f || direction.y != 0.0f )
{
direction.x /= currentLength;
direction.y /= currentLength;
//move to goal positions
Vector2 moveVector = 0.5f * (currentLength - length) * direction;
soft.masses[p1].pos.x += moveVector.x;
soft.masses[p1].pos.y += moveVector.y;
soft.masses[p2].pos.x += -moveVector.x;
soft.masses[p2].pos.y += -moveVector.y;
}
}
}
public void ApplyPointConstraint2D(MegaSoft2D soft)
{
if ( active )
soft.masses[p1].pos = pos;
}
public void ApplyAngleConstraint(MegaSoft2D soft)
{
}
}
[System.Serializable]
public class Mass2D
{
public Vector2 pos;
public Vector2 last;
public Vector2 force;
public Vector2 vel;
public Vector2 posc;
public Vector2 velc;
public Vector2 forcec;
public Vector2 coef1;
public Vector2 coef2;
public float mass;
public float oneovermass;
public Mass2D(float m, Vector2 p)
{
mass = m;
oneovermass = 1.0f / mass;
pos = p;
last = p;
force = Vector2.zero;
vel = Vector2.zero;
}
}
[System.Serializable]
public class Spring2D
{
public int p1;
public int p2;
public float restLen;
public float ks;
public float kd;
public float len;
public Spring2D(int _p1, int _p2, float _ks, float _kd, MegaSoft2D mod)
{
p1 = _p1;
p2 = _p2;
ks = _ks;
kd = _kd;
restLen = Vector2.Distance(mod.masses[p1].pos, mod.masses[p2].pos);
len = restLen;
}
public void doCalculateSpringForce(MegaSoft2D mod)
{
Vector2 deltaP = mod.masses[p1].pos - mod.masses[p2].pos;
float dist = deltaP.magnitude; //VectorLength(&deltaP); // Magnitude of deltaP
float Hterm = (dist - restLen) * ks; // Ks * (dist - rest)
Vector2 deltaV = mod.masses[p1].vel - mod.masses[p2].vel;
float Dterm = (Vector2.Dot(deltaV, deltaP) * kd) / dist; // Damping Term
Vector2 springForce = deltaP * (1.0f / dist);
springForce *= -(Hterm + Dterm);
mod.masses[p1].force += springForce;
mod.masses[p2].force -= springForce;
}
public void doCalculateSpringForce1(MegaSoft2D mod)
{
//get the direction vector
Vector2 direction = mod.masses[p1].pos - mod.masses[p2].pos;
//check for zero vector
if ( direction != Vector2.zero )
{
//get length
float currLength = direction.magnitude;
//normalize
direction = direction.normalized;
//add spring force
Vector2 force = -ks * ((currLength - restLen) * direction);
//add spring damping force
//float v = (currLength - len) / mod.timeStep;
//force += -kd * v * direction;
//apply the equal and opposite forces to the objects
mod.masses[p1].force += force;
mod.masses[p2].force -= force;
len = currLength;
}
}
public void doCalculateSpringForce2(MegaSoft2D mod)
{
Vector2 deltaP = mod.masses[p1].pos - mod.masses[p2].pos;
float dist = deltaP.magnitude; //VectorLength(&deltaP); // Magnitude of deltaP
float Hterm = (dist - restLen) * ks; // Ks * (dist - rest)
//Vector2 deltaV = mod.masses[p1].vel - mod.masses[p2].vel;
float v = (dist - len); // / mod.timeStep;
float Dterm = (v * kd) / dist; // Damping Term
Vector2 springForce = deltaP * (1.0f / dist);
springForce *= -(Hterm + Dterm);
mod.masses[p1].force += springForce;
mod.masses[p2].force -= springForce;
}
}
// Want verlet for this as no collision will be done, solver type enum
// need to add contact forces for weights on bridge
[System.Serializable]
public class MegaSoft2D
{
public List<Mass2D> masses = new List<Mass2D>();
public List<Spring2D> springs = new List<Spring2D>();
public List<Constraint2D> constraints = new List<Constraint2D>();
public Vector2 gravity = new Vector2(0.0f, -9.81f);
public float airdrag = 0.999f;
public float friction = 1.0f;
public float timeStep = 0.01f;
public int iters = 4;
public MegaIntegrator method = MegaIntegrator.Verlet;
public bool applyConstraints = true;
void doCalculateForceseuler()
{
for ( int i = 0; i < masses.Count; i++ )
{
masses[i].force = masses[i].mass * gravity;
masses[i].force += masses[i].forcec;
}
for ( int i = 0; i < springs.Count; i++ )
springs[i].doCalculateSpringForce(this);
}
void doCalculateForces()
{
for ( int i = 0; i < masses.Count; i++ )
{
masses[i].force = masses[i].mass * gravity;
masses[i].force += masses[i].forcec;
}
for ( int i = 0; i < springs.Count; i++ )
springs[i].doCalculateSpringForce1(this);
}
void doIntegration1(float dt)
{
doCalculateForceseuler(); // Calculate forces, only changes _f
/* Then do correction step by integration with central average (Heun) */
for ( int i = 0; i < masses.Count; i++ )
{
masses[i].last = masses[i].pos;
masses[i].vel += dt * masses[i].force * masses[i].oneovermass;
masses[i].pos += masses[i].vel * dt;
masses[i].vel *= friction;
}
DoConstraints();
}
public float floor = 0.0f;
void DoCollisions(float dt)
{
for ( int i = 0; i < masses.Count; i++ )
{
if ( masses[i].pos.y < floor )
masses[i].pos.y = floor;
}
}
// Change the base code over to Skeel or similar
//public bool UseVerlet = false;
// Can do drag per point using a curve
// perform the verlet integration step
void VerletIntegrate(float t, float lastt)
{
doCalculateForces(); // Calculate forces, only changes _f
float t2 = t * t;
/* Then do correction step by integration with central average (Heun) */
for ( int i = 0; i < masses.Count; i++ )
{
Vector2 last = masses[i].pos;
masses[i].pos += airdrag * (masses[i].pos - masses[i].last) + masses[i].force * masses[i].oneovermass * t2; // * t;
masses[i].last = last;
}
DoConstraints();
}
// Pointless
void VerletIntegrateTC(float t, float lastt)
{
doCalculateForces(); // Calculate forces, only changes _f
float t2 = t * t;
float dt = t / lastt;
/* Then do correction step by integration with central average (Heun) */
for ( int i = 0; i < masses.Count; i++ )
{
Vector2 last = masses[i].pos;
masses[i].pos += airdrag * (masses[i].pos - masses[i].last) * dt + (masses[i].force * masses[i].oneovermass) * t2; // * t;
masses[i].last = last;
}
DoConstraints();
}
void MidPointIntegrate(float t)
{
}
// Satisfy constraints
public void DoConstraints()
{
for ( int i = 0; i < iters; i++ )
{
for ( int c = 0; c < constraints.Count; c++ )
{
constraints[c].Apply(this);
}
}
}
public float lasttime = 0.0f;
public float simtime = 0.0f;
public void Update()
{
if ( masses == null )
return;
simtime += Time.deltaTime; // * fudge;
if ( Time.deltaTime == 0.0f )
{
simtime = 0.01f;
}
if ( timeStep <= 0.0f )
timeStep = 0.001f;
float ts = 0.0f;
if ( lasttime == 0.0f )
lasttime = timeStep;
while ( simtime > 0.0f) //timeStep ) //0.0f )
{
simtime -= timeStep;
ts = timeStep;
switch ( method )
{
case MegaIntegrator.Euler:
doIntegration1(ts);
break;
case MegaIntegrator.Verlet:
VerletIntegrate(ts, lasttime); //timeStep);
break;
case MegaIntegrator.VerletTimeCorrected:
VerletIntegrateTC(ts, lasttime); //timeStep);
break;
case MegaIntegrator.MidPoint:
MidPointIntegrate(ts); //timeStep);
break;
}
lasttime = ts;
}
}
}
| |
// ArrayElementGroup.cs
//
// Authors: Lluis Sanchez Gual <[email protected]>
// Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2008 Novell, Inc (http://www.novell.com)
// Copyright (c) 2012 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.Generic;
using System.Text;
using Mono.Debugging.Client;
using Mono.Debugging.Backend;
namespace Mono.Debugging.Evaluation
{
public class ArrayElementGroup: RemoteFrameObject, IObjectValueSource
{
readonly ICollectionAdaptor array;
readonly EvaluationContext ctx;
int[] baseIndices;
int[] dimensions;
int firstIndex;
int lastIndex;
const int MaxChildCount = 150;
public ArrayElementGroup (EvaluationContext ctx, ICollectionAdaptor array)
: this (ctx, array, new int [0])
{
}
public ArrayElementGroup (EvaluationContext ctx, ICollectionAdaptor array, int[] baseIndices)
: this (ctx, array, baseIndices, 0, -1)
{
}
public ArrayElementGroup (EvaluationContext ctx, ICollectionAdaptor array, int[] baseIndices, int firstIndex, int lastIndex)
{
this.array = array;
this.ctx = ctx;
this.dimensions = array.GetDimensions ();
this.baseIndices = baseIndices;
this.firstIndex = firstIndex;
this.lastIndex = lastIndex;
}
public bool IsRange {
get { return lastIndex != -1; }
}
public ObjectValue CreateObjectValue ()
{
Connect ();
var sb = new StringBuilder ("[");
for (int i = 0; i < baseIndices.Length; i++) {
if (i > 0)
sb.Append (", ");
sb.Append (baseIndices[i].ToString ());
}
if (IsRange) {
if (baseIndices.Length > 0)
sb.Append (", ");
sb.Append (firstIndex.ToString ()).Append ("..").Append (lastIndex.ToString ());
}
if (dimensions.Length > 1 && baseIndices.Length < dimensions.Length)
sb.Append (", ...");
sb.Append ("]");
ObjectValue res = ObjectValue.CreateObject (this, new ObjectPath (sb.ToString ()), "", "", ObjectValueFlags.ArrayElement|ObjectValueFlags.ReadOnly|ObjectValueFlags.NoRefresh, null);
res.ChildSelector = "";
return res;
}
public ObjectValue[] GetChildren (EvaluationOptions options)
{
return GetChildren (new ObjectPath ("this"), -1, -1, options);
}
public ObjectValue[] GetChildren (ObjectPath path, int firstItemIndex, int count, EvaluationOptions options)
{
EvaluationContext cctx = ctx.WithOptions (options);
if (path.Length > 1) {
// Looking for children of an array element
int[] idx = StringToIndices (path [1]);
object obj = array.GetElement (idx);
return cctx.Adapter.GetObjectValueChildren (cctx, new ArrayObjectSource (array, path[1]), obj, firstItemIndex, count);
}
int lowerBound;
int upperBound;
bool isLastDimension;
if (dimensions.Length > 1) {
int rank = baseIndices.Length;
lowerBound = array.GetLowerBounds () [rank];
upperBound = lowerBound + dimensions [rank] - 1;
isLastDimension = rank == dimensions.Length - 1;
} else {
lowerBound = array.GetLowerBounds () [0];
upperBound = lowerBound + dimensions [0] - 1;
isLastDimension = true;
}
int len;
int initalIndex;
if (!IsRange) {
initalIndex = lowerBound;
len = upperBound + 1 - lowerBound;
} else {
initalIndex = firstIndex;
len = lastIndex - firstIndex + 1;
}
if (firstItemIndex == -1) {
firstItemIndex = 0;
count = len;
}
// Make sure the group doesn't have too many elements. If so, divide
int div = 1;
while (len / div > MaxChildCount)
div *= 10;
if (div == 1 && isLastDimension) {
// Return array elements
ObjectValue[] values = new ObjectValue [count];
ObjectPath newPath = new ObjectPath ("this");
int[] curIndex = new int [baseIndices.Length + 1];
Array.Copy (baseIndices, curIndex, baseIndices.Length);
string curIndexStr = IndicesToString (baseIndices);
if (baseIndices.Length > 0)
curIndexStr += ",";
curIndex [curIndex.Length - 1] = initalIndex + firstItemIndex;
var elems = array.GetElements (curIndex, System.Math.Min (values.Length, upperBound + 1));
for (int n = 0; n < values.Length; n++) {
int index = n + initalIndex + firstItemIndex;
string sidx = curIndexStr + index;
ObjectValue val;
string ename = "[" + sidx.Replace (",", ", ") + "]";
if (index > upperBound)
val = ObjectValue.CreateUnknown (sidx);
else {
curIndex [curIndex.Length - 1] = index;
val = cctx.Adapter.CreateObjectValue (cctx, this, newPath.Append (sidx), elems.GetValue (n), ObjectValueFlags.ArrayElement);
if (elems.GetValue (n) != null && !cctx.Adapter.IsNull (cctx, elems.GetValue (n))) {
TypeDisplayData tdata = cctx.Adapter.GetTypeDisplayData (cctx, cctx.Adapter.GetValueType (cctx, elems.GetValue (n)));
if (!string.IsNullOrEmpty (tdata.NameDisplayString)) {
try {
ename = cctx.Adapter.EvaluateDisplayString (cctx, elems.GetValue (n), tdata.NameDisplayString);
} catch (MissingMemberException) {
// missing property or otherwise malformed DebuggerDisplay string
}
}
}
}
val.Name = ename;
values [n] = val;
}
return values;
}
if (!isLastDimension && div == 1) {
// Return an array element group for each index
var list = new List<ObjectValue> ();
for (int i=0; i<count; i++) {
int index = i + initalIndex + firstItemIndex;
ObjectValue val;
// This array must be created at every call to avoid sharing
// changes with all array groups
int[] curIndex = new int [baseIndices.Length + 1];
Array.Copy (baseIndices, curIndex, baseIndices.Length);
curIndex [curIndex.Length - 1] = index;
if (index > upperBound)
val = ObjectValue.CreateUnknown ("");
else {
ArrayElementGroup grp = new ArrayElementGroup (cctx, array, curIndex);
val = grp.CreateObjectValue ();
}
list.Add (val);
}
return list.ToArray ();
} else {
// Too many elements. Split the array.
// Don't make divisions of 10 elements, min is 100
if (div == 10)
div = 100;
// Create the child groups
int i = initalIndex + firstItemIndex;
len += i;
var list = new List<ObjectValue> ();
while (i < len) {
int end = i + div - 1;
if (end >= len)
end = len - 1;
ArrayElementGroup grp = new ArrayElementGroup (cctx, array, baseIndices, i, end);
list.Add (grp.CreateObjectValue ());
i += div;
}
return list.ToArray ();
}
}
internal static string IndicesToString (int[] indices)
{
var sb = new StringBuilder ();
for (int i = 0; i < indices.Length; i++) {
if (i > 0)
sb.Append (',');
sb.Append (indices[i].ToString ());
}
return sb.ToString ();
}
internal static int[] StringToIndices (string str)
{
var sidx = str.Split (',');
var idx = new int [sidx.Length];
for (int i = 0; i < sidx.Length; i++)
idx[i] = int.Parse (sidx[i]);
return idx;
}
public static string GetArrayDescription (int[] bounds)
{
if (bounds.Length == 0)
return "[...]";
var sb = new StringBuilder ("[");
for (int i = 0; i < bounds.Length; i++) {
if (i > 0)
sb.Append (", ");
sb.Append (bounds [i].ToString ());
}
sb.Append ("]");
return sb.ToString ();
}
public EvaluationResult SetValue (ObjectPath path, string value, EvaluationOptions options)
{
if (path.Length != 2)
throw new NotSupportedException ();
int[] idx = StringToIndices (path [1]);
object val;
try {
EvaluationContext cctx = ctx.Clone ();
EvaluationOptions ops = options ?? cctx.Options;
ops.AllowMethodEvaluation = true;
ops.AllowTargetInvoke = true;
cctx.Options = ops;
ValueReference var = ctx.Evaluator.Evaluate (ctx, value, array.ElementType);
val = var.Value;
val = ctx.Adapter.Convert (ctx, val, array.ElementType);
array.SetElement (idx, val);
} catch {
val = array.GetElement (idx);
}
try {
return ctx.Evaluator.TargetObjectToExpression (ctx, val);
} catch (Exception ex) {
ctx.WriteDebuggerError (ex);
return new EvaluationResult ("? (" + ex.Message + ")");
}
}
public ObjectValue GetValue (ObjectPath path, EvaluationOptions options)
{
if (path.Length != 2)
throw new NotSupportedException ();
int[] idx = StringToIndices (path [1]);
object elem = array.GetElement (idx);
EvaluationContext cctx = ctx.WithOptions (options);
ObjectValue val = cctx.Adapter.CreateObjectValue (cctx, this, path, elem, ObjectValueFlags.ArrayElement);
if (elem != null && !cctx.Adapter.IsNull (cctx, elem)) {
TypeDisplayData tdata = cctx.Adapter.GetTypeDisplayData (cctx, cctx.Adapter.GetValueType (cctx, elem));
if (!string.IsNullOrEmpty (tdata.NameDisplayString)) {
try {
val.Name = cctx.Adapter.EvaluateDisplayString (cctx, elem, tdata.NameDisplayString);
} catch (MissingMemberException) {
// missing property or otherwise malformed DebuggerDisplay string
}
}
}
return val;
}
public object GetRawValue (ObjectPath path, EvaluationOptions options)
{
if (path.Length != 2)
throw new NotSupportedException ();
int[] idx = StringToIndices (path [1]);
object elem = array.GetElement (idx);
EvaluationContext cctx = ctx.WithOptions (options);
return cctx.Adapter.ToRawValue (cctx, new ArrayObjectSource (array, idx), elem);
}
public void SetRawValue (ObjectPath path, object value, EvaluationOptions options)
{
if (path.Length != 2)
throw new NotSupportedException ();
int[] idx = StringToIndices (path [1]);
EvaluationContext cctx = ctx.WithOptions (options);
object val = cctx.Adapter.FromRawValue (cctx, value);
array.SetElement (idx, val);
}
}
class ArrayObjectSource: IObjectSource
{
readonly ICollectionAdaptor source;
readonly string path;
public ArrayObjectSource (ICollectionAdaptor source, string path)
{
this.source = source;
this.path = path;
}
public ArrayObjectSource (ICollectionAdaptor source, int[] index)
{
this.source = source;
this.path = ArrayElementGroup.IndicesToString (index);
}
public object Value {
get {
return source.GetElement (ArrayElementGroup.StringToIndices (path));
}
set {
source.SetElement (ArrayElementGroup.StringToIndices (path), value);
}
}
}
}
| |
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------
// <copyright file="XmlFile.cs">(c) 2017 Mike Fourie and Contributors (https://github.com/mikefourie/MSBuildExtensionPack) under MIT License. See https://opensource.org/licenses/MIT </copyright>
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Xml
{
using System;
using System.Globalization;
using System.Xml;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>AddAttribute</i> (<b>Required: </b>File, Element or XPath, Key, Value <b>Optional:</b>Prefix, Namespaces, RetryCount)</para>
/// <para><i>AddElement</i> (<b>Required: </b>File, Element and ParentElement or Element and XPath, <b>Optional:</b> Prefix, Key, Value, Namespaces, RetryCount, InnerText, InnerXml, InsertBeforeXPath / InsertAfterXPath)</para>
/// <para><i>ReadAttribute</i> (<b>Required: </b>File, XPath <b>Optional:</b> Namespaces <b>Output:</b> Value)</para>
/// <para><i>ReadElements</i> (<b>Required: </b>File, XPath <b>Optional:</b> Namespaces, ReadChildrenToMetadata <b>Output: </b> Elements). Attributes are added as metadata. Use ReadChildrenToMetadata to add first level children as metadata</para>
/// <para><i>ReadElementText</i> (<b>Required: </b>File, XPath <b>Optional:</b> Namespaces <b>Output:</b> Value)</para>
/// <para><i>ReadElementXml</i> (<b>Required: </b>File, XPath <b>Optional:</b> Namespaces <b>Output:</b> Value)</para>
/// <para><i>RemoveAttribute</i> (<b>Required: </b>File, Key, Element or XPath <b>Optional:</b> Namespaces, RetryCount)</para>
/// <para><i>RemoveElement</i> (<b>Required: </b>File, Element and ParentElement or Element and XPath <b>Optional:</b> Namespaces, RetryCount)</para>
/// <para><i>UpdateAttribute</i> (<b>Required: </b>File, XPath <b>Optional:</b> Namespaces, Key, Value, RetryCount)</para>
/// <para><i>UpdateElement</i> (<b>Required: </b>File, XPath <b>Optional:</b> Namespaces, InnerText, InnerXml, RetryCount)</para>
/// <para><b>Remote Execution Support:</b> NA</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <ItemGroup>
/// <ConfigSettingsToDeploy Include="c:\machine.config">
/// <Action>RemoveElement</Action>
/// <Element>processModel</Element>
/// <ParentElement>/configuration/system.web</ParentElement>
/// </ConfigSettingsToDeploy>
/// <ConfigSettingsToDeploy Include="c:\machine.config">
/// <Action>AddElement</Action>
/// <Element>processModel</Element>
/// <ParentElement>/configuration/system.web</ParentElement>
/// </ConfigSettingsToDeploy>
/// <ConfigSettingsToDeploy Include="c:\machine.config">
/// <Action>AddAttribute</Action>
/// <Key>enable</Key>
/// <ValueToAdd>true</ValueToAdd>
/// <Element>/configuration/system.web/processModel</Element>
/// </ConfigSettingsToDeploy>
/// <ConfigSettingsToDeploy Include="c:\machine.config">
/// <Action>AddAttribute</Action>
/// <Key>timeout</Key>
/// <ValueToAdd>Infinite</ValueToAdd>
/// <Element>/configuration/system.web/processModel</Element>
/// </ConfigSettingsToDeploy>
/// <ConfigSettingsToDeploy Include="c:\machine.config">
/// <Action>RemoveAttribute</Action>
/// <Key>timeout</Key>
/// <Element>/configuration/system.web/processModel</Element>
/// </ConfigSettingsToDeploy>
/// <XMLConfigElementsToAdd Include="c:\machine.config">
/// <XPath>/configuration/configSections</XPath>
/// <Name>section</Name>
/// <KeyAttributeName>name</KeyAttributeName>
/// <KeyAttributeValue>enterpriseLibrary.ConfigurationSource</KeyAttributeValue>
/// </XMLConfigElementsToAdd>
/// <XMLConfigElementsToAdd Include="c:\machine.config">
/// <XPath>/configuration</XPath>
/// <Name>enterpriseLibrary.ConfigurationSource</Name>
/// <KeyAttributeName>selectedSource</KeyAttributeName>
/// <KeyAttributeValue>MyKeyAttribute</KeyAttributeValue>
/// </XMLConfigElementsToAdd>
/// <XMLConfigElementsToAdd Include="c:\machine.config">
/// <XPath>/configuration/enterpriseLibrary.ConfigurationSource</XPath>
/// <Name>sources</Name>
/// </XMLConfigElementsToAdd>
/// <XMLConfigElementsToAdd Include="c:\machine.config">
/// <XPath>/configuration/enterpriseLibrary.ConfigurationSource/sources</XPath>
/// <Name>add</Name>
/// <KeyAttributeName>name</KeyAttributeName>
/// <KeyAttributeValue>MyKeyAttribute</KeyAttributeValue>
/// </XMLConfigElementsToAdd>
/// <XMLConfigAttributesToAdd Include="c:\machine.config">
/// <XPath>/configuration/configSections/section[@name='enterpriseLibrary.ConfigurationSource']</XPath>
/// <Name>type</Name>
/// <Value>Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</Value>
/// </XMLConfigAttributesToAdd>
/// <XMLConfigAttributesToAdd Include="c:\machine.config">
/// <XPath>/configuration/enterpriseLibrary.ConfigurationSource/sources/add[@name='MyKeyAttribute']</XPath>
/// <Name>type</Name>
/// <Value>MyKeyAttribute.Common, MyKeyAttribute.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=fb2f49125f05d89</Value>
/// </XMLConfigAttributesToAdd>
/// <XMLConfigElementsToDelete Include="c:\machine.config">
/// <XPath>/configuration/configSections/section[@name='enterpriseLibrary.ConfigurationSource']</XPath>
/// </XMLConfigElementsToDelete>
/// <XMLConfigElementsToDelete Include="c:\machine.config">
/// <XPath>/configuration/enterpriseLibrary.ConfigurationSource[@selectedSource='MyKeyAttribute']</XPath>
/// </XMLConfigElementsToDelete>
/// </ItemGroup>
/// <Target Name="Default">
/// <!-- Work through some manipulations that don't use XPath-->
/// <MSBuild.ExtensionPack.Xml.XmlFile TaskAction="%(ConfigSettingsToDeploy.Action)" File="%(ConfigSettingsToDeploy.Identity)" Key="%(ConfigSettingsToDeploy.Key)" Value="%(ConfigSettingsToDeploy.ValueToAdd)" Element="%(ConfigSettingsToDeploy.Element)" ParentElement="%(ConfigSettingsToDeploy.ParentElement)" Condition="'%(ConfigSettingsToDeploy.Identity)'!=''"/>
/// <!-- Work through some manipulations that use XPath-->
/// <MSBuild.ExtensionPack.Xml.XmlFile TaskAction="RemoveElement" File="%(XMLConfigElementsToDelete.Identity)" XPath="%(XMLConfigElementsToDelete.XPath)" Condition="'%(XMLConfigElementsToDelete.Identity)'!=''"/>
/// <MSBuild.ExtensionPack.Xml.XmlFile TaskAction="AddElement" File="%(XMLConfigElementsToAdd.Identity)" Key="%(XMLConfigElementsToAdd.KeyAttributeName)" Value="%(XMLConfigElementsToAdd.KeyAttributeValue)" Element="%(XMLConfigElementsToAdd.Name)" XPath="%(XMLConfigElementsToAdd.XPath)" Condition="'%(XMLConfigElementsToAdd.Identity)'!=''"/>
/// <MSBuild.ExtensionPack.Xml.XmlFile TaskAction="AddAttribute" File="%(XMLConfigAttributesToAdd.Identity)" Key="%(XMLConfigAttributesToAdd.Name)" Value="%(XMLConfigAttributesToAdd.Value)" XPath="%(XMLConfigAttributesToAdd.XPath)" Condition="'%(XMLConfigAttributesToAdd.Identity)'!=''"/>
/// <MSBuild.ExtensionPack.Xml.XmlFile TaskAction="UpdateElement" File="c:\machine.config" XPath="/configuration/configSections/section[@name='system.data']" InnerText="NewValue"/>
/// <MSBuild.ExtensionPack.Xml.XmlFile TaskAction="UpdateAttribute" File="c:\machine.config" XPath="/configuration/configSections/section[@name='system.data']" Key="SomeAttribute" Value="NewValue"/>
/// </Target>
/// <!-- The following illustrates Namespace usage -->
/// <ItemGroup>
/// <Namespaces Include="Mynamespace">
/// <Prefix>me</Prefix>
/// <Uri>http://mynamespace</Uri>
/// </Namespaces>
/// <XMLConfigElementsToDelete1 Include="c:\test.xml">
/// <XPath>//me:MyNodes/me:sources</XPath>
/// </XMLConfigElementsToDelete1>
/// <XMLConfigElementsToAdd1 Include="c:\test.xml">
/// <XPath>//me:MyNodes</XPath>
/// <Name>sources</Name>
/// </XMLConfigElementsToAdd1>
/// </ItemGroup>
/// <Target Name="DefaultWithNameSpace">
/// <MSBuild.ExtensionPack.Xml.XmlFile TaskAction="RemoveElement" Namespaces="@(Namespaces)" File="%(XMLConfigElementsToDelete1.Identity)" XPath="%(XMLConfigElementsToDelete1.XPath)" Condition="'%(XMLConfigElementsToDelete1.Identity)'!=''"/>
/// <MSBuild.ExtensionPack.Xml.XmlFile TaskAction="AddElement" Namespaces="@(Namespaces)" File="%(XMLConfigElementsToAdd1.Identity)" Key="%(XMLConfigElementsToAdd1.KeyAttributeName)" Value="%(XMLConfigElementsToAdd1.KeyAttributeValue)" Element="%(XMLConfigElementsToAdd1.Name)" XPath="%(XMLConfigElementsToAdd1.XPath)" Condition="'%(XMLConfigElementsToAdd1.Identity)'!=''"/>
/// </Target>
/// <ItemGroup>
/// <Namespaces2 Include="Mynamespace">
/// <Prefix>xs</Prefix>
/// <Uri>http://www.w3.org/2001/XMLSchema</Uri>
/// </Namespaces2>
/// </ItemGroup>
/// <Target Name="InsertBeforeXPath">
/// <MSBuild.ExtensionPack.Xml.XmlFile TaskAction="AddElement"
/// File="d:\a\tempinsertbeforexpath.xml"
/// Namespaces="@(Namespaces2)"
/// ParentElement="/xs:schema"
/// Prefix="xs"
/// Element="test"
/// Key="name"
/// Value ="new"
/// InsertBeforeXPath="/xs:schema/xs:log[@name='logger']"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class XmlFile : BaseTask
{
private const string AddAttributeTaskAction = "AddAttribute";
private const string AddElementTaskAction = "AddElement";
private const string ReadAttributeTaskAction = "ReadAttribute";
private const string ReadElementsTaskAction = "ReadElements";
private const string ReadElementTextTaskAction = "ReadElementText";
private const string ReadElementXmlTaskAction = "ReadElementXml";
private const string RemoveAttributeTaskAction = "RemoveAttribute";
private const string RemoveElementTaskAction = "RemoveElement";
private const string UpdateAttributeTaskAction = "UpdateAttribute";
private const string UpdateElementTaskAction = "UpdateElement";
private XmlDocument xmlFileDoc;
private XmlNamespaceManager namespaceManager;
private XmlNodeList elements;
/// <summary>
/// Sets the element. For AddElement, if the element exists, it's InnerText / InnerXml will be updated
/// </summary>
public string Element { get; set; }
/// <summary>
/// Sets the InnerText.
/// </summary>
public string InnerText { get; set; }
/// <summary>
/// Sets the InnerXml.
/// </summary>
public string InnerXml { get; set; }
/// <summary>
/// Sets the Prefix used for an added element/attribute, prefix must exists in Namespaces.
/// </summary>
public string Prefix { get; set; }
/// <summary>
/// Sets the parent element.
/// </summary>
public string ParentElement { get; set; }
/// <summary>
/// Sets the Attribute key.
/// </summary>
public string Key { get; set; }
/// <summary>
/// Gets or Sets the Attribute key value. Also stores the result of any Read TaskActions
/// </summary>
[Output]
public string Value { get; set; }
/// <summary>
/// Gets the elements selected using ReadElements
/// </summary>
[Output]
public ITaskItem[] Elements { get; set; }
/// <summary>
/// Sets the file.
/// </summary>
[Required]
public ITaskItem File { get; set; }
/// <summary>
/// Specifies the XPath to be used
/// </summary>
public string XPath { get; set; }
/// <summary>
/// Specifies the XPath to be used to control where a new element is added. The Xpath must resolve to single node.
/// </summary>
public string InsertBeforeXPath { get; set; }
/// <summary>
/// Specifies the XPath to be used to control where a new element is added. The Xpath must resolve to single node.
/// </summary>
public string InsertAfterXPath { get; set; }
/// <summary>
/// TaskItems specifiying "Prefix" and "Uri" attributes for use with the specified XPath
/// </summary>
public ITaskItem[] Namespaces { get; set; }
/// <summary>
/// Sets a value indicating how many times to retry saving the file, e.g. if files are temporarily locked. Default is 5. The retry occurs every 5 seconds.
/// </summary>
public int RetryCount { get; set; } = 5;
/// <summary>
/// When using ReadElements, specifies whether the first level child elements should be added as metadata. Child elements will override any read attributes of the same name. Default is false.
/// </summary>
public bool ReadChildrenToMetadata { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
if (!System.IO.File.Exists(this.File.ItemSpec))
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "File not found: {0}", this.File.ItemSpec));
return;
}
this.xmlFileDoc = new XmlDocument();
try
{
this.xmlFileDoc.Load(this.File.ItemSpec);
}
catch (Exception ex)
{
this.LogTaskWarning(ex.Message);
bool loaded = false;
int count = 1;
while (!loaded && count <= this.RetryCount)
{
this.LogTaskMessage(MessageImportance.High, string.Format(CultureInfo.InvariantCulture, "Load failed, trying again in 5 seconds. Attempt {0} of {1}", count, this.RetryCount));
System.Threading.Thread.Sleep(5000);
count++;
try
{
this.xmlFileDoc.Load(this.File.ItemSpec);
loaded = true;
}
catch
{
this.LogTaskWarning(ex.Message);
}
}
if (loaded != true)
{
throw;
}
}
this.namespaceManager = this.GetNamespaceManagerForDoc();
if (!string.IsNullOrEmpty(this.XPath))
{
this.elements = this.xmlFileDoc.SelectNodes(this.XPath, this.namespaceManager);
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "XmlFile: {0}", this.File.ItemSpec));
switch (this.TaskAction)
{
case AddElementTaskAction:
this.AddElement();
break;
case AddAttributeTaskAction:
this.AddAttribute();
break;
case ReadAttributeTaskAction:
this.ReadAttribute();
break;
case ReadElementsTaskAction:
this.ReadElements();
break;
case ReadElementTextTaskAction:
case ReadElementXmlTaskAction:
this.ReadElement();
break;
case RemoveAttributeTaskAction:
this.RemoveAttribute();
break;
case RemoveElementTaskAction:
this.RemoveElement();
break;
case UpdateElementTaskAction:
this.UpdateElement();
break;
case UpdateAttributeTaskAction:
this.UpdateAttribute();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private void ReadElements()
{
if (string.IsNullOrEmpty(this.XPath))
{
this.Log.LogError("XPath is Required");
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Read Elements: {0}", this.XPath));
XmlNodeList nodelist = this.xmlFileDoc.SelectNodes(this.XPath, this.namespaceManager);
if (nodelist != null)
{
this.Elements = new ITaskItem[nodelist.Count];
int i = 0;
foreach (XmlNode node in nodelist)
{
ITaskItem newItem = new TaskItem(node.Name);
if (node.Attributes != null)
{
foreach (XmlAttribute a in node.Attributes)
{
newItem.SetMetadata(a.Name, a.Value);
}
}
if (this.ReadChildrenToMetadata)
{
foreach (XmlNode child in node.ChildNodes)
{
newItem.SetMetadata(child.Name, child.InnerText);
}
}
this.Elements[i] = newItem;
i++;
}
}
}
private void ReadElement()
{
if (string.IsNullOrEmpty(this.XPath))
{
this.Log.LogError("XPath is Required");
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Read Element: {0}", this.XPath));
XmlNode node = this.xmlFileDoc.SelectSingleNode(this.XPath, this.namespaceManager);
if (node != null && (node.NodeType == XmlNodeType.Element || node.NodeType == XmlNodeType.Document))
{
this.Value = this.TaskAction == ReadElementTextTaskAction ? node.InnerText : node.InnerXml;
}
}
private void ReadAttribute()
{
if (string.IsNullOrEmpty(this.XPath))
{
this.Log.LogError("XPath is Required");
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Read Attribute: {0}", this.XPath));
XmlNode node = this.xmlFileDoc.SelectSingleNode(this.XPath, this.namespaceManager);
if (node != null && node.NodeType == XmlNodeType.Attribute)
{
this.Value = node.Value;
}
}
private void UpdateElement()
{
if (string.IsNullOrEmpty(this.XPath))
{
this.Log.LogError("XPath is Required");
return;
}
if (string.IsNullOrEmpty(this.InnerXml))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Update Element: {0}. InnerText: {1}", this.XPath, this.InnerText));
if (this.elements != null && this.elements.Count > 0)
{
foreach (XmlNode element in this.elements)
{
element.InnerText = this.InnerText;
}
this.TrySave();
}
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Update Element: {0}. InnerXml: {1}", this.XPath, this.InnerXml));
if (this.elements != null && this.elements.Count > 0)
{
foreach (XmlNode element in this.elements)
{
element.InnerXml = this.InnerXml;
}
this.TrySave();
}
}
private void UpdateAttribute()
{
if (string.IsNullOrEmpty(this.XPath))
{
this.Log.LogError("XPath is Required");
return;
}
if (string.IsNullOrEmpty(this.Key))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Update Attribute: {0}. Value: {1}", this.XPath, this.Value));
XmlNode node = this.xmlFileDoc.SelectSingleNode(this.XPath, this.namespaceManager);
if (node != null && node.NodeType == XmlNodeType.Attribute)
{
node.Value = this.Value;
}
}
else
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Update Attribute: {0} @ {1}. Value: {2}", this.Key, this.XPath, this.Value));
if (this.elements != null && this.elements.Count > 0)
{
foreach (XmlNode element in this.elements)
{
XmlAttribute attNode = element.Attributes.GetNamedItem(this.Key) as XmlAttribute;
if (attNode != null)
{
attNode.Value = this.Value;
}
}
}
}
this.TrySave();
}
private void RemoveAttribute()
{
if (string.IsNullOrEmpty(this.XPath))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Remove Attribute: {0}", this.Key));
XmlNode elementNode = this.xmlFileDoc.SelectSingleNode(this.Element, this.namespaceManager);
if (elementNode == null)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Element not found: {0}", this.Element));
return;
}
XmlAttribute attNode = elementNode.Attributes.GetNamedItem(this.Key) as XmlAttribute;
if (attNode != null)
{
elementNode.Attributes.Remove(attNode);
this.TrySave();
}
}
else
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Remove Attribute: {0}", this.Key));
if (this.elements != null && this.elements.Count > 0)
{
foreach (XmlNode element in this.elements)
{
XmlAttribute attNode = element.Attributes.GetNamedItem(this.Key) as XmlAttribute;
if (attNode != null)
{
element.Attributes.Remove(attNode);
this.TrySave();
}
}
}
}
}
private void AddAttribute()
{
if (string.IsNullOrEmpty(this.XPath))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Set Attribute: {0}={1}", this.Key, this.Value));
XmlNode elementNode = this.xmlFileDoc.SelectSingleNode(this.Element, this.namespaceManager);
if (elementNode == null)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Element not found: {0}", this.Element));
return;
}
XmlNode attNode = elementNode.Attributes[this.Key] ?? elementNode.Attributes.Append(this.CreateAttribute());
attNode.Value = this.Value;
this.TrySave();
}
else
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Set Attribute: {0}={1}", this.Key, this.Value));
if (this.elements != null && this.elements.Count > 0)
{
foreach (XmlNode element in this.elements)
{
XmlNode attrib = element.Attributes[this.Key] ?? element.Attributes.Append(this.CreateAttribute());
attrib.Value = this.Value;
}
this.TrySave();
}
}
}
private XmlAttribute CreateAttribute()
{
XmlAttribute xmlAttribute;
if (string.IsNullOrEmpty(this.Prefix))
{
xmlAttribute = this.xmlFileDoc.CreateAttribute(this.Key);
}
else
{
string prefixNamespace = this.namespaceManager.LookupNamespace(this.Prefix);
if (string.IsNullOrEmpty(prefixNamespace))
{
this.Log.LogError("Prefix not defined in Namespaces in parameters: " + this.Prefix);
return null;
}
xmlAttribute = this.xmlFileDoc.CreateAttribute(this.Prefix, this.Key, prefixNamespace);
}
return xmlAttribute;
}
private XmlNamespaceManager GetNamespaceManagerForDoc()
{
XmlNamespaceManager localnamespaceManager = new XmlNamespaceManager(this.xmlFileDoc.NameTable);
// If we have had namespace declarations specified add them to the Namespace Mgr for the XML Document.
if (this.Namespaces != null && this.Namespaces.Length > 0)
{
foreach (ITaskItem item in this.Namespaces)
{
string prefix = item.GetMetadata("Prefix");
string uri = item.GetMetadata("Uri");
localnamespaceManager.AddNamespace(prefix, uri);
}
}
return localnamespaceManager;
}
private void AddElement()
{
if (string.IsNullOrEmpty(this.XPath))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Add Element: {0}", this.Element));
XmlNode parentNode = this.xmlFileDoc.SelectSingleNode(this.ParentElement, this.namespaceManager);
if (parentNode == null)
{
this.Log.LogError("ParentElement not found: " + this.ParentElement);
return;
}
// Ensure node does not already exist
XmlNode newNode = this.xmlFileDoc.SelectSingleNode(this.ParentElement + "/" + this.Element, this.namespaceManager);
if (newNode == null)
{
newNode = this.CreateElement();
if (!string.IsNullOrEmpty(this.Key))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Add Attribute: {0} to: {1}", this.Key, this.Element));
XmlAttribute attNode = this.xmlFileDoc.CreateAttribute(this.Key);
attNode.Value = this.Value;
newNode.Attributes.Append(attNode);
}
if (string.IsNullOrEmpty(this.InsertAfterXPath) && string.IsNullOrEmpty(this.InsertBeforeXPath))
{
parentNode.AppendChild(newNode);
}
else if (!string.IsNullOrEmpty(this.InsertAfterXPath))
{
parentNode.InsertAfter(newNode, parentNode.SelectSingleNode(this.InsertAfterXPath, this.namespaceManager));
}
else if (!string.IsNullOrEmpty(this.InsertBeforeXPath))
{
parentNode.InsertBefore(newNode, parentNode.SelectSingleNode(this.InsertBeforeXPath, this.namespaceManager));
}
this.TrySave();
}
else
{
if (!string.IsNullOrEmpty(this.InnerText))
{
newNode.InnerText = this.InnerText;
}
else if (!string.IsNullOrEmpty(this.InnerXml))
{
newNode.InnerXml = this.InnerXml;
}
this.TrySave();
}
}
else
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Add Element: {0}", this.XPath));
if (this.elements != null && this.elements.Count > 0)
{
foreach (XmlNode element in this.elements)
{
XmlNode newNode = this.CreateElement();
if (!string.IsNullOrEmpty(this.Key))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Add Attribute: {0} to: {1}", this.Key, this.Element));
XmlAttribute attNode = this.xmlFileDoc.CreateAttribute(this.Key);
attNode.Value = this.Value;
newNode.Attributes.Append(attNode);
}
element.AppendChild(newNode);
}
this.TrySave();
}
}
}
private XmlNode CreateElement()
{
XmlNode newNode;
if (string.IsNullOrEmpty(this.Prefix))
{
newNode = this.xmlFileDoc.CreateElement(this.Element, this.xmlFileDoc.DocumentElement.NamespaceURI);
}
else
{
string prefixNamespace = this.namespaceManager.LookupNamespace(this.Prefix);
if (string.IsNullOrEmpty(prefixNamespace))
{
this.Log.LogError("Prefix not defined in Namespaces in parameters: " + this.Prefix);
return null;
}
newNode = this.xmlFileDoc.CreateElement(this.Prefix, this.Element, prefixNamespace);
}
if (!string.IsNullOrEmpty(this.InnerText))
{
newNode.InnerText = this.InnerText;
}
else if (!string.IsNullOrEmpty(this.InnerXml))
{
newNode.InnerXml = this.InnerXml;
}
return newNode;
}
private void RemoveElement()
{
if (string.IsNullOrEmpty(this.XPath))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Remove Element: {0}", this.Element));
XmlNode parentNode = this.xmlFileDoc.SelectSingleNode(this.ParentElement, this.namespaceManager);
if (parentNode == null)
{
this.Log.LogError("ParentElement not found: " + this.ParentElement);
return;
}
XmlNode nodeToRemove = this.xmlFileDoc.SelectSingleNode(this.ParentElement + "/" + this.Element, this.namespaceManager);
if (nodeToRemove != null)
{
parentNode.RemoveChild(nodeToRemove);
this.TrySave();
}
}
else
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Remove Element: {0}", this.XPath));
if (this.elements != null && this.elements.Count > 0)
{
foreach (XmlNode element in this.elements)
{
element.ParentNode.RemoveChild(element);
}
this.TrySave();
}
}
}
private void TrySave()
{
try
{
if (this.xmlFileDoc.DocumentType != null)
{
this.xmlFileDoc.ReplaceChild(this.xmlFileDoc.CreateDocumentType(this.xmlFileDoc.DocumentType.Name, this.xmlFileDoc.DocumentType.PublicId, this.xmlFileDoc.DocumentType.SystemId, null), this.xmlFileDoc.DocumentType);
}
this.xmlFileDoc.Save(this.File.ItemSpec);
}
catch (Exception ex)
{
this.LogTaskWarning(ex.Message);
bool saved = false;
int count = 1;
while (!saved && count <= this.RetryCount)
{
this.LogTaskMessage(MessageImportance.High, string.Format(CultureInfo.InvariantCulture, "Save failed, trying again in 5 seconds. Attempt {0} of {1}", count, this.RetryCount));
System.Threading.Thread.Sleep(5000);
count++;
try
{
this.xmlFileDoc.Save(this.File.ItemSpec);
saved = true;
}
catch
{
this.LogTaskWarning(ex.Message);
}
}
if (saved != true)
{
throw;
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
using System.Reflection;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure.Identity;
namespace Azure.Core.TestFramework
{
/// <summary>
/// Represents the ambient environment in which the test suite is
/// being run.
/// </summary>
public abstract class TestEnvironment
{
private static readonly string RepositoryRoot;
private readonly string _prefix;
private TokenCredential _credential;
private TestRecording _recording;
private readonly Dictionary<string, string> _environmentFile = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
protected TestEnvironment(string serviceName)
{
_prefix = serviceName.ToUpperInvariant() + "_";
if (RepositoryRoot == null)
{
throw new InvalidOperationException("Unexpected error, repository root not found");
}
var sdkDirectory = Path.Combine(RepositoryRoot, "sdk", serviceName);
if (!Directory.Exists(sdkDirectory))
{
throw new InvalidOperationException($"SDK directory {sdkDirectory} not found");
}
var testEnvironmentFile = Path.Combine(RepositoryRoot, "sdk", serviceName, "test-resources.json.env");
if (File.Exists(testEnvironmentFile))
{
var json = JsonDocument.Parse(
ProtectedData.Unprotect(File.ReadAllBytes(testEnvironmentFile), null, DataProtectionScope.CurrentUser)
);
foreach (var property in json.RootElement.EnumerateObject())
{
_environmentFile[property.Name] = property.Value.GetString();
}
}
}
static TestEnvironment()
{
// Traverse parent directories until we find an "artifacts" directory
// parent of that would become a repo root for test environment resolution purposes
var directoryInfo = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);
while (directoryInfo.Name != "artifacts")
{
if (directoryInfo.Parent == null)
{
return;
}
directoryInfo = directoryInfo.Parent;
}
RepositoryRoot = directoryInfo?.Parent?.FullName;
}
public RecordedTestMode? Mode { get; set; }
/// <summary>
/// The name of the Azure subscription containing the resource group to be used for Live tests. Recorded.
/// </summary>
public string SubscriptionId => GetRecordedVariable("SUBSCRIPTION_ID");
/// <summary>
/// The name of the Azure resource group to be used for Live tests. Recorded.
/// </summary>
public string ResourceGroup => GetRecordedVariable("RESOURCE_GROUP");
/// <summary>
/// The location of the Azure resource group to be used for Live tests (e.g. westus2). Recorded.
/// </summary>
public string Location => GetRecordedVariable("LOCATION");
/// <summary>
/// The environment of the Azure resource group to be used for Live tests (e.g. AzureCloud). Recorded.
/// </summary>
public string AzureEnvironment => GetRecordedVariable("ENVIRONMENT");
/// <summary>
/// The name of the Azure Active Directory tenant that holds the service principal to use during Live tests. Recorded.
/// </summary>
public string TenantId => GetRecordedVariable("TENANT_ID");
/// <summary>
/// The URL of the Azure Resource Manager to be used for management plane operations. Recorded.
/// </summary>
public string ResourceManagerUrl => GetRecordedOptionalVariable("RESOURCE_MANAGER_URL");
/// <summary>
/// The URL of the Azure Service Management endpoint to be used for management plane authentication. Recorded.
/// </summary>
public string ServiceManagementUrl => GetRecordedOptionalVariable("SERVICE_MANAGEMENT_URL");
/// <summary>
/// The URL of the Azure Authority host to be used for authentication. Recorded.
/// </summary>
public string AuthorityHostUrl => GetRecordedOptionalVariable("AZURE_AUTHORITY_HOST");
/// <summary>
/// The suffix for Azure Storage accounts for the active cloud environment, such as "core.windows.net". Recorded.
/// </summary>
public string StorageEndpointSuffix => GetRecordedOptionalVariable("STORAGE_ENDPOINT_SUFFIX");
/// <summary>
/// The client id of the Azure Active Directory service principal to use during Live tests. Recorded.
/// </summary>
public string ClientId => GetRecordedVariable("CLIENT_ID");
/// <summary>
/// The client secret of the Azure Active Directory service principal to use during Live tests. Not recorded.
/// </summary>
public string ClientSecret => GetVariable("CLIENT_SECRET");
public TokenCredential Credential
{
get
{
if (_credential != null)
{
return _credential;
}
if (Mode == RecordedTestMode.Playback)
{
_credential = new MockCredential();
}
else
{
_credential = new ClientSecretCredential(
GetVariable("TENANT_ID"),
GetVariable("CLIENT_ID"),
GetVariable("CLIENT_SECRET")
);
}
return _credential;
}
}
/// <summary>
/// Returns and records an environment variable value when running live or recorded value during playback.
/// </summary>
protected string GetRecordedOptionalVariable(string name)
{
return GetRecordedOptionalVariable(name, _ => { });
}
/// <summary>
/// Returns and records an environment variable value when running live or recorded value during playback.
/// </summary>
protected string GetRecordedOptionalVariable(string name, Action<RecordedVariableOptions> options)
{
if (Mode == RecordedTestMode.Playback)
{
return GetRecordedValue(name);
}
string value = GetOptionalVariable(name);
if (!Mode.HasValue)
{
return value;
}
if (_recording == null)
{
throw new InvalidOperationException("Recorded value should not be set outside the test method invocation");
}
// If the value was populated, sanitize before recording it.
string sanitizedValue = value;
if (!string.IsNullOrEmpty(value))
{
var optionsInstance = new RecordedVariableOptions();
options?.Invoke(optionsInstance);
sanitizedValue = optionsInstance.Apply(sanitizedValue);
}
_recording?.SetVariable(name, sanitizedValue);
return value;
}
/// <summary>
/// Returns and records an environment variable value when running live or recorded value during playback.
/// Throws when variable is not found.
/// </summary>
protected string GetRecordedVariable(string name)
{
return GetRecordedVariable(name, null);
}
/// <summary>
/// Returns and records an environment variable value when running live or recorded value during playback.
/// Throws when variable is not found.
/// </summary>
protected string GetRecordedVariable(string name, Action<RecordedVariableOptions> options)
{
var value = GetRecordedOptionalVariable(name, options);
EnsureValue(name, value);
return value;
}
/// <summary>
/// Returns an environment variable value or null when variable is not found.
/// </summary>
protected string GetOptionalVariable(string name)
{
var prefixedName = _prefix + name;
// Environment variables override the environment file
var value = Environment.GetEnvironmentVariable(prefixedName) ??
Environment.GetEnvironmentVariable(name);
if (value == null)
{
_environmentFile.TryGetValue(prefixedName, out value);
}
if (value == null)
{
_environmentFile.TryGetValue(name, out value);
}
return value;
}
/// <summary>
/// Returns an environment variable value.
/// Throws when variable is not found.
/// </summary>
protected string GetVariable(string name)
{
var value = GetOptionalVariable(name);
EnsureValue(name, value);
return value;
}
private void EnsureValue(string name, string value)
{
if (value == null)
{
var prefixedName = _prefix + name;
throw new InvalidOperationException(
$"Unable to find environment variable {prefixedName} or {name} required by test." + Environment.NewLine +
"Make sure the test environment was initialized using eng/common/TestResources/New-TestResources.ps1 script.");
}
}
public void SetRecording(TestRecording recording)
{
_credential = null;
_recording = recording;
}
private string GetRecordedValue(string name)
{
if (_recording == null)
{
throw new InvalidOperationException("Recorded value should not be retrieved outside the test method invocation");
}
return _recording.GetVariable(name, null);
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
// .NET Compact Framework 1.0 has no support for Marshal.StringToHGlobalAnsi
// SSCLI 1.0 has no support for Marshal.StringToHGlobalAnsi
#if !NETCF && !SSCLI && !NETMF
using System;
using System.Runtime.InteropServices;
using log4net.Core;
using log4net.Appender;
using log4net.Util;
using log4net.Layout;
namespace log4net.Appender
{
/// <summary>
/// Logs events to a local syslog service.
/// </summary>
/// <remarks>
/// <note>
/// This appender uses the POSIX libc library functions <c>openlog</c>, <c>syslog</c>, and <c>closelog</c>.
/// If these functions are not available on the local system then this appender will not work!
/// </note>
/// <para>
/// The functions <c>openlog</c>, <c>syslog</c>, and <c>closelog</c> are specified in SUSv2 and
/// POSIX 1003.1-2001 standards. These are used to log messages to the local syslog service.
/// </para>
/// <para>
/// This appender talks to a local syslog service. If you need to log to a remote syslog
/// daemon and you cannot configure your local syslog service to do this you may be
/// able to use the <see cref="RemoteSyslogAppender"/> to log via UDP.
/// </para>
/// <para>
/// Syslog messages must have a facility and and a severity. The severity
/// is derived from the Level of the logging event.
/// The facility must be chosen from the set of defined syslog
/// <see cref="SyslogFacility"/> values. The facilities list is predefined
/// and cannot be extended.
/// </para>
/// <para>
/// An identifier is specified with each log message. This can be specified
/// by setting the <see cref="Identity"/> property. The identity (also know
/// as the tag) must not contain white space. The default value for the
/// identity is the application name (from <see cref="SystemInfo.ApplicationFriendlyName"/>).
/// </para>
/// </remarks>
/// <author>Rob Lyon</author>
/// <author>Nicko Cadell</author>
public class LocalSyslogAppender : AppenderSkeleton
{
#region Enumerations
/// <summary>
/// syslog severities
/// </summary>
/// <remarks>
/// <para>
/// The log4net Level maps to a syslog severity using the
/// <see cref="LocalSyslogAppender.AddMapping"/> method and the <see cref="LevelSeverity"/>
/// class. The severity is set on <see cref="LevelSeverity.Severity"/>.
/// </para>
/// </remarks>
public enum SyslogSeverity
{
/// <summary>
/// system is unusable
/// </summary>
Emergency = 0,
/// <summary>
/// action must be taken immediately
/// </summary>
Alert = 1,
/// <summary>
/// critical conditions
/// </summary>
Critical = 2,
/// <summary>
/// error conditions
/// </summary>
Error = 3,
/// <summary>
/// warning conditions
/// </summary>
Warning = 4,
/// <summary>
/// normal but significant condition
/// </summary>
Notice = 5,
/// <summary>
/// informational
/// </summary>
Informational = 6,
/// <summary>
/// debug-level messages
/// </summary>
Debug = 7
};
/// <summary>
/// syslog facilities
/// </summary>
/// <remarks>
/// <para>
/// The syslog facility defines which subsystem the logging comes from.
/// This is set on the <see cref="Facility"/> property.
/// </para>
/// </remarks>
public enum SyslogFacility
{
/// <summary>
/// kernel messages
/// </summary>
Kernel = 0,
/// <summary>
/// random user-level messages
/// </summary>
User = 1,
/// <summary>
/// mail system
/// </summary>
Mail = 2,
/// <summary>
/// system daemons
/// </summary>
Daemons = 3,
/// <summary>
/// security/authorization messages
/// </summary>
Authorization = 4,
/// <summary>
/// messages generated internally by syslogd
/// </summary>
Syslog = 5,
/// <summary>
/// line printer subsystem
/// </summary>
Printer = 6,
/// <summary>
/// network news subsystem
/// </summary>
News = 7,
/// <summary>
/// UUCP subsystem
/// </summary>
Uucp = 8,
/// <summary>
/// clock (cron/at) daemon
/// </summary>
Clock = 9,
/// <summary>
/// security/authorization messages (private)
/// </summary>
Authorization2 = 10,
/// <summary>
/// ftp daemon
/// </summary>
Ftp = 11,
/// <summary>
/// NTP subsystem
/// </summary>
Ntp = 12,
/// <summary>
/// log audit
/// </summary>
Audit = 13,
/// <summary>
/// log alert
/// </summary>
Alert = 14,
/// <summary>
/// clock daemon
/// </summary>
Clock2 = 15,
/// <summary>
/// reserved for local use
/// </summary>
Local0 = 16,
/// <summary>
/// reserved for local use
/// </summary>
Local1 = 17,
/// <summary>
/// reserved for local use
/// </summary>
Local2 = 18,
/// <summary>
/// reserved for local use
/// </summary>
Local3 = 19,
/// <summary>
/// reserved for local use
/// </summary>
Local4 = 20,
/// <summary>
/// reserved for local use
/// </summary>
Local5 = 21,
/// <summary>
/// reserved for local use
/// </summary>
Local6 = 22,
/// <summary>
/// reserved for local use
/// </summary>
Local7 = 23
}
#endregion // Enumerations
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LocalSyslogAppender" /> class.
/// </summary>
/// <remarks>
/// This instance of the <see cref="LocalSyslogAppender" /> class is set up to write
/// to a local syslog service.
/// </remarks>
public LocalSyslogAppender()
{
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Message identity
/// </summary>
/// <remarks>
/// <para>
/// An identifier is specified with each log message. This can be specified
/// by setting the <see cref="Identity"/> property. The identity (also know
/// as the tag) must not contain white space. The default value for the
/// identity is the application name (from <see cref="SystemInfo.ApplicationFriendlyName"/>).
/// </para>
/// </remarks>
public string Identity
{
get { return m_identity; }
set { m_identity = value; }
}
/// <summary>
/// Syslog facility
/// </summary>
/// <remarks>
/// Set to one of the <see cref="SyslogFacility"/> values. The list of
/// facilities is predefined and cannot be extended. The default value
/// is <see cref="SyslogFacility.User"/>.
/// </remarks>
public SyslogFacility Facility
{
get { return m_facility; }
set { m_facility = value; }
}
#endregion // Public Instance Properties
/// <summary>
/// Add a mapping of level to severity
/// </summary>
/// <param name="mapping">The mapping to add</param>
/// <remarks>
/// <para>
/// Adds a <see cref="LevelSeverity"/> to this appender.
/// </para>
/// </remarks>
public void AddMapping(LevelSeverity mapping)
{
m_levelMapping.Add(mapping);
}
#region IOptionHandler Implementation
/// <summary>
/// Initialize the appender based on the options set.
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
public override void ActivateOptions()
{
base.ActivateOptions();
m_levelMapping.ActivateOptions();
string identString = m_identity;
if (identString == null)
{
// Set to app name by default
identString = SystemInfo.ApplicationFriendlyName;
}
// create the native heap ansi string. Note this is a copy of our string
// so we do not need to hold on to the string itself, holding on to the
// handle will keep the heap ansi string alive.
m_handleToIdentity = Marshal.StringToHGlobalAnsi(identString);
// open syslog
openlog(m_handleToIdentity, 1, m_facility);
}
#endregion // IOptionHandler Implementation
#region AppenderSkeleton Implementation
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Writes the event to a remote syslog daemon.
/// </para>
/// <para>
/// The format of the output will depend on the appender's layout.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
protected override void Append(LoggingEvent loggingEvent)
{
int priority = GeneratePriority(m_facility, GetSeverity(loggingEvent.Level));
string message = RenderLoggingEvent(loggingEvent);
// Call the local libc syslog method
// The second argument is a printf style format string
syslog(priority, "%s", message);
}
/// <summary>
/// Close the syslog when the appender is closed
/// </summary>
/// <remarks>
/// <para>
/// Close the syslog when the appender is closed
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
protected override void OnClose()
{
base.OnClose();
try
{
// close syslog
closelog();
}
catch(DllNotFoundException)
{
// Ignore dll not found at this point
}
if (m_handleToIdentity != IntPtr.Zero)
{
// free global ident
Marshal.FreeHGlobal(m_handleToIdentity);
}
}
/// <summary>
/// This appender requires a <see cref="AppenderSkeleton.Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="AppenderSkeleton.Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion // AppenderSkeleton Implementation
#region Protected Members
/// <summary>
/// Translates a log4net level to a syslog severity.
/// </summary>
/// <param name="level">A log4net level.</param>
/// <returns>A syslog severity.</returns>
/// <remarks>
/// <para>
/// Translates a log4net level to a syslog severity.
/// </para>
/// </remarks>
virtual protected SyslogSeverity GetSeverity(Level level)
{
LevelSeverity levelSeverity = m_levelMapping.Lookup(level) as LevelSeverity;
if (levelSeverity != null)
{
return levelSeverity.Severity;
}
//
// Fallback to sensible default values
//
if (level >= Level.Alert)
{
return SyslogSeverity.Alert;
}
else if (level >= Level.Critical)
{
return SyslogSeverity.Critical;
}
else if (level >= Level.Error)
{
return SyslogSeverity.Error;
}
else if (level >= Level.Warn)
{
return SyslogSeverity.Warning;
}
else if (level >= Level.Notice)
{
return SyslogSeverity.Notice;
}
else if (level >= Level.Info)
{
return SyslogSeverity.Informational;
}
// Default setting
return SyslogSeverity.Debug;
}
#endregion // Protected Members
#region Public Static Members
/// <summary>
/// Generate a syslog priority.
/// </summary>
/// <param name="facility">The syslog facility.</param>
/// <param name="severity">The syslog severity.</param>
/// <returns>A syslog priority.</returns>
private static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity)
{
return ((int)facility * 8) + (int)severity;
}
#endregion // Public Static Members
#region Private Instances Fields
/// <summary>
/// The facility. The default facility is <see cref="SyslogFacility.User"/>.
/// </summary>
private SyslogFacility m_facility = SyslogFacility.User;
/// <summary>
/// The message identity
/// </summary>
private string m_identity;
/// <summary>
/// Marshaled handle to the identity string. We have to hold on to the
/// string as the <c>openlog</c> and <c>syslog</c> APIs just hold the
/// pointer to the ident and dereference it for each log message.
/// </summary>
private IntPtr m_handleToIdentity = IntPtr.Zero;
/// <summary>
/// Mapping from level object to syslog severity
/// </summary>
private LevelMapping m_levelMapping = new LevelMapping();
#endregion // Private Instances Fields
#region External Members
/// <summary>
/// Open connection to system logger.
/// </summary>
[DllImport("libc")]
private static extern void openlog(IntPtr ident, int option, SyslogFacility facility);
/// <summary>
/// Generate a log message.
/// </summary>
/// <remarks>
/// <para>
/// The libc syslog method takes a format string and a variable argument list similar
/// to the classic printf function. As this type of vararg list is not supported
/// by C# we need to specify the arguments explicitly. Here we have specified the
/// format string with a single message argument. The caller must set the format
/// string to <c>"%s"</c>.
/// </para>
/// </remarks>
[DllImport("libc", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)]
private static extern void syslog(int priority, string format, string message);
/// <summary>
/// Close descriptor used to write to system logger.
/// </summary>
[DllImport("libc")]
private static extern void closelog();
#endregion // External Members
#region LevelSeverity LevelMapping Entry
/// <summary>
/// A class to act as a mapping between the level that a logging call is made at and
/// the syslog severity that is should be logged at.
/// </summary>
/// <remarks>
/// <para>
/// A class to act as a mapping between the level that a logging call is made at and
/// the syslog severity that is should be logged at.
/// </para>
/// </remarks>
public class LevelSeverity : LevelMappingEntry
{
private SyslogSeverity m_severity;
/// <summary>
/// The mapped syslog severity for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped syslog severity for the specified level
/// </para>
/// </remarks>
public SyslogSeverity Severity
{
get { return m_severity; }
set { m_severity = value; }
}
}
#endregion // LevelSeverity LevelMapping Entry
}
}
#endif
| |
#region Using directives
using System;
using System.Collections;
using System.Text;
using System.Runtime.InteropServices;
using GuiLabs.Utils;
using System.Collections.Generic;
#endregion
namespace GuiLabs.Canvas.DrawStyle
{
internal class GDIFont : IFontInfo
{
#region Constructors
public GDIFont(String FamilyName, float size)
: this(FamilyName, size, System.Drawing.FontStyle.Regular)
{
}
public GDIFont(GDIFont ExistingFont)
{
this.mName = ExistingFont.Name;
this.mSize = ExistingFont.Size;
this.mBold = ExistingFont.Bold;
this.mItalic = ExistingFont.Italic;
this.mUnderline = ExistingFont.Underline;
this.hFont = ExistingFont.hFont;
}
public GDIFont(String FamilyName, float size, System.Drawing.FontStyle style)
{
Init();
this.mName = FamilyName;
this.mSize = (int)size;
this.mBold = (style & System.Drawing.FontStyle.Bold) != 0;
this.mItalic = (style & System.Drawing.FontStyle.Italic) != 0;
this.mUnderline = (style & System.Drawing.FontStyle.Underline) != 0;
AssignHandle();
}
#endregion
#region Init, Exit
private static bool WasInit = false;
private void Init()
{
if (!WasInit)
{
System.Windows.Forms.Application.ApplicationExit += OnApplicationExit;
WasInit = true;
}
}
private void OnApplicationExit(object sender, System.EventArgs e)
{
if (WasInit)
{
System.Windows.Forms.Application.ApplicationExit -= OnApplicationExit;
foreach (IntPtr h in FontHandles.Values)
{
API.DeleteObject(h);
}
WasInit = false;
}
}
#endregion
private void AssignHandle()
{
IntPtr handle = FindHandle(GetSignature());
if (handle == IntPtr.Zero)
{
CreateHandle();
AddHandle(hFont);
}
else
{
hFont = handle;
}
}
#region CreateHandle
private void CreateHandle()
{
hFont = API.CreateFont(FontSize(this.Size), 0, 0, 0,
(this.Bold) ? 700 : 400, (this.Italic) ? 1 : 0,
(this.Underline) ? 1 : 0, 0,
// (int)API.CHARSET.DEFAULT_CHARSET
1
, 0, 0, 2, 0, this.Name);
}
private int FontSize(int Size)
{
const int LOGPIXELSY = 90;
IntPtr hDC = API.GetDC(API.GetDesktopWindow());
int result = -API.MulDiv(Size, API.GetDeviceCaps(hDC, LOGPIXELSY), 72);
API.ReleaseDC(API.GetDesktopWindow(), hDC);
return result;
}
#endregion
private static Dictionary<string, IntPtr> FontHandles
= new Dictionary<string, IntPtr>();
#region AddHandle, FindHandle
private void AddHandle(IntPtr h)
{
FontHandles[GetSignature()] = h;
}
private IntPtr FindHandle(string Signature)
{
IntPtr o = IntPtr.Zero;
FontHandles.TryGetValue(Signature, out o);
return o;
}
private string GetSignature()
{
return GetSignature(
this.Name,
this.Size.ToString(),
this.GetFontStyle().ToString());
}
private string GetSignature(string name, string size, string style)
{
StringBuilder s = new StringBuilder();
s.Append(name);
s.Append(" ");
s.Append(size);
s.Append(", ");
s.Append(style);
return s.ToString();
}
#endregion
#region Properties
private IntPtr mhFont;
public IntPtr hFont
{
get
{
return mhFont;
}
set
{
mhFont = value;
}
}
private string mName;
public string Name
{
get
{
return mName;
}
}
private int mSize;
public int Size
{
get
{
return mSize;
}
set
{
if (mSize == value
|| value < 4
|| value > 100)
{
return;
}
this.mSize = value;
mSpaceCharSize.Set0();
string newSignature = GetSignature();
IntPtr existing = FindHandle(newSignature);
if (existing == IntPtr.Zero)
{
CreateHandle();
AddHandle(hFont);
}
else
{
hFont = existing;
}
}
}
#region Style
private System.Drawing.FontStyle GetFontStyle()
{
System.Drawing.FontStyle result = System.Drawing.FontStyle.Regular;
if (this.Bold)
{
result |= System.Drawing.FontStyle.Bold;
}
if (this.Italic)
{
result |= System.Drawing.FontStyle.Italic;
}
if (this.Underline)
{
result |= System.Drawing.FontStyle.Underline;
}
return result;
}
private bool mBold;
public bool Bold
{
get
{
return mBold;
}
}
private bool mItalic;
public bool Italic
{
get
{
return mItalic;
}
}
private bool mUnderline;
public bool Underline
{
get
{
return mUnderline;
}
}
public System.Drawing.FontStyle FontStyle
{
get
{
System.Drawing.FontStyle result = System.Drawing.FontStyle.Regular;
if (Bold)
{
result |= System.Drawing.FontStyle.Bold;
}
if (Italic)
{
result |= System.Drawing.FontStyle.Italic;
}
if (Underline)
{
result |= System.Drawing.FontStyle.Underline;
}
return result;
}
}
private readonly Point mSpaceCharSize = new Point();
public Point SpaceCharSize
{
get
{
if (mSpaceCharSize.X == 0 || mSpaceCharSize.Y == 0)
{
mSpaceCharSize.Set(Renderer.RendererSingleton.DrawOperations.StringSize(" ", this));
}
return mSpaceCharSize;
}
}
#endregion
#endregion
public override string ToString()
{
return GetSignature();
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
namespace System.IO.Compression
{
public class GZipStream : Stream
{
private DeflateStream _deflateStream;
public GZipStream(Stream stream, CompressionMode mode): this(stream, mode, leaveOpen: false)
{
}
public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen)
{
_deflateStream = new DeflateStream(stream, mode, leaveOpen, ZLibNative.GZip_DefaultWindowBits);
}
// Implies mode = Compress
public GZipStream(Stream stream, CompressionLevel compressionLevel): this(stream, compressionLevel, leaveOpen: false)
{
}
// Implies mode = Compress
public GZipStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen)
{
_deflateStream = new DeflateStream(stream, compressionLevel, leaveOpen, ZLibNative.GZip_DefaultWindowBits);
}
public override bool CanRead => _deflateStream?.CanRead ?? false;
public override bool CanWrite => _deflateStream?.CanWrite ?? false;
public override bool CanSeek => _deflateStream?.CanSeek ?? false;
public override long Length
{
get { throw new NotSupportedException(SR.NotSupported); }
}
public override long Position
{
get { throw new NotSupportedException(SR.NotSupported); }
set { throw new NotSupportedException(SR.NotSupported); }
}
public override void Flush()
{
CheckDeflateStream();
_deflateStream.Flush();
return;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.NotSupported);
}
public override void SetLength(long value)
{
throw new NotSupportedException(SR.NotSupported);
}
public override int ReadByte()
{
CheckDeflateStream();
return _deflateStream.ReadByte();
}
public override IAsyncResult BeginRead(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) =>
TaskToApm.Begin(ReadAsync(array, offset, count, CancellationToken.None), asyncCallback, asyncState);
public override int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
public override int Read(byte[] array, int offset, int count)
{
CheckDeflateStream();
return _deflateStream.Read(array, offset, count);
}
public override int Read(Span<byte> destination)
{
if (GetType() != typeof(GZipStream))
{
// GZipStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior
// to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload
// should use the behavior of Read(byte[],int,int) overload.
return base.Read(destination);
}
else
{
CheckDeflateStream();
return _deflateStream.ReadCore(destination);
}
}
public override IAsyncResult BeginWrite(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) =>
TaskToApm.Begin(WriteAsync(array, offset, count, CancellationToken.None), asyncCallback, asyncState);
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
public override void Write(byte[] array, int offset, int count)
{
CheckDeflateStream();
_deflateStream.Write(array, offset, count);
}
public override void Write(ReadOnlySpan<byte> source)
{
if (GetType() != typeof(GZipStream))
{
// GZipStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior
// to this Write(ReadOnlySpan<byte>) overload being introduced. In that case, this Write(ReadOnlySpan<byte>) overload
// should use the behavior of Write(byte[],int,int) overload.
base.Write(source);
}
else
{
CheckDeflateStream();
_deflateStream.WriteCore(source);
}
}
public override void CopyTo(Stream destination, int bufferSize)
{
CheckDeflateStream();
_deflateStream.CopyTo(destination, bufferSize);
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && _deflateStream != null)
{
_deflateStream.Dispose();
}
_deflateStream = null;
}
finally
{
base.Dispose(disposing);
}
}
public Stream BaseStream => _deflateStream?.BaseStream;
public override Task<int> ReadAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
CheckDeflateStream();
return _deflateStream.ReadAsync(array, offset, count, cancellationToken);
}
public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
{
if (GetType() != typeof(GZipStream))
{
// GZipStream is not sealed, and a derived type may have overridden ReadAsync(byte[], int, int) prior
// to this ReadAsync(Memory<byte>) overload being introduced. In that case, this ReadAsync(Memory<byte>) overload
// should use the behavior of ReadAsync(byte[],int,int) overload.
return base.ReadAsync(destination, cancellationToken);
}
else
{
CheckDeflateStream();
return _deflateStream.ReadAsyncMemory(destination, cancellationToken);
}
}
public override Task WriteAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
CheckDeflateStream();
return _deflateStream.WriteAsync(array, offset, count, cancellationToken);
}
public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
{
if (GetType() != typeof(GZipStream))
{
// GZipStream is not sealed, and a derived type may have overridden WriteAsync(byte[], int, int) prior
// to this WriteAsync(ReadOnlyMemory<byte>) overload being introduced. In that case, this
// WriteAsync(ReadOnlyMemory<byte>) overload should use the behavior of Write(byte[],int,int) overload.
return base.WriteAsync(source, cancellationToken);
}
else
{
CheckDeflateStream();
return _deflateStream.WriteAsyncMemory(source, cancellationToken);
}
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
CheckDeflateStream();
return _deflateStream.FlushAsync(cancellationToken);
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
CheckDeflateStream();
return _deflateStream.CopyToAsync(destination, bufferSize, cancellationToken);
}
private void CheckDeflateStream()
{
if (_deflateStream == null)
{
ThrowStreamClosedException();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowStreamClosedException()
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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 NUnit.Framework;
#if !NETCF
using System.Security.Principal;
#endif
namespace NUnit.TestData.TestFixtureData
{
/// <summary>
/// Classes used for testing NUnit
/// </summary>
[TestFixture]
public class NoDefaultCtorFixture
{
public NoDefaultCtorFixture(int index) { }
[Test]
public void OneTest() { }
}
[TestFixture(7,3)]
public class FixtureWithArgsSupplied
{
public FixtureWithArgsSupplied(int x, int y) { }
[Test]
public void OneTest() { }
}
[TestFixture]
public class BadCtorFixture
{
BadCtorFixture()
{
throw new Exception();
}
[Test] public void OneTest()
{}
}
[TestFixture]
public class FixtureWithTestFixtureAttribute
{
[Test]
public void SomeTest() { }
}
public class FixtureWithoutTestFixtureAttributeContainingTest
{
[Test]
public void SomeTest() { }
}
public class FixtureWithoutTestFixtureAttributeContainingTestCase
{
[TestCase(42)]
public void SomeTest(int x) { }
}
public class FixtureWithoutTestFixtureAttributeContainingTestCaseSource
{
[TestCaseSource("data")]
public void SomeTest(int x) { }
}
#if !NUNITLITE
public class FixtureWithoutTestFixtureAttributeContainingTheory
{
[Theory]
public void SomeTest(int x) { }
}
#endif
#if CLR_2_0 || CLR_4_0
public static class StaticFixtureWithoutTestFixtureAttribute
{
[Test]
public static void StaticTest() { }
}
#endif
[TestFixture]
public class MultipleSetUpAttributes
{
[SetUp]
public void Init1()
{}
[SetUp]
public void Init2()
{}
[Test] public void OneTest()
{}
}
[TestFixture]
public class MultipleTearDownAttributes
{
[TearDown]
public void Destroy1()
{}
[TearDown]
public void Destroy2()
{}
[Test] public void OneTest()
{}
}
[TestFixture]
[Ignore("testing ignore a fixture")]
public class IgnoredFixture
{
[Test]
public void Success()
{}
}
[TestFixture]
public class OuterClass
{
[TestFixture]
public class NestedTestFixture
{
[TestFixture]
public class DoublyNestedTestFixture
{
[Test]
public void Test()
{
}
}
}
}
[TestFixture]
public abstract class AbstractTestFixture
{
[TearDown]
public void Destroy1()
{}
[Test]
public void SomeTest()
{
}
}
public class DerivedFromAbstractTestFixture : AbstractTestFixture
{
}
[TestFixture]
public class BaseClassTestFixture
{
[Test]
public void Success() { }
}
public abstract class AbstractDerivedTestFixture : BaseClassTestFixture
{
[Test]
public void Test()
{
}
}
public class DerivedFromAbstractDerivedTestFixture : AbstractDerivedTestFixture
{
}
[TestFixture]
public abstract class AbstractBaseFixtureWithAttribute
{
}
[TestFixture]
public abstract class AbstractDerivedFixtureWithSecondAttribute
: AbstractBaseFixtureWithAttribute
{
}
public class DoubleDerivedClassWithTwoInheritedAttributes
: AbstractDerivedFixtureWithSecondAttribute
{
}
[TestFixture]
public class MultipleFixtureSetUpAttributes
{
[TestFixtureSetUp]
public void Init1()
{}
[TestFixtureSetUp]
public void Init2()
{}
[Test] public void OneTest()
{}
}
[TestFixture]
public class MultipleFixtureTearDownAttributes
{
[TestFixtureTearDown]
public void Destroy1()
{}
[TestFixtureTearDown]
public void Destroy2()
{}
[Test] public void OneTest()
{}
}
// Base class used to ensure following classes
// all have at least one test
public class OneTestBase
{
[Test] public void OneTest() { }
}
[TestFixture]
public class PrivateSetUp : OneTestBase
{
[SetUp]
private void Setup() {}
}
[TestFixture]
public class ProtectedSetUp : OneTestBase
{
[SetUp]
protected void Setup() {}
}
[TestFixture]
public class StaticSetUp : OneTestBase
{
[SetUp]
public static void Setup() {}
}
[TestFixture]
public class SetUpWithReturnValue : OneTestBase
{
[SetUp]
public int Setup() { return 0; }
}
[TestFixture]
public class SetUpWithParameters : OneTestBase
{
[SetUp]
public void Setup(int j) { }
}
[TestFixture]
public class PrivateTearDown : OneTestBase
{
[TearDown]
private void Teardown() {}
}
[TestFixture]
public class ProtectedTearDown : OneTestBase
{
[TearDown]
protected void Teardown() {}
}
[TestFixture]
public class StaticTearDown : OneTestBase
{
[SetUp]
public static void TearDown() {}
}
[TestFixture]
public class TearDownWithReturnValue : OneTestBase
{
[TearDown]
public int Teardown() { return 0; }
}
[TestFixture]
public class TearDownWithParameters : OneTestBase
{
[TearDown]
public void Teardown(int j) { }
}
[TestFixture]
public class PrivateFixtureSetUp : OneTestBase
{
[TestFixtureSetUp]
private void Setup() {}
}
[TestFixture]
public class ProtectedFixtureSetUp : OneTestBase
{
[TestFixtureSetUp]
protected void Setup() {}
}
[TestFixture]
public class StaticFixtureSetUp : OneTestBase
{
[TestFixtureSetUp]
public static void Setup() {}
}
[TestFixture]
public class FixtureSetUpWithReturnValue : OneTestBase
{
[TestFixtureSetUp]
public int Setup() { return 0; }
}
[TestFixture]
public class FixtureSetUpWithParameters : OneTestBase
{
[SetUp]
public void Setup(int j) { }
}
[TestFixture]
public class PrivateFixtureTearDown : OneTestBase
{
[TestFixtureTearDown]
private void Teardown() {}
}
[TestFixture]
public class ProtectedFixtureTearDown : OneTestBase
{
[TestFixtureTearDown]
protected void Teardown() {}
}
[TestFixture]
public class StaticFixtureTearDown : OneTestBase
{
[TestFixtureTearDown]
public static void Teardown() {}
}
[TestFixture]
public class FixtureTearDownWithReturnValue : OneTestBase
{
[TestFixtureTearDown]
public int Teardown() { return 0; }
}
[TestFixture]
public class FixtureTearDownWithParameters : OneTestBase
{
[TestFixtureTearDown]
public void Teardown(int j) { }
}
#if !NETCF && !SILVERLIGHT && !PORTABLE
[TestFixture]
public class FixtureThatChangesTheCurrentPrincipal
{
[Test]
public void ChangeCurrentPrincipal()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
GenericPrincipal principal = new GenericPrincipal( identity, new string[] { } );
System.Threading.Thread.CurrentPrincipal = principal;
}
}
#endif
#if CLR_2_0 || CLR_4_0
#if !NETCF
[TestFixture(typeof(int))]
[TestFixture(typeof(string))]
public class GenericFixtureWithProperArgsProvided<T>
{
[Test]
public void SomeTest() { }
}
public class GenericFixtureWithNoTestFixtureAttribute<T>
{
[Test]
public void SomeTest() { }
}
[TestFixture]
public class GenericFixtureWithNoArgsProvided<T>
{
[Test]
public void SomeTest() { }
}
[TestFixture]
public abstract class AbstractFixtureBase
{
[Test]
public void SomeTest() { }
}
public class GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided<T> : AbstractFixtureBase
{
}
[TestFixture(typeof(int))]
[TestFixture(typeof(string))]
public class GenericFixtureDerivedFromAbstractFixtureWithArgsProvided<T> : AbstractFixtureBase
{
}
#endif
#endif
}
| |
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 MiniTrello.Api.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;
}
}
}
| |
/*
* NPlot - A charting library for .NET
*
* StepPlot.cs
* Copyright (C) 2003-2006 Matt Howlett and others.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Drawing;
namespace NPlot
{
/// <summary>
/// Encapsulates functionality for plotting data as a stepped line.
/// </summary>
public class StepPlot : BaseSequencePlot, IPlot, ISequencePlot
{
private bool center_;
private bool hideHorizontalSegments_;
private bool hideVerticalSegments_;
private Pen pen_ = new Pen(Color.Black);
private float scale_ = 1.0f;
/// <summary>
/// Constructor.
/// </summary>
public StepPlot()
{
Center = false;
}
/// <summary>
/// Gets or sets whether or not steps should be centered. If true, steps will be centered on the
/// X abscissa values. If false, the step corresponding to a given x-value will be drawn between
/// this x-value and the next x-value at the current y-height.
/// </summary>
public bool Center
{
set { center_ = value; }
get { return center_; }
}
/// <summary>
/// The pen used to draw the plot
/// </summary>
public Pen Pen
{
get { return pen_; }
set { pen_ = value; }
}
/// <summary>
/// The color of the pen used to draw lines in this plot.
/// </summary>
public Color Color
{
set
{
if (pen_ != null)
{
pen_.Color = value;
}
else
{
pen_ = new Pen(value);
}
}
get { return pen_.Color; }
}
/// <summary>
/// If true, then vertical lines are hidden.
/// </summary>
public bool HideVerticalSegments
{
get { return hideVerticalSegments_; }
set { hideVerticalSegments_ = value; }
}
/// <summary>
/// If true, then vertical lines are hidden.
/// </summary>
public bool HideHorizontalSegments
{
get { return hideHorizontalSegments_; }
set { hideHorizontalSegments_ = value; }
}
/// <summary>
/// The horizontal line length is multiplied by this amount. Default
/// corresponds to a value of 1.0.
/// </summary>
public float WidthScale
{
get { return scale_; }
set { scale_ = value; }
}
/// <summary>
/// Draws the step plot on a GDI+ surface against the provided x and y axes.
/// </summary>
/// <param name="g">The GDI+ surface on which to draw.</param>
/// <param name="xAxis">The X-Axis to draw against.</param>
/// <param name="yAxis">The Y-Axis to draw against.</param>
public virtual void Draw(Graphics g, PhysicalAxis xAxis, PhysicalAxis yAxis)
{
SequenceAdapter data =
new SequenceAdapter(DataSource, DataMember, OrdinateData, AbscissaData);
double leftCutoff = xAxis.PhysicalToWorld(xAxis.PhysicalMin, false);
double rightCutoff = xAxis.PhysicalToWorld(xAxis.PhysicalMax, false);
for (int i = 0; i < data.Count; ++i)
{
PointD p1 = data[i];
if (Double.IsNaN(p1.X) || Double.IsNaN(p1.Y))
{
continue;
}
PointD p2;
PointD p3;
if (i + 1 != data.Count)
{
p2 = data[i + 1];
if (Double.IsNaN(p2.X) || Double.IsNaN(p2.Y))
{
continue;
}
p2.Y = p1.Y;
p3 = data[i + 1];
}
else
{
// Check that we are not dealing with a DataSource of 1 point.
// This check is done here so it is only checked on the end
// condition and not for every point in the DataSource.
if (data.Count > 1)
{
p2 = data[i - 1];
}
else
{
// TODO: Once log4net is set up post a message to the user that a step-plot of 1 really does not make any sense.
p2 = p1;
}
double offset = p1.X - p2.X;
p2.X = p1.X + offset;
p2.Y = p1.Y;
p3 = p2;
}
if (center_)
{
double offset = (p2.X - p1.X)/2.0f;
p1.X -= offset;
p2.X -= offset;
p3.X -= offset;
}
PointF xPos1 = xAxis.WorldToPhysical(p1.X, false);
PointF yPos1 = yAxis.WorldToPhysical(p1.Y, false);
PointF xPos2 = xAxis.WorldToPhysical(p2.X, false);
PointF yPos2 = yAxis.WorldToPhysical(p2.Y, false);
PointF xPos3 = xAxis.WorldToPhysical(p3.X, false);
PointF yPos3 = yAxis.WorldToPhysical(p3.Y, false);
// do horizontal clipping here, to speed up
if ((p1.X < leftCutoff || p1.X > rightCutoff) &&
(p2.X < leftCutoff || p2.X > rightCutoff) &&
(p3.X < leftCutoff || p3.X > rightCutoff))
{
continue;
}
if (!hideHorizontalSegments_)
{
if (scale_ != 1.0f)
{
float middle = (xPos2.X + xPos1.X)/2.0f;
float width = xPos2.X - xPos1.X;
width *= scale_;
g.DrawLine(Pen, (int) (middle - width/2.0f), yPos1.Y, (int) (middle + width/2.0f), yPos2.Y);
}
else
{
g.DrawLine(Pen, xPos1.X, yPos1.Y, xPos2.X, yPos2.Y);
}
}
if (!hideVerticalSegments_)
{
g.DrawLine(Pen, xPos2.X, yPos2.Y, xPos3.X, yPos3.Y);
}
}
}
/// <summary>
/// Returns an X-axis suitable for use by this plot. The axis will be one that is just long
/// enough to show all data.
/// </summary>
/// <returns>X-axis suitable for use by this plot.</returns>
public Axis SuggestXAxis()
{
SequenceAdapter data =
new SequenceAdapter(DataSource, DataMember, OrdinateData, AbscissaData);
if (data.Count < 2)
{
return data.SuggestXAxis();
}
// else
Axis a = data.SuggestXAxis();
PointD p1 = data[0];
PointD p2 = data[1];
PointD p3 = data[data.Count - 2];
PointD p4 = data[data.Count - 1];
double offset1;
double offset2;
if (!center_)
{
offset1 = 0.0f;
offset2 = p4.X - p3.X;
}
else
{
offset1 = (p2.X - p1.X)/2.0f;
offset2 = (p4.X - p3.X)/2.0f;
}
a.WorldMin -= offset1;
a.WorldMax += offset2;
return a;
}
/// <summary>
/// Returns an Y-axis suitable for use by this plot. The axis will be one that is just long
/// enough to show all data.
/// </summary>
/// <returns>Y-axis suitable for use by this plot.</returns>
public Axis SuggestYAxis()
{
SequenceAdapter data =
new SequenceAdapter(DataSource, DataMember, OrdinateData, AbscissaData);
return data.SuggestYAxis();
}
/// <summary>
/// Draws a representation of this plot in the legend.
/// </summary>
/// <param name="g">The graphics surface on which to draw.</param>
/// <param name="startEnd">A rectangle specifying the bounds of the area in the legend set aside for drawing.</param>
public virtual void DrawInLegend(Graphics g, Rectangle startEnd)
{
g.DrawLine(pen_, startEnd.Left, (startEnd.Top + startEnd.Bottom)/2,
startEnd.Right, (startEnd.Top + startEnd.Bottom)/2);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void AbsSingle()
{
var test = new SimpleUnaryOpTest__AbsSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__AbsSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__AbsSingle testClass)
{
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__AbsSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar1;
private Vector128<Single> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__AbsSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleUnaryOpTest__AbsSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Abs(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Abs(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Single*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__AbsSingle();
var result = AdvSimd.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__AbsSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Single*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(Math.Abs(firstOp[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(Math.Abs(firstOp[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Abs)}<Single>(Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using selfies.Areas.HelpPage.Models;
namespace selfies.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 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 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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: uploads/uploads_service.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace KillrVideo.Uploads {
/// <summary>Holder for reflection information generated from uploads/uploads_service.proto</summary>
public static partial class UploadsServiceReflection {
#region Descriptor
/// <summary>File descriptor for uploads/uploads_service.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static UploadsServiceReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch11cGxvYWRzL3VwbG9hZHNfc2VydmljZS5wcm90bxISa2lsbHJ2aWRlby51",
"cGxvYWRzGh9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvGhljb21t",
"b24vY29tbW9uX3R5cGVzLnByb3RvIjAKG0dldFVwbG9hZERlc3RpbmF0aW9u",
"UmVxdWVzdBIRCglmaWxlX25hbWUYASABKAkiMgocR2V0VXBsb2FkRGVzdGlu",
"YXRpb25SZXNwb25zZRISCgp1cGxvYWRfdXJsGAEgASgJIi8KGU1hcmtVcGxv",
"YWRDb21wbGV0ZVJlcXVlc3QSEgoKdXBsb2FkX3VybBgBIAEoCSIcChpNYXJr",
"VXBsb2FkQ29tcGxldGVSZXNwb25zZSJEChdHZXRTdGF0dXNPZlZpZGVvUmVx",
"dWVzdBIpCgh2aWRlb19pZBgBIAEoCzIXLmtpbGxydmlkZW8uY29tbW9uLlV1",
"aWQiYgoYR2V0U3RhdHVzT2ZWaWRlb1Jlc3BvbnNlEi8KC3N0YXR1c19kYXRl",
"GAEgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIVCg1jdXJyZW50",
"X3N0YXRlGAIgASgJMu8CCg5VcGxvYWRzU2VydmljZRJ5ChRHZXRVcGxvYWRE",
"ZXN0aW5hdGlvbhIvLmtpbGxydmlkZW8udXBsb2Fkcy5HZXRVcGxvYWREZXN0",
"aW5hdGlvblJlcXVlc3QaMC5raWxscnZpZGVvLnVwbG9hZHMuR2V0VXBsb2Fk",
"RGVzdGluYXRpb25SZXNwb25zZRJzChJNYXJrVXBsb2FkQ29tcGxldGUSLS5r",
"aWxscnZpZGVvLnVwbG9hZHMuTWFya1VwbG9hZENvbXBsZXRlUmVxdWVzdBou",
"LmtpbGxydmlkZW8udXBsb2Fkcy5NYXJrVXBsb2FkQ29tcGxldGVSZXNwb25z",
"ZRJtChBHZXRTdGF0dXNPZlZpZGVvEisua2lsbHJ2aWRlby51cGxvYWRzLkdl",
"dFN0YXR1c09mVmlkZW9SZXF1ZXN0Giwua2lsbHJ2aWRlby51cGxvYWRzLkdl",
"dFN0YXR1c09mVmlkZW9SZXNwb25zZUIVqgISS2lsbHJWaWRlby5VcGxvYWRz",
"YgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::KillrVideo.Protobuf.CommonTypesReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.Uploads.GetUploadDestinationRequest), global::KillrVideo.Uploads.GetUploadDestinationRequest.Parser, new[]{ "FileName" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.Uploads.GetUploadDestinationResponse), global::KillrVideo.Uploads.GetUploadDestinationResponse.Parser, new[]{ "UploadUrl" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.Uploads.MarkUploadCompleteRequest), global::KillrVideo.Uploads.MarkUploadCompleteRequest.Parser, new[]{ "UploadUrl" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.Uploads.MarkUploadCompleteResponse), global::KillrVideo.Uploads.MarkUploadCompleteResponse.Parser, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.Uploads.GetStatusOfVideoRequest), global::KillrVideo.Uploads.GetStatusOfVideoRequest.Parser, new[]{ "VideoId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::KillrVideo.Uploads.GetStatusOfVideoResponse), global::KillrVideo.Uploads.GetStatusOfVideoResponse.Parser, new[]{ "StatusDate", "CurrentState" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Request to get/generate a location where a video can be uploaded
/// </summary>
public sealed partial class GetUploadDestinationRequest : pb::IMessage<GetUploadDestinationRequest> {
private static readonly pb::MessageParser<GetUploadDestinationRequest> _parser = new pb::MessageParser<GetUploadDestinationRequest>(() => new GetUploadDestinationRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetUploadDestinationRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::KillrVideo.Uploads.UploadsServiceReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetUploadDestinationRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetUploadDestinationRequest(GetUploadDestinationRequest other) : this() {
fileName_ = other.fileName_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetUploadDestinationRequest Clone() {
return new GetUploadDestinationRequest(this);
}
/// <summary>Field number for the "file_name" field.</summary>
public const int FileNameFieldNumber = 1;
private string fileName_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string FileName {
get { return fileName_; }
set {
fileName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetUploadDestinationRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetUploadDestinationRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (FileName != other.FileName) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (FileName.Length != 0) hash ^= FileName.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (FileName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(FileName);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (FileName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FileName);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetUploadDestinationRequest other) {
if (other == null) {
return;
}
if (other.FileName.Length != 0) {
FileName = other.FileName;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
FileName = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// Response that has the location where a video can be uploaded
/// </summary>
public sealed partial class GetUploadDestinationResponse : pb::IMessage<GetUploadDestinationResponse> {
private static readonly pb::MessageParser<GetUploadDestinationResponse> _parser = new pb::MessageParser<GetUploadDestinationResponse>(() => new GetUploadDestinationResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetUploadDestinationResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::KillrVideo.Uploads.UploadsServiceReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetUploadDestinationResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetUploadDestinationResponse(GetUploadDestinationResponse other) : this() {
uploadUrl_ = other.uploadUrl_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetUploadDestinationResponse Clone() {
return new GetUploadDestinationResponse(this);
}
/// <summary>Field number for the "upload_url" field.</summary>
public const int UploadUrlFieldNumber = 1;
private string uploadUrl_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string UploadUrl {
get { return uploadUrl_; }
set {
uploadUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetUploadDestinationResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetUploadDestinationResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (UploadUrl != other.UploadUrl) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (UploadUrl.Length != 0) hash ^= UploadUrl.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (UploadUrl.Length != 0) {
output.WriteRawTag(10);
output.WriteString(UploadUrl);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (UploadUrl.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(UploadUrl);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetUploadDestinationResponse other) {
if (other == null) {
return;
}
if (other.UploadUrl.Length != 0) {
UploadUrl = other.UploadUrl;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
UploadUrl = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// Request to tell the upload service that a video is finished uploading
/// </summary>
public sealed partial class MarkUploadCompleteRequest : pb::IMessage<MarkUploadCompleteRequest> {
private static readonly pb::MessageParser<MarkUploadCompleteRequest> _parser = new pb::MessageParser<MarkUploadCompleteRequest>(() => new MarkUploadCompleteRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<MarkUploadCompleteRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::KillrVideo.Uploads.UploadsServiceReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MarkUploadCompleteRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MarkUploadCompleteRequest(MarkUploadCompleteRequest other) : this() {
uploadUrl_ = other.uploadUrl_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MarkUploadCompleteRequest Clone() {
return new MarkUploadCompleteRequest(this);
}
/// <summary>Field number for the "upload_url" field.</summary>
public const int UploadUrlFieldNumber = 1;
private string uploadUrl_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string UploadUrl {
get { return uploadUrl_; }
set {
uploadUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as MarkUploadCompleteRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(MarkUploadCompleteRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (UploadUrl != other.UploadUrl) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (UploadUrl.Length != 0) hash ^= UploadUrl.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (UploadUrl.Length != 0) {
output.WriteRawTag(10);
output.WriteString(UploadUrl);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (UploadUrl.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(UploadUrl);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(MarkUploadCompleteRequest other) {
if (other == null) {
return;
}
if (other.UploadUrl.Length != 0) {
UploadUrl = other.UploadUrl;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
UploadUrl = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// Response when marking an upload complete
/// </summary>
public sealed partial class MarkUploadCompleteResponse : pb::IMessage<MarkUploadCompleteResponse> {
private static readonly pb::MessageParser<MarkUploadCompleteResponse> _parser = new pb::MessageParser<MarkUploadCompleteResponse>(() => new MarkUploadCompleteResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<MarkUploadCompleteResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::KillrVideo.Uploads.UploadsServiceReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MarkUploadCompleteResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MarkUploadCompleteResponse(MarkUploadCompleteResponse other) : this() {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MarkUploadCompleteResponse Clone() {
return new MarkUploadCompleteResponse(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as MarkUploadCompleteResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(MarkUploadCompleteResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(MarkUploadCompleteResponse other) {
if (other == null) {
return;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
/// <summary>
/// Get the current status of an uploaded video
/// </summary>
public sealed partial class GetStatusOfVideoRequest : pb::IMessage<GetStatusOfVideoRequest> {
private static readonly pb::MessageParser<GetStatusOfVideoRequest> _parser = new pb::MessageParser<GetStatusOfVideoRequest>(() => new GetStatusOfVideoRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetStatusOfVideoRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::KillrVideo.Uploads.UploadsServiceReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetStatusOfVideoRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetStatusOfVideoRequest(GetStatusOfVideoRequest other) : this() {
VideoId = other.videoId_ != null ? other.VideoId.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetStatusOfVideoRequest Clone() {
return new GetStatusOfVideoRequest(this);
}
/// <summary>Field number for the "video_id" field.</summary>
public const int VideoIdFieldNumber = 1;
private global::KillrVideo.Protobuf.Uuid videoId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::KillrVideo.Protobuf.Uuid VideoId {
get { return videoId_; }
set {
videoId_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetStatusOfVideoRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetStatusOfVideoRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(VideoId, other.VideoId)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (videoId_ != null) hash ^= VideoId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (videoId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(VideoId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (videoId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(VideoId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetStatusOfVideoRequest other) {
if (other == null) {
return;
}
if (other.videoId_ != null) {
if (videoId_ == null) {
videoId_ = new global::KillrVideo.Protobuf.Uuid();
}
VideoId.MergeFrom(other.VideoId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (videoId_ == null) {
videoId_ = new global::KillrVideo.Protobuf.Uuid();
}
input.ReadMessage(videoId_);
break;
}
}
}
}
}
/// <summary>
/// Response with the current status of an uploaded video
/// </summary>
public sealed partial class GetStatusOfVideoResponse : pb::IMessage<GetStatusOfVideoResponse> {
private static readonly pb::MessageParser<GetStatusOfVideoResponse> _parser = new pb::MessageParser<GetStatusOfVideoResponse>(() => new GetStatusOfVideoResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetStatusOfVideoResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::KillrVideo.Uploads.UploadsServiceReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetStatusOfVideoResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetStatusOfVideoResponse(GetStatusOfVideoResponse other) : this() {
StatusDate = other.statusDate_ != null ? other.StatusDate.Clone() : null;
currentState_ = other.currentState_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetStatusOfVideoResponse Clone() {
return new GetStatusOfVideoResponse(this);
}
/// <summary>Field number for the "status_date" field.</summary>
public const int StatusDateFieldNumber = 1;
private global::Google.Protobuf.WellKnownTypes.Timestamp statusDate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp StatusDate {
get { return statusDate_; }
set {
statusDate_ = value;
}
}
/// <summary>Field number for the "current_state" field.</summary>
public const int CurrentStateFieldNumber = 2;
private string currentState_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string CurrentState {
get { return currentState_; }
set {
currentState_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetStatusOfVideoResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetStatusOfVideoResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(StatusDate, other.StatusDate)) return false;
if (CurrentState != other.CurrentState) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (statusDate_ != null) hash ^= StatusDate.GetHashCode();
if (CurrentState.Length != 0) hash ^= CurrentState.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (statusDate_ != null) {
output.WriteRawTag(10);
output.WriteMessage(StatusDate);
}
if (CurrentState.Length != 0) {
output.WriteRawTag(18);
output.WriteString(CurrentState);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (statusDate_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(StatusDate);
}
if (CurrentState.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(CurrentState);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetStatusOfVideoResponse other) {
if (other == null) {
return;
}
if (other.statusDate_ != null) {
if (statusDate_ == null) {
statusDate_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
StatusDate.MergeFrom(other.StatusDate);
}
if (other.CurrentState.Length != 0) {
CurrentState = other.CurrentState;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (statusDate_ == null) {
statusDate_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(statusDate_);
break;
}
case 18: {
CurrentState = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using Lucene.Net.Documents;
using Lucene.Net.Support;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Text;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Analyzer = Lucene.Net.Analysis.Analyzer;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockTokenizer = Lucene.Net.Analysis.MockTokenizer;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using StoredField = StoredField;
using StringField = StringField;
using TextField = TextField;
public class DocHelper
{
public static readonly FieldType CustomType;
public const string FIELD_1_TEXT = "field one text";
public const string TEXT_FIELD_1_KEY = "textField1";
public static Field TextField1;
public static readonly FieldType CustomType2;
public const string FIELD_2_TEXT = "field field field two text";
//Fields will be lexicographically sorted. So, the order is: field, text, two
public static readonly int[] FIELD_2_FREQS = new int[] { 3, 1, 1 };
public const string TEXT_FIELD_2_KEY = "textField2";
public static Field TextField2;
public static readonly FieldType CustomType3;
public const string FIELD_3_TEXT = "aaaNoNorms aaaNoNorms bbbNoNorms";
public const string TEXT_FIELD_3_KEY = "textField3";
public static Field TextField3;
public const string KEYWORD_TEXT = "Keyword";
public const string KEYWORD_FIELD_KEY = "keyField";
public static Field KeyField;
public static readonly FieldType CustomType5;
public const string NO_NORMS_TEXT = "omitNormsText";
public const string NO_NORMS_KEY = "omitNorms";
public static Field NoNormsField;
public static readonly FieldType CustomType6;
public const string NO_TF_TEXT = "analyzed with no tf and positions";
public const string NO_TF_KEY = "omitTermFreqAndPositions";
public static Field NoTFField;
public static readonly FieldType CustomType7;
public const string UNINDEXED_FIELD_TEXT = "unindexed field text";
public const string UNINDEXED_FIELD_KEY = "unIndField";
public static Field UnIndField;
public const string UNSTORED_1_FIELD_TEXT = "unstored field text";
public const string UNSTORED_FIELD_1_KEY = "unStoredField1";
public static Field UnStoredField1;// = new TextField(UNSTORED_FIELD_1_KEY, UNSTORED_1_FIELD_TEXT, Field.Store.NO);
public static readonly FieldType CustomType8;
public const string UNSTORED_2_FIELD_TEXT = "unstored field text";
public const string UNSTORED_FIELD_2_KEY = "unStoredField2";
public static Field UnStoredField2;
public const string LAZY_FIELD_BINARY_KEY = "lazyFieldBinary";
public static byte[] LAZY_FIELD_BINARY_BYTES;
public static Field LazyFieldBinary;
public const string LAZY_FIELD_KEY = "lazyField";
public const string LAZY_FIELD_TEXT = "These are some field bytes";
public static Field LazyField;// = new Field(LAZY_FIELD_KEY, LAZY_FIELD_TEXT, CustomType);
public const string LARGE_LAZY_FIELD_KEY = "largeLazyField";
public static string LARGE_LAZY_FIELD_TEXT;
public static Field LargeLazyField;
//From Issue 509
public const string FIELD_UTF1_TEXT = "field one \u4e00text";
public const string TEXT_FIELD_UTF1_KEY = "textField1Utf8";
public static Field TextUtfField1;// = new Field(TEXT_FIELD_UTF1_KEY, FIELD_UTF1_TEXT, CustomType);
public const string FIELD_UTF2_TEXT = "field field field \u4e00two text";
//Fields will be lexicographically sorted. So, the order is: field, text, two
public static readonly int[] FIELD_UTF2_FREQS = new int[] { 3, 1, 1 };
public const string TEXT_FIELD_UTF2_KEY = "textField2Utf8";
public static Field TextUtfField2;// = new Field(TEXT_FIELD_UTF2_KEY, FIELD_UTF2_TEXT, CustomType2);
public static IDictionary<string, object> NameValues = null;
// ordered list of all the fields...
// could use LinkedHashMap for this purpose if Java1.4 is OK
public static Field[] Fields = null;
public static IDictionary<string, IndexableField> All = new Dictionary<string, IndexableField>();
public static IDictionary<string, IndexableField> Indexed = new Dictionary<string, IndexableField>();
public static IDictionary<string, IndexableField> Stored = new Dictionary<string, IndexableField>();
public static IDictionary<string, IndexableField> Unstored = new Dictionary<string, IndexableField>();
public static IDictionary<string, IndexableField> Unindexed = new Dictionary<string, IndexableField>();
public static IDictionary<string, IndexableField> Termvector = new Dictionary<string, IndexableField>();
public static IDictionary<string, IndexableField> Notermvector = new Dictionary<string, IndexableField>();
public static IDictionary<string, IndexableField> Lazy = new Dictionary<string, IndexableField>();
public static IDictionary<string, IndexableField> NoNorms = new Dictionary<string, IndexableField>();
public static IDictionary<string, IndexableField> NoTf = new Dictionary<string, IndexableField>();
private static void Add(IDictionary<string, IndexableField> map, IndexableField field)
{
map[field.Name()] = field;
}
/// <summary>
/// Adds the fields above to a document </summary>
/// <param name="doc"> The document to write </param>
public static void SetupDoc(Document doc)
{
for (int i = 0; i < Fields.Length; i++)
{
doc.Add(Fields[i]);
}
}
/// <summary>
/// Writes the document to the directory using a segment
/// named "test"; returns the SegmentInfo describing the new
/// segment
/// </summary>
public static SegmentCommitInfo WriteDoc(Random random, Directory dir, Document doc)
{
return WriteDoc(random, dir, new MockAnalyzer(random, MockTokenizer.WHITESPACE, false), null, doc);
}
/// <summary>
/// Writes the document to the directory using the analyzer
/// and the similarity score; returns the SegmentInfo
/// describing the new segment
/// </summary>
public static SegmentCommitInfo WriteDoc(Random random, Directory dir, Analyzer analyzer, Similarity similarity, Document doc)
{
IndexWriter writer = new IndexWriter(dir, (new IndexWriterConfig(Util.LuceneTestCase.TEST_VERSION_CURRENT, analyzer)).SetSimilarity(similarity ?? IndexSearcher.DefaultSimilarity)); // LuceneTestCase.newIndexWriterConfig(random,
//writer.SetNoCFSRatio(0.0);
writer.AddDocument(doc);
writer.Commit();
SegmentCommitInfo info = writer.NewestSegment();
writer.Dispose();
return info;
}
public static int NumFields(Document doc)
{
return doc.Fields.Count;
}
public static Document CreateDocument(int n, string indexName, int numFields)
{
StringBuilder sb = new StringBuilder();
FieldType customType = new FieldType(TextField.TYPE_STORED);
customType.StoreTermVectors = true;
customType.StoreTermVectorPositions = true;
customType.StoreTermVectorOffsets = true;
FieldType customType1 = new FieldType(StringField.TYPE_STORED);
customType1.StoreTermVectors = true;
customType1.StoreTermVectorPositions = true;
customType1.StoreTermVectorOffsets = true;
Document doc = new Document();
doc.Add(new Field("id", Convert.ToString(n), customType1));
doc.Add(new Field("indexname", indexName, customType1));
sb.Append("a");
sb.Append(n);
doc.Add(new Field("field1", sb.ToString(), customType));
sb.Append(" b");
sb.Append(n);
for (int i = 1; i < numFields; i++)
{
doc.Add(new Field("field" + (i + 1), sb.ToString(), customType));
}
return doc;
}
static DocHelper()
{
CustomType = new FieldType(TextField.TYPE_STORED);
TextField1 = new Field(TEXT_FIELD_1_KEY, FIELD_1_TEXT, CustomType);
CustomType2 = new FieldType(TextField.TYPE_STORED);
CustomType2.StoreTermVectors = true;
CustomType2.StoreTermVectorPositions = true;
CustomType2.StoreTermVectorOffsets = true;
TextField2 = new Field(TEXT_FIELD_2_KEY, FIELD_2_TEXT, CustomType2);
CustomType3 = new FieldType(TextField.TYPE_STORED);
CustomType3.OmitNorms = true;
TextField3 = new Field(TEXT_FIELD_3_KEY, FIELD_3_TEXT, CustomType3);
KeyField = new StringField(KEYWORD_FIELD_KEY, KEYWORD_TEXT, Field.Store.YES);
CustomType5 = new FieldType(TextField.TYPE_STORED);
CustomType5.OmitNorms = true;
CustomType5.Tokenized = false;
NoNormsField = new Field(NO_NORMS_KEY, NO_NORMS_TEXT, CustomType5);
CustomType6 = new FieldType(TextField.TYPE_STORED);
CustomType6.IndexOptions = FieldInfo.IndexOptions.DOCS_ONLY;
NoTFField = new Field(NO_TF_KEY, NO_TF_TEXT, CustomType6);
CustomType7 = new FieldType();
CustomType7.Stored = true;
UnIndField = new Field(UNINDEXED_FIELD_KEY, UNINDEXED_FIELD_TEXT, CustomType7);
CustomType8 = new FieldType(TextField.TYPE_NOT_STORED);
CustomType8.StoreTermVectors = true;
UnStoredField2 = new Field(UNSTORED_FIELD_2_KEY, UNSTORED_2_FIELD_TEXT, CustomType8);
UnStoredField1 = new TextField(UNSTORED_FIELD_1_KEY, UNSTORED_1_FIELD_TEXT, Field.Store.NO);
LazyField = new Field(LAZY_FIELD_KEY, LAZY_FIELD_TEXT, CustomType);
TextUtfField1 = new Field(TEXT_FIELD_UTF1_KEY, FIELD_UTF1_TEXT, CustomType);
TextUtfField2 = new Field(TEXT_FIELD_UTF2_KEY, FIELD_UTF2_TEXT, CustomType2);
Fields = new Field[] { TextField1, TextField2, TextField3, KeyField, NoNormsField, NoTFField, UnIndField, UnStoredField1, UnStoredField2, TextUtfField1, TextUtfField2, LazyField, LazyFieldBinary, LargeLazyField };
//Initialize the large Lazy Field
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < 10000; i++)
{
buffer.Append("Lazily loading lengths of language in lieu of laughing ");
}
try
{
LAZY_FIELD_BINARY_BYTES = "These are some binary field bytes".GetBytes(IOUtils.CHARSET_UTF_8);
}
catch (EncoderFallbackException e)
{
}
LazyFieldBinary = new StoredField(LAZY_FIELD_BINARY_KEY, LAZY_FIELD_BINARY_BYTES);
Fields[Fields.Length - 2] = LazyFieldBinary;
LARGE_LAZY_FIELD_TEXT = buffer.ToString();
LargeLazyField = new Field(LARGE_LAZY_FIELD_KEY, LARGE_LAZY_FIELD_TEXT, CustomType);
Fields[Fields.Length - 1] = LargeLazyField;
for (int i = 0; i < Fields.Length; i++)
{
IndexableField f = Fields[i];
Add(All, f);
if (f.FieldType().Indexed)
{
Add(Indexed, f);
}
else
{
Add(Unindexed, f);
}
if (f.FieldType().StoreTermVectors)
{
Add(Termvector, f);
}
if (f.FieldType().Indexed && !f.FieldType().StoreTermVectors)
{
Add(Notermvector, f);
}
if (f.FieldType().Stored)
{
Add(Stored, f);
}
else
{
Add(Unstored, f);
}
if (f.FieldType().IndexOptions == FieldInfo.IndexOptions.DOCS_ONLY)
{
Add(NoTf, f);
}
if (f.FieldType().OmitNorms)
{
Add(NoNorms, f);
}
if (f.FieldType().IndexOptions == FieldInfo.IndexOptions.DOCS_ONLY)
{
Add(NoTf, f);
}
//if (f.isLazy()) add(lazy, f);
}
NameValues = new Dictionary<string, object>();
NameValues[TEXT_FIELD_1_KEY] = FIELD_1_TEXT;
NameValues[TEXT_FIELD_2_KEY] = FIELD_2_TEXT;
NameValues[TEXT_FIELD_3_KEY] = FIELD_3_TEXT;
NameValues[KEYWORD_FIELD_KEY] = KEYWORD_TEXT;
NameValues[NO_NORMS_KEY] = NO_NORMS_TEXT;
NameValues[NO_TF_KEY] = NO_TF_TEXT;
NameValues[UNINDEXED_FIELD_KEY] = UNINDEXED_FIELD_TEXT;
NameValues[UNSTORED_FIELD_1_KEY] = UNSTORED_1_FIELD_TEXT;
NameValues[UNSTORED_FIELD_2_KEY] = UNSTORED_2_FIELD_TEXT;
NameValues[LAZY_FIELD_KEY] = LAZY_FIELD_TEXT;
NameValues[LAZY_FIELD_BINARY_KEY] = LAZY_FIELD_BINARY_BYTES;
NameValues[LARGE_LAZY_FIELD_KEY] = LARGE_LAZY_FIELD_TEXT;
NameValues[TEXT_FIELD_UTF1_KEY] = FIELD_UTF1_TEXT;
NameValues[TEXT_FIELD_UTF2_KEY] = FIELD_UTF2_TEXT;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ModestTree
{
public static class TypeExtensions
{
public static bool DerivesFrom<T>(this Type a)
{
return DerivesFrom(a, typeof(T));
}
// This seems easier to think about than IsAssignableFrom
public static bool DerivesFrom(this Type a, Type b)
{
return b != a && a.DerivesFromOrEqual(b);
}
public static bool DerivesFromOrEqual<T>(this Type a)
{
return DerivesFromOrEqual(a, typeof(T));
}
public static bool DerivesFromOrEqual(this Type a, Type b)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return b == a || b.GetTypeInfo().IsAssignableFrom(a.GetTypeInfo());
#else
return b == a || b.IsAssignableFrom(a);
#endif
}
public static bool IsEnum(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsEnum;
#else
return type.IsEnum;
#endif
}
public static bool IsValueType(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsValueType;
#else
return type.IsValueType;
#endif
}
public static MethodInfo[] DeclaredMethods(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetRuntimeMethods()
.Where(x => x.DeclaringType == type).ToArray();
#else
return type.GetMethods(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
#endif
}
public static PropertyInfo[] DeclaredProperties(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
// There doesn't appear to be an IsStatic member on PropertyInfo
return type.GetRuntimeProperties()
.Where(x => x.DeclaringType == type).ToArray();
#else
return type.GetProperties(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
#endif
}
public static FieldInfo[] DeclaredFields(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetRuntimeFields()
.Where(x => x.DeclaringType == type && !x.IsStatic).ToArray();
#else
return type.GetFields(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
#endif
}
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
public static bool IsAssignableFrom(this Type a, Type b)
{
return a.GetTypeInfo().IsAssignableFrom(b.GetTypeInfo());
}
#endif
public static Type BaseType(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().BaseType;
#else
return type.BaseType;
#endif
}
public static bool IsGenericType(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsGenericType;
#else
return type.IsGenericType;
#endif
}
public static bool IsGenericTypeDefinition(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsGenericTypeDefinition;
#else
return type.IsGenericType;
#endif
}
public static bool IsPrimitive(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsPrimitive;
#else
return type.IsPrimitive;
#endif
}
public static bool IsInterface(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsInterface;
#else
return type.IsInterface;
#endif
}
public static bool IsAbstract(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsAbstract;
#else
return type.IsAbstract;
#endif
}
public static bool IsSealed(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().IsSealed;
#else
return type.IsSealed;
#endif
}
public static bool IsStatic(this Type type) {
return type.IsAbstract() && type.IsSealed();
}
public static MethodInfo Method(this Delegate del)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return del.GetMethodInfo();
#else
return del.Method;
#endif
}
public static Type[] GenericArguments(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().GenericTypeArguments;
#else
return type.GetGenericArguments();
#endif
}
public static Type[] Interfaces(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().ImplementedInterfaces.ToArray();
#else
return type.GetInterfaces();
#endif
}
public static ConstructorInfo[] Constructors(this Type type)
{
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
return type.GetTypeInfo().DeclaredConstructors.ToArray();
#else
return type.GetConstructors(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
#endif
}
public static object GetDefaultValue(this Type type)
{
if (type.IsValueType())
{
return Activator.CreateInstance(type);
}
return null;
}
// Returns name without generic arguments
public static string GetSimpleName(this Type type)
{
var name = type.Name;
var quoteIndex = name.IndexOf("`");
if (quoteIndex == -1)
{
return name;
}
// Remove the backtick
return name.Substring(0, quoteIndex);
}
public static IEnumerable<Type> GetParentTypes(this Type type)
{
if (type == null || type.BaseType() == null || type == typeof(object) || type.BaseType() == typeof(object))
{
yield break;
}
yield return type.BaseType();
foreach (var ancestor in type.BaseType().GetParentTypes())
{
yield return ancestor;
}
}
public static string NameWithParents(this Type type)
{
var typeList = type.GetParentTypes().Prepend(type).Select(x => x.Name()).ToArray();
return string.Join(":", typeList);
}
public static bool IsClosedGenericType(this Type type)
{
return type.IsGenericType() && type != type.GetGenericTypeDefinition();
}
public static bool IsOpenGenericType(this Type type)
{
return type.IsGenericType() && type == type.GetGenericTypeDefinition();
}
// Returns all instance and static properties fields, including private and public and also those in base classes
public static IEnumerable<FieldInfo> GetAllFields(this Type type)
{
foreach (var fieldInfo in type.DeclaredFields())
{
yield return fieldInfo;
}
if (type.BaseType() != null && type.BaseType() != typeof(object))
{
foreach (var fieldInfo in type.BaseType().GetAllFields())
{
yield return fieldInfo;
}
}
}
// Returns all instance and static properties, including private and public and also those in base classes
public static IEnumerable<PropertyInfo> GetAllProperties(this Type type)
{
foreach (var propInfo in type.DeclaredProperties())
{
yield return propInfo;
}
if (type.BaseType() != null && type.BaseType() != typeof(object))
{
foreach (var propInfo in type.BaseType().GetAllProperties())
{
yield return propInfo;
}
}
}
// Returns all instance and static properties methods, including private and public and also those in base classes
public static IEnumerable<MethodInfo> GetAllMethods(this Type type)
{
foreach (var methodInfo in type.DeclaredMethods())
{
yield return methodInfo;
}
if (type.BaseType() != null && type.BaseType() != typeof(object))
{
foreach (var methodInfo in type.BaseType().GetAllMethods())
{
yield return methodInfo;
}
}
}
public static string Name(this Type type)
{
if (type.IsArray)
{
return string.Format("{0}[]", type.GetElementType().Name());
}
return (type.DeclaringType == null ? "" : type.DeclaringType.Name() + ".") + GetCSharpTypeName(type.Name);
}
static string GetCSharpTypeName(string typeName)
{
switch (typeName)
{
case "String":
case "Object":
case "Void":
case "Byte":
case "Double":
case "Decimal":
return typeName.ToLower();
case "Int16":
return "short";
case "Int32":
return "int";
case "Int64":
return "long";
case "Single":
return "float";
case "Boolean":
return "bool";
default:
return typeName;
}
}
public static T GetAttribute<T>(this MemberInfo provider)
where T : Attribute
{
return provider.AllAttributes<T>().Single();
}
public static T TryGetAttribute<T>(this MemberInfo provider)
where T : Attribute
{
return provider.AllAttributes<T>().OnlyOrDefault();
}
public static bool HasAttribute(
this MemberInfo provider, params Type[] attributeTypes)
{
return provider.AllAttributes(attributeTypes).Any();
}
public static bool HasAttribute<T>(this MemberInfo provider)
where T : Attribute
{
return provider.AllAttributes(typeof(T)).Any();
}
public static IEnumerable<T> AllAttributes<T>(
this MemberInfo provider)
where T : Attribute
{
return provider.AllAttributes(typeof(T)).Cast<T>();
}
public static IEnumerable<Attribute> AllAttributes(
this MemberInfo provider, params Type[] attributeTypes)
{
var allAttributes = provider.GetCustomAttributes(true).Cast<Attribute>();
if (attributeTypes.Length == 0)
{
return allAttributes;
}
return allAttributes.Where(a => attributeTypes.Any(x => a.GetType().DerivesFromOrEqual(x)));
}
// We could avoid this duplication here by using ICustomAttributeProvider but this class
// does not exist on the WP8 platform
public static bool HasAttribute(
this ParameterInfo provider, params Type[] attributeTypes)
{
return provider.AllAttributes(attributeTypes).Any();
}
public static bool HasAttribute<T>(this ParameterInfo provider)
where T : Attribute
{
return provider.AllAttributes(typeof(T)).Any();
}
public static IEnumerable<T> AllAttributes<T>(
this ParameterInfo provider)
where T : Attribute
{
return provider.AllAttributes(typeof(T)).Cast<T>();
}
public static IEnumerable<Attribute> AllAttributes(
this ParameterInfo provider, params Type[] attributeTypes)
{
var allAttributes = provider.GetCustomAttributes(true).Cast<Attribute>();
if (attributeTypes.Length == 0)
{
return allAttributes;
}
return allAttributes.Where(a => attributeTypes.Any(x => a.GetType().DerivesFromOrEqual(x)));
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Linq;
using System.Reflection;
using Aurora.Framework;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
namespace Aurora.Modules.Chat
{
/// <summary>
/// This dialog module has support for mute lists
/// </summary>
public class AuroraDialogModule : INonSharedRegionModule, IDialogModule
{
protected bool m_enabled = true;
protected IMuteListModule m_muteListModule;
protected IScene m_scene;
public bool IsSharedModule
{
get { return false; }
}
#region IDialogModule Members
public void SendAlertToUser(IClientAPI client, string message)
{
SendAlertToUser(client, message, false);
}
public void SendAlertToUser(IClientAPI client, string message, bool modal)
{
client.SendAgentAlertMessage(message, modal);
}
public void SendAlertToUser(UUID agentID, string message)
{
SendAlertToUser(agentID, message, false);
}
public void SendAlertToUser(UUID agentID, string message, bool modal)
{
IScenePresence sp = m_scene.GetScenePresence(agentID);
if (sp != null && !sp.IsChildAgent)
sp.ControllingClient.SendAgentAlertMessage(message, modal);
}
public void SendAlertToUser(string firstName, string lastName, string message, bool modal)
{
IScenePresence presence = m_scene.SceneGraph.GetScenePresence(firstName, lastName);
if (presence != null && !presence.IsChildAgent)
presence.ControllingClient.SendAgentAlertMessage(message, modal);
}
public void SendGeneralAlert(string message)
{
m_scene.ForEachScenePresence(delegate(IScenePresence presence)
{
if (!presence.IsChildAgent)
presence.ControllingClient.SendAlertMessage(message);
});
}
public void SendDialogToUser(
UUID avatarID, string objectName, UUID objectID, UUID ownerID,
string message, UUID textureID, int ch, string[] buttonlabels)
{
UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.AllScopeIDs, ownerID);
string ownerFirstName, ownerLastName;
if (account != null)
{
ownerFirstName = account.FirstName;
ownerLastName = account.LastName;
}
else
{
ownerFirstName = "(unknown";
ownerLastName = "user)";
}
//If the user is muted, we do NOT send them dialog boxes
if (m_muteListModule != null)
{
bool cached = false; //Unneeded
#if (!ISWIN)
foreach (MuteList mute in m_muteListModule.GetMutes(avatarID, out cached))
{
if (mute.MuteID == ownerID)
{
return;
}
}
#else
if (m_muteListModule.GetMutes(avatarID, out cached).Any(mute => mute.MuteID == ownerID))
{
return;
}
#endif
}
IScenePresence sp = m_scene.GetScenePresence(avatarID);
if (sp != null && !sp.IsChildAgent)
sp.ControllingClient.SendDialog(objectName, objectID, ownerID, ownerFirstName, ownerLastName, message,
textureID, ch, buttonlabels);
}
public void SendUrlToUser(
UUID avatarID, string objectName, UUID objectID, UUID ownerID, bool groupOwned, string message, string url)
{
IScenePresence sp = m_scene.GetScenePresence(avatarID);
//If the user is muted, do NOT send them URL boxes
if (m_muteListModule != null)
{
bool cached = false; //Unneeded
#if (!ISWIN)
foreach (MuteList mute in m_muteListModule.GetMutes(avatarID, out cached))
{
if (mute.MuteID == ownerID)
{
return;
}
}
#else
if (m_muteListModule.GetMutes(avatarID, out cached).Any(mute => mute.MuteID == ownerID))
{
return;
}
#endif
}
if (sp != null && !sp.IsChildAgent)
sp.ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned, message, url);
}
public void SendTextBoxToUser(UUID avatarID, string message, int chatChannel, string name, UUID objectID,
UUID ownerID)
{
IScenePresence sp = m_scene.GetScenePresence(avatarID);
if (sp != null && !sp.IsChildAgent)
{
UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.AllScopeIDs, ownerID);
string ownerFirstName, ownerLastName;
if (account != null)
{
ownerFirstName = account.FirstName;
ownerLastName = account.LastName;
}
else
{
if (name != "")
{
ownerFirstName = name;
ownerLastName = "";
}
else
{
ownerFirstName = "(unknown";
ownerLastName = "user)";
}
}
//If the user is muted, do not send the text box
if (m_muteListModule != null)
{
bool cached = false; //Unneeded
#if (!ISWIN)
foreach (MuteList mute in m_muteListModule.GetMutes(avatarID, out cached))
{
if (mute.MuteID == ownerID)
{
return;
}
}
#else
if (m_muteListModule.GetMutes(avatarID, out cached).Any(mute => mute.MuteID == ownerID))
{
return;
}
#endif
}
sp.ControllingClient.SendTextBoxRequest(message, chatChannel, name, ownerFirstName, ownerLastName,
objectID);
}
}
public void SendNotificationToUsersInRegion(
UUID fromAvatarID, string fromAvatarName, string message)
{
m_scene.ForEachScenePresence(delegate(IScenePresence presence)
{
if (!presence.IsChildAgent)
presence.ControllingClient.SendBlueBoxMessage(fromAvatarID,
fromAvatarName,
message);
});
}
#endregion
#region INonSharedRegionModule Members
public void Initialise(IConfigSource source)
{
IConfig m_config = source.Configs["Dialog"];
if (null == m_config)
{
m_enabled = false;
return;
}
if (m_config.GetString("DialogModule", "DialogModule") != "AuroraDialogModule")
{
m_enabled = false;
}
}
public void AddRegion(IScene scene)
{
if (!m_enabled)
return;
m_scene = scene;
m_scene.RegisterModuleInterface<IDialogModule>(this);
m_scene.EventManager.OnPermissionError += SendAlertToUser;
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand(
"alert", "alert [first] [last] [message]", "Send an alert to a user", HandleAlertConsoleCommand);
MainConsole.Instance.Commands.AddCommand(
"alert general", "alert general [message]", "Send an alert to everyone", HandleAlertConsoleCommand);
}
}
public void RemoveRegion(IScene scene)
{
}
public void RegionLoaded(IScene scene)
{
m_muteListModule = m_scene.RequestModuleInterface<IMuteListModule>();
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Close()
{
}
public string Name
{
get { return "Dialog Module"; }
}
#endregion
public void PostInitialise()
{
}
/// <summary>
/// Handle an alert command from the console.
/// </summary>
/// <param name = "module"></param>
/// <param name = "cmdparams"></param>
public void HandleAlertConsoleCommand(string[] cmdparams)
{
if (MainConsole.Instance.ConsoleScene != m_scene && MainConsole.Instance.ConsoleScene == null)
return;
if (cmdparams[1] == "general")
{
string message = Util.CombineParams(cmdparams, 2);
MainConsole.Instance.InfoFormat(
"[DIALOG]: Sending general alert in region {0} with message {1}", m_scene.RegionInfo.RegionName,
message);
SendGeneralAlert(message);
}
else
{
string firstName = cmdparams[1];
string lastName = cmdparams[2];
string message = Util.CombineParams(cmdparams, 3);
MainConsole.Instance.InfoFormat(
"[DIALOG]: Sending alert in region {0} to {1} {2} with message {3}",
m_scene.RegionInfo.RegionName, firstName, lastName, message);
SendAlertToUser(firstName, lastName, message, false);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text;
namespace System.Diagnostics
{
public partial class Process : IDisposable
{
/// <summary>
/// Creates an array of <see cref="Process"/> components that are associated with process resources on a
/// remote computer. These process resources share the specified process name.
/// </summary>
public static Process[] GetProcessesByName(string processName, string machineName)
{
ProcessManager.ThrowIfRemoteMachine(machineName);
if (processName == null)
{
processName = string.Empty;
}
var reusableReader = new ReusableTextReader();
var processes = new List<Process>();
foreach (int pid in ProcessManager.EnumerateProcessIds())
{
Interop.procfs.ParsedStat parsedStat;
if (Interop.procfs.TryReadStatFile(pid, out parsedStat, reusableReader) &&
string.Equals(processName, Process.GetUntruncatedProcessName(ref parsedStat), StringComparison.OrdinalIgnoreCase))
{
ProcessInfo processInfo = ProcessManager.CreateProcessInfo(ref parsedStat, reusableReader, processName);
processes.Add(new Process(machineName, false, processInfo.ProcessId, processInfo));
}
}
return processes.ToArray();
}
/// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary>
public TimeSpan PrivilegedProcessorTime
{
get
{
return TicksToTimeSpan(GetStat().stime);
}
}
/// <summary>Gets the time the associated process was started.</summary>
internal DateTime StartTimeCore
{
get
{
return BootTimeToDateTime(TicksToTimeSpan(GetStat().starttime));
}
}
/// <summary>Computes a time based on a number of ticks since boot.</summary>
/// <param name="timespanAfterBoot">The timespan since boot.</param>
/// <returns>The converted time.</returns>
internal static DateTime BootTimeToDateTime(TimeSpan timespanAfterBoot)
{
// And use that to determine the absolute time for timespan.
DateTime dt = BootTime + timespanAfterBoot;
// The return value is expected to be in the local time zone.
// It is converted here (rather than starting with DateTime.Now) to avoid DST issues.
return dt.ToLocalTime();
}
/// <summary>Gets the system boot time.</summary>
private static DateTime BootTime
{
get
{
// '/proc/stat -> btime' gets the boot time.
// btime is the time of system boot in seconds since the Unix epoch.
// It includes suspended time and is updated based on the system time (settimeofday).
const string StatFile = Interop.procfs.ProcStatFilePath;
string text = File.ReadAllText(StatFile);
int btimeLineStart = text.IndexOf("\nbtime ");
if (btimeLineStart >= 0)
{
int btimeStart = btimeLineStart + "\nbtime ".Length;
int btimeEnd = text.IndexOf('\n', btimeStart);
if (btimeEnd > btimeStart)
{
if (long.TryParse(text.AsSpan(btimeStart, btimeEnd - btimeStart), out long bootTimeSeconds))
{
return DateTime.UnixEpoch + TimeSpan.FromSeconds(bootTimeSeconds);
}
}
}
return DateTime.UtcNow;
}
}
/// <summary>Gets the parent process ID</summary>
private int ParentProcessId =>
GetStat().ppid;
/// <summary>Gets execution path</summary>
private string GetPathToOpenFile()
{
string[] allowedProgramsToRun = { "xdg-open", "gnome-open", "kfmclient" };
foreach (var program in allowedProgramsToRun)
{
string pathToProgram = FindProgramInPath(program);
if (!string.IsNullOrEmpty(pathToProgram))
{
return pathToProgram;
}
}
return null;
}
/// <summary>
/// Gets the amount of time the associated process has spent utilizing the CPU.
/// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and
/// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>.
/// </summary>
public TimeSpan TotalProcessorTime
{
get
{
Interop.procfs.ParsedStat stat = GetStat();
return TicksToTimeSpan(stat.utime + stat.stime);
}
}
/// <summary>
/// Gets the amount of time the associated process has spent running code
/// inside the application portion of the process (not the operating system core).
/// </summary>
public TimeSpan UserProcessorTime
{
get
{
return TicksToTimeSpan(GetStat().utime);
}
}
partial void EnsureHandleCountPopulated()
{
if (_processInfo.HandleCount <= 0 && _haveProcessId)
{
// Don't get information for a PID that exited and has possibly been recycled.
if (GetHasExited(refresh: false))
{
return;
}
string path = Interop.procfs.GetFileDescriptorDirectoryPathForProcess(_processId);
if (Directory.Exists(path))
{
try
{
_processInfo.HandleCount = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly).Length;
}
catch (DirectoryNotFoundException) // Occurs when the process is deleted between the Exists check and the GetFiles call.
{
}
}
}
}
/// <summary>
/// Gets or sets which processors the threads in this process can be scheduled to run on.
/// </summary>
private unsafe IntPtr ProcessorAffinityCore
{
get
{
EnsureState(State.HaveNonExitedId);
IntPtr set;
if (Interop.Sys.SchedGetAffinity(_processId, out set) != 0)
{
throw new Win32Exception(); // match Windows exception
}
return set;
}
set
{
EnsureState(State.HaveNonExitedId);
if (Interop.Sys.SchedSetAffinity(_processId, ref value) != 0)
{
throw new Win32Exception(); // match Windows exception
}
}
}
/// <summary>
/// Make sure we have obtained the min and max working set limits.
/// </summary>
private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet)
{
minWorkingSet = IntPtr.Zero; // no defined limit available
// For max working set, try to respect container limits by reading
// from cgroup, but if it's unavailable, fall back to reading from procfs.
EnsureState(State.HaveNonExitedId);
if (!Interop.cgroups.TryGetMemoryLimit(out ulong rsslim))
{
rsslim = GetStat().rsslim;
}
// rsslim is a ulong, but maxWorkingSet is an IntPtr, so we need to cap rsslim
// at the max size of IntPtr. This often happens when there is no configured
// rsslim other than ulong.MaxValue, which without these checks would show up
// as a maxWorkingSet == -1.
switch (IntPtr.Size)
{
case 4:
if (rsslim > int.MaxValue)
rsslim = int.MaxValue;
break;
case 8:
if (rsslim > long.MaxValue)
rsslim = long.MaxValue;
break;
}
maxWorkingSet = (IntPtr)rsslim;
}
/// <summary>Sets one or both of the minimum and maximum working set limits.</summary>
/// <param name="newMin">The new minimum working set limit, or null not to change it.</param>
/// <param name="newMax">The new maximum working set limit, or null not to change it.</param>
/// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param>
/// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param>
private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax)
{
// RLIMIT_RSS with setrlimit not supported on Linux > 2.4.30.
throw new PlatformNotSupportedException(SR.MinimumWorkingSetNotSupported);
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Gets the path to the executable for the process, or null if it could not be retrieved.</summary>
/// <param name="processId">The pid for the target process, or -1 for the current process.</param>
internal static string GetExePath(int processId = -1)
{
string exeFilePath = processId == -1 ?
Interop.procfs.SelfExeFilePath :
Interop.procfs.GetExeFilePathForProcess(processId);
return Interop.Sys.ReadLink(exeFilePath);
}
/// <summary>Gets the name that was used to start the process, or null if it could not be retrieved.</summary>
/// <param name="stat">The stat for the target process.</param>
internal static string GetUntruncatedProcessName(ref Interop.procfs.ParsedStat stat)
{
string cmdLineFilePath = Interop.procfs.GetCmdLinePathForProcess(stat.pid);
byte[] rentedArray = null;
try
{
// bufferSize == 1 used to avoid unnecessary buffer in FileStream
using (var fs = new FileStream(cmdLineFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1, useAsync: false))
{
Span<byte> buffer = stackalloc byte[512];
int bytesRead = 0;
while (true)
{
// Resize buffer if it was too small.
if (bytesRead == buffer.Length)
{
uint newLength = (uint)buffer.Length * 2;
byte[] tmp = ArrayPool<byte>.Shared.Rent((int)newLength);
buffer.CopyTo(tmp);
byte[] toReturn = rentedArray;
buffer = rentedArray = tmp;
if (toReturn != null)
{
ArrayPool<byte>.Shared.Return(toReturn);
}
}
Debug.Assert(bytesRead < buffer.Length);
int n = fs.Read(buffer.Slice(bytesRead));
bytesRead += n;
// cmdline contains the argv array separated by '\0' bytes.
// stat.comm contains a possibly truncated version of the process name.
// When the program is a native executable, the process name will be in argv[0].
// When the program is a script, argv[0] contains the interpreter, and argv[1] contains the script name.
Span<byte> argRemainder = buffer.Slice(0, bytesRead);
int argEnd = argRemainder.IndexOf((byte)'\0');
if (argEnd != -1)
{
// Check if argv[0] has the process name.
string name = GetUntruncatedNameFromArg(argRemainder.Slice(0, argEnd), prefix: stat.comm);
if (name != null)
{
return name;
}
// Check if argv[1] has the process name.
argRemainder = argRemainder.Slice(argEnd + 1);
argEnd = argRemainder.IndexOf((byte)'\0');
if (argEnd != -1)
{
name = GetUntruncatedNameFromArg(argRemainder.Slice(0, argEnd), prefix: stat.comm);
return name ?? stat.comm;
}
}
if (n == 0)
{
return stat.comm;
}
}
}
}
catch (IOException)
{
return stat.comm;
}
finally
{
if (rentedArray != null)
{
ArrayPool<byte>.Shared.Return(rentedArray);
}
}
string GetUntruncatedNameFromArg(Span<byte> arg, string prefix)
{
// Strip directory names from arg.
int nameStart = arg.LastIndexOf((byte)'/') + 1;
string argString = Encoding.UTF8.GetString(arg.Slice(nameStart));
if (argString.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
return argString;
}
else
{
return null;
}
}
}
// ----------------------------------
// ---- Unix PAL layer ends here ----
// ----------------------------------
/// <summary>Reads the stats information for this process from the procfs file system.</summary>
private Interop.procfs.ParsedStat GetStat()
{
EnsureState(State.HaveNonExitedId);
Interop.procfs.ParsedStat stat;
if (!Interop.procfs.TryReadStatFile(_processId, out stat, new ReusableTextReader()))
{
throw new Win32Exception(SR.ProcessInformationUnavailable);
}
return stat;
}
}
}
| |
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 TodoList_Service.Areas.HelpPage.ModelDescriptions;
using TodoList_Service.Areas.HelpPage.Models;
namespace TodoList_Service.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);
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Security;
using ASC.Common.Data.Sql;
using ASC.Common.Data.Sql.Expressions;
using ASC.Common.Logging;
using ASC.Common.Utils;
using ASC.Core;
using ASC.Mail.Core.Dao.Expressions.Mailbox;
using ASC.Mail.Core.Dao.Interfaces;
using ASC.Mail.Core.DbSchema.Tables;
using ASC.Mail.Core.Entities;
using ASC.Mail.Data.Contracts;
using ASC.Mail.Extensions;
using ASC.Mail.Server.Core.Entities;
using ASC.Mail.Server.Utils;
using ASC.Mail.Utils;
using ASC.Web.Core;
using SecurityContext = ASC.Core.SecurityContext;
namespace ASC.Mail.Core.Engine
{
public class ServerEngine
{
public int Tenant { get; private set; }
public string User { get; private set; }
public ILog Log { get; private set; }
public ServerEngine(int tenant, string user, ILog log = null)
{
Tenant = tenant;
User = user;
Log = log ?? LogManager.GetLogger("ASC.Mail.ServerEngine");
}
public List<MailAddressInfo> GetAliases(int mailboxId)
{
const string server_address = "sa";
const string server_domain = "sd";
var queryForExecution = new SqlQuery(ServerAddressTable.TABLE_NAME.Alias(server_address))
.Select(ServerAddressTable.Columns.Id.Prefix(server_address))
.Select(ServerAddressTable.Columns.AddressName.Prefix(server_address))
.Select(ServerDomainTable.Columns.DomainName.Prefix(server_domain))
.Select(ServerDomainTable.Columns.Id.Prefix(server_domain))
.InnerJoin(ServerDomainTable.TABLE_NAME.Alias(server_domain),
Exp.EqColumns(ServerAddressTable.Columns.DomainId.Prefix(server_address),
ServerDomainTable.Columns.Id.Prefix(server_domain)))
.Where(ServerAddressTable.Columns.MailboxId.Prefix(server_address), mailboxId)
.Where(ServerAddressTable.Columns.IsAlias.Prefix(server_address), true);
using (var daoFactory = new DaoFactory())
{
var res = daoFactory.DbManager.ExecuteList(queryForExecution);
if (res == null)
{
return new List<MailAddressInfo>();
}
return res.ConvertAll(r => new MailAddressInfo(Convert.ToInt32(r[0]),
string.Format("{0}@{1}", r[1], r[2]), Convert.ToInt32(r[3])));
}
}
public List<MailAddressInfo> GetGroups(int mailboxId)
{
const string groups = "sg";
const string group_x_address = "ga";
const string server_address = "sa";
const string server_domain = "sd";
var queryForExecution = new SqlQuery(ServerAddressTable.TABLE_NAME.Alias(server_address))
.Select(ServerMailGroupTable.Columns.Id.Prefix(groups))
.Select(ServerMailGroupTable.Columns.Address.Prefix(groups))
.Select(ServerDomainTable.Columns.Id.Prefix(server_domain))
.InnerJoin(ServerDomainTable.TABLE_NAME.Alias(server_domain),
Exp.EqColumns(ServerAddressTable.Columns.DomainId.Prefix(server_address),
ServerDomainTable.Columns.Id.Prefix(server_domain)))
.InnerJoin(ServerMailGroupXAddressesTable.TABLE_NAME.Alias(group_x_address),
Exp.EqColumns(ServerAddressTable.Columns.Id.Prefix(server_address),
ServerMailGroupXAddressesTable.Columns.AddressId.Prefix(group_x_address)))
.InnerJoin(ServerMailGroupTable.TABLE_NAME.Alias(groups),
Exp.EqColumns(ServerMailGroupXAddressesTable.Columns.MailGroupId.Prefix(group_x_address),
ServerMailGroupTable.Columns.Id.Prefix(groups)))
.Where(ServerAddressTable.Columns.MailboxId.Prefix(server_address), mailboxId);
using (var daoFactory = new DaoFactory())
{
var res = daoFactory.DbManager.ExecuteList(queryForExecution);
if (res == null)
{
return new List<MailAddressInfo>();
}
return res.ConvertAll(r =>
new MailAddressInfo(Convert.ToInt32(r[0]), Convert.ToString(r[1]), Convert.ToInt32(r[2])));
}
}
public Entities.Server GetLinkedServer()
{
using (var daoFactory = new DaoFactory())
{
var serverDao = daoFactory.CreateServerDao();
var linkedServer = serverDao.Get(Tenant);
return linkedServer;
}
}
public List<Entities.Server> GetAllServers()
{
using (var daoFactory = new DaoFactory())
{
return GetAllServers(daoFactory);
}
}
private static List<Entities.Server> GetAllServers(IDaoFactory daoFactory)
{
var serverDao = daoFactory.CreateServerDao();
var servers = serverDao.GetList();
return servers;
}
public void Link(Entities.Server server, int tenant)
{
if (server == null)
return;
using (var daoFactory = new DaoFactory())
{
Link(daoFactory, server, tenant);
}
}
public void Link(IDaoFactory daoFactory, Entities.Server server, int tenant)
{
if (server == null)
return;
var serverDao = daoFactory.CreateServerDao();
var result = serverDao.Link(server, Tenant);
if (result <= 0)
throw new Exception("Invalid insert operation");
}
public void UnLink(Entities.Server server, int tenant)
{
if (server == null)
return;
using (var daoFactory = new DaoFactory())
{
var serverDao = daoFactory.CreateServerDao();
serverDao.UnLink(server, Tenant);
}
}
public int Save(Entities.Server server)
{
if (server == null)
throw new ArgumentNullException("server");
using (var daoFactory = new DaoFactory())
{
var serverDao = daoFactory.CreateServerDao();
var id = serverDao.Save(server);
return id;
}
}
public void Delete(int serverId)
{
if (serverId <= 0)
throw new ArgumentOutOfRangeException("serverId");
using (var daoFactory = new DaoFactory())
{
var serverDao = daoFactory.CreateServerDao();
serverDao.Delete(serverId);
}
}
public Entities.Server GetOrCreate(IDaoFactory daoFactory)
{
var serverDao = daoFactory.CreateServerDao();
var linkedServer = serverDao.Get(Tenant);
if (linkedServer != null)
return linkedServer;
var servers = GetAllServers(daoFactory);
if (!servers.Any())
throw new Exception("Mail Server not configured");
var server = servers.First();
Link(daoFactory, server, Tenant);
linkedServer = server;
return linkedServer;
}
public ServerData GetMailServer()
{
if (!IsAdmin)
throw new SecurityException("Need admin privileges.");
using (var daoFactory = new DaoFactory())
{
return GetMailServer(daoFactory);
}
}
public string GetMailServerMxDomain()
{
using (var daoFactory = new DaoFactory())
{
var server = GetMailServer(daoFactory);
return server.Dns.MxRecord.Host;
}
}
private ServerData GetMailServer(IDaoFactory daoFactory)
{
var linkedServer = GetOrCreate(daoFactory);
var dns = GetOrCreateUnusedDnsData(daoFactory, linkedServer);
var mailboxServerDao = daoFactory.CreateMailboxServerDao();
var inServer = mailboxServerDao.GetServer(linkedServer.ImapSettingsId);
var outServer = mailboxServerDao.GetServer(linkedServer.SmtpSettingsId);
return new ServerData
{
Id = linkedServer.Id,
Dns = dns,
ServerLimits = new ServerLimitData
{
MailboxMaxCountPerUser = Defines.ServerDomainMailboxPerUserLimit
},
InServer = inServer,
OutServer = outServer
};
}
public ServerDomainDnsData GetOrCreateUnusedDnsData()
{
if (!IsAdmin)
throw new SecurityException("Need admin privileges.");
using (var daoFactory = new DaoFactory())
{
var server = GetOrCreate(daoFactory);
return GetOrCreateUnusedDnsData(daoFactory, server);
}
}
public ServerDomainDnsData GetOrCreateUnusedDnsData(IDaoFactory daoFactory, Entities.Server server)
{
var serverDnsDao = daoFactory.CreateServerDnsDao(Tenant, User);
var dnsSettings = serverDnsDao.GetFree();
if (dnsSettings == null)
{
string privateKey, publicKey;
CryptoUtil.GenerateDkimKeys(out privateKey, out publicKey);
var domainCheckValue = PasswordGenerator.GenerateNewPassword(16);
var domainCheck = Defines.ServerDnsDomainCheckPrefix + ": " + domainCheckValue;
var serverDns = new ServerDns
{
Id = 0,
Tenant = Tenant,
User = User,
DomainId = Defines.UNUSED_DNS_SETTING_DOMAIN_ID,
DomainCheck = domainCheck,
DkimSelector = Defines.ServerDnsDkimSelector,
DkimPrivateKey = privateKey,
DkimPublicKey = publicKey,
DkimTtl = Defines.ServerDnsDefaultTtl,
DkimVerified = false,
DkimDateChecked = null,
Spf = Defines.ServerDnsSpfRecordValue,
SpfTtl = Defines.ServerDnsDefaultTtl,
SpfVerified = false,
SpfDateChecked = null,
Mx = server.MxRecord,
MxTtl = Defines.ServerDnsDefaultTtl,
MxVerified = false,
MxDateChecked = null,
TimeModified = DateTime.UtcNow
};
serverDns.Id = serverDnsDao.Save(serverDns);
dnsSettings = serverDns;
}
var dnsData = new ServerDomainDnsData
{
Id = dnsSettings.Id,
MxRecord = new ServerDomainMxRecordData
{
Host = dnsSettings.Mx,
IsVerified = false,
Priority = Defines.ServerDnsMxRecordPriority
},
DkimRecord = new ServerDomainDkimRecordData
{
Selector = dnsSettings.DkimSelector,
IsVerified = false,
PublicKey = dnsSettings.DkimPublicKey
},
DomainCheckRecord = new ServerDomainDnsRecordData
{
Name = Defines.DNS_DEFAULT_ORIGIN,
IsVerified = false,
Value = dnsSettings.DomainCheck
},
SpfRecord = new ServerDomainDnsRecordData
{
Name = Defines.DNS_DEFAULT_ORIGIN,
IsVerified = false,
Value = dnsSettings.Spf
}
};
return dnsData;
}
public bool CheckDomainOwnership(string domain)
{
if (!IsAdmin)
throw new SecurityException("Need admin privileges.");
if (string.IsNullOrEmpty(domain))
throw new ArgumentException(@"Invalid domain name.", "domain");
if (domain.Length > 255)
throw new ArgumentException(@"Domain name exceed limitation of 255 characters.", "domain");
if (!Parser.IsDomainValid(domain))
throw new ArgumentException(@"Incorrect domain name.", "domain");
var domainName = domain.ToLowerInvariant();
var dns = GetOrCreateUnusedDnsData();
var dnsLookup = new DnsLookup();
return dnsLookup.IsDomainTxtRecordExists(domainName, dns.DomainCheckRecord.Value);
}
public ServerNotificationAddressData CreateNotificationAddress(string localPart, string password, int domainId)
{
if (!CoreContext.Configuration.Standalone)
throw new SecurityException("Only for standalone");
if (!IsAdmin)
throw new SecurityException("Need admin privileges.");
if (string.IsNullOrEmpty(localPart))
throw new ArgumentNullException("localPart", @"Invalid address username.");
localPart = localPart.ToLowerInvariant().Trim();
if (localPart.Length > 64)
throw new ArgumentException(@"Local part of address exceed limitation of 64 characters.", "localPart");
if (!Parser.IsEmailLocalPartValid(localPart))
throw new ArgumentException(@"Incorrect address username.", "localPart");
var trimPwd = Parser.GetValidPassword(password);
if (domainId < 0)
throw new ArgumentException(@"Invalid domain id.", "domainId");
var notificationAddressSettings = ServerNotificationAddressSettings.LoadForTenant(Tenant);
if (!string.IsNullOrEmpty(notificationAddressSettings.NotificationAddress))
{
RemoveNotificationAddress(notificationAddressSettings.NotificationAddress);
}
var utcNow = DateTime.UtcNow;
using (var daoFactory = new DaoFactory())
{
var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);
var serverDomain = serverDomainDao.GetDomain(domainId);
if (localPart.Length + serverDomain.Name.Length > 318) // 318 because of @ sign
throw new ArgumentException(@"Address of mailbox exceed limitation of 319 characters.", "localPart");
var login = string.Format("{0}@{1}", localPart, serverDomain.Name);
var serverDao = daoFactory.CreateServerDao();
var server = serverDao.Get(Tenant);
if (server == null)
throw new ArgumentException("Server not configured");
var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);
var maildir = PostfixMaildirUtil.GenerateMaildirPath(serverDomain.Name, localPart, utcNow);
var serverMailbox = new Server.Core.Entities.Mailbox
{
Name = localPart,
Password = trimPwd,
Login = login,
LocalPart = localPart,
Domain = serverDomain.Name,
Active = true,
Quota = 0,
Maldir = maildir,
Modified = utcNow,
Created = utcNow,
};
var serverAddress = new Alias
{
Name = localPart,
Address = login,
GoTo = login,
Domain = serverDomain.Name,
IsActive = true,
IsGroup = false,
Modified = utcNow,
Created = utcNow
};
engine.SaveMailbox(serverMailbox, serverAddress, false);
notificationAddressSettings = new ServerNotificationAddressSettings { NotificationAddress = login };
notificationAddressSettings.SaveForTenant(Tenant);
var mailboxServerDao = daoFactory.CreateMailboxServerDao();
var smtpSettings = mailboxServerDao.GetServer(server.SmtpSettingsId);
var address = new MailAddress(login);
var notifyAddress = new ServerNotificationAddressData
{
Email = address.ToString(),
SmtpPort = smtpSettings.Port,
SmtpServer = smtpSettings.Hostname,
SmtpAccount = address.ToLogin(smtpSettings.Username),
SmptEncryptionType = smtpSettings.SocketType,
SmtpAuth = true,
SmtpAuthenticationType = smtpSettings.Authentication
};
return notifyAddress;
}
}
public void RemoveNotificationAddress(string address)
{
if (!CoreContext.Configuration.Standalone)
throw new SecurityException("Only for standalone");
if (!IsAdmin)
throw new SecurityException("Need admin privileges.");
if (string.IsNullOrEmpty(address))
throw new ArgumentNullException("address");
var deleteAddress = address.ToLowerInvariant().Trim();
var notificationAddressSettings = ServerNotificationAddressSettings.LoadForTenant(Tenant);
if (notificationAddressSettings.NotificationAddress != deleteAddress)
throw new ArgumentException("Mailbox not exists");
var mailAddress = new MailAddress(deleteAddress);
using (var daoFactory = new DaoFactory())
{
var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);
var serverDomain = serverDomainDao.GetDomains().FirstOrDefault(d => d.Name == mailAddress.Host);
if (serverDomain == null)
throw new ArgumentException("Domain not exists");
var serverDao = daoFactory.CreateServerDao();
var server = serverDao.Get(Tenant);
if (server == null)
throw new ArgumentException("Server not configured");
var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);
engine.RemoveMailbox(deleteAddress);
}
var addressSettings = notificationAddressSettings.GetDefault() as ServerNotificationAddressSettings;
if (addressSettings != null && !addressSettings.SaveForTenant(Tenant))
{
throw new Exception("Could not delete notification address setting.");
}
}
public ServerFullData GetMailServerFullInfo()
{
if (!IsAdmin)
throw new SecurityException("Need admin privileges.");
var fullServerInfo = new ServerFullData();
var mailboxDataList = new List<ServerMailboxData>();
var mailgroupDataList = new List<ServerDomainGroupData>();
var domainEngine = new ServerDomainEngine(Tenant, User);
using (var daoFactory = new DaoFactory())
{
var server = GetMailServer(daoFactory);
var domains = domainEngine.GetDomains(daoFactory);
var mailboxDao = daoFactory.CreateMailboxDao();
var mailboxes = mailboxDao.GetMailBoxes(new TenantServerMailboxesExp(Tenant));
var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);
var addresses = serverAddressDao.GetList();
foreach (var mailbox in mailboxes)
{
var address =
addresses.FirstOrDefault(
a => a.MailboxId == mailbox.Id && a.IsAlias == false && a.IsMailGroup == false);
if (address == null)
continue;
var domain = domains.FirstOrDefault(d => d.Id == address.DomainId);
if (domain == null)
continue;
var serverAddressData = ServerMailboxEngine.ToServerDomainAddressData(address, domain);
var aliases =
addresses.Where(a => a.MailboxId == mailbox.Id && a.IsAlias && !a.IsMailGroup)
.ToList()
.ConvertAll(a => ServerMailboxEngine.ToServerDomainAddressData(a, domain));
mailboxDataList.Add(ServerMailboxEngine.ToMailboxData(mailbox, serverAddressData, aliases));
}
var serverGroupDao = daoFactory.CreateServerGroupDao(Tenant);
var groups = serverGroupDao.GetList();
foreach (var serverGroup in groups)
{
var address =
addresses.FirstOrDefault(
a => a.Id == serverGroup.AddressId && !a.IsAlias && a.IsMailGroup);
if (address == null)
continue;
var domain = domains.FirstOrDefault(d => d.Id == address.DomainId);
if (domain == null)
continue;
var email = string.Format("{0}@{1}", address.AddressName, domain.Name);
var serverGroupAddress = ServerMailboxEngine.ToServerDomainAddressData(address, email);
var serverGroupAddresses =
serverAddressDao.GetGroupAddresses(serverGroup.Id)
.ConvertAll(a => ServerMailboxEngine.ToServerDomainAddressData(a,
string.Format("{0}@{1}", a.AddressName, domain.Name)));
mailgroupDataList.Add(ServerMailgroupEngine.ToServerDomainGroupData(serverGroup.Id, serverGroupAddress, serverGroupAddresses));
}
fullServerInfo.Server = server;
fullServerInfo.Domains = domains;
fullServerInfo.Mailboxes = mailboxDataList;
fullServerInfo.Mailgroups = mailgroupDataList;
}
return fullServerInfo;
}
public string GetServerVersion()
{
using (var daoFactory = new DaoFactory())
{
var serverDao = daoFactory.CreateServerDao();
var server = serverDao.Get(Tenant);
if (server == null)
return null;
var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);
var version = engine.GetVersion();
return version;
}
}
private static bool IsAdmin
{
get
{
return WebItemSecurity.IsProductAdministrator(WebItemManager.MailProductID, SecurityContext.CurrentAccount.ID);
}
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2006, Frank Blumenberg
//
// See License.txt for complete licensing and attribution information.
// 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.
//
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//
// This code contains code from SimplePsd class library by Igor Tolmachev.
// http://www.codeproject.com/csharp/simplepsd.asp
//
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace PhotoshopFile
{
public class ImageDecoder
{
///////////////////////////////////////////////////////////////////////////
#if false // fix -- not used, causes warnings
#if !TEST
private struct PixelData
{
public byte Blue;
public byte Green;
public byte Red;
public byte Alpha;
}
#endif
#endif
///////////////////////////////////////////////////////////////////////////
public static Bitmap DecodeImage(PsdFile psdFile)
{
var bitmap = new Bitmap(psdFile.Columns, psdFile.Rows, PixelFormat.Format32bppArgb);
// Fix to support different pixel resolutions
bitmap.SetResolution(psdFile.Resolution.HRes, psdFile.Resolution.VRes);
#if TEST
for (int y = 0; y < psdFile.Rows; y++)
{
int rowIndex = y * psdFile.Columns;
for (int x = 0; x < psdFile.Columns; x++)
{
int pos = rowIndex + x;
Color pixelColor=GetColor(psdFile,pos);
bitmap.SetPixel(x, y, pixelColor);
}
}
#else
#if true // fix remove unsafeness (admittedly slower)
#if false // safe + slow
for (int y = 0; y < psdFile.Rows; y++)
{
int rowIndex = y * psdFile.Columns;
for (int x = 0; x < psdFile.Columns; x++)
{
int pos = rowIndex + x;
Color pixelColor = GetColor(psdFile, pos);
bitmap.SetPixel(x, y, pixelColor/*Color.FromArgb(255, pixelColor)*/);
}
}
#else // safe + fast
// based on MSDN -- Bitmap.LockBits
// Lock the bitmap's bits.
var bmpData = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadWrite,
bitmap.PixelFormat);
// Get the address of the first line.
var ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
var nDestLength = Math.Abs(bmpData.Stride)*bitmap.Height;
var arrayOutputARGB = new byte[nDestLength];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(ptr, arrayOutputARGB, 0, nDestLength);
var nOutputOffset = 0;
for (var y = 0; y < psdFile.Rows; y++)
{
var rowIndex = y*psdFile.Columns;
for (var x = 0; x < psdFile.Columns; x++)
{
var nSourcePosition = rowIndex + x;
SetDestinationColor(psdFile, arrayOutputARGB, nOutputOffset, nSourcePosition);
nOutputOffset += 4;
}
}
// Copy the RGB values back to the bitmap
System.Runtime.InteropServices.Marshal.Copy(arrayOutputARGB, 0, ptr, nDestLength);
// Unlock the bits.
bitmap.UnlockBits(bmpData);
#endif
#else
Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData bd = bitmap.LockBits(r, ImageLockMode.ReadWrite, bitmap.PixelFormat);
unsafe
{
byte* pCurrRowPixel = (byte*)bd.Scan0.ToPointer();
for (int y = 0; y < psdFile.Rows; y++)
{
int rowIndex = y * psdFile.Columns;
PixelData* pCurrPixel = (PixelData*)pCurrRowPixel;
for (int x = 0; x < psdFile.Columns; x++)
{
int pos = rowIndex + x;
Color pixelColor = GetColor(psdFile, pos);
pCurrPixel->Alpha = 255;
pCurrPixel->Red = pixelColor.R;
pCurrPixel->Green = pixelColor.G;
pCurrPixel->Blue = pixelColor.B;
pCurrPixel += 1;
}
pCurrRowPixel += bd.Stride;
}
}
bitmap.UnlockBits(bd);
#endif
#endif
return bitmap;
}
///////////////////////////////////////////////////////////////////////////
// fix for performance
private static void SetDestinationColor(PsdFile psdFile, byte[] arrayARGB, int nOutputOffset,
int nSourcePosition)
{
Color c = Color.White;
switch (psdFile.ColorMode)
{
case PsdFile.ColorModes.RGB:
// can take advantage of a direct copy of the bytes
arrayARGB[nOutputOffset + 3] = (3 < psdFile.ImageData.Length
? psdFile.ImageData[3][nSourcePosition]
: (byte) 255);
// ABGR - apparently
arrayARGB[nOutputOffset + 2] = psdFile.ImageData[0][nSourcePosition];
arrayARGB[nOutputOffset + 1] = psdFile.ImageData[1][nSourcePosition];
arrayARGB[nOutputOffset + 0] = psdFile.ImageData[2][nSourcePosition];
return;
case PsdFile.ColorModes.CMYK:
c = CMYKToRGB(psdFile.ImageData[0][nSourcePosition],
psdFile.ImageData[1][nSourcePosition],
psdFile.ImageData[2][nSourcePosition],
psdFile.ImageData[3][nSourcePosition]);
break;
case PsdFile.ColorModes.Multichannel:
c = CMYKToRGB(psdFile.ImageData[0][nSourcePosition],
psdFile.ImageData[1][nSourcePosition],
psdFile.ImageData[2][nSourcePosition],
0);
break;
case PsdFile.ColorModes.Grayscale:
case PsdFile.ColorModes.Duotone:
// can take advantage of a direct copy of the bytes
// TODO: can alpha channel be used?
arrayARGB[nOutputOffset + 3] = 0xff;
arrayARGB[nOutputOffset + 0] = psdFile.ImageData[0][nSourcePosition];
arrayARGB[nOutputOffset + 1] = psdFile.ImageData[0][nSourcePosition];
arrayARGB[nOutputOffset + 2] = psdFile.ImageData[0][nSourcePosition];
return;
case PsdFile.ColorModes.Indexed:
{
var index = (int) psdFile.ImageData[0][nSourcePosition];
c = Color.FromArgb(psdFile.ColorModeData[index],
psdFile.ColorModeData[index + 256],
psdFile.ColorModeData[index + 2*256]);
}
break;
case PsdFile.ColorModes.Lab:
{
c = LabToRGB(psdFile.ImageData[0][nSourcePosition],
psdFile.ImageData[1][nSourcePosition],
psdFile.ImageData[2][nSourcePosition]);
}
break;
}
// populate the color data
// ABGR - apparently
arrayARGB[nOutputOffset + 3] = c.A;
arrayARGB[nOutputOffset + 0] = c.B;
arrayARGB[nOutputOffset + 1] = c.G;
arrayARGB[nOutputOffset + 2] = c.R;
}
#if false
private static Color GetColor(PsdFile psdFile, int pos)
{
Color c = Color.White;
switch (psdFile.ColorMode)
{
case PsdFile.ColorModes.RGB:
c = Color.FromArgb(
// read alpha if that channel is available (otherwise default to full alpha)
(3 < psdFile.ImageData.Length ? psdFile.ImageData[3][pos] : 255),
psdFile.ImageData[0][pos],
psdFile.ImageData[1][pos],
psdFile.ImageData[2][pos]);
break;
case PsdFile.ColorModes.CMYK:
c = CMYKToRGB(psdFile.ImageData[0][pos],
psdFile.ImageData[1][pos],
psdFile.ImageData[2][pos],
psdFile.ImageData[3][pos]);
break;
case PsdFile.ColorModes.Multichannel:
c = CMYKToRGB(psdFile.ImageData[0][pos],
psdFile.ImageData[1][pos],
psdFile.ImageData[2][pos],
0);
break;
case PsdFile.ColorModes.Grayscale:
case PsdFile.ColorModes.Duotone:
c = Color.FromArgb(psdFile.ImageData[0][pos],
psdFile.ImageData[0][pos],
psdFile.ImageData[0][pos]);
break;
case PsdFile.ColorModes.Indexed:
{
int index = (int) psdFile.ImageData[0][pos];
c = Color.FromArgb((int) psdFile.ColorModeData[index],
psdFile.ColorModeData[index + 256],
psdFile.ColorModeData[index + 2*256]);
}
break;
case PsdFile.ColorModes.Lab:
{
c = LabToRGB(psdFile.ImageData[0][pos],
psdFile.ImageData[1][pos],
psdFile.ImageData[2][pos]);
}
break;
}
return c;
}
#endif
///////////////////////////////////////////////////////////////////////////
public static Bitmap DecodeImage(Layer layer)
{
if (layer.Rect.Width == 0 || layer.Rect.Height == 0)
{
return null;
}
var bitmap = new Bitmap(layer.Rect.Width, layer.Rect.Height, PixelFormat.Format32bppArgb);
#if TEST
for (int y = 0; y < layer.Rect.Height; y++)
{
int rowIndex = y * layer.Rect.Width;
for (int x = 0; x < layer.Rect.Width; x++)
{
int pos = rowIndex + x;
//Color pixelColor=GetColor(psdFile,pos);
Color pixelColor = Color.FromArgb(x % 255, Color.ForestGreen);// 255, 128, 0);
bitmap.SetPixel(x, y, pixelColor);
}
}
#else
#if true // fix remove unsafeness (admittedly slower)
// TODO: fast mode
for (var y = 0; y < layer.Rect.Height; y++)
{
var rowIndex = y * layer.Rect.Width;
for (var x = 0; x < layer.Rect.Width; x++)
{
var pos = rowIndex + x;
var pixelColor = GetColor(layer, pos);
if (layer.SortedChannels.ContainsKey(-2))
{
var maskAlpha = GetColor(layer.MaskData, x, y);
int oldAlpha = pixelColor.A;
var newAlpha = (oldAlpha * maskAlpha) / 255;
pixelColor = Color.FromArgb(newAlpha, pixelColor);
}
bitmap.SetPixel(x, y, pixelColor);
}
}
#else
Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData bd = bitmap.LockBits(r, ImageLockMode.ReadWrite, bitmap.PixelFormat);
unsafe
{
byte* pCurrRowPixel = (byte*)bd.Scan0.ToPointer();
for (int y = 0; y < layer.Rect.Height; y++)
{
int rowIndex = y * layer.Rect.Width;
PixelData* pCurrPixel = (PixelData*)pCurrRowPixel;
for (int x = 0; x < layer.Rect.Width; x++)
{
int pos = rowIndex + x;
Color pixelColor = GetColor(layer, pos);
if (layer.SortedChannels.ContainsKey(-2))
{
int maskAlpha = GetColor(layer.MaskData, x, y);
int oldAlpha = pixelColor.A;
int newAlpha = (oldAlpha * maskAlpha) / 255;
pixelColor = Color.FromArgb(newAlpha,pixelColor);
}
pCurrPixel->Alpha = pixelColor.A;
pCurrPixel->Red = pixelColor.R;
pCurrPixel->Green = pixelColor.G;
pCurrPixel->Blue = pixelColor.B;
pCurrPixel += 1;
}
pCurrRowPixel += bd.Stride;
}
}
bitmap.UnlockBits(bd);
#endif
#endif
return bitmap;
}
///////////////////////////////////////////////////////////////////////////
private static Color GetColor(Layer layer, int pos)
{
var c = Color.White;
switch (layer.PsdFile.ColorMode)
{
case PsdFile.ColorModes.RGB:
c = Color.FromArgb(layer.SortedChannels[0].ImageData[pos],
layer.SortedChannels[1].ImageData[pos],
layer.SortedChannels[2].ImageData[pos]);
break;
case PsdFile.ColorModes.CMYK:
c = CMYKToRGB(layer.SortedChannels[0].ImageData[pos],
layer.SortedChannels[1].ImageData[pos],
layer.SortedChannels[2].ImageData[pos],
layer.SortedChannels[3].ImageData[pos]);
break;
case PsdFile.ColorModes.Multichannel:
c = CMYKToRGB(layer.SortedChannels[0].ImageData[pos],
layer.SortedChannels[1].ImageData[pos],
layer.SortedChannels[2].ImageData[pos],
0);
break;
case PsdFile.ColorModes.Grayscale:
case PsdFile.ColorModes.Duotone:
c = Color.FromArgb(layer.SortedChannels[0].ImageData[pos],
layer.SortedChannels[0].ImageData[pos],
layer.SortedChannels[0].ImageData[pos]);
break;
case PsdFile.ColorModes.Indexed:
{
var index = (int)layer.SortedChannels[0].ImageData[pos];
c = Color.FromArgb(layer.PsdFile.ColorModeData[index],
layer.PsdFile.ColorModeData[index + 256],
layer.PsdFile.ColorModeData[index + 2*256]);
}
break;
case PsdFile.ColorModes.Lab:
{
c = LabToRGB(layer.SortedChannels[0].ImageData[pos],
layer.SortedChannels[1].ImageData[pos],
layer.SortedChannels[2].ImageData[pos]);
}
break;
}
if (layer.SortedChannels.ContainsKey(-1))
c = Color.FromArgb(layer.SortedChannels[-1].ImageData[pos], c);
return c;
}
///////////////////////////////////////////////////////////////////////////
private static int GetColor(Layer.Mask mask, int x, int y)
{
int c = 255;
if (mask.PositionIsRelative)
{
x -= mask.Rect.X;
y -= mask.Rect.Y;
}
else
{
x = (x + mask.Layer.Rect.X) - mask.Rect.X;
y = (y + mask.Layer.Rect.Y) - mask.Rect.Y;
}
if (y >= 0 && y < mask.Rect.Height &&
x >= 0 && x < mask.Rect.Width)
{
var pos = y * mask.Rect.Width + x;
if (pos < mask.ImageData.Length)
{
c = mask.ImageData[pos];
}
else
{
c = 255;
}
}
return c;
}
///////////////////////////////////////////////////////////////////////////
public static Bitmap DecodeImage(Layer.Mask mask)
{
if (mask.Rect.Width == 0 || mask.Rect.Height == 0)
{
return null;
}
var bitmap = new Bitmap(mask.Rect.Width, mask.Rect.Height, PixelFormat.Format32bppArgb);
#if true // fix remove unsafeness (admittedly slower)
// TODO: fast mode
for (var y = 0; y < mask.Rect.Height; y++)
{
var rowIndex = y*mask.Rect.Width;
for (var x = 0; x < mask.Rect.Width; x++)
{
var pos = rowIndex + x;
var pixelColor = Color.FromArgb(mask.ImageData[pos], mask.ImageData[pos], mask.ImageData[pos]);
// TODO: why is alpha ignored
bitmap.SetPixel(x, y, Color.FromArgb(255, pixelColor));
}
}
#else
Layer layer = mask.Layer;
Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData bd = bitmap.LockBits(r, ImageLockMode.ReadWrite, bitmap.PixelFormat);
unsafe
{
byte* pCurrRowPixel = (byte*)bd.Scan0.ToPointer();
for (int y = 0; y < mask.Rect.Height; y++)
{
int rowIndex = y * mask.Rect.Width;
PixelData* pCurrPixel = (PixelData*)pCurrRowPixel;
for (int x = 0; x < mask.Rect.Width; x++)
{
int pos = rowIndex + x;
Color pixelColor = Color.FromArgb(mask.ImageData[pos], mask.ImageData[pos], mask.ImageData[pos]);
pCurrPixel->Alpha = 255;
pCurrPixel->Red = pixelColor.R;
pCurrPixel->Green = pixelColor.G;
pCurrPixel->Blue = pixelColor.B;
pCurrPixel += 1;
}
pCurrRowPixel += bd.Stride;
}
}
bitmap.UnlockBits(bd);
#endif
return bitmap;
}
///////////////////////////////////////////////////////////////////////////
private static Color LabToRGB(byte lb, byte ab, byte bb)
{
var exL = (double) lb;
var exA = (double) ab;
var exB = (double) bb;
const double L_coef = 256.0/100.0;
const double a_coef = 256.0/256.0;
const double b_coef = 256.0/256.0;
var L = (int) (exL/L_coef);
var a = (int) (exA/a_coef - 128.0);
var b = (int) (exB/b_coef - 128.0);
// For the conversion we first convert values to XYZ and then to RGB
// Standards used Observer = 2, Illuminant = D65
const double ref_X = 95.047;
const double ref_Y = 100.000;
const double ref_Z = 108.883;
var var_Y = ((double)L + 16.0) / 116.0;
var var_X = (double)a / 500.0 + var_Y;
var var_Z = var_Y - (double)b / 200.0;
if (Math.Pow(var_Y, 3) > 0.008856)
var_Y = Math.Pow(var_Y, 3);
else
var_Y = (var_Y - 16/116)/7.787;
if (Math.Pow(var_X, 3) > 0.008856)
var_X = Math.Pow(var_X, 3);
else
var_X = (var_X - 16/116)/7.787;
if (Math.Pow(var_Z, 3) > 0.008856)
var_Z = Math.Pow(var_Z, 3);
else
var_Z = (var_Z - 16/116)/7.787;
var X = ref_X * var_X;
var Y = ref_Y * var_Y;
var Z = ref_Z * var_Z;
return XYZToRGB(X, Y, Z);
}
////////////////////////////////////////////////////////////////////////////
private static Color XYZToRGB(double X, double Y, double Z)
{
// Standards used Observer = 2, Illuminant = D65
// ref_X = 95.047, ref_Y = 100.000, ref_Z = 108.883
var var_X = X / 100.0;
var var_Y = Y / 100.0;
var var_Z = Z / 100.0;
var var_R = var_X * 3.2406 + var_Y * (-1.5372) + var_Z * (-0.4986);
var var_G = var_X * (-0.9689) + var_Y * 1.8758 + var_Z * 0.0415;
var var_B = var_X * 0.0557 + var_Y * (-0.2040) + var_Z * 1.0570;
if (var_R > 0.0031308)
var_R = 1.055*(Math.Pow(var_R, 1/2.4)) - 0.055;
else
var_R = 12.92*var_R;
if (var_G > 0.0031308)
var_G = 1.055*(Math.Pow(var_G, 1/2.4)) - 0.055;
else
var_G = 12.92*var_G;
if (var_B > 0.0031308)
var_B = 1.055*(Math.Pow(var_B, 1/2.4)) - 0.055;
else
var_B = 12.92*var_B;
var nRed = (int)(var_R * 256.0);
var nGreen = (int)(var_G * 256.0);
var nBlue = (int)(var_B * 256.0);
if (nRed < 0) nRed = 0;
else if (nRed > 255) nRed = 255;
if (nGreen < 0) nGreen = 0;
else if (nGreen > 255) nGreen = 255;
if (nBlue < 0) nBlue = 0;
else if (nBlue > 255) nBlue = 255;
return Color.FromArgb(nRed, nGreen, nBlue);
}
///////////////////////////////////////////////////////////////////////////////
//
// The algorithms for these routines were taken from:
// http://www.neuro.sfc.keio.ac.jp/~aly/polygon/info/color-space-faq.html
//
// RGB --> CMYK CMYK --> RGB
// --------------------------------------- --------------------------------------------
// Black = minimum(1-Red,1-Green,1-Blue) Red = 1-minimum(1,Cyan*(1-Black)+Black)
// Cyan = (1-Red-Black)/(1-Black) Green = 1-minimum(1,Magenta*(1-Black)+Black)
// Magenta = (1-Green-Black)/(1-Black) Blue = 1-minimum(1,Yellow*(1-Black)+Black)
// Yellow = (1-Blue-Black)/(1-Black)
//
private static Color CMYKToRGB(byte c, byte m, byte y, byte k)
{
const double dMaxColours = 256; //Math.Pow(2, 8);
var exC = (double) c;
var exM = (double) m;
var exY = (double) y;
var exK = (double) k;
var C = (1.0 - exC / dMaxColours);
var M = (1.0 - exM / dMaxColours);
var Y = (1.0 - exY / dMaxColours);
var K = (1.0 - exK / dMaxColours);
var nRed = (int)((1.0 - (C * (1 - K) + K)) * 255);
var nGreen = (int)((1.0 - (M * (1 - K) + K)) * 255);
var nBlue = (int)((1.0 - (Y * (1 - K) + K)) * 255);
if (nRed < 0) nRed = 0;
else if (nRed > 255) nRed = 255;
if (nGreen < 0) nGreen = 0;
else if (nGreen > 255) nGreen = 255;
if (nBlue < 0) nBlue = 0;
else if (nBlue > 255) nBlue = 255;
return Color.FromArgb(nRed, nGreen, nBlue);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Cache;
using System.Net.Http;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
public delegate void HttpContinueDelegate(int StatusCode, WebHeaderCollection httpHeaders);
[Serializable]
public class HttpWebRequest : WebRequest, ISerializable
{
private const int DefaultContinueTimeout = 350; // Current default value from .NET Desktop.
private WebHeaderCollection _webHeaderCollection = new WebHeaderCollection();
private Uri _requestUri;
private string _originVerb = HttpMethod.Get.Method;
// We allow getting and setting this (to preserve app-compat). But we don't do anything with it
// as the underlying System.Net.Http API doesn't support it.
private int _continueTimeout = DefaultContinueTimeout;
private bool _allowReadStreamBuffering = false;
private CookieContainer _cookieContainer = null;
private ICredentials _credentials = null;
private IWebProxy _proxy = WebRequest.DefaultWebProxy;
private Task<HttpResponseMessage> _sendRequestTask;
private static int _defaultMaxResponseHeaderLength = HttpHandlerDefaults.DefaultMaxResponseHeaderLength;
private int _beginGetRequestStreamCalled = 0;
private int _beginGetResponseCalled = 0;
private int _endGetRequestStreamCalled = 0;
private int _endGetResponseCalled = 0;
private int _maximumAllowedRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private int _maximumResponseHeaderLen = _defaultMaxResponseHeaderLength;
private ServicePoint _servicePoint;
private int _timeout = WebRequest.DefaultTimeoutMilliseconds;
private HttpContinueDelegate _continueDelegate;
private RequestStream _requestStream;
private TaskCompletionSource<Stream> _requestStreamOperation = null;
private TaskCompletionSource<WebResponse> _responseOperation = null;
private AsyncCallback _requestStreamCallback = null;
private AsyncCallback _responseCallback = null;
private int _abortCalled = 0;
private CancellationTokenSource _sendRequestCts;
private X509CertificateCollection _clientCertificates;
private Booleans _booleans = Booleans.Default;
private bool _pipelined = true;
private bool _preAuthenticate;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
//these should be safe.
[Flags]
private enum Booleans : uint
{
AllowAutoRedirect = 0x00000001,
AllowWriteStreamBuffering = 0x00000002,
ExpectContinue = 0x00000004,
ProxySet = 0x00000010,
UnsafeAuthenticatedConnectionSharing = 0x00000040,
IsVersionHttp10 = 0x00000080,
SendChunked = 0x00000100,
EnableDecompression = 0x00000200,
IsTunnelRequest = 0x00000400,
IsWebSocketRequest = 0x00000800,
Default = AllowAutoRedirect | AllowWriteStreamBuffering | ExpectContinue
}
private const string ContinueHeader = "100-continue";
private const string ChunkedHeader = "chunked";
private const string GZipHeader = "gzip";
private const string DeflateHeader = "deflate";
public HttpWebRequest()
{
}
[Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?linkid=14202")]
protected HttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
internal HttpWebRequest(Uri uri)
{
_requestUri = uri;
}
private void SetSpecialHeaders(string HeaderName, string value)
{
_webHeaderCollection.Remove(HeaderName);
if (!string.IsNullOrEmpty(value))
{
_webHeaderCollection[HeaderName] = value;
}
}
public string Accept
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Accept];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.Accept, value);
}
}
public virtual bool AllowReadStreamBuffering
{
get
{
return _allowReadStreamBuffering;
}
set
{
_allowReadStreamBuffering = value;
}
}
public int MaximumResponseHeadersLength
{
get
{
return _maximumResponseHeaderLen;
}
set
{
_maximumResponseHeaderLen = value;
}
}
public int MaximumAutomaticRedirections
{
get
{
return _maximumAllowedRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentException(SR.net_toosmall, nameof(value));
}
_maximumAllowedRedirections = value;
}
}
public override String ContentType
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.ContentType];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.ContentType, value);
}
}
public int ContinueTimeout
{
get
{
return _continueTimeout;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if ((value < 0) && (value != System.Threading.Timeout.Infinite))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
_continueTimeout = value;
}
}
public override int Timeout
{
get
{
return _timeout;
}
set
{
if (value < 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
_timeout = value;
}
}
public override long ContentLength
{
get
{
long value;
long.TryParse(_webHeaderCollection[HttpKnownHeaderNames.ContentLength], out value);
return value;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
SetSpecialHeaders(HttpKnownHeaderNames.ContentLength, value.ToString());
}
}
public Uri Address
{
get
{
return _requestUri;
}
}
public string UserAgent
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.UserAgent];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.UserAgent, value);
}
}
public string Host
{
get
{
throw new PlatformNotSupportedException();
}
set
{
throw new PlatformNotSupportedException();
}
}
public bool Pipelined
{
get
{
return _pipelined;
}
set
{
_pipelined = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Referer header.
/// </para>
/// </devdoc>
public string Referer
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Referer];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.Referer, value);
}
}
/// <devdoc>
/// <para>Sets the media type header</para>
/// </devdoc>
public string MediaType
{
get
{
throw new PlatformNotSupportedException();
}
set
{
throw new PlatformNotSupportedException();
}
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Transfer-Encoding header. Setting null clears it out.
/// </para>
/// </devdoc>
public string TransferEncoding
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.TransferEncoding];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
bool fChunked;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
//
// if the value is blank, then remove the header
//
_webHeaderCollection.Remove(HttpKnownHeaderNames.TransferEncoding);
return;
}
//
// if not check if the user is trying to set chunked:
//
string newValue = value.ToLower();
fChunked = (newValue.IndexOf(ChunkedHeader) != -1);
//
// prevent them from adding chunked, or from adding an Encoding without
// turing on chunked, the reason is due to the HTTP Spec which prevents
// additional encoding types from being used without chunked
//
if (fChunked)
{
throw new ArgumentException(SR.net_nochunked, nameof(value));
}
else if (!SendChunked)
{
throw new InvalidOperationException(SR.net_needchunked);
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.TransferEncoding] = checkedValue;
}
#if DEBUG
}
#endif
}
}
public bool KeepAlive
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.KeepAlive] == bool.TrueString;
}
set
{
if (value)
{
SetSpecialHeaders(HttpKnownHeaderNames.KeepAlive, bool.TrueString);
}
else
{
SetSpecialHeaders(HttpKnownHeaderNames.KeepAlive, bool.FalseString);
}
}
}
public bool UnsafeAuthenticatedConnectionSharing
{
get
{
return (_booleans & Booleans.UnsafeAuthenticatedConnectionSharing) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.UnsafeAuthenticatedConnectionSharing;
}
else
{
_booleans &= ~Booleans.UnsafeAuthenticatedConnectionSharing;
}
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
_automaticDecompression = value;
}
}
public virtual bool AllowWriteStreamBuffering
{
get
{
return (_booleans & Booleans.AllowWriteStreamBuffering) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.AllowWriteStreamBuffering;
}
else
{
_booleans &= ~Booleans.AllowWriteStreamBuffering;
}
}
}
/// <devdoc>
/// <para>
/// Enables or disables automatically following redirection responses.
/// </para>
/// </devdoc>
public virtual bool AllowAutoRedirect
{
get
{
return (_booleans & Booleans.AllowAutoRedirect) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.AllowAutoRedirect;
}
else
{
_booleans &= ~Booleans.AllowAutoRedirect;
}
}
}
public override string ConnectionGroupName
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public override bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public string Connection
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Connection];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
bool fKeepAlive;
bool fClose;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
_webHeaderCollection.Remove(HttpKnownHeaderNames.Connection);
return;
}
string newValue = value.ToLower();
fKeepAlive = (newValue.IndexOf("keep-alive") != -1);
fClose = (newValue.IndexOf("close") != -1);
//
// Prevent keep-alive and close from being added
//
if (fKeepAlive ||
fClose)
{
throw new ArgumentException(SR.net_connarg, nameof(value));
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.Connection] = checkedValue;
}
#if DEBUG
}
#endif
}
}
/*
Accessor: Expect
The property that controls the Expect header
Input:
string Expect, null clears the Expect except for 100-continue value
Returns: The value of the Expect on get.
*/
public string Expect
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Expect];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
// only remove everything other than 100-cont
bool fContinue100;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
_webHeaderCollection.Remove(HttpKnownHeaderNames.Expect);
return;
}
//
// Prevent 100-continues from being added
//
string newValue = value.ToLower();
fContinue100 = (newValue.IndexOf(ContinueHeader) != -1);
if (fContinue100)
{
throw new ArgumentException(SR.net_no100, nameof(value));
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.Expect] = checkedValue;
}
#if DEBUG
}
#endif
}
}
/// <devdoc>
/// <para>
/// Gets or sets the default for the MaximumResponseHeadersLength property.
/// </para>
/// <remarks>
/// This value can be set in the config file, the default can be overridden using the MaximumResponseHeadersLength property.
/// </remarks>
/// </devdoc>
public static int DefaultMaximumResponseHeadersLength
{
get
{
return _defaultMaxResponseHeaderLength;
}
set
{
_defaultMaxResponseHeaderLength = value;
}
}
// NOP
public static int DefaultMaximumErrorResponseLength
{
get;set;
}
public static new RequestCachePolicy DefaultCachePolicy { get; set; } = new RequestCachePolicy(RequestCacheLevel.BypassCache);
public DateTime IfModifiedSince
{
get
{
return GetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince);
}
set
{
SetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince, value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Date header.
/// </para>
/// </devdoc>
public DateTime Date
{
get
{
return GetDateHeaderHelper(HttpKnownHeaderNames.Date);
}
set
{
SetDateHeaderHelper(HttpKnownHeaderNames.Date, value);
}
}
public bool SendChunked
{
get
{
return (_booleans & Booleans.SendChunked) != 0;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value)
{
_booleans |= Booleans.SendChunked;
}
else
{
_booleans &= ~Booleans.SendChunked;
}
}
}
public HttpContinueDelegate ContinueDelegate
{
// Nop since the underlying API do not expose 100 continue.
get
{
return _continueDelegate;
}
set
{
_continueDelegate = value;
}
}
public ServicePoint ServicePoint
{
get
{
if (_servicePoint == null)
{
_servicePoint = ServicePointManager.FindServicePoint(Address, Proxy);
}
return _servicePoint;
}
}
public RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; set; }
//
// ClientCertificates - sets our certs for our reqest,
// uses a hash of the collection to create a private connection
// group, to prevent us from using the same Connection as
// non-Client Authenticated requests.
//
public X509CertificateCollection ClientCertificates
{
get
{
if (_clientCertificates == null)
_clientCertificates = new X509CertificateCollection();
return _clientCertificates;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_clientCertificates = value;
}
}
// HTTP Version
/// <devdoc>
/// <para>
/// Gets and sets
/// the HTTP protocol version used in this request.
/// </para>
/// </devdoc>
public Version ProtocolVersion
{
get
{
return IsVersionHttp10 ? HttpVersion.Version10 : HttpVersion.Version11;
}
set
{
if (value.Equals(HttpVersion.Version11))
{
IsVersionHttp10 = false;
}
else if (value.Equals(HttpVersion.Version10))
{
IsVersionHttp10 = true;
}
else
{
throw new ArgumentException(SR.net_wrongversion, nameof(value));
}
}
}
public int ReadWriteTimeout
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
_cookieContainer = value;
}
}
public override ICredentials Credentials
{
get
{
return _credentials;
}
set
{
_credentials = value;
}
}
public virtual bool HaveResponse
{
get
{
return (_sendRequestTask != null) && (_sendRequestTask.Status == TaskStatus.RanToCompletion);
}
}
public override WebHeaderCollection Headers
{
get
{
return _webHeaderCollection;
}
set
{
// We can't change headers after they've already been sent.
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
WebHeaderCollection webHeaders = value;
WebHeaderCollection newWebHeaders = new WebHeaderCollection();
// Copy And Validate -
// Handle the case where their object tries to change
// name, value pairs after they call set, so therefore,
// we need to clone their headers.
foreach (String headerName in webHeaders.AllKeys)
{
newWebHeaders[headerName] = webHeaders[headerName];
}
_webHeaderCollection = newWebHeaders;
}
}
public override string Method
{
get
{
return _originVerb;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_badmethod, nameof(value));
}
if (HttpValidationHelpers.IsInvalidMethodOrHeaderString(value))
{
throw new ArgumentException(SR.net_badmethod, nameof(value));
}
_originVerb = value;
}
}
public override Uri RequestUri
{
get
{
return _requestUri;
}
}
public virtual bool SupportsCookieContainer
{
get
{
return true;
}
}
public override bool UseDefaultCredentials
{
get
{
return (_credentials == CredentialCache.DefaultCredentials);
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
// Match Desktop behavior. Changing this property will also
// change the .Credentials property as well.
_credentials = value ? CredentialCache.DefaultCredentials : null;
}
}
public override IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
// We can't change the proxy while the request is already fired.
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_proxy = value;
}
}
public override void Abort()
{
if (Interlocked.Exchange(ref _abortCalled, 1) != 0)
{
return;
}
// .NET Desktop behavior requires us to invoke outstanding callbacks
// before returning if used in either the BeginGetRequestStream or
// BeginGetResponse methods.
//
// If we can transition the task to the canceled state, then we invoke
// the callback. If we can't transition the task, it is because it is
// already in the terminal state and the callback has already been invoked
// via the async task continuation.
if (_responseOperation != null)
{
if (_responseOperation.TrySetCanceled() && _responseCallback != null)
{
_responseCallback(_responseOperation.Task);
}
// Cancel the underlying send operation.
Debug.Assert(_sendRequestCts != null);
_sendRequestCts.Cancel();
}
else if (_requestStreamOperation != null)
{
if (_requestStreamOperation.TrySetCanceled() && _requestStreamCallback != null)
{
_requestStreamCallback(_requestStreamOperation.Task);
}
}
}
// HTTP version of the request
private bool IsVersionHttp10
{
get
{
return (_booleans & Booleans.IsVersionHttp10) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.IsVersionHttp10;
}
else
{
_booleans &= ~Booleans.IsVersionHttp10;
}
}
}
public override WebResponse GetResponse()
{
try
{
_sendRequestCts = new CancellationTokenSource();
return SendRequest().GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
}
public override Stream GetRequestStream()
{
return InternalGetRequestStream().Result;
}
private Task<Stream> InternalGetRequestStream()
{
CheckAbort();
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
// Match Desktop behavior: prevent someone from getting a request stream
// if the protocol verb/method doesn't support it. Note that this is not
// entirely compliant RFC2616 for the aforementioned compatibility reasons.
if (string.Equals(HttpMethod.Get.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals(HttpMethod.Head.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals("CONNECT", _originVerb, StringComparison.OrdinalIgnoreCase))
{
throw new ProtocolViolationException(SR.net_nouploadonget);
}
_requestStream = new RequestStream();
return Task.FromResult((Stream)_requestStream);
}
public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext context)
{
context = null;
return EndGetRequestStream(asyncResult);
}
public Stream GetRequestStream(out TransportContext context)
{
context = null;
return GetRequestStream();
}
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, Object state)
{
CheckAbort();
if (Interlocked.Exchange(ref _beginGetRequestStreamCalled, 1) != 0)
{
throw new InvalidOperationException(SR.net_repcall);
}
_requestStreamCallback = callback;
_requestStreamOperation = GetRequestStreamTask().ToApm(callback, state);
return _requestStreamOperation.Task;
}
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
CheckAbort();
if (asyncResult == null || !(asyncResult is Task<Stream>))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (Interlocked.Exchange(ref _endGetRequestStreamCalled, 1) != 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetRequestStream"));
}
Stream stream;
try
{
stream = ((Task<Stream>)asyncResult).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
return stream;
}
private Task<Stream> GetRequestStreamTask()
{
CheckAbort();
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
// Match Desktop behavior: prevent someone from getting a request stream
// if the protocol verb/method doesn't support it. Note that this is not
// entirely compliant RFC2616 for the aforementioned compatibility reasons.
if (string.Equals(HttpMethod.Get.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals(HttpMethod.Head.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals("CONNECT", _originVerb, StringComparison.OrdinalIgnoreCase))
{
throw new ProtocolViolationException(SR.net_nouploadonget);
}
_requestStream = new RequestStream();
return Task.FromResult((Stream)_requestStream);
}
private async Task<WebResponse> SendRequest()
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
var handler = new HttpClientHandler();
var request = new HttpRequestMessage(new HttpMethod(_originVerb), _requestUri);
using (var client = new HttpClient(handler))
{
if (_requestStream != null)
{
ArraySegment<byte> bytes = _requestStream.GetBuffer();
request.Content = new ByteArrayContent(bytes.Array, bytes.Offset, bytes.Count);
}
handler.AutomaticDecompression = AutomaticDecompression;
handler.Credentials = _credentials;
handler.AllowAutoRedirect = AllowAutoRedirect;
handler.MaxAutomaticRedirections = MaximumAutomaticRedirections;
handler.MaxResponseHeadersLength = MaximumResponseHeadersLength;
handler.PreAuthenticate = PreAuthenticate;
client.Timeout = Timeout == Threading.Timeout.Infinite ?
Threading.Timeout.InfiniteTimeSpan :
TimeSpan.FromMilliseconds(Timeout);
if (_cookieContainer != null)
{
handler.CookieContainer = _cookieContainer;
Debug.Assert(handler.UseCookies); // Default of handler.UseCookies is true.
}
else
{
handler.UseCookies = false;
}
Debug.Assert(handler.UseProxy); // Default of handler.UseProxy is true.
Debug.Assert(handler.Proxy == null); // Default of handler.Proxy is null.
if (_proxy == null)
{
handler.UseProxy = false;
}
else
{
handler.Proxy = _proxy;
}
handler.ClientCertificates.AddRange(ClientCertificates);
// Set relevant properties from ServicePointManager
handler.SslProtocols = (SslProtocols)ServicePointManager.SecurityProtocol;
handler.CheckCertificateRevocationList = ServicePointManager.CheckCertificateRevocationList;
RemoteCertificateValidationCallback rcvc = ServerCertificateValidationCallback != null ?
ServerCertificateValidationCallback :
ServicePointManager.ServerCertificateValidationCallback;
if (rcvc != null)
{
RemoteCertificateValidationCallback localRcvc = rcvc;
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => localRcvc(this, cert, chain, errors);
}
// Copy the HttpWebRequest request headers from the WebHeaderCollection into HttpRequestMessage.Headers and
// HttpRequestMessage.Content.Headers.
foreach (string headerName in _webHeaderCollection)
{
// The System.Net.Http APIs require HttpRequestMessage headers to be properly divided between the request headers
// collection and the request content headers collection for all well-known header names. And custom headers
// are only allowed in the request headers collection and not in the request content headers collection.
if (IsWellKnownContentHeader(headerName))
{
if (request.Content == null)
{
// Create empty content so that we can send the entity-body header.
request.Content = new ByteArrayContent(Array.Empty<byte>());
}
request.Content.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
else
{
request.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
}
request.Headers.TransferEncodingChunked = SendChunked;
_sendRequestTask = client.SendAsync(
request,
_allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
_sendRequestCts.Token);
HttpResponseMessage responseMessage = await _sendRequestTask.ConfigureAwait(false);
HttpWebResponse response = new HttpWebResponse(responseMessage, _requestUri, _cookieContainer);
if (!responseMessage.IsSuccessStatusCode)
{
throw new WebException(
SR.Format(SR.net_servererror, (int)response.StatusCode, response.StatusDescription),
null,
WebExceptionStatus.ProtocolError,
response);
}
return response;
}
}
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
CheckAbort();
if (Interlocked.Exchange(ref _beginGetResponseCalled, 1) != 0)
{
throw new InvalidOperationException(SR.net_repcall);
}
_sendRequestCts = new CancellationTokenSource();
_responseCallback = callback;
_responseOperation = SendRequest().ToApm(callback, state);
return _responseOperation.Task;
}
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
CheckAbort();
if (asyncResult == null || !(asyncResult is Task<WebResponse>))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (Interlocked.Exchange(ref _endGetResponseCalled, 1) != 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse"));
}
WebResponse response;
try
{
response = ((Task<WebResponse>)asyncResult).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
return response;
}
/// <devdoc>
/// <para>
/// Adds a range header to the request for a specified range.
/// </para>
/// </devdoc>
public void AddRange(int from, int to)
{
AddRange("bytes", (long)from, (long)to);
}
/// <devdoc>
/// <para>
/// Adds a range header to the request for a specified range.
/// </para>
/// </devdoc>
public void AddRange(long from, long to)
{
AddRange("bytes", from, to);
}
/// <devdoc>
/// <para>
/// Adds a range header to a request for a specific
/// range from the beginning or end
/// of the requested data.
/// To add the range from the end pass negative value
/// To add the range from the some offset to the end pass positive value
/// </para>
/// </devdoc>
public void AddRange(int range)
{
AddRange("bytes", (long)range);
}
/// <devdoc>
/// <para>
/// Adds a range header to a request for a specific
/// range from the beginning or end
/// of the requested data.
/// To add the range from the end pass negative value
/// To add the range from the some offset to the end pass positive value
/// </para>
/// </devdoc>
public void AddRange(long range)
{
AddRange("bytes", range);
}
public void AddRange(string rangeSpecifier, int from, int to)
{
AddRange(rangeSpecifier, (long)from, (long)to);
}
public void AddRange(string rangeSpecifier, long from, long to)
{
//
// Do some range checking before assembling the header
//
if (rangeSpecifier == null)
{
throw new ArgumentNullException(nameof(rangeSpecifier));
}
if ((from < 0) || (to < 0))
{
throw new ArgumentOutOfRangeException(from < 0 ? nameof(from) : nameof(to), SR.net_rangetoosmall);
}
if (from > to)
{
throw new ArgumentOutOfRangeException(nameof(from), SR.net_fromto);
}
if (!HttpValidationHelpers.IsValidToken(rangeSpecifier))
{
throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier));
}
if (!AddRange(rangeSpecifier, from.ToString(NumberFormatInfo.InvariantInfo), to.ToString(NumberFormatInfo.InvariantInfo)))
{
throw new InvalidOperationException(SR.net_rangetype);
}
}
public void AddRange(string rangeSpecifier, int range)
{
AddRange(rangeSpecifier, (long)range);
}
public void AddRange(string rangeSpecifier, long range)
{
if (rangeSpecifier == null)
{
throw new ArgumentNullException(nameof(rangeSpecifier));
}
if (!HttpValidationHelpers.IsValidToken(rangeSpecifier))
{
throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier));
}
if (!AddRange(rangeSpecifier, range.ToString(NumberFormatInfo.InvariantInfo), (range >= 0) ? "" : null))
{
throw new InvalidOperationException(SR.net_rangetype);
}
}
private bool AddRange(string rangeSpecifier, string from, string to)
{
string curRange = _webHeaderCollection[HttpKnownHeaderNames.Range];
if ((curRange == null) || (curRange.Length == 0))
{
curRange = rangeSpecifier + "=";
}
else
{
if (String.Compare(curRange.Substring(0, curRange.IndexOf('=')), rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
{
return false;
}
curRange = string.Empty;
}
curRange += from.ToString();
if (to != null)
{
curRange += "-" + to;
}
_webHeaderCollection[HttpKnownHeaderNames.Range] = curRange;
return true;
}
private bool RequestSubmitted
{
get
{
return _sendRequestTask != null;
}
}
private void CheckAbort()
{
if (Volatile.Read(ref _abortCalled) == 1)
{
throw new WebException(SR.net_reqaborted, WebExceptionStatus.RequestCanceled);
}
}
private static readonly string[] s_wellKnownContentHeaders = {
HttpKnownHeaderNames.ContentDisposition,
HttpKnownHeaderNames.ContentEncoding,
HttpKnownHeaderNames.ContentLanguage,
HttpKnownHeaderNames.ContentLength,
HttpKnownHeaderNames.ContentLocation,
HttpKnownHeaderNames.ContentMD5,
HttpKnownHeaderNames.ContentRange,
HttpKnownHeaderNames.ContentType,
HttpKnownHeaderNames.Expires,
HttpKnownHeaderNames.LastModified
};
private bool IsWellKnownContentHeader(string header)
{
foreach (string contentHeaderName in s_wellKnownContentHeaders)
{
if (string.Equals(header, contentHeaderName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private DateTime GetDateHeaderHelper(string headerName)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
string headerValue = _webHeaderCollection[headerName];
if (headerValue == null)
{
return DateTime.MinValue; // MinValue means header is not present
}
return StringToDate(headerValue);
#if DEBUG
}
#endif
}
private void SetDateHeaderHelper(string headerName, DateTime dateTime)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
if (dateTime == DateTime.MinValue)
SetSpecialHeaders(headerName, null); // remove header
else
SetSpecialHeaders(headerName, DateToString(dateTime));
#if DEBUG
}
#endif
}
// parse String to DateTime format.
private static DateTime StringToDate(String S)
{
DateTime dtOut;
if (HttpDateParse.ParseHttpDate(S, out dtOut))
{
return dtOut;
}
else
{
throw new ProtocolViolationException(SR.net_baddate);
}
}
// convert Date to String using RFC 1123 pattern
private static string DateToString(DateTime D)
{
DateTimeFormatInfo dateFormat = new DateTimeFormatInfo();
return D.ToUniversalTime().ToString("R", dateFormat);
}
}
}
| |
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8
#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.Globalization;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaBuilder
{
private readonly IList<JsonSchema> _stack;
private readonly JsonSchemaResolver _resolver;
private readonly IDictionary<string, JsonSchema> _documentSchemas;
private JsonSchema _currentSchema;
private JObject _rootSchema;
public JsonSchemaBuilder(JsonSchemaResolver resolver)
{
_stack = new List<JsonSchema>();
_documentSchemas = new Dictionary<string, JsonSchema>();
_resolver = resolver;
}
private void Push(JsonSchema value)
{
_currentSchema = value;
_stack.Add(value);
_resolver.LoadedSchemas.Add(value);
_documentSchemas.Add(value.Location, value);
}
private JsonSchema Pop()
{
JsonSchema poppedSchema = _currentSchema;
_stack.RemoveAt(_stack.Count - 1);
_currentSchema = _stack.LastOrDefault();
return poppedSchema;
}
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
internal JsonSchema Read(JsonReader reader)
{
JToken schemaToken = JToken.ReadFrom(reader);
_rootSchema = schemaToken as JObject;
JsonSchema schema = BuildSchema(schemaToken);
ResolveReferences(schema);
return schema;
}
private string UnescapeReference(string reference)
{
return Uri.UnescapeDataString(reference).Replace("~1", "/").Replace("~0", "~");
}
private JsonSchema ResolveReferences(JsonSchema schema)
{
if (schema.DeferredReference != null)
{
string reference = schema.DeferredReference;
bool locationReference = (reference.StartsWith("#", StringComparison.OrdinalIgnoreCase));
if (locationReference)
reference = UnescapeReference(reference);
JsonSchema resolvedSchema = _resolver.GetSchema(reference);
if (resolvedSchema == null)
{
if (locationReference)
{
string[] escapedParts = schema.DeferredReference.TrimStart('#').Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
JToken currentToken = _rootSchema;
foreach (string escapedPart in escapedParts)
{
string part = UnescapeReference(escapedPart);
if (currentToken.Type == JTokenType.Object)
{
currentToken = currentToken[part];
}
else if (currentToken.Type == JTokenType.Array || currentToken.Type == JTokenType.Constructor)
{
int index;
if (int.TryParse(part, out index) && index >= 0 && index < currentToken.Count())
currentToken = currentToken[index];
else
currentToken = null;
}
if (currentToken == null)
break;
}
if (currentToken != null)
resolvedSchema = BuildSchema(currentToken);
}
if (resolvedSchema == null)
throw new JsonException("Could not resolve schema reference '{0}'.".FormatWith(CultureInfo.InvariantCulture, schema.DeferredReference));
}
schema = resolvedSchema;
}
if (schema.ReferencesResolved)
return schema;
schema.ReferencesResolved = true;
if (schema.Extends != null)
{
for (int i = 0; i < schema.Extends.Count; i++)
{
schema.Extends[i] = ResolveReferences(schema.Extends[i]);
}
}
if (schema.Items != null)
{
for (int i = 0; i < schema.Items.Count; i++)
{
schema.Items[i] = ResolveReferences(schema.Items[i]);
}
}
if (schema.AdditionalItems != null)
schema.AdditionalItems = ResolveReferences(schema.AdditionalItems);
if (schema.PatternProperties != null)
{
foreach (KeyValuePair<string, JsonSchema> patternProperty in schema.PatternProperties.ToList())
{
schema.PatternProperties[patternProperty.Key] = ResolveReferences(patternProperty.Value);
}
}
if (schema.Properties != null)
{
foreach (KeyValuePair<string, JsonSchema> property in schema.Properties.ToList())
{
schema.Properties[property.Key] = ResolveReferences(property.Value);
}
}
if (schema.AdditionalProperties != null)
schema.AdditionalProperties = ResolveReferences(schema.AdditionalProperties);
return schema;
}
private JsonSchema BuildSchema(JToken token)
{
JObject schemaObject = token as JObject;
if (schemaObject == null)
throw JsonException.Create(token, token.Path, "Expected object while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
JToken referenceToken;
if (schemaObject.TryGetValue(JsonSchemaConstants.ReferencePropertyName, out referenceToken))
{
JsonSchema deferredSchema = new JsonSchema();
deferredSchema.DeferredReference = (string)referenceToken;
return deferredSchema;
}
string location = token.Path.Replace(".", "/").Replace("[", "/").Replace("]", string.Empty);
if (!string.IsNullOrEmpty(location))
location = "/" + location;
location = "#" + location;
JsonSchema existingSchema;
if (_documentSchemas.TryGetValue(location, out existingSchema))
return existingSchema;
Push(new JsonSchema { Location = location });
ProcessSchemaProperties(schemaObject);
return Pop();
}
private void ProcessSchemaProperties(JObject schemaObject)
{
foreach (KeyValuePair<string, JToken> property in schemaObject)
{
switch (property.Key)
{
case JsonSchemaConstants.TypePropertyName:
CurrentSchema.Type = ProcessType(property.Value);
break;
case JsonSchemaConstants.IdPropertyName:
CurrentSchema.Id = (string)property.Value;
break;
case JsonSchemaConstants.TitlePropertyName:
CurrentSchema.Title = (string)property.Value;
break;
case JsonSchemaConstants.DescriptionPropertyName:
CurrentSchema.Description = (string)property.Value;
break;
case JsonSchemaConstants.PropertiesPropertyName:
CurrentSchema.Properties = ProcessProperties(property.Value);
break;
case JsonSchemaConstants.ItemsPropertyName:
ProcessItems(property.Value);
break;
case JsonSchemaConstants.AdditionalPropertiesPropertyName:
ProcessAdditionalProperties(property.Value);
break;
case JsonSchemaConstants.AdditionalItemsPropertyName:
ProcessAdditionalItems(property.Value);
break;
case JsonSchemaConstants.PatternPropertiesPropertyName:
CurrentSchema.PatternProperties = ProcessProperties(property.Value);
break;
case JsonSchemaConstants.RequiredPropertyName:
CurrentSchema.Required = (bool)property.Value;
break;
case JsonSchemaConstants.RequiresPropertyName:
CurrentSchema.Requires = (string)property.Value;
break;
case JsonSchemaConstants.MinimumPropertyName:
CurrentSchema.Minimum = (double)property.Value;
break;
case JsonSchemaConstants.MaximumPropertyName:
CurrentSchema.Maximum = (double)property.Value;
break;
case JsonSchemaConstants.ExclusiveMinimumPropertyName:
CurrentSchema.ExclusiveMinimum = (bool)property.Value;
break;
case JsonSchemaConstants.ExclusiveMaximumPropertyName:
CurrentSchema.ExclusiveMaximum = (bool)property.Value;
break;
case JsonSchemaConstants.MaximumLengthPropertyName:
CurrentSchema.MaximumLength = (int)property.Value;
break;
case JsonSchemaConstants.MinimumLengthPropertyName:
CurrentSchema.MinimumLength = (int)property.Value;
break;
case JsonSchemaConstants.MaximumItemsPropertyName:
CurrentSchema.MaximumItems = (int)property.Value;
break;
case JsonSchemaConstants.MinimumItemsPropertyName:
CurrentSchema.MinimumItems = (int)property.Value;
break;
case JsonSchemaConstants.DivisibleByPropertyName:
CurrentSchema.DivisibleBy = (double)property.Value;
break;
case JsonSchemaConstants.DisallowPropertyName:
CurrentSchema.Disallow = ProcessType(property.Value);
break;
case JsonSchemaConstants.DefaultPropertyName:
CurrentSchema.Default = property.Value.DeepClone();
break;
case JsonSchemaConstants.HiddenPropertyName:
CurrentSchema.Hidden = (bool)property.Value;
break;
case JsonSchemaConstants.ReadOnlyPropertyName:
CurrentSchema.ReadOnly = (bool)property.Value;
break;
case JsonSchemaConstants.FormatPropertyName:
CurrentSchema.Format = (string)property.Value;
break;
case JsonSchemaConstants.PatternPropertyName:
CurrentSchema.Pattern = (string)property.Value;
break;
case JsonSchemaConstants.EnumPropertyName:
ProcessEnum(property.Value);
break;
case JsonSchemaConstants.ExtendsPropertyName:
ProcessExtends(property.Value);
break;
case JsonSchemaConstants.UniqueItemsPropertyName:
CurrentSchema.UniqueItems = (bool)property.Value;
break;
}
}
}
private void ProcessExtends(JToken token)
{
IList<JsonSchema> schemas = new List<JsonSchema>();
if (token.Type == JTokenType.Array)
{
foreach (JToken schemaObject in token)
{
schemas.Add(BuildSchema(schemaObject));
}
}
else
{
JsonSchema schema = BuildSchema(token);
if (schema != null)
schemas.Add(schema);
}
if (schemas.Count > 0)
CurrentSchema.Extends = schemas;
}
private void ProcessEnum(JToken token)
{
if (token.Type != JTokenType.Array)
throw JsonException.Create(token, token.Path, "Expected Array token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
CurrentSchema.Enum = new List<JToken>();
foreach (JToken enumValue in token)
{
CurrentSchema.Enum.Add(enumValue.DeepClone());
}
}
private void ProcessAdditionalProperties(JToken token)
{
if (token.Type == JTokenType.Boolean)
CurrentSchema.AllowAdditionalProperties = (bool)token;
else
CurrentSchema.AdditionalProperties = BuildSchema(token);
}
private void ProcessAdditionalItems(JToken token)
{
if (token.Type == JTokenType.Boolean)
CurrentSchema.AllowAdditionalItems = (bool)token;
else
CurrentSchema.AdditionalItems = BuildSchema(token);
}
private IDictionary<string, JsonSchema> ProcessProperties(JToken token)
{
IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>();
if (token.Type != JTokenType.Object)
throw JsonException.Create(token, token.Path, "Expected Object token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
foreach (JProperty propertyToken in token)
{
if (properties.ContainsKey(propertyToken.Name))
throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyToken.Name));
properties.Add(propertyToken.Name, BuildSchema(propertyToken.Value));
}
return properties;
}
private void ProcessItems(JToken token)
{
CurrentSchema.Items = new List<JsonSchema>();
switch (token.Type)
{
case JTokenType.Object:
CurrentSchema.Items.Add(BuildSchema(token));
CurrentSchema.PositionalItemsValidation = false;
break;
case JTokenType.Array:
CurrentSchema.PositionalItemsValidation = true;
foreach (JToken schemaToken in token)
{
CurrentSchema.Items.Add(BuildSchema(schemaToken));
}
break;
default:
throw JsonException.Create(token, token.Path, "Expected array or JSON schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
}
private JsonSchemaType? ProcessType(JToken token)
{
switch (token.Type)
{
case JTokenType.Array:
// ensure type is in blank state before ORing values
JsonSchemaType? type = JsonSchemaType.None;
foreach (JToken typeToken in token)
{
if (typeToken.Type != JTokenType.String)
throw JsonException.Create(typeToken, typeToken.Path, "Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
type = type | MapType((string) typeToken);
}
return type;
case JTokenType.String:
return MapType((string)token);
default:
throw JsonException.Create(token, token.Path, "Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
}
internal static JsonSchemaType MapType(string type)
{
JsonSchemaType mappedType;
if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType))
throw new JsonException("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type));
return mappedType;
}
internal static string MapType(JsonSchemaType type)
{
return JsonSchemaConstants.JsonSchemaTypeMapping.Single(kv => kv.Value == type).Key;
}
}
}
#endif
| |
// Copyright (c) 2015 ZZZ Projects. All rights reserved
// Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
// Website: http://www.zzzprojects.com/
// Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
// All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library
using System;
using System.IO;
using System.Linq;
public static partial class Extensions
{
/// <summary>
/// Returns an enumerable collection of file names in a specified @this.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the files in the directory specified by
/// <paramref
/// name="this" />
/// .
/// </returns>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static FileInfo[] GetFilesWhere(this DirectoryInfo @this, Func<FileInfo, bool> predicate)
{
return Directory.EnumerateFiles(@this.FullName).Select(x => new FileInfo(x)).Where(x => predicate(x)).ToArray();
}
/// <summary>
/// Returns an enumerable collection of file names that match a search pattern in a specified @this.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in
/// <paramref name="this" />.
/// </param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the files in the directory specified by
/// <paramref
/// name="this" />
/// and that match the specified search pattern.
/// </returns>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetFilesWhere
/// {
/// [TestMethod]
/// public void GetFilesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetFilesWhere"));
/// Directory.CreateDirectory(root.FullName);
///
/// var file1 = new FileInfo(Path.Combine(root.FullName, "test.txt"));
/// var file2 = new FileInfo(Path.Combine(root.FullName, "test.cs"));
/// var file3 = new FileInfo(Path.Combine(root.FullName, "test.asp"));
/// file1.Create();
/// file2.Create();
/// file3.Create();
///
/// // Exemples
/// FileInfo[] result = root.GetFilesWhere(x => x.Extension == ".txt" || x.Extension == ".cs");
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetFilesWhere
/// {
/// [TestMethod]
/// public void GetFilesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetFilesWhere"));
/// Directory.CreateDirectory(root.FullName);
///
/// var file1 = new FileInfo(Path.Combine(root.FullName, "test.txt"));
/// var file2 = new FileInfo(Path.Combine(root.FullName, "test.cs"));
/// var file3 = new FileInfo(Path.Combine(root.FullName, "test.asp"));
/// file1.Create();
/// file2.Create();
/// file3.Create();
///
/// // Exemples
/// FileInfo[] result = root.GetFilesWhere(x => x.Extension == ".txt" || x.Extension == ".cs");
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .- or -<paramref name="searchPattern" /> does not contain a valid pattern.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.-or-
/// <paramref name="searchPattern" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static FileInfo[] GetFilesWhere(this DirectoryInfo @this, String searchPattern, Func<FileInfo, bool> predicate)
{
return Directory.EnumerateFiles(@this.FullName, searchPattern).Select(x => new FileInfo(x)).Where(x => predicate(x)).ToArray();
}
/// <summary>
/// Returns an enumerable collection of file names that match a search pattern in a specified @this, and
/// optionally searches subdirectories.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in
/// <paramref name="this" />.
/// </param>
/// <param name="searchOption">
/// One of the enumeration values that specifies whether the search operation should
/// include only the current directory or should include all subdirectories.The default value is
/// <see
/// cref="F:System.IO.SearchOption.TopDirectoryOnly" />
/// .
/// </param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the files in the directory specified by
/// <paramref
/// name="this" />
/// and that match the specified search pattern and option.
/// </returns>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetFilesWhere
/// {
/// [TestMethod]
/// public void GetFilesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetFilesWhere"));
/// Directory.CreateDirectory(root.FullName);
///
/// var file1 = new FileInfo(Path.Combine(root.FullName, "test.txt"));
/// var file2 = new FileInfo(Path.Combine(root.FullName, "test.cs"));
/// var file3 = new FileInfo(Path.Combine(root.FullName, "test.asp"));
/// file1.Create();
/// file2.Create();
/// file3.Create();
///
/// // Exemples
/// FileInfo[] result = root.GetFilesWhere(x => x.Extension == ".txt" || x.Extension == ".cs");
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetFilesWhere
/// {
/// [TestMethod]
/// public void GetFilesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetFilesWhere"));
/// Directory.CreateDirectory(root.FullName);
///
/// var file1 = new FileInfo(Path.Combine(root.FullName, "test.txt"));
/// var file2 = new FileInfo(Path.Combine(root.FullName, "test.cs"));
/// var file3 = new FileInfo(Path.Combine(root.FullName, "test.asp"));
/// file1.Create();
/// file2.Create();
/// file3.Create();
///
/// // Exemples
/// FileInfo[] result = root.GetFilesWhere(x => x.Extension == ".txt" || x.Extension == ".cs");
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .- or -<paramref name="searchPattern" /> does not contain a valid pattern.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.-or-
/// <paramref name="searchPattern" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="searchOption" /> is not a valid
/// <see cref="T:System.IO.SearchOption" /> value.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static FileInfo[] GetFilesWhere(this DirectoryInfo @this, String searchPattern, SearchOption searchOption, Func<FileInfo, bool> predicate)
{
return Directory.EnumerateFiles(@this.FullName, searchPattern, searchOption).Select(x => new FileInfo(x)).Where(x => predicate(x)).ToArray();
}
/// <summary>
/// Returns an enumerable collection of file names that match a search pattern in a specified @this.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="searchPatterns">The search string to match against the names of directories in.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the files in the directory specified by
/// <paramref
/// name="this" />
/// and that match the specified search pattern.
/// </returns>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetFilesWhere
/// {
/// [TestMethod]
/// public void GetFilesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetFilesWhere"));
/// Directory.CreateDirectory(root.FullName);
///
/// var file1 = new FileInfo(Path.Combine(root.FullName, "test.txt"));
/// var file2 = new FileInfo(Path.Combine(root.FullName, "test.cs"));
/// var file3 = new FileInfo(Path.Combine(root.FullName, "test.asp"));
/// file1.Create();
/// file2.Create();
/// file3.Create();
///
/// // Exemples
/// FileInfo[] result = root.GetFilesWhere(x => x.Extension == ".txt" || x.Extension == ".cs");
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetFilesWhere
/// {
/// [TestMethod]
/// public void GetFilesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetFilesWhere"));
/// Directory.CreateDirectory(root.FullName);
///
/// var file1 = new FileInfo(Path.Combine(root.FullName, "test.txt"));
/// var file2 = new FileInfo(Path.Combine(root.FullName, "test.cs"));
/// var file3 = new FileInfo(Path.Combine(root.FullName, "test.asp"));
/// file1.Create();
/// file2.Create();
/// file3.Create();
///
/// // Exemples
/// FileInfo[] result = root.GetFilesWhere(x => x.Extension == ".txt" || x.Extension == ".cs");
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// ###
/// <param name="searchPattern">
/// The search string to match against the names of directories in
/// <paramref name="this" />.
/// </param>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .- or -<paramref name="searchPattern" /> does not contain a valid pattern.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.-or-
/// <paramref name="searchPattern" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static FileInfo[] GetFilesWhere(this DirectoryInfo @this, String[] searchPatterns, Func<FileInfo, bool> predicate)
{
return searchPatterns.SelectMany(x => @this.GetFiles(x)).Distinct().Where(x => predicate(x)).ToArray();
}
/// <summary>
/// Returns an enumerable collection of file names that match a search pattern in a specified @this, and
/// optionally searches subdirectories.
/// </summary>
/// <param name="this">The directory to search.</param>
/// <param name="searchPatterns">
/// The search string to match against the names of directories in
/// <paramref name="this" />.
/// </param>
/// <param name="searchOption">
/// One of the enumeration values that specifies whether the search operation should
/// include only the current directory or should include all subdirectories.The default value is
/// <see
/// cref="F:System.IO.SearchOption.TopDirectoryOnly" />
/// .
/// </param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// An enumerable collection of the full names (including paths) for the files in the directory specified by
/// <paramref
/// name="this" />
/// and that match the specified search pattern and option.
/// </returns>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetFilesWhere
/// {
/// [TestMethod]
/// public void GetFilesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetFilesWhere"));
/// Directory.CreateDirectory(root.FullName);
///
/// var file1 = new FileInfo(Path.Combine(root.FullName, "test.txt"));
/// var file2 = new FileInfo(Path.Combine(root.FullName, "test.cs"));
/// var file3 = new FileInfo(Path.Combine(root.FullName, "test.asp"));
/// file1.Create();
/// file2.Create();
/// file3.Create();
///
/// // Exemples
/// FileInfo[] result = root.GetFilesWhere(x => x.Extension == ".txt" || x.Extension == ".cs");
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.IO;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_IO_DirectoryInfo_GetFilesWhere
/// {
/// [TestMethod]
/// public void GetFilesWhere()
/// {
/// // Type
/// var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetFilesWhere"));
/// Directory.CreateDirectory(root.FullName);
///
/// var file1 = new FileInfo(Path.Combine(root.FullName, "test.txt"));
/// var file2 = new FileInfo(Path.Combine(root.FullName, "test.cs"));
/// var file3 = new FileInfo(Path.Combine(root.FullName, "test.asp"));
/// file1.Create();
/// file2.Create();
/// file3.Create();
///
/// // Exemples
/// FileInfo[] result = root.GetFilesWhere(x => x.Extension == ".txt" || x.Extension == ".cs");
///
/// // Unit Test
/// Assert.AreEqual(2, result.Length);
/// }
/// }
/// }
/// </code>
/// </example>
/// ###
/// <exception cref="T:System.ArgumentException">
/// <paramref name="this " />is a zero-length string, contains only
/// white space, or contains invalid characters as defined by
/// <see
/// cref="M:System.IO.Path.GetInvalidPathChars" />
/// .- or -<paramref name="searchPattern" /> does not contain a valid pattern.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="this" /> is null.-or-
/// <paramref name="searchPattern" /> is null.
/// </exception>
/// ###
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="searchOption" /> is not a valid
/// <see cref="T:System.IO.SearchOption" /> value.
/// </exception>
/// ###
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// <paramref name="this" /> is invalid, such as
/// referring to an unmapped drive.
/// </exception>
/// ###
/// <exception cref="T:System.IO.IOException">
/// <paramref name="this" /> is a file name.
/// </exception>
/// ###
/// <exception cref="T:System.IO.PathTooLongException">
/// The specified @this, file name, or combined exceed the
/// system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters
/// and file names must be less than 260 characters.
/// </exception>
/// ###
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// ###
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
public static FileInfo[] GetFilesWhere(this DirectoryInfo @this, String[] searchPatterns, SearchOption searchOption, Func<FileInfo, bool> predicate)
{
return searchPatterns.SelectMany(x => @this.GetFiles(x, searchOption)).Distinct().Where(x => predicate(x)).ToArray();
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
using System.Reflection;
using Sensus.Probes;
using Sensus.Probes.User.Scripts;
using Sensus.Probes.User.Scripts.ProbeTriggerProperties;
using Xamarin.Forms;
namespace Sensus.UI
{
/// <summary>
/// Allows the user to add a script trigger to a script runner.
/// </summary>
public class AddScriptTriggerPage : ContentPage
{
private ScriptRunner _scriptRunner;
private Probe _selectedProbe;
private PropertyInfo _selectedDatumProperty;
private TriggerValueCondition _selectedCondition;
private object _conditionValue;
/// <summary>
/// Initializes a new instance of the <see cref="AddScriptTriggerPage"/> class.
/// </summary>
/// <param name="scriptRunner">Script runner to add trigger to.</param>
public AddScriptTriggerPage(ScriptRunner scriptRunner)
{
_scriptRunner = scriptRunner;
Title = "Add Trigger";
var enabledProbes = _scriptRunner.Probe.Protocol.Probes.Where(p => p != _scriptRunner.Probe && p.Enabled).ToArray();
if (!enabledProbes.Any())
{
Content = new Label { Text = "No enabled probes. Please enable them before creating triggers.", FontSize = 20 };
return;
}
var contentLayout = new StackLayout
{
Orientation = StackOrientation.Vertical,
VerticalOptions = LayoutOptions.FillAndExpand
};
var probeLabel = new Label { Text = "Probe:", FontSize = 20 };
Picker probePicker = new Picker { Title = "Select Probe", HorizontalOptions = LayoutOptions.FillAndExpand };
foreach (Probe enabledProbe in enabledProbes)
{
probePicker.Items.Add(enabledProbe.DisplayName);
}
contentLayout.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { probeLabel, probePicker }
});
StackLayout triggerDefinitionLayout = new StackLayout
{
Orientation = StackOrientation.Vertical,
VerticalOptions = LayoutOptions.Start
};
contentLayout.Children.Add(triggerDefinitionLayout);
Switch changeSwitch = new Switch();
Switch regexSwitch = new Switch();
Switch fireRepeatedlySwitch = new Switch();
TimePicker startTimePicker = new TimePicker { HorizontalOptions = LayoutOptions.FillAndExpand };
TimePicker endTimePicker = new TimePicker { HorizontalOptions = LayoutOptions.FillAndExpand };
probePicker.SelectedIndexChanged += (o, e) =>
{
_selectedProbe = null;
_selectedDatumProperty = null;
_conditionValue = null;
triggerDefinitionLayout.Children.Clear();
if (probePicker.SelectedIndex < 0)
return;
_selectedProbe = enabledProbes[probePicker.SelectedIndex];
PropertyInfo[] datumProperties = _selectedProbe.DatumType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttributes<ProbeTriggerProperty>().Any()).ToArray();
if (datumProperties.Length == 0)
return;
#region datum property picker
Label datumPropertyLabel = new Label
{
Text = "Property:",
FontSize = 20
};
Picker datumPropertyPicker = new Picker { Title = "Select Datum Property", HorizontalOptions = LayoutOptions.FillAndExpand };
foreach (PropertyInfo datumProperty in datumProperties)
{
var triggerProperty = datumProperty.GetCustomAttributes<ProbeTriggerProperty>().First();
datumPropertyPicker.Items.Add(triggerProperty.Name ?? datumProperty.Name);
}
triggerDefinitionLayout.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { datumPropertyLabel, datumPropertyPicker }
});
#endregion
#region condition picker (same for all datum types)
Label conditionLabel = new Label
{
Text = "Condition:",
FontSize = 20
};
Picker conditionPicker = new Picker { Title = "Select Condition", HorizontalOptions = LayoutOptions.FillAndExpand };
TriggerValueCondition[] conditions = Enum.GetValues(typeof(TriggerValueCondition)) as TriggerValueCondition[];
foreach (TriggerValueCondition condition in conditions)
conditionPicker.Items.Add(condition.ToString());
conditionPicker.SelectedIndexChanged += (oo, ee) =>
{
if (conditionPicker.SelectedIndex < 0)
return;
_selectedCondition = conditions[conditionPicker.SelectedIndex];
};
triggerDefinitionLayout.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { conditionLabel, conditionPicker }
});
#endregion
#region condition value for comparison, based on selected datum property -- includes change calculation (for double datum) and regex (for string datum)
StackLayout conditionValueStack = new StackLayout
{
Orientation = StackOrientation.Vertical,
HorizontalOptions = LayoutOptions.FillAndExpand
};
triggerDefinitionLayout.Children.Add(conditionValueStack);
datumPropertyPicker.SelectedIndexChanged += (oo, ee) =>
{
_selectedDatumProperty = null;
_conditionValue = null;
conditionValueStack.Children.Clear();
if (datumPropertyPicker.SelectedIndex < 0)
return;
_selectedDatumProperty = datumProperties[datumPropertyPicker.SelectedIndex];
ProbeTriggerProperty datumTriggerAttribute = _selectedDatumProperty.GetCustomAttribute<ProbeTriggerProperty>();
View conditionValueStackView = null;
bool allowChangeCalculation = false;
bool allowRegularExpression = false;
if (datumTriggerAttribute is ListProbeTriggerProperty)
{
Picker conditionValuePicker = new Picker { Title = "Select Condition Value", HorizontalOptions = LayoutOptions.FillAndExpand };
object[] items = (datumTriggerAttribute as ListProbeTriggerProperty).Items;
foreach (object item in items)
conditionValuePicker.Items.Add(item.ToString());
conditionValuePicker.SelectedIndexChanged += (ooo, eee) =>
{
if (conditionValuePicker.SelectedIndex < 0)
return;
_conditionValue = items[conditionValuePicker.SelectedIndex];
};
conditionValueStackView = conditionValuePicker;
}
else if (datumTriggerAttribute is DoubleProbeTriggerProperty)
{
Entry entry = new Entry
{
Keyboard = Keyboard.Numeric,
HorizontalOptions = LayoutOptions.FillAndExpand
};
entry.TextChanged += (ooo, eee) =>
{
double value;
if (double.TryParse(eee.NewTextValue, out value))
_conditionValue = value;
};
conditionValueStackView = entry;
allowChangeCalculation = true;
}
else if (datumTriggerAttribute is StringProbeTriggerProperty)
{
Entry entry = new Entry
{
Keyboard = Keyboard.Default,
HorizontalOptions = LayoutOptions.FillAndExpand
};
entry.TextChanged += (ooo, eee) => _conditionValue = eee.NewTextValue;
conditionValueStackView = entry;
allowRegularExpression = true;
}
else if (datumTriggerAttribute is BooleanProbeTriggerProperty)
{
Switch booleanSwitch = new Switch();
booleanSwitch.Toggled += (ooo, eee) => _conditionValue = eee.Value;
conditionValueStackView = booleanSwitch;
}
Label conditionValueStackLabel = new Label
{
Text = "Value:",
FontSize = 20
};
conditionValueStack.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { conditionValueStackLabel, conditionValueStackView }
});
#region change calculation
if (allowChangeCalculation)
{
Label changeLabel = new Label
{
Text = "Change:",
FontSize = 20
};
changeSwitch.IsToggled = false;
conditionValueStack.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { changeLabel, changeSwitch }
});
}
#endregion
#region regular expression
if (allowRegularExpression)
{
Label regexLabel = new Label
{
Text = "Regular Expression:",
FontSize = 20
};
regexSwitch.IsToggled = false;
conditionValueStack.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { regexLabel, regexSwitch }
});
}
#endregion
};
datumPropertyPicker.SelectedIndex = 0;
#endregion
#region fire repeatedly
Label fireRepeatedlyLabel = new Label
{
Text = "Fire Repeatedly:",
FontSize = 20
};
fireRepeatedlySwitch.IsToggled = false;
triggerDefinitionLayout.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { fireRepeatedlyLabel, fireRepeatedlySwitch }
});
#endregion
#region start/end times
Label startTimeLabel = new Label
{
Text = "Start Time:",
FontSize = 20
};
startTimePicker.Time = new TimeSpan(0, 0, 0);
triggerDefinitionLayout.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { startTimeLabel, startTimePicker }
});
Label endTimeLabel = new Label
{
Text = "End Time:",
FontSize = 20
};
endTimePicker.Time = new TimeSpan(23, 59, 59);
triggerDefinitionLayout.Children.Add(new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { endTimeLabel, endTimePicker }
});
#endregion
};
probePicker.SelectedIndex = 0;
Button okButton = new Button
{
Text = "OK",
FontSize = 20,
VerticalOptions = LayoutOptions.Start
};
okButton.Clicked += async (o, e) =>
{
try
{
_scriptRunner.Triggers.Add(new Probes.User.Scripts.Trigger(_selectedProbe, _selectedDatumProperty, _selectedCondition, _conditionValue, changeSwitch.IsToggled, fireRepeatedlySwitch.IsToggled, regexSwitch.IsToggled, startTimePicker.Time, endTimePicker.Time));
await Navigation.PopAsync();
}
catch (Exception ex)
{
SensusServiceHelper.Get().FlashNotificationAsync($"Failed to add trigger: {ex.Message}");
SensusServiceHelper.Get().Logger.Log($"Failed to add trigger: {ex.Message}", LoggingLevel.Normal, GetType());
}
};
contentLayout.Children.Add(okButton);
Content = new ScrollView
{
Content = contentLayout
};
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Automation;
using Microsoft.WindowsAzure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.WindowsAzure.Management.Automation
{
/// <summary>
/// Service operation for automation variables. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
internal partial class VariableOperations : IServiceOperations<AutomationManagementClient>, IVariableOperations
{
/// <summary>
/// Initializes a new instance of the VariableOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal VariableOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a variable. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create variable operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the create variable operation.
/// </returns>
public async Task<VariableCreateResponse> CreateAsync(string automationAccount, VariableCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/OaaSCS/resources/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/~/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/variables/";
url = url + Uri.EscapeDataString(parameters.Name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-12-08");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject variableCreateParametersValue = new JObject();
requestDoc = variableCreateParametersValue;
variableCreateParametersValue["name"] = parameters.Name;
JObject propertiesValue = new JObject();
variableCreateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Value != null)
{
propertiesValue["value"] = parameters.Properties.Value;
}
if (parameters.Properties.Description != null)
{
propertiesValue["description"] = parameters.Properties.Description;
}
propertiesValue["isEncrypted"] = parameters.Properties.IsEncrypted;
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VariableCreateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VariableCreateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Variable variableInstance = new Variable();
result.Variable = variableInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
variableInstance.Name = nameInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
VariableProperties propertiesInstance = new VariableProperties();
variableInstance.Properties = propertiesInstance;
JToken valueValue = propertiesValue2["value"];
if (valueValue != null && valueValue.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue);
propertiesInstance.Value = valueInstance;
}
JToken isEncryptedValue = propertiesValue2["isEncrypted"];
if (isEncryptedValue != null && isEncryptedValue.Type != JTokenType.Null)
{
bool isEncryptedInstance = ((bool)isEncryptedValue);
propertiesInstance.IsEncrypted = isEncryptedInstance;
}
JToken descriptionValue = propertiesValue2["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken creationTimeValue = propertiesValue2["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete the variable. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='variableName'>
/// Required. The name of variable.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string automationAccount, string variableName, CancellationToken cancellationToken)
{
// Validate
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (variableName == null)
{
throw new ArgumentNullException("variableName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("variableName", variableName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/OaaSCS/resources/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/~/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/variables/";
url = url + Uri.EscapeDataString(variableName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-12-08");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the variable identified by variable name. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='variableName'>
/// Required. The name of variable.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get variable operation.
/// </returns>
public async Task<VariableGetResponse> GetAsync(string automationAccount, string variableName, CancellationToken cancellationToken)
{
// Validate
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (variableName == null)
{
throw new ArgumentNullException("variableName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("variableName", variableName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/OaaSCS/resources/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/~/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/variables/";
url = url + Uri.EscapeDataString(variableName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-12-08");
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", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VariableGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VariableGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Variable variableInstance = new Variable();
result.Variable = variableInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
variableInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
VariableProperties propertiesInstance = new VariableProperties();
variableInstance.Properties = propertiesInstance;
JToken valueValue = propertiesValue["value"];
if (valueValue != null && valueValue.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue);
propertiesInstance.Value = valueInstance;
}
JToken isEncryptedValue = propertiesValue["isEncrypted"];
if (isEncryptedValue != null && isEncryptedValue.Type != JTokenType.Null)
{
bool isEncryptedInstance = ((bool)isEncryptedValue);
propertiesInstance.IsEncrypted = isEncryptedInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve a list of variables. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list variables operation.
/// </returns>
public async Task<VariableListResponse> ListAsync(string automationAccount, CancellationToken cancellationToken)
{
// Validate
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("automationAccount", automationAccount);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/OaaSCS/resources/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/~/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/variables";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-12-08");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VariableListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VariableListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Variable variableInstance = new Variable();
result.Variables.Add(variableInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
variableInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
VariableProperties propertiesInstance = new VariableProperties();
variableInstance.Properties = propertiesInstance;
JToken valueValue2 = propertiesValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
propertiesInstance.Value = valueInstance;
}
JToken isEncryptedValue = propertiesValue["isEncrypted"];
if (isEncryptedValue != null && isEncryptedValue.Type != JTokenType.Null)
{
bool isEncryptedInstance = ((bool)isEncryptedValue);
propertiesInstance.IsEncrypted = isEncryptedInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve next list of variables. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list variables operation.
/// </returns>
public async Task<VariableListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VariableListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VariableListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Variable variableInstance = new Variable();
result.Variables.Add(variableInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
variableInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
VariableProperties propertiesInstance = new VariableProperties();
variableInstance.Properties = propertiesInstance;
JToken valueValue2 = propertiesValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
propertiesInstance.Value = valueInstance;
}
JToken isEncryptedValue = propertiesValue["isEncrypted"];
if (isEncryptedValue != null && isEncryptedValue.Type != JTokenType.Null)
{
bool isEncryptedInstance = ((bool)isEncryptedValue);
propertiesInstance.IsEncrypted = isEncryptedInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update a variable. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the update variable operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> UpdateAsync(string automationAccount, VariableUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/OaaSCS/resources/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/~/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/variables/";
url = url + Uri.EscapeDataString(parameters.Name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-12-08");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2013-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject variableUpdateParametersValue = new JObject();
requestDoc = variableUpdateParametersValue;
variableUpdateParametersValue["name"] = parameters.Name;
if (parameters.Properties != null)
{
JObject propertiesValue = new JObject();
variableUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Value != null)
{
propertiesValue["value"] = parameters.Properties.Value;
}
if (parameters.Properties.Description != null)
{
propertiesValue["description"] = parameters.Properties.Description;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="AboutBox1.Designer.cs" company="VillageIdiot">
// Copyright (c) Village Idiot. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TQ.SaveFilesExplorer
{
/// <summary>
/// Designer for the About Box.
/// </summary>
public partial class AboutBox
{
/// <summary>
/// Generated TableLayoutPanel
/// </summary>
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel;
/// <summary>
/// Generated PictureBox for logo
/// </summary>
private System.Windows.Forms.PictureBox logoPictureBox;
/// <summary>
/// Generated Label for product name
/// </summary>
private System.Windows.Forms.Label labelProductName;
/// <summary>
/// Generated Label for version
/// </summary>
private System.Windows.Forms.Label labelVersion;
/// <summary>
/// Generated Label for copyright
/// </summary>
private System.Windows.Forms.Label labelCopyright;
/// <summary>
/// Generated Label for company name
/// </summary>
private System.Windows.Forms.Label labelCompanyName;
/// <summary>
/// Generated description text box
/// </summary>
private System.Windows.Forms.TextBox textBoxDescription;
/// <summary>
/// Generated OK button
/// </summary>
private System.Windows.Forms.Button okayButton;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">Indicates whether we are disposing</param>
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutBox));
this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.logoPictureBox = new System.Windows.Forms.PictureBox();
this.labelProductName = new System.Windows.Forms.Label();
this.labelVersion = new System.Windows.Forms.Label();
this.labelCopyright = new System.Windows.Forms.Label();
this.labelCompanyName = new System.Windows.Forms.Label();
this.textBoxDescription = new System.Windows.Forms.TextBox();
this.okayButton = new System.Windows.Forms.Button();
this.tableLayoutPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel
//
this.tableLayoutPanel.ColumnCount = 2;
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33F));
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 67F));
this.tableLayoutPanel.Controls.Add(this.logoPictureBox, 0, 0);
this.tableLayoutPanel.Controls.Add(this.labelProductName, 1, 0);
this.tableLayoutPanel.Controls.Add(this.labelVersion, 1, 1);
this.tableLayoutPanel.Controls.Add(this.labelCopyright, 1, 2);
this.tableLayoutPanel.Controls.Add(this.labelCompanyName, 1, 3);
this.tableLayoutPanel.Controls.Add(this.textBoxDescription, 1, 4);
this.tableLayoutPanel.Controls.Add(this.okayButton, 1, 5);
this.tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel.Location = new System.Drawing.Point(12, 11);
this.tableLayoutPanel.Margin = new System.Windows.Forms.Padding(4);
this.tableLayoutPanel.Name = "tableLayoutPanel";
this.tableLayoutPanel.RowCount = 6;
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.Size = new System.Drawing.Size(556, 326);
this.tableLayoutPanel.TabIndex = 0;
//
// logoPictureBox
//
this.logoPictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.logoPictureBox.Image = ((System.Drawing.Image)(resources.GetObject("logoPictureBox.Image")));
this.logoPictureBox.Location = new System.Drawing.Point(4, 4);
this.logoPictureBox.Margin = new System.Windows.Forms.Padding(4);
this.logoPictureBox.Name = "logoPictureBox";
this.tableLayoutPanel.SetRowSpan(this.logoPictureBox, 6);
this.logoPictureBox.Size = new System.Drawing.Size(175, 318);
this.logoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.logoPictureBox.TabIndex = 12;
this.logoPictureBox.TabStop = false;
//
// labelProductName
//
this.labelProductName.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelProductName.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelProductName.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelProductName.Location = new System.Drawing.Point(191, 0);
this.labelProductName.Margin = new System.Windows.Forms.Padding(8, 0, 4, 0);
this.labelProductName.MaximumSize = new System.Drawing.Size(0, 21);
this.labelProductName.Name = "labelProductName";
this.labelProductName.Size = new System.Drawing.Size(361, 21);
this.labelProductName.TabIndex = 19;
this.labelProductName.Text = "Product Name";
this.labelProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelVersion
//
this.labelVersion.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelVersion.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelVersion.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelVersion.Location = new System.Drawing.Point(191, 32);
this.labelVersion.Margin = new System.Windows.Forms.Padding(8, 0, 4, 0);
this.labelVersion.MaximumSize = new System.Drawing.Size(0, 21);
this.labelVersion.Name = "labelVersion";
this.labelVersion.Size = new System.Drawing.Size(361, 21);
this.labelVersion.TabIndex = 0;
this.labelVersion.Text = "Version";
this.labelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelCopyright
//
this.labelCopyright.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelCopyright.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelCopyright.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelCopyright.Location = new System.Drawing.Point(191, 64);
this.labelCopyright.Margin = new System.Windows.Forms.Padding(8, 0, 4, 0);
this.labelCopyright.MaximumSize = new System.Drawing.Size(0, 21);
this.labelCopyright.Name = "labelCopyright";
this.labelCopyright.Size = new System.Drawing.Size(361, 21);
this.labelCopyright.TabIndex = 21;
this.labelCopyright.Text = "Copyright";
this.labelCopyright.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelCompanyName
//
this.labelCompanyName.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelCompanyName.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelCompanyName.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelCompanyName.Location = new System.Drawing.Point(191, 96);
this.labelCompanyName.Margin = new System.Windows.Forms.Padding(8, 0, 4, 0);
this.labelCompanyName.MaximumSize = new System.Drawing.Size(0, 21);
this.labelCompanyName.Name = "labelCompanyName";
this.labelCompanyName.Size = new System.Drawing.Size(361, 21);
this.labelCompanyName.TabIndex = 22;
this.labelCompanyName.Text = "Company Name";
this.labelCompanyName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// textBoxDescription
//
this.textBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBoxDescription.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textBoxDescription.Location = new System.Drawing.Point(191, 132);
this.textBoxDescription.Margin = new System.Windows.Forms.Padding(8, 4, 4, 4);
this.textBoxDescription.Multiline = true;
this.textBoxDescription.Name = "textBoxDescription";
this.textBoxDescription.ReadOnly = true;
this.textBoxDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxDescription.Size = new System.Drawing.Size(361, 155);
this.textBoxDescription.TabIndex = 23;
this.textBoxDescription.TabStop = false;
//
// okayButton
//
this.okayButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.okayButton.BackColor = System.Drawing.SystemColors.Control;
this.okayButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.okayButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.okayButton.Location = new System.Drawing.Point(452, 295);
this.okayButton.Margin = new System.Windows.Forms.Padding(4);
this.okayButton.Name = "okayButton";
this.okayButton.Size = new System.Drawing.Size(100, 27);
this.okayButton.TabIndex = 24;
this.okayButton.Text = "&OK";
this.okayButton.UseVisualStyleBackColor = true;
//
// AboutBox
//
this.AcceptButton = this.okayButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(580, 348);
this.Controls.Add(this.tableLayoutPanel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Margin = new System.Windows.Forms.Padding(4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AboutBox";
this.Padding = new System.Windows.Forms.Padding(12, 11, 12, 11);
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "AboutBox1";
this.tableLayoutPanel.ResumeLayout(false);
this.tableLayoutPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace Scintilla.Configuration
{
/// <summary>
///
/// </summary>
public enum PropertyType
{
/// <summary>
///
/// </summary>
Property = 0,
/// <summary>
///
/// </summary>
Comment,
/// <summary>
///
/// </summary>
Import,
/// <summary>
///
/// </summary>
If,
/// <summary>
///
/// </summary>
IgnoredLine,
/// <summary>
///
/// </summary>
EmptyLine
}
/// <summary>
///
/// </summary>
/// <param name="file"></param>
/// <param name="propertyType"></param>
/// <param name="key"></param>
/// <param name="val"></param>
/// <returns></returns>
public delegate bool PropertyReadDelegate(FileInfo file, PropertyType propertyType, Queue<string> keyQueue, string key, string val);
public delegate string PropertyGetValueDelegate(string key);
public delegate bool PropertyContainsKeyDelegate(string key);
/// <summary>
/// A class that reads in ths properties from the
/// Justin Greenwood - [email protected]
/// </summary>
public static class PropertiesReader
{
private static Regex regExFindVars = new Regex(@"[\$][\(](?<varname>.*?)[\)]", RegexOptions.Compiled);
private static Regex regExKeyValPairs = new Regex(@"[\s]*(?:(?<key>[^,]*?)[\s]*:[\s]*(?<value>[^,^:]*[,]*?)|(?<single>[^,^:]*[,]*?))[\s]*", RegexOptions.Compiled);
private static PropertyGetValueDelegate getValue;
private static PropertyContainsKeyDelegate containsKey;
private static int replaceCount = 0;
private enum ReadMode
{
Key = 0,
Value,
Import,
If,
FlushWhiteSpace
}
/// <summary>
///
/// </summary>
/// <param name="propsFileInfo"></param>
/// <param name="propertyRead"></param>
public static void Read(FileInfo propsFileInfo, PropertyReadDelegate propertyRead)
{
StreamReader reader = new StreamReader(propsFileInfo.OpenRead());
char c = ' ', prev = '\\';
int lastStart = 0, ignoreCount = 0;
bool ignoreProperties = false;
string key = null, var = null;
StringBuilder currentVar = new StringBuilder();
StringBuilder currentToken = new StringBuilder();
Queue<string> queue = new Queue<string>();
StringBuilder currentTokenPiece = new StringBuilder();
ReadMode mode = ReadMode.Key;
ReadMode nextModeAfterSpaces = ReadMode.Key;
string line = reader.ReadLine();
while (line != null)
{
int start = 0;
bool skipLine = false;
while ((start < line.Length) && char.IsWhiteSpace(line[start])) ++start;
if (start >= line.Length)
{
propertyRead(propsFileInfo, PropertyType.EmptyLine, queue, string.Empty, string.Empty);
}
else if (line[start] == '#')
{
propertyRead(propsFileInfo, PropertyType.Comment, queue, "#", line);
}
else
{
if (ignoreProperties)
{
if ((ignoreCount == 0) || (start == lastStart))
{
ignoreCount++;
lastStart = start;
skipLine = true;
}
else
{
ignoreCount = 0;
ignoreProperties = false;
}
}
if (skipLine)
{
propertyRead(propsFileInfo, PropertyType.EmptyLine, queue, string.Empty, string.Empty);
}
else
{
for (int i = start; i < line.Length; i++)
{
c = line[i];
if (mode == ReadMode.Key)
{
if (c == '=')
{
if (currentTokenPiece.Length > 0)
{
queue.Enqueue(currentTokenPiece.ToString());
}
currentTokenPiece.Remove(0, currentTokenPiece.Length);
key = currentToken.ToString();
currentToken.Remove(0, currentToken.Length);
mode = ReadMode.Value;
continue;
}
else if (char.IsWhiteSpace(c))
{
key = currentToken.ToString();
currentToken.Remove(0, currentToken.Length);
currentTokenPiece.Remove(0, currentTokenPiece.Length);
if (key == "if")
{
nextModeAfterSpaces = ReadMode.If;
}
else if (key == "import")
{
nextModeAfterSpaces = ReadMode.Import;
}
else
{
break;
}
mode = ReadMode.FlushWhiteSpace;
continue;
}
else if (c == '.')
{
currentToken.Append(c);
queue.Enqueue(currentTokenPiece.ToString());
currentTokenPiece.Remove(0, currentTokenPiece.Length);
}
else
{
currentTokenPiece.Append(c);
currentToken.Append(c);
}
}
else if (mode == ReadMode.FlushWhiteSpace)
{
if (!char.IsWhiteSpace(c))
{
currentToken.Append(c);
mode = nextModeAfterSpaces;
}
}
else if (mode == ReadMode.Import)
{
currentToken.Append(c);
}
else if (mode == ReadMode.If)
{
currentToken.Append(c);
}
else if (mode == ReadMode.Value)
{
currentToken.Append(c);
}
prev = c;
}
if (prev != '\\')
{
var = currentToken.ToString();
if (mode == ReadMode.If)
{
ignoreProperties = propertyRead(propsFileInfo, PropertyType.If, queue, key, var);
}
else if (mode == ReadMode.Import)
{
// Open another file inline with this one.
if (propertyRead(propsFileInfo, PropertyType.Import, queue, key, var))
{
FileInfo fileToImport = new FileInfo(string.Format(@"{0}\{1}.properties", propsFileInfo.Directory.FullName, var));
if (fileToImport.Exists)
{
Read(fileToImport, propertyRead);
}
}
}
else if (mode == ReadMode.Value)
{
propertyRead(propsFileInfo, PropertyType.Property, queue, key, var);
}
currentToken.Remove(0, currentToken.Length);
queue.Clear();
key = null;
mode = ReadMode.Key;
}
else
{
currentToken.Remove(currentToken.Length - 1, 1);
}
}
}
line = reader.ReadLine();
}
reader.Close();
if (key != null)
{
var = currentToken.ToString();
propertyRead(propsFileInfo, PropertyType.Property, queue, key, var);
}
}
#region Evaluate String with embedded variables
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Evaluate(string str, PropertyGetValueDelegate getValueDel, PropertyContainsKeyDelegate containsKeyDel)
{
string tmp = str;
if ((getValueDel != null) && (containsKeyDel != null))
{
getValue = getValueDel;
containsKey = containsKeyDel;
do
{
replaceCount = 0;
tmp = regExFindVars.Replace(tmp, new MatchEvaluator(ReplaceVariableMatch));
} while (replaceCount > 0);
}
return tmp;
}
/// <summary>
///
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
private static string ReplaceVariableMatch(Match m)
{
string output = m.Value;
if ((getValue != null) && (containsKey != null))
{
if ((m.Groups["varname"].Length > 0) && (m.Groups["varname"].Captures.Count > 0))
{
Capture capture = m.Groups["varname"].Captures[0];
if (containsKey(capture.Value))
{
output = getValue(capture.Value);
}
else
{
output = string.Empty;
}
replaceCount++;
}
}
return output;
}
#endregion
#region Parse out "key:value," pairs for those properties that use them.
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static Dictionary<string, string> GetKeyValuePairs(string str)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
MatchCollection matches = regExKeyValPairs.Matches(str);
foreach (Match m in matches)
{
if (((m.Groups["key"].Length > 0) && (m.Groups["key"].Captures.Count > 0)) &&
((m.Groups["value"].Length > 0) && (m.Groups["value"].Captures.Count > 0)))
{
string captureKey = m.Groups["key"].Captures[0].Value;
string captureValue = m.Groups["value"].Captures[0].Value;
if (!string.IsNullOrEmpty(captureKey))
{
dictionary[captureKey] = (captureValue != null) ? captureValue : Boolean.TrueString;
}
}
else if ((m.Groups["single"].Length > 0) && (m.Groups["single"].Captures.Count > 0))
{
string captureKey = m.Groups["single"].Captures[0].Value;
if (!string.IsNullOrEmpty(captureKey))
{
dictionary[captureKey] = Boolean.TrueString;
}
}
}
return dictionary;
}
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.SS.UserModel;
using NPOI.OpenXml4Net.OPC;
using System;
using NPOI.SS.Util;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.Util;
namespace NPOI.XSSF.UserModel
{
/**
* XSSF Implementation of a Hyperlink.
* Note - unlike with HSSF, many kinds of hyperlink
* are largely stored as relations of the sheet
*/
public class XSSFHyperlink : IHyperlink
{
private HyperlinkType _type;
private PackageRelationship _externalRel;
private CT_Hyperlink _ctHyperlink; //contains a reference to the cell where the hyperlink is anchored, getRef()
private String _location; //what the hyperlink refers to
/**
* Create a new XSSFHyperlink. This method is protected to be used only by XSSFCreationHelper
*
* @param type - the type of hyperlink to create
*/
public XSSFHyperlink(HyperlinkType type)
{
_type = type;
_ctHyperlink = new CT_Hyperlink();
_externalRel = null;
}
/**
* Create a XSSFHyperlink amd Initialize it from the supplied CTHyperlink bean and namespace relationship
*
* @param ctHyperlink the xml bean Containing xml properties
* @param hyperlinkRel the relationship in the underlying OPC namespace which stores the actual link's Address
*/
public XSSFHyperlink(CT_Hyperlink ctHyperlink, PackageRelationship hyperlinkRel)
{
_ctHyperlink = ctHyperlink;
_externalRel = hyperlinkRel;
// Figure out the Hyperlink type and destination
if (_externalRel == null)
{
// If it has a location, it's internal
if (ctHyperlink.location != null)
{
_type = HyperlinkType.Document;
_location = ctHyperlink.location;
}
else if (ctHyperlink.id != null)
{
throw new InvalidOperationException("The hyperlink for cell "
+ ctHyperlink.@ref + " references relation "
+ ctHyperlink.id + ", but that didn't exist!");
}
else
{
// hyperlink is internal and is not related to other parts
_type = HyperlinkType.Document;
}
}
else
{
Uri target = _externalRel.TargetUri;
_location = target.ToString();
if (ctHyperlink.location != null)
{
// URI fragment
_location += "#" + ctHyperlink.location;
}
// Try to figure out the type
if (_location.StartsWith("http://") || _location.StartsWith("https://")
|| _location.StartsWith("ftp://"))
{
_type = HyperlinkType.Url;
}
else if (_location.StartsWith("mailto:"))
{
_type = HyperlinkType.Email;
}
else
{
_type = HyperlinkType.File;
}
}
}
/**
* Create a new XSSFHyperlink. This method is for Internal use only.
* XSSFHyperlinks can be created by XSSFCreationHelper.
*
* @param type - the type of hyperlink to create, see {@link Hyperlink}
*/
//FIXME: change to protected if/when SXSSFHyperlink class is created
public XSSFHyperlink(IHyperlink other)
{
if (other is XSSFHyperlink)
{
XSSFHyperlink xlink = (XSSFHyperlink)other;
_type = xlink.Type;
_location = xlink._location;
_externalRel = xlink._externalRel;
_ctHyperlink = xlink._ctHyperlink.Copy();
}
else
{
_type = other.Type;
_location = other.Address;
_externalRel = null;
_ctHyperlink = new CT_Hyperlink();
SetCellReference(new CellReference(other.FirstRow, other.FirstColumn));
}
}
/**
* @return the underlying CTHyperlink object
*/
public CT_Hyperlink GetCTHyperlink()
{
return _ctHyperlink;
}
/**
* Do we need to a relation too, to represent
* this hyperlink?
*/
public bool NeedsRelationToo()
{
return (_type != HyperlinkType.Document);
}
/**
* Generates the relation if required
*/
internal void GenerateRelationIfNeeded(PackagePart sheetPart)
{
if (_externalRel == null && NeedsRelationToo())
{
// Generate the relation
PackageRelationship rel =
sheetPart.AddExternalRelationship(_location, XSSFRelation.SHEET_HYPERLINKS.Relation);
// Update the r:id
_ctHyperlink.id = rel.Id;
}
}
/**
* Return the type of this hyperlink
*
* @return the type of this hyperlink
*/
public HyperlinkType Type
{
get
{
return _type;
}
}
[Obsolete("use property CellRef")]
public string GetCellRef()
{
return _ctHyperlink.@ref;
}
/**
* Get the reference of the cell this applies to,
* es A55
*/
public String CellRef
{
get
{
return _ctHyperlink.@ref;
}
}
/**
* Hyperlink Address. Depending on the hyperlink type it can be URL, e-mail, path to a file
*
* @return the Address of this hyperlink
*/
public String Address
{
get
{
return _location;
}
set
{
Validate(value);
_location = value;
//we must Set location for internal hyperlinks
if (_type == HyperlinkType.Document)
{
this.Location = value;
}
}
}
private void Validate(String address)
{
switch (_type)
{
// email, path to file and url must be valid URIs
case HyperlinkType.Email:
case HyperlinkType.File:
case HyperlinkType.Url:
if(!Uri.TryCreate(address,UriKind.RelativeOrAbsolute,out Uri uri))
throw new ArgumentException("Address of hyperlink must be a valid URI:" + address);
break;
case HyperlinkType.Document:
// currently not evaluating anything.
break;
default:
// this check wouldn't need to be done if _type was checked when object was set
// since _type is final, this check would only need to be done once
throw new InvalidOperationException("Invalid Hyperlink type: " + _type);
}
}
/**
* Return text label for this hyperlink
*
* @return text to display
*/
public String Label
{
get
{
return _ctHyperlink.display;
}
set
{
_ctHyperlink.display = value;
}
}
/**
* Location within target. If target is a workbook (or this workbook) this shall refer to a
* sheet and cell or a defined name. Can also be an HTML anchor if target is HTML file.
*
* @return location
*/
public String Location
{
get
{
return _ctHyperlink.location;
}
set
{
_ctHyperlink.location = value;
}
}
/**
* Assigns this hyperlink to the given cell reference
*/
public void SetCellReference(String ref1)
{
_ctHyperlink.@ref = ref1;
}
protected void SetCellReference(CellReference ref1)
{
SetCellReference(ref1.FormatAsString());
}
private CellReference buildCellReference()
{
String ref1 = _ctHyperlink.@ref;
if (ref1 == null)
{
ref1 = "A1";
}
return new CellReference(ref1);
}
/**
* 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 buildCellReference().Col;
}
set
{
SetCellReference(new CellReference(FirstRow, value));
}
}
/**
* Return the column of the last cell that Contains the hyperlink
* For XSSF, a Hyperlink may only reference one cell
*
* @return the 0-based column of the last cell that Contains the hyperlink
*/
public int LastColumn
{
get
{
return buildCellReference().Col;
}
set
{
this.FirstColumn = value;
}
}
/**
* Return the row of the first cell that Contains the hyperlink
*
* @return the 0-based row of the cell that Contains the hyperlink
*/
public int FirstRow
{
get
{
return buildCellReference().Row;
}
set
{
SetCellReference(new CellReference(value, FirstColumn));
}
}
/**
* Return the row of the last cell that Contains the hyperlink
* For XSSF, a Hyperlink may only reference one cell
*
* @return the 0-based row of the last cell that Contains the hyperlink
*/
public int LastRow
{
get
{
return buildCellReference().Row;
}
set
{
this.FirstRow = value;
}
}
public string TextMark
{
get
{ throw new NotImplementedException(); }
set
{ throw new NotImplementedException(); }
}
/// <summary>
/// get or set additional text to help the user understand more about the hyperlink
/// </summary>
public String Tooltip
{
get
{
return _ctHyperlink.tooltip;
}
set
{
_ctHyperlink.tooltip = (value);
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 the Outercurve Foundation 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using WebsitePanel.Providers.OS;
using WebsitePanel.Providers.Utils;
using WebsitePanel.Server.Utils;
namespace WebsitePanel.Providers.SharePoint
{
public class Sps20 : HostingServiceProviderBase, ISharePointServer
{
#region Classes
class ProcessExecutionResults
{
public int ExitCode;
public string Output;
}
#endregion
#region Constants
private const string SHAREPOINT_REGLOC = @"SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\6.0";
#endregion
#region Properties
protected string UsersOU
{
get { return ProviderSettings["ADUsersOU"]; }
}
protected string GroupsOU
{
get { return ProviderSettings["ADGroupsOU"]; }
}
protected bool ExclusiveNTLM
{
get { return ProviderSettings.GetBool("ExclusiveNTLM"); }
}
#endregion
#region Sites
public virtual void ExtendVirtualServer(SharePointSite site)
{
// install SharePoint
string cmdPath = GetAdminToolPath();
string cmdArgs = String.Format(@"-o extendvs -url http://{0} -ownerlogin {1}\{2} -owneremail {3} -databaseserver {4} -databasename {5} -databaseuser {6} -databasepassword {7}",
site.Name, Environment.MachineName, site.OwnerLogin, site.OwnerEmail,
site.DatabaseServer, site.DatabaseName, site.DatabaseUser, site.DatabasePassword);
ProcessExecutionResults result = ExecuteSystemCommand(cmdPath, cmdArgs);
if (result.ExitCode < 0)
throw new Exception("Error while installing SharePoint: " + result.Output);
}
public virtual void UnextendVirtualServer(string url, bool deleteContent)
{
// uninstall SharePoint
string cmdPath = GetAdminToolPath();
string cmdArgs = String.Format(@"-o unextendvs -url http://{0}{1}", url,
(deleteContent ? " -deletecontent" : ""));
ProcessExecutionResults result = ExecuteSystemCommand(cmdPath, cmdArgs);
if (result.ExitCode < 0)
throw new Exception("Error while uninstalling SharePoint: " + result.Output);
}
#endregion
#region Backup/Restore
public virtual string BackupVirtualServer(string url, string fileName, bool zipBackup)
{
string tempPath = Path.GetTempPath();
string bakFile = Path.Combine(tempPath, (zipBackup
? StringUtils.CleanIdentifier(url) + ".bsh"
: StringUtils.CleanIdentifier(fileName)));
// backup portal
string cmdPath = GetAdminToolPath();
string cmdArgs = String.Format(@"-o backup -url http://{0} -filename {1} -overwrite",
url, bakFile);
ProcessExecutionResults result = ExecuteSystemCommand(cmdPath, cmdArgs);
if (result.ExitCode < 0)
throw new Exception("Error while backing up SharePoint site: " + result.Output);
// zip backup file
if (zipBackup)
{
string zipFile = Path.Combine(tempPath, fileName);
string zipRoot = Path.GetDirectoryName(bakFile);
// zip files
FileUtils.ZipFiles(zipFile, zipRoot, new string[] { Path.GetFileName(bakFile) });
// delete data files
FileUtils.DeleteFile(bakFile);
bakFile = zipFile;
}
return bakFile;
}
public virtual void RestoreVirtualServer(string url, string fileName)
{
string tempPath = Path.GetTempPath();
// unzip uploaded files if required
string expandedFile = fileName;
if (Path.GetExtension(fileName).ToLower() == ".zip")
{
// unpack file
expandedFile = FileUtils.UnzipFiles(fileName, tempPath)[0];
// delete zip archive
FileUtils.DeleteFile(fileName);
}
// restore portal
string cmdPath = GetAdminToolPath();
string cmdArgs = String.Format(@"-o restore -url http://{0} -filename {1} -overwrite",
url, expandedFile);
ProcessExecutionResults result = ExecuteSystemCommand(cmdPath, cmdArgs);
if (result.ExitCode < 0)
throw new Exception("Error while restoring SharePoint site: " + result.Output);
// delete expanded file
FileUtils.DeleteFile(expandedFile);
}
public virtual byte[] GetTempFileBinaryChunk(string path, int offset, int length)
{
byte[] buffer = FileUtils.GetFileBinaryChunk(path, offset, length);
// delete temp file
if (buffer.Length < length)
FileUtils.DeleteFile(path);
return buffer;
}
public virtual string AppendTempFileBinaryChunk(string fileName, string path, byte[] chunk)
{
if (path == null)
{
path = Path.Combine(Path.GetTempPath(), fileName);
if (FileUtils.FileExists(path))
FileUtils.DeleteFile(path);
}
FileUtils.AppendFileBinaryContent(path, chunk);
return path;
}
#endregion
#region Web Parts
public virtual string[] GetInstalledWebParts(string url)
{
string cmdPath = GetAdminToolPath();
string cmdArgs = String.Format(@"-o enumwppacks -url http://{0}", url);
ProcessExecutionResults result = ExecuteSystemCommand(cmdPath, cmdArgs);
List<string> list = new List<string>();
string line = null;
StringReader reader = new StringReader(result.Output);
while ((line = reader.ReadLine()) != null)
{
line = line.Trim();
int commaIdx = line.IndexOf(",");
if (!String.IsNullOrEmpty(line) && commaIdx != -1)
list.Add(line.Substring(0, commaIdx));
}
return list.ToArray();
}
public virtual void InstallWebPartsPackage(string url, string fileName)
{
string tempPath = Path.GetTempPath();
// unzip uploaded files if required
string expandedFile = fileName;
if (Path.GetExtension(fileName).ToLower() == ".zip")
{
// unpack file
expandedFile = FileUtils.UnzipFiles(fileName, tempPath)[0];
// delete zip archive
FileUtils.DeleteFile(fileName);
}
// install webparts
string cmdPath = GetAdminToolPath();
string cmdArgs = String.Format(@"-o addwppack -url http://{0} -filename {1} -force",
url, expandedFile);
ProcessExecutionResults result = ExecuteSystemCommand(cmdPath, cmdArgs);
if (result.ExitCode < 0)
throw new Exception("Error while installing WebParts package: " + result.Output);
// delete expanded file
FileUtils.DeleteFile(expandedFile);
}
public virtual void DeleteWebPartsPackage(string url, string packageName)
{
// uninstall webparts
string cmdPath = GetAdminToolPath();
string cmdArgs = String.Format(@"-o deletewppack -url http://{0} -name {1}",
url, packageName);
ProcessExecutionResults result = ExecuteSystemCommand(cmdPath, cmdArgs);
if (result.ExitCode < 0)
throw new Exception("Error while installing WebParts package: " + result.Output);
}
#endregion
#region Users and Groups
public virtual bool UserExists(string username)
{
return SecurityUtils.UserExists(username, ServerSettings, UsersOU);
}
public virtual string[] GetUsers()
{
return SecurityUtils.GetUsers(ServerSettings, UsersOU);
}
public virtual SystemUser GetUser(string username)
{
return SecurityUtils.GetUser(username, ServerSettings, UsersOU);
}
public virtual void CreateUser(SystemUser user)
{
SecurityUtils.CreateUser(user, ServerSettings, UsersOU, GroupsOU);
}
public virtual void UpdateUser(SystemUser user)
{
SecurityUtils.UpdateUser(user, ServerSettings, UsersOU, GroupsOU);
}
public virtual void ChangeUserPassword(string username, string password)
{
SecurityUtils.ChangeUserPassword(username, password, ServerSettings, UsersOU);
}
public virtual void DeleteUser(string username)
{
SecurityUtils.DeleteUser(username, ServerSettings, UsersOU);
}
public virtual bool GroupExists(string groupName)
{
return SecurityUtils.GroupExists(groupName, ServerSettings, GroupsOU);
}
public virtual string[] GetGroups()
{
return SecurityUtils.GetGroups(ServerSettings, GroupsOU);
}
public virtual SystemGroup GetGroup(string groupName)
{
return SecurityUtils.GetGroup(groupName, ServerSettings, GroupsOU);
}
public virtual void CreateGroup(SystemGroup group)
{
SecurityUtils.CreateGroup(group, ServerSettings, UsersOU, GroupsOU);
}
public virtual void UpdateGroup(SystemGroup group)
{
SecurityUtils.UpdateGroup(group, ServerSettings, UsersOU, GroupsOU);
}
public virtual void DeleteGroup(string groupName)
{
SecurityUtils.DeleteGroup(groupName, ServerSettings, GroupsOU);
}
#endregion
#region HostingServiceProvider
public override string[] Install()
{
List<string> messages = new List<string>();
try
{
SecurityUtils.EnsureOrganizationalUnitsExist(ServerSettings, UsersOU, GroupsOU);
}
catch (Exception ex)
{
messages.Add(String.Format("Could not check/create Organizational Units: {0}", ex.Message));
return messages.ToArray();
}
// check if SharePoint is installed
if (!IsSharePointInstalled())
{
messages.Add("Most probably Windows SharePoint Services is not installed on this server.");
return messages.ToArray();
}
return messages.ToArray();
}
public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled)
{
foreach (ServiceProviderItem item in items)
{
try
{
if (item is SystemUser)
{
// enable/disable user account
if (UserExists(item.Name))
{
SystemUser user = GetUser(item.Name);
user.AccountDisabled = !enabled;
UpdateUser(user);
}
}
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error switching '{0}' {1}", item.Name, item.GetType().Name), ex);
}
}
}
public override void DeleteServiceItems(ServiceProviderItem[] items)
{
foreach (ServiceProviderItem item in items)
{
if (item is SharePointSite)
{
// delete SP site
try
{
UnextendVirtualServer(item.Name, true);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
}
}
else if (item is SystemUser)
{
// delete user
try
{
DeleteUser(item.Name);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
}
}
else if (item is SystemGroup)
{
// delete user
try
{
DeleteGroup(item.Name);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
}
}
}
}
#endregion
#region Private Helpers
protected virtual string GetAdminToolPath()
{
RegistryKey spKey = Registry.LocalMachine.OpenSubKey(SHAREPOINT_REGLOC);
if (spKey == null)
throw new Exception("SharePoint Services is not installed on the system");
return ((string)spKey.GetValue("Location")) + @"\bin\stsadm.exe";
}
protected virtual bool IsSharePointInstalled()
{
RegistryKey spKey = Registry.LocalMachine.OpenSubKey(SHAREPOINT_REGLOC);
if (spKey == null)
return false;
string spVal = (string)spKey.GetValue("SharePoint");
return (String.Compare(spVal, "installed", true) == 0);
}
private ProcessExecutionResults ExecuteSystemCommand(string cmd, string args)
{
ProcessExecutionResults result = new ProcessExecutionResults();
// launch system process
ProcessStartInfo startInfo = new ProcessStartInfo(cmd, args);
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
Process proc = Process.Start(startInfo);
// analyze results
StreamReader reader = proc.StandardOutput;
result.Output = reader.ReadToEnd();
result.ExitCode = proc.ExitCode;
reader.Close();
return result;
}
#endregion
public override bool IsInstalled()
{
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata;
namespace System.Reflection.PortableExecutable
{
/// <summary>
/// Managed .text PE section.
/// </summary>
/// <remarks>
/// Contains in the following order:
/// - Import Address Table
/// - COR Header
/// - IL
/// - Metadata
/// - Managed Resource Data
/// - Strong Name Signature
/// - Debug Data (directory and extra info)
/// - Import Table
/// - Name Table
/// - Runtime Startup Stub
/// - Mapped Field Data
/// </remarks>
internal sealed class ManagedTextSection
{
public Characteristics ImageCharacteristics { get; }
public Machine Machine { get; }
/// <summary>
/// The size of IL stream (unaligned).
/// </summary>
public int ILStreamSize { get; }
/// <summary>
/// Total size of metadata (header and all streams).
/// </summary>
public int MetadataSize { get; }
/// <summary>
/// The size of managed resource data stream.
/// Aligned to <see cref="ManagedResourcesDataAlignment"/>.
/// </summary>
public int ResourceDataSize { get; }
/// <summary>
/// Size of strong name hash.
/// </summary>
public int StrongNameSignatureSize { get; }
/// <summary>
/// Size of Debug data.
/// </summary>
public int DebugDataSize { get; }
/// <summary>
/// The size of mapped field data stream.
/// Aligned to <see cref="MappedFieldDataAlignment"/>.
/// </summary>
public int MappedFieldDataSize { get; }
public ManagedTextSection(
Characteristics imageCharacteristics,
Machine machine,
int ilStreamSize,
int metadataSize,
int resourceDataSize,
int strongNameSignatureSize,
int debugDataSize,
int mappedFieldDataSize)
{
MetadataSize = metadataSize;
ResourceDataSize = resourceDataSize;
ILStreamSize = ilStreamSize;
MappedFieldDataSize = mappedFieldDataSize;
StrongNameSignatureSize = strongNameSignatureSize;
ImageCharacteristics = imageCharacteristics;
Machine = machine;
DebugDataSize = debugDataSize;
}
/// <summary>
/// If set, the module must include a machine code stub that transfers control to the virtual execution system.
/// </summary>
internal bool RequiresStartupStub => Machine == Machine.I386 || Machine == 0;
/// <summary>
/// If set, the module contains instructions that assume a 64 bit instruction set. For example it may depend on an address being 64 bits.
/// This may be true even if the module contains only IL instructions because of PlatformInvoke and COM interop.
/// </summary>
internal bool Requires64bits => Machine == Machine.Amd64 || Machine == Machine.IA64 || Machine == Machine.Arm64;
public bool Is32Bit => !Requires64bits;
public const int ManagedResourcesDataAlignment = 8;
private const string CorEntryPointDll = "mscoree.dll";
private string CorEntryPointName => (ImageCharacteristics & Characteristics.Dll) != 0 ? "_CorDllMain" : "_CorExeMain";
private int SizeOfImportAddressTable => RequiresStartupStub ? (Is32Bit ? 2 * sizeof(uint) : 2 * sizeof(ulong)) : 0;
// (_is32bit ? 66 : 70);
private int SizeOfImportTable =>
sizeof(uint) + // RVA
sizeof(uint) + // 0
sizeof(uint) + // 0
sizeof(uint) + // name RVA
sizeof(uint) + // import address table RVA
20 + // ?
(Is32Bit ? 3 * sizeof(uint) : 2 * sizeof(ulong)) + // import lookup table
sizeof(ushort) + // hint
CorEntryPointName.Length +
1; // NUL
private static int SizeOfNameTable =>
CorEntryPointDll.Length + 1 + sizeof(ushort);
private int SizeOfRuntimeStartupStub => Is32Bit ? 8 : 16;
public const int MappedFieldDataAlignment = 8;
public int CalculateOffsetToMappedFieldDataStream()
{
int result = ComputeOffsetToImportTable();
if (RequiresStartupStub)
{
result += SizeOfImportTable + SizeOfNameTable;
result = BitArithmetic.Align(result, Is32Bit ? 4 : 8); //optional padding to make startup stub's target address align on word or double word boundary
result += SizeOfRuntimeStartupStub;
}
return result;
}
internal int ComputeOffsetToDebugDirectory()
{
Debug.Assert(MetadataSize % 4 == 0);
Debug.Assert(ResourceDataSize % 4 == 0);
return
ComputeOffsetToMetadata() +
MetadataSize +
ResourceDataSize +
StrongNameSignatureSize;
}
private int ComputeOffsetToImportTable()
{
return
ComputeOffsetToDebugDirectory() +
DebugDataSize;
}
private const int CorHeaderSize =
sizeof(int) + // header size
sizeof(short) + // major runtime version
sizeof(short) + // minor runtime version
sizeof(long) + // metadata directory
sizeof(int) + // COR flags
sizeof(int) + // entry point
sizeof(long) + // resources directory
sizeof(long) + // strong name signature directory
sizeof(long) + // code manager table directory
sizeof(long) + // vtable fixups directory
sizeof(long) + // export address table jumps directory
sizeof(long); // managed-native header directory
public int OffsetToILStream => SizeOfImportAddressTable + CorHeaderSize;
private int ComputeOffsetToMetadata()
{
return OffsetToILStream + BitArithmetic.Align(ILStreamSize, 4);
}
public int ComputeSizeOfTextSection()
{
Debug.Assert(MappedFieldDataSize % MappedFieldDataAlignment == 0);
return CalculateOffsetToMappedFieldDataStream() + MappedFieldDataSize;
}
public int GetEntryPointAddress(int rva)
{
// TODO: constants
return RequiresStartupStub ?
rva + CalculateOffsetToMappedFieldDataStream() - (Is32Bit ? 6 : 10) :
0;
}
public DirectoryEntry GetImportAddressTableDirectoryEntry(int rva)
{
return RequiresStartupStub ?
new DirectoryEntry(rva, SizeOfImportAddressTable) :
default(DirectoryEntry);
}
public DirectoryEntry GetImportTableDirectoryEntry(int rva)
{
// TODO: constants
return RequiresStartupStub ?
new DirectoryEntry(rva + ComputeOffsetToImportTable(), (Is32Bit ? 66 : 70) + 13) :
default(DirectoryEntry);
}
public DirectoryEntry GetCorHeaderDirectoryEntry(int rva)
{
return new DirectoryEntry(rva + SizeOfImportAddressTable, CorHeaderSize);
}
#region Serialization
/// <summary>
/// Serializes .text section data into a specified <paramref name="builder"/>.
/// </summary>
/// <param name="builder">An empty builder to serialize section data to.</param>
/// <param name="relativeVirtualAddess">Relative virtual address of the section within the containing PE file.</param>
/// <param name="entryPointTokenOrRelativeVirtualAddress">Entry point token or RVA (<see cref="CorHeader.EntryPointTokenOrRelativeVirtualAddress"/>)</param>
/// <param name="corFlags">COR Flags (<see cref="CorHeader.Flags"/>).</param>
/// <param name="baseAddress">Base address of the PE image.</param>
/// <param name="metadataBuilder"><see cref="BlobBuilder"/> containing metadata. Must be populated with data. Linked into the <paramref name="builder"/> and can't be expanded afterwards.</param>
/// <param name="ilBuilder"><see cref="BlobBuilder"/> containing IL stream. Must be populated with data. Linked into the <paramref name="builder"/> and can't be expanded afterwards.</param>
/// <param name="mappedFieldDataBuilderOpt"><see cref="BlobBuilder"/> containing mapped field data. Must be populated with data. Linked into the <paramref name="builder"/> and can't be expanded afterwards.</param>
/// <param name="resourceBuilderOpt"><see cref="BlobBuilder"/> containing managed resource data. Must be populated with data. Linked into the <paramref name="builder"/> and can't be expanded afterwards.</param>
/// <param name="debugDataBuilderOpt"><see cref="BlobBuilder"/> containing PE debug table and data. Must be populated with data. Linked into the <paramref name="builder"/> and can't be expanded afterwards.</param>
/// <param name="strongNameSignature">Blob reserved in the <paramref name="builder"/> for strong name signature.</param>
public void Serialize(
BlobBuilder builder,
int relativeVirtualAddess,
int entryPointTokenOrRelativeVirtualAddress,
CorFlags corFlags,
ulong baseAddress,
BlobBuilder metadataBuilder,
BlobBuilder ilBuilder,
BlobBuilder mappedFieldDataBuilderOpt,
BlobBuilder resourceBuilderOpt,
BlobBuilder debugDataBuilderOpt,
out Blob strongNameSignature)
{
Debug.Assert(builder.Count == 0);
Debug.Assert(metadataBuilder.Count == MetadataSize);
Debug.Assert(metadataBuilder.Count % 4 == 0);
Debug.Assert(ilBuilder.Count == ILStreamSize);
Debug.Assert((mappedFieldDataBuilderOpt?.Count ?? 0) == MappedFieldDataSize);
Debug.Assert((resourceBuilderOpt?.Count ?? 0) == ResourceDataSize);
Debug.Assert((resourceBuilderOpt?.Count ?? 0) % 4 == 0);
// TODO: avoid recalculation
int importTableRva = GetImportTableDirectoryEntry(relativeVirtualAddess).RelativeVirtualAddress;
int importAddressTableRva = GetImportAddressTableDirectoryEntry(relativeVirtualAddess).RelativeVirtualAddress;
if (RequiresStartupStub)
{
WriteImportAddressTable(builder, importTableRva);
}
WriteCorHeader(builder, relativeVirtualAddess, entryPointTokenOrRelativeVirtualAddress, corFlags);
// IL:
ilBuilder.Align(4);
builder.LinkSuffix(ilBuilder);
// metadata:
builder.LinkSuffix(metadataBuilder);
// managed resources:
if (resourceBuilderOpt != null)
{
builder.LinkSuffix(resourceBuilderOpt);
}
// strong name signature:
strongNameSignature = builder.ReserveBytes(StrongNameSignatureSize);
// The bytes are required to be 0 for the purpose of calculating hash of the PE content
// when strong name signing.
new BlobWriter(strongNameSignature).WriteBytes(0, StrongNameSignatureSize);
// debug directory and data:
if (debugDataBuilderOpt != null)
{
builder.LinkSuffix(debugDataBuilderOpt);
}
if (RequiresStartupStub)
{
WriteImportTable(builder, importTableRva, importAddressTableRva);
WriteNameTable(builder);
WriteRuntimeStartupStub(builder, importAddressTableRva, baseAddress);
}
// mapped field data:
if (mappedFieldDataBuilderOpt != null)
{
builder.LinkSuffix(mappedFieldDataBuilderOpt);
}
Debug.Assert(builder.Count == ComputeSizeOfTextSection());
}
private void WriteImportAddressTable(BlobBuilder builder, int importTableRva)
{
int start = builder.Count;
int ilRva = importTableRva + 40;
int hintRva = ilRva + (Is32Bit ? 12 : 16);
// Import Address Table
if (Is32Bit)
{
builder.WriteUInt32((uint)hintRva); // 4
builder.WriteUInt32(0); // 8
}
else
{
builder.WriteUInt64((uint)hintRva); // 8
builder.WriteUInt64(0); // 16
}
Debug.Assert(builder.Count - start == SizeOfImportAddressTable);
}
private void WriteImportTable(BlobBuilder builder, int importTableRva, int importAddressTableRva)
{
int start = builder.Count;
int ilRVA = importTableRva + 40;
int hintRva = ilRVA + (Is32Bit ? 12 : 16);
int nameRva = hintRva + 12 + 2;
// Import table
builder.WriteUInt32((uint)ilRVA); // 4
builder.WriteUInt32(0); // 8
builder.WriteUInt32(0); // 12
builder.WriteUInt32((uint)nameRva); // 16
builder.WriteUInt32((uint)importAddressTableRva); // 20
builder.WriteBytes(0, 20); // 40
// Import Lookup table
if (Is32Bit)
{
builder.WriteUInt32((uint)hintRva); // 44
builder.WriteUInt32(0); // 48
builder.WriteUInt32(0); // 52
}
else
{
builder.WriteUInt64((uint)hintRva); // 48
builder.WriteUInt64(0); // 56
}
// Hint table
builder.WriteUInt16(0); // Hint 54|58
foreach (char ch in CorEntryPointName)
{
builder.WriteByte((byte)ch); // 65|69
}
builder.WriteByte(0); // 66|70
Debug.Assert(builder.Count - start == SizeOfImportTable);
}
private static void WriteNameTable(BlobBuilder builder)
{
int start = builder.Count;
foreach (char ch in CorEntryPointDll)
{
builder.WriteByte((byte)ch);
}
builder.WriteByte(0);
builder.WriteUInt16(0);
Debug.Assert(builder.Count - start == SizeOfNameTable);
}
private void WriteCorHeader(BlobBuilder builder, int textSectionRva, int entryPointTokenOrRva, CorFlags corFlags)
{
const ushort majorRuntimeVersion = 2;
const ushort minorRuntimeVersion = 5;
int metadataRva = textSectionRva + ComputeOffsetToMetadata();
int resourcesRva = metadataRva + MetadataSize;
int signatureRva = resourcesRva + ResourceDataSize;
int start = builder.Count;
// Size:
builder.WriteUInt32(CorHeaderSize);
// Version:
builder.WriteUInt16(majorRuntimeVersion);
builder.WriteUInt16(minorRuntimeVersion);
// MetadataDirectory:
builder.WriteUInt32((uint)metadataRva);
builder.WriteUInt32((uint)MetadataSize);
// COR Flags:
builder.WriteUInt32((uint)corFlags);
// EntryPoint:
builder.WriteUInt32((uint)entryPointTokenOrRva);
// ResourcesDirectory:
builder.WriteUInt32((uint)(ResourceDataSize == 0 ? 0 : resourcesRva)); // 28
builder.WriteUInt32((uint)ResourceDataSize);
// StrongNameSignatureDirectory:
builder.WriteUInt32((uint)(StrongNameSignatureSize == 0 ? 0 : signatureRva)); // 36
builder.WriteUInt32((uint)StrongNameSignatureSize);
// CodeManagerTableDirectory (not supported):
builder.WriteUInt32(0);
builder.WriteUInt32(0);
// VtableFixupsDirectory (not supported):
builder.WriteUInt32(0);
builder.WriteUInt32(0);
// ExportAddressTableJumpsDirectory (not supported):
builder.WriteUInt32(0);
builder.WriteUInt32(0);
// ManagedNativeHeaderDirectory (not supported):
builder.WriteUInt32(0);
builder.WriteUInt32(0);
Debug.Assert(builder.Count - start == CorHeaderSize);
Debug.Assert(builder.Count % 4 == 0);
}
private void WriteRuntimeStartupStub(BlobBuilder sectionBuilder, int importAddressTableRva, ulong baseAddress)
{
// entry point code, consisting of a jump indirect to _CorXXXMain
if (Is32Bit)
{
// Write zeros (nops) to pad the entry point code so that the target address is aligned on a 4 byte boundary.
// Note that the section is aligned to FileAlignment, which is at least 512, so we can align relatively to the start of the section.
sectionBuilder.Align(4);
sectionBuilder.WriteUInt16(0);
sectionBuilder.WriteByte(0xff);
sectionBuilder.WriteByte(0x25); //4
sectionBuilder.WriteUInt32((uint)importAddressTableRva + (uint)baseAddress); //8
}
else
{
// Write zeros (nops) to pad the entry point code so that the target address is aligned on a 8 byte boundary.
// Note that the section is aligned to FileAlignment, which is at least 512, so we can align relatively to the start of the section.
sectionBuilder.Align(8);
sectionBuilder.WriteUInt32(0);
sectionBuilder.WriteUInt16(0);
sectionBuilder.WriteByte(0xff);
sectionBuilder.WriteByte(0x25); //8
sectionBuilder.WriteUInt64((ulong)importAddressTableRva + baseAddress); //16
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using TestExtensions;
using TestGrainInterfaces;
using UnitTests.GrainInterfaces;
using Xunit;
namespace UnitTests.General
{
/// <summary>
/// Unit tests for grains implementing generic interfaces
/// </summary>
public class GenericGrainTests : HostedTestClusterEnsureDefaultStarted
{
private static int grainId = 0;
public TGrainInterface GetGrain<TGrainInterface>(long i) where TGrainInterface : IGrainWithIntegerKey
{
return GrainFactory.GetGrain<TGrainInterface>(i);
}
public TGrainInterface GetGrain<TGrainInterface>() where TGrainInterface : IGrainWithIntegerKey
{
return GrainFactory.GetGrain<TGrainInterface>(GetRandomGrainId());
}
/// Can instantiate multiple concrete grain types that implement
/// different specializations of the same generic interface
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithGenericInterfaceGetGrain()
{
var grainOfIntFloat1 = GetGrain<IGenericGrain<int, float>>();
var grainOfIntFloat2 = GetGrain<IGenericGrain<int, float>>();
var grainOfFloatString = GetGrain<IGenericGrain<float, string>>();
await grainOfIntFloat1.SetT(123);
await grainOfIntFloat2.SetT(456);
await grainOfFloatString.SetT(789.0f);
var floatResult1 = await grainOfIntFloat1.MapT2U();
var floatResult2 = await grainOfIntFloat2.MapT2U();
var stringResult = await grainOfFloatString.MapT2U();
Assert.Equal(123f, floatResult1);
Assert.Equal(456f, floatResult2);
Assert.Equal("789", stringResult);
}
/// Multiple GetGrain requests with the same id return the same concrete grain
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithGenericInterfaceMultiplicity()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<IGenericGrain<int, float>>(grainId);
await grainRef1.SetT(123);
var grainRef2 = GetGrain<IGenericGrain<int, float>>(grainId);
var floatResult = await grainRef2.MapT2U();
Assert.Equal(123f, floatResult);
}
/// Can instantiate generic grain specializations
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_SimpleGenericGrainGetGrain()
{
var grainOfFloat1 = GetGrain<ISimpleGenericGrain<float>>();
var grainOfFloat2 = GetGrain<ISimpleGenericGrain<float>>();
var grainOfString = GetGrain<ISimpleGenericGrain<string>>();
await grainOfFloat1.Set(1.2f);
await grainOfFloat2.Set(3.4f);
await grainOfString.Set("5.6");
// generic grain implementation does not change the set value:
await grainOfFloat1.Transform();
await grainOfFloat2.Transform();
await grainOfString.Transform();
var floatResult1 = await grainOfFloat1.Get();
var floatResult2 = await grainOfFloat2.Get();
var stringResult = await grainOfString.Get();
Assert.Equal(1.2f, floatResult1);
Assert.Equal(3.4f, floatResult2);
Assert.Equal("5.6", stringResult);
}
/// Can instantiate grains that implement generic interfaces with generic type parameters
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_GenericInterfaceWithGenericParametersGetGrain()
{
var grain = GetGrain<ISimpleGenericGrain<List<float>>>();
var list = new List<float>();
list.Add(0.1f);
await grain.Set(list);
var result = await grain.Get();
Assert.Equal(1, result.Count);
Assert.Equal(0.1f, result[0]);
}
/// Multiple GetGrain requests with the same id return the same generic grain specialization
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_SimpleGenericGrainMultiplicity()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<float>>(grainId);
await grainRef1.Set(1.2f);
await grainRef1.Transform(); // NOP for generic grain class
var grainRef2 = GetGrain<ISimpleGenericGrain<float>>(grainId);
var floatResult = await grainRef2.Get();
Assert.Equal(1.2f, floatResult);
}
/// If both a concrete implementation and a generic implementation of a
/// generic interface exist, prefer the concrete implementation.
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_PreferConcreteGrainImplementationOfGenericInterface()
{
var grainOfDouble1 = GetGrain<ISimpleGenericGrain<double>>();
var grainOfDouble2 = GetGrain<ISimpleGenericGrain<double>>();
await grainOfDouble1.Set(1.0);
await grainOfDouble2.Set(2.0);
// concrete implementation (SpecializedSimpleGenericGrain) doubles the set value:
await grainOfDouble1.Transform();
await grainOfDouble2.Transform();
var result1 = await grainOfDouble1.Get();
var result2 = await grainOfDouble2.Get();
Assert.Equal(2.0, result1);
Assert.Equal(4.0, result2);
}
/// Multiple GetGrain requests with the same id return the same concrete grain implementation
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_PreferConcreteGrainImplementationOfGenericInterfaceMultiplicity()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<double>>(grainId);
await grainRef1.Set(1.0);
await grainRef1.Transform(); // SpecializedSimpleGenericGrain doubles the value for generic grain class
// a second reference with the same id points to the same grain:
var grainRef2 = GetGrain<ISimpleGenericGrain<double>>(grainId);
await grainRef2.Transform();
var floatResult = await grainRef2.Get();
Assert.Equal(4.0f, floatResult);
}
/// Can instantiate concrete grains that implement multiple generic interfaces
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesGetGrain()
{
var grain1 = GetGrain<ISimpleGenericGrain<int>>();
var grain2 = GetGrain<ISimpleGenericGrain<int>>();
await grain1.Set(1);
await grain2.Set(2);
// ConcreteGrainWith2GenericInterfaces multiplies the set value by 10:
await grain1.Transform();
await grain2.Transform();
var result1 = await grain1.Get();
var result2 = await grain2.Get();
Assert.Equal(10, result1);
Assert.Equal(20, result2);
}
/// Multiple GetGrain requests with the same id and interface return the same concrete grain implementation
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesMultiplicity1()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<int>>(grainId);
await grainRef1.Set(1);
// ConcreteGrainWith2GenericInterfaces multiplies the set value by 10:
await grainRef1.Transform();
//A second reference to the interface will point to the same grain
var grainRef2 = GetGrain<ISimpleGenericGrain<int>>(grainId);
await grainRef2.Transform();
var floatResult = await grainRef2.Get();
Assert.Equal(100, floatResult);
}
/// Multiple GetGrain requests with the same id and different interfaces return the same concrete grain implementation
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesMultiplicity2()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<int>>(grainId);
await grainRef1.Set(1);
await grainRef1.Transform(); // ConcreteGrainWith2GenericInterfaces multiplies the set value by 10:
// A second reference to a different interface implemented by ConcreteGrainWith2GenericInterfaces
// will reference the same grain:
var grainRef2 = GetGrain<IGenericGrain<int, string>>(grainId);
// ConcreteGrainWith2GenericInterfaces returns a string representation of the current value multiplied by 10:
var floatResult = await grainRef2.MapT2U();
Assert.Equal("100", floatResult);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_UseGenericFactoryInsideGrain()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<string>>(grainId);
await grainRef1.Set("JustString");
await grainRef1.CompareGrainReferences(grainRef1);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrain_GetGrain()
{
var grain = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
await grain.GetA();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainControlFlow()
{
var a = random.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var grain = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
await grain.SetA(a);
await grain.SetB(b);
Task<string> stringPromise = grain.GetAxB();
Assert.Equal(expected, stringPromise.Result);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public void Generic_SimpleGrainControlFlow_Blocking()
{
var a = random.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var grain = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
// explicitly use .Wait() and .Result to make sure the client does not deadlock in these cases.
grain.SetA(a).Wait();
grain.SetB(b).Wait();
Task<string> stringPromise = grain.GetAxB();
Assert.Equal(expected, stringPromise.Result);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainDataFlow()
{
var a = random.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var grain = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
var setAPromise = grain.SetA(a);
var setBPromise = grain.SetB(b);
var stringPromise = Task.WhenAll(setAPromise, setBPromise).ContinueWith((_) => grain.GetAxB()).Unwrap();
var x = await stringPromise;
Assert.Equal(expected, x);
}
[Fact, TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrain2_GetGrain()
{
var g1 = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
var g2 = GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++);
var g3 = GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++);
await g1.GetA();
await g2.GetA();
await g3.GetA();
}
[Fact, TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainGenericParameterWithMultipleArguments_GetGrain()
{
var g1 = GrainFactory.GetGrain<ISimpleGenericGrain1<Dictionary<int, int>>>(GetRandomGrainId());
await g1.GetA();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainControlFlow2_GetAB()
{
var a = random.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var g1 = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
var g2 = GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++);
var g3 = GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++);
string r1 = await g1.GetAxB(a, b);
string r2 = await g2.GetAxB(a, b);
string r3 = await g3.GetAxB(a, b);
Assert.Equal(expected, r1);
Assert.Equal(expected, r2);
Assert.Equal(expected, r3);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainControlFlow3()
{
ISimpleGenericGrain2<int, float> g = GrainFactory.GetGrain<ISimpleGenericGrain2<int, float>>(grainId++);
await g.SetA(3);
await g.SetB(1.25f);
Assert.Equal("3x1.25", await g.GetAxB());
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_BasicGrainControlFlow()
{
IBasicGenericGrain<int, float> g = GrainFactory.GetGrain<IBasicGenericGrain<int, float>>(0);
await g.SetA(3);
await g.SetB(1.25f);
Assert.Equal("3x1.25", await g.GetAxB());
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GrainWithListFields()
{
string a = random.Next(100).ToString(CultureInfo.InvariantCulture);
string b = random.Next(100).ToString(CultureInfo.InvariantCulture);
var g1 = GrainFactory.GetGrain<IGrainWithListFields>(grainId++);
var p1 = g1.AddItem(a);
var p2 = g1.AddItem(b);
await Task.WhenAll(p1, p2);
var r1 = await g1.GetItems();
Assert.True(
(a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved.
string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1]));
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_GrainWithListFields()
{
int a = random.Next(100);
int b = random.Next(100);
var g1 = GrainFactory.GetGrain<IGenericGrainWithListFields<int>>(grainId++);
var p1 = g1.AddItem(a);
var p2 = g1.AddItem(b);
await Task.WhenAll(p1, p2);
var r1 = await g1.GetItems();
Assert.True(
(a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved.
string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1]));
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_GrainWithNoProperties_ControlFlow()
{
int a = random.Next(100);
int b = random.Next(100);
string expected = a + "x" + b;
var g1 = GrainFactory.GetGrain<IGenericGrainWithNoProperties<int>>(grainId++);
string r1 = await g1.GetAxB(a, b);
Assert.Equal(expected, r1);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GrainWithNoProperties_ControlFlow()
{
int a = random.Next(100);
int b = random.Next(100);
string expected = a + "x" + b;
long grainId = GetRandomGrainId();
var g1 = GrainFactory.GetGrain<IGrainWithNoProperties>(grainId);
string r1 = await g1.GetAxB(a, b);
Assert.Equal(expected, r1);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_ReaderWriterGrain1()
{
int a = random.Next(100);
var g = GrainFactory.GetGrain<IGenericReaderWriterGrain1<int>>(grainId++);
await g.SetValue(a);
var res = await g.GetValue();
Assert.Equal(a, res);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_ReaderWriterGrain2()
{
int a = random.Next(100);
string b = "bbbbb";
var g = GrainFactory.GetGrain<IGenericReaderWriterGrain2<int, string>>(grainId++);
await g.SetValue1(a);
await g.SetValue2(b);
var r1 = await g.GetValue1();
Assert.Equal(a, r1);
var r2 = await g.GetValue2();
Assert.Equal(b, r2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_ReaderWriterGrain3()
{
int a = random.Next(100);
string b = "bbbbb";
double c = 3.145;
var g = GrainFactory.GetGrain<IGenericReaderWriterGrain3<int, string, double>>(grainId++);
await g.SetValue1(a);
await g.SetValue2(b);
await g.SetValue3(c);
var r1 = await g.GetValue1();
Assert.Equal(a, r1);
var r2 = await g.GetValue2();
Assert.Equal(b, r2);
var r3 = await g.GetValue3();
Assert.Equal(c, r3);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Non_Primitive_Type_Argument()
{
IEchoHubGrain<Guid, string> g1 = GrainFactory.GetGrain<IEchoHubGrain<Guid, string>>(1);
IEchoHubGrain<Guid, int> g2 = GrainFactory.GetGrain<IEchoHubGrain<Guid, int>>(1);
IEchoHubGrain<Guid, byte[]> g3 = GrainFactory.GetGrain<IEchoHubGrain<Guid, byte[]>>(1);
Assert.NotEqual((GrainReference)g1, (GrainReference)g2);
Assert.NotEqual((GrainReference)g1, (GrainReference)g3);
Assert.NotEqual((GrainReference)g2, (GrainReference)g3);
await g1.Foo(Guid.Empty, "", 1);
await g2.Foo(Guid.Empty, 0, 2);
await g3.Foo(Guid.Empty, new byte[] { }, 3);
Assert.Equal(1, await g1.GetX());
Assert.Equal(2, await g2.GetX());
Assert.Equal(3m, await g3.GetX());
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_1()
{
const string msg1 = "Hello from EchoGenericChainGrain-1";
IEchoGenericChainGrain<string> g1 = GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g1.Echo(msg1);
Assert.Equal(msg1, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_2()
{
const string msg2 = "Hello from EchoGenericChainGrain-2";
IEchoGenericChainGrain<string> g2 = GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g2.Echo2(msg2);
Assert.Equal(msg2, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_3()
{
const string msg3 = "Hello from EchoGenericChainGrain-3";
IEchoGenericChainGrain<string> g3 = GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g3.Echo3(msg3);
Assert.Equal(msg3, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_4()
{
const string msg4 = "Hello from EchoGenericChainGrain-4";
var g4 = GrainClient.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g4.Echo4(msg4);
Assert.Equal(msg4, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_5()
{
const string msg5 = "Hello from EchoGenericChainGrain-5";
var g5 = GrainClient.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g5.Echo5(msg5);
Assert.Equal(msg5, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_6()
{
const string msg6 = "Hello from EchoGenericChainGrain-6";
var g6 = GrainClient.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g6.Echo6(msg6);
Assert.Equal(msg6, received);
}
[Fact, TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_1Argument_GenericCallOnly()
{
var grain = GrainFactory.GetGrain<IGeneric1Argument<string>>(Guid.NewGuid(), "UnitTests.Grains.Generic1ArgumentGrain");
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.Ping(s1);
Assert.Equal(s1, s2);
}
[Fact, TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_1Argument_NonGenericCallFirst()
{
var id = Guid.NewGuid();
var nonGenericFacet = GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain");
await Xunit.Assert.ThrowsAsync(typeof(OrleansException), async () =>
{
try
{
await nonGenericFacet.Ping();
}
catch (AggregateException exc)
{
throw exc.GetBaseException();
}
});
}
[Fact, TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_1Argument_GenericCallFirst()
{
var id = Guid.NewGuid();
var grain = GrainFactory.GetGrain<IGeneric1Argument<string>>(id, "UnitTests.Grains.Generic1ArgumentGrain");
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.Ping(s1);
Assert.Equal(s1, s2);
var nonGenericFacet = GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain");
await Xunit.Assert.ThrowsAsync(typeof(OrleansException), async () =>
{
try
{
await nonGenericFacet.Ping();
}
catch (AggregateException exc)
{
throw exc.GetBaseException();
}
});
}
[Fact, TestCategory("Functional"), TestCategory("Generics")]
public async Task DifferentTypeArgsProduceIndependentActivations()
{
var grain1 = GrainFactory.GetGrain<IDbGrain<int>>(0);
await grain1.SetValue(123);
var grain2 = GrainFactory.GetGrain<IDbGrain<string>>(0);
var v = await grain2.GetValue();
Assert.Null(v);
}
[Fact, TestCategory("Functional"), TestCategory("Generics"), TestCategory("Echo")]
public async Task Generic_PingSelf()
{
var id = Guid.NewGuid();
var grain = GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.PingSelf(s1);
Assert.Equal(s1, s2);
}
[Fact, TestCategory("Functional"), TestCategory("Generics"), TestCategory("Echo")]
public async Task Generic_PingOther()
{
var id = Guid.NewGuid();
var targetId = Guid.NewGuid();
var grain = GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var target = GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId);
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.PingOther(target, s1);
Assert.Equal(s1, s2);
}
[Fact, TestCategory("Functional"), TestCategory("Generics"), TestCategory("Echo")]
public async Task Generic_PingSelfThroughOther()
{
var id = Guid.NewGuid();
var targetId = Guid.NewGuid();
var grain = GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var target = GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId);
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.PingSelfThroughOther(target, s1);
Assert.Equal(s1, s2);
}
[Fact, TestCategory("Functional"), TestCategory("Generics"), TestCategory("ActivateDeactivate")]
public async Task Generic_ScheduleDelayedPingAndDeactivate()
{
var id = Guid.NewGuid();
var targetId = Guid.NewGuid();
var grain = GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var target = GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId);
var s1 = Guid.NewGuid().ToString();
await grain.ScheduleDelayedPingToSelfAndDeactivate(target, s1, TimeSpan.FromSeconds(5));
await Task.Delay(TimeSpan.FromSeconds(6));
var s2 = await grain.GetLastValue();
Assert.Equal(s1, s2);
}
[Fact, TestCategory("Functional"), TestCategory("Generics"), TestCategory("Serialization")]
public async Task SerializationTests_Generic_CircularReferenceTest()
{
var grainId = Guid.NewGuid();
var grain = GrainFactory.GetGrain<ICircularStateTestGrain>(primaryKey: grainId, keyExtension: grainId.ToString("N"));
var c1 = await grain.GetState();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_GrainWithTypeConstraints()
{
var grainId = Guid.NewGuid().ToString();
var grain = GrainFactory.GetGrain<IGenericGrainWithConstraints<List<int>, int, string>>(grainId);
var result = await grain.GetCount();
Assert.Equal(0, result);
await grain.Add(42);
result = await grain.GetCount();
Assert.Equal(1, result);
}
[Fact, TestCategory("Functional"), TestCategory("Persistence")]
public async Task Generic_GrainWithValueTypeState()
{
Guid id = Guid.NewGuid();
var grain = GrainClient.GrainFactory.GetGrain<IValueTypeTestGrain>(id);
var initial = await grain.GetStateData();
Assert.Equal(new ValueTypeTestData(0), initial);
var expectedValue = new ValueTypeTestData(42);
await grain.SetStateData(expectedValue);
Assert.Equal(expectedValue, await grain.GetStateData());
}
[Fact(Skip = "https://github.com/dotnet/orleans/issues/1655 Casting from non-generic to generic interface fails with an obscure error message"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")]
public async Task Generic_CastToGenericInterfaceAfterActivation()
{
var grain = GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid());
await grain.DoSomething(); //activates original grain type here
var castRef = grain.AsReference<ISomeGenericGrain<string>>();
var result = await castRef.Hello();
Assert.Equal(result, "Hello!");
}
[Fact(Skip= "https://github.com/dotnet/orleans/issues/1655 Casting from non-generic to generic interface fails with an obscure error message"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")]
public async Task Generic_CastToDifferentlyConcretizedGenericInterfaceBeforeActivation() {
var grain = GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid());
var castRef = grain.AsReference<IIndependentlyConcretizedGenericGrain<string>>();
var result = await castRef.Hello();
Assert.Equal(result, "Hello!");
}
[Fact, TestCategory("Functional"), TestCategory("Cast")]
public async Task Generic_CastToDifferentlyConcretizedInterfaceBeforeActivation() {
var grain = GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid());
var castRef = grain.AsReference<IIndependentlyConcretizedGrain>();
var result = await castRef.Hello();
Assert.Equal(result, "Hello!");
}
[Fact, TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")]
public async Task Generic_CastGenericInterfaceToNonGenericInterfaceBeforeActivation() {
var grain = GrainFactory.GetGrain<IGenericCastableGrain<string>>(Guid.NewGuid());
var castRef = grain.AsReference<INonGenericCastGrain>();
var result = await castRef.Hello();
Assert.Equal(result, "Hello!");
}
}
namespace Generic.EdgeCases
{
using UnitTests.GrainInterfaces.Generic.EdgeCases;
public class GenericEdgeCaseTests : HostedTestClusterEnsureDefaultStarted
{
static async Task<Type[]> GetConcreteGenArgs(IBasicGrain @this) {
var genArgTypeNames = await @this.ConcreteGenArgTypeNames();
return genArgTypeNames.Select(n => Type.GetType(n))
.ToArray();
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_PartiallySpecifyingGenericGrainFulfilsInterface() {
var grain = GrainFactory.GetGrain<IGrainWithTwoGenArgs<string, int>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_GenericGrainCanReuseOwnGenArgRepeatedly() {
//resolves correctly but can't be activated: too many gen args supplied for concrete class
var grain = GrainFactory.GetGrain<IGrainReceivingRepeatedGenArgs<int, int>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_PartiallySpecifyingGenericInterfaceIsCastable() {
var grain = GrainFactory.GetGrain<IPartiallySpecifyingInterface<string>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<IGrainWithTwoGenArgs<string, int>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_PartiallySpecifyingGenericInterfaceIsCastable_Activating() {
var grain = GrainFactory.GetGrain<IPartiallySpecifyingInterface<string>>(Guid.NewGuid());
var castRef = grain.AsReference<IGrainWithTwoGenArgs<string, int>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RepeatedRearrangedGenArgsResolved() {
//again resolves to the correct generic type definition, but fails on activation as too many args
//gen args aren't being properly inferred from matched concrete type
var grain = GrainFactory.GetGrain<IReceivingRepeatedGenArgsAmongstOthers<int, string, int>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(string), typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInTypeResolution() {
var grain = GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(Enumerable.Empty<Type>())
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInCasting() {
var grain = GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<ISpecifyingGenArgsRepeatedlyToParentInterface<bool>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInCasting_Activating() {
//Only errors on invocation: wrong arity again
var grain = GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid());
var castRef = grain.AsReference<ISpecifyingGenArgsRepeatedlyToParentInterface<bool>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RearrangedGenArgsOfCorrectArityAreResolved() {
var grain = GrainFactory.GetGrain<IReceivingRearrangedGenArgs<int, long>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(long), typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RearrangedGenArgsOfCorrectNumberAreCastable() {
var grain = GrainFactory.GetGrain<ISpecifyingRearrangedGenArgsToParentInterface<int, long>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<IReceivingRearrangedGenArgsViaCast<long, int>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RearrangedGenArgsOfCorrectNumberAreCastable_Activating() {
var grain = GrainFactory.GetGrain<ISpecifyingRearrangedGenArgsToParentInterface<int, long>>(Guid.NewGuid());
var castRef = grain.AsReference<IReceivingRearrangedGenArgsViaCast<long, int>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
//**************************************************************************************************************
//**************************************************************************************************************
//Below must be commented out, as supplying multiple fully-specified generic interfaces
//to a class causes the codegen to fall over, stopping all other tests from working.
//See new test here of the bit causing the issue - type info conflation:
//UnitTests.CodeGeneration.CodeGeneratorTests.CodeGen_EncounteredFullySpecifiedInterfacesAreEncodedDistinctly()
//public interface IFullySpecifiedGenericInterface<T> : IBasicGrain
//{ }
//public interface IDerivedFromMultipleSpecializationsOfSameInterface : IFullySpecifiedGenericInterface<int>, IFullySpecifiedGenericInterface<long>
//{ }
//public class GrainFulfillingMultipleSpecializationsOfSameInterfaceViaIntermediate : BasicGrain, IDerivedFromMultipleSpecializationsOfSameInterface
//{ }
//[Fact, TestCategory("Generics")]
//public async Task CastingBetweenFullySpecifiedGenericInterfaces()
//{
// //Is this legitimate? Solely in the realm of virtual grain interfaces - no special knowledge of implementation implicated, only of interface hierarchy
// //codegen falling over: duplicate key when both specializations are matched to same concrete type
// var grain = GrainFactory.GetGrain<IDerivedFromMultipleSpecializationsOfSameInterface>(Guid.NewGuid());
// await grain.Hello();
// var castRef = grain.AsReference<IFullySpecifiedGenericInterface<int>>();
// await castRef.Hello();
// var castRef2 = castRef.AsReference<IFullySpecifiedGenericInterface<long>>();
// await castRef2.Hello();
//}
//*******************************************************************************************************
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_CanCastToFullySpecifiedInterfaceUnrelatedToConcreteGenArgs() {
var grain = GrainFactory.GetGrain<IArbitraryInterface<int, long>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<IInterfaceUnrelatedToConcreteGenArgs<float>>();
var response = await grain.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_CanCastToFullySpecifiedInterfaceUnrelatedToConcreteGenArgs_Activating() {
var grain = GrainFactory.GetGrain<IArbitraryInterface<int, long>>(Guid.NewGuid());
var castRef = grain.AsReference<IInterfaceUnrelatedToConcreteGenArgs<float>>();
var response = await grain.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_GenArgsCanBeFurtherSpecialized() {
var grain = GrainFactory.GetGrain<IInterfaceTakingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_GenArgsCanBeFurtherSpecializedIntoArrays() {
var grain = GrainFactory.GetGrain<IInterfaceTakingFurtherSpecializedGenArg<long[]>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(long) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_CanCastBetweenInterfacesWithFurtherSpecializedGenArgs() {
var grain = GrainFactory.GetGrain<IAnotherReceivingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<IYetOneMoreReceivingFurtherSpecializedGenArg<int[]>>();
var response = await grain.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_CanCastBetweenInterfacesWithFurtherSpecializedGenArgs_Activating() {
var grain = GrainFactory.GetGrain<IAnotherReceivingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid());
var castRef = grain.AsReference<IYetOneMoreReceivingFurtherSpecializedGenArg<int[]>>();
var response = await grain.Hello();
Assert.Equal(response, "Hello!");
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="IDataWriter.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Stratus.OdinSerializer
{
using System;
using System.IO;
/// <summary>
/// Provides a set of methods for reading data stored in a format that can be read by a corresponding <see cref="IDataReader"/> class.
/// <para />
/// If you implement this interface, it is VERY IMPORTANT that you implement each method to the *exact* specifications the documentation specifies.
/// <para />
/// It is strongly recommended to inherit from the <see cref="BaseDataWriter"/> class if you wish to implement a new data writer.
/// </summary>
/// <seealso cref="System.IDisposable" />
public interface IDataWriter : IDisposable
{
/// <summary>
/// Gets or sets the reader's serialization binder.
/// </summary>
/// <value>
/// The reader's serialization binder.
/// </value>
TwoWaySerializationBinder Binder { get; set; }
/// <summary>
/// Gets or sets the base stream of the writer.
/// </summary>
/// <value>
/// The base stream of the writer.
/// </value>
[Obsolete("Data readers and writers don't necessarily have streams any longer, so this API has been made obsolete. Using this property may result in NotSupportedExceptions being thrown.", false)]
Stream Stream { get; set; }
/// <summary>
/// Gets a value indicating whether the writer is in an array node.
/// </summary>
/// <value>
/// <c>true</c> if the writer is in an array node; otherwise, <c>false</c>.
/// </value>
bool IsInArrayNode { get; }
/// <summary>
/// Gets the serialization context.
/// </summary>
/// <value>
/// The serialization context.
/// </value>
SerializationContext Context { get; set; }
/// <summary>
/// Gets a dump of the data currently written by the writer. The format of this dump varies, but should be useful for debugging purposes.
/// </summary>
string GetDataDump();
/// <summary>
/// Flushes everything that has been written so far to the writer's base stream.
/// </summary>
void FlushToStream();
/// <summary>
/// Writes the beginning of a reference node.
/// <para />
/// This call MUST eventually be followed by a corresponding call to <see cref="IDataWriter.EndNode(string)"/>, with the same name.
/// </summary>
/// <param name="name">The name of the reference node.</param>
/// <param name="type">The type of the reference node. If null, no type metadata will be written.</param>
/// <param name="id">The id of the reference node. This id is acquired by calling <see cref="SerializationContext.TryRegisterInternalReference(object, out int)"/>.</param>
void BeginReferenceNode(string name, Type type, int id);
/// <summary>
/// Begins a struct/value type node. This is essentially the same as a reference node, except it has no internal reference id.
/// <para />
/// This call MUST eventually be followed by a corresponding call to <see cref="IDataWriter.EndNode(string)"/>, with the same name.
/// </summary>
/// <param name="name">The name of the struct node.</param>
/// <param name="type">The type of the struct node. If null, no type metadata will be written.</param>
void BeginStructNode(string name, Type type);
/// <summary>
/// Ends the current node with the given name. If the current node has another name, an <see cref="InvalidOperationException"/> is thrown.
/// </summary>
/// <param name="name">The name of the node to end. This has to be the name of the current node.</param>
void EndNode(string name);
/// <summary>
/// Begins an array node of the given length.
/// </summary>
/// <param name="length">The length of the array to come.</param>
void BeginArrayNode(long length);
/// <summary>
/// Ends the current array node, if the current node is an array node.
/// </summary>
void EndArrayNode();
/// <summary>
/// Writes a primitive array to the stream.
/// </summary>
/// <typeparam name="T">The element type of the primitive array. Valid element types can be determined using <see cref="FormatterUtilities.IsPrimitiveArrayType(Type)"/>.</typeparam>
/// <param name="array">The primitive array to write.</param>
void WritePrimitiveArray<T>(T[] array) where T : struct;
/// <summary>
/// Writes a null value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
void WriteNull(string name);
/// <summary>
/// Writes an internal reference to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="id">The value to write.</param>
void WriteInternalReference(string name, int id);
/// <summary>
/// Writes an external index reference to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="index">The value to write.</param>
void WriteExternalReference(string name, int index);
/// <summary>
/// Writes an external guid reference to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="guid">The value to write.</param>
void WriteExternalReference(string name, Guid guid);
/// <summary>
/// Writes an external string reference to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="id">The value to write.</param>
void WriteExternalReference(string name, string id);
/// <summary>
/// Writes a <see cref="char"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteChar(string name, char value);
/// <summary>
/// Writes a <see cref="string"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteString(string name, string value);
/// <summary>
/// Writes a <see cref="Guid"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteGuid(string name, Guid value);
/// <summary>
/// Writes an <see cref="sbyte"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteSByte(string name, sbyte value);
/// <summary>
/// Writes a <see cref="short"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteInt16(string name, short value);
/// <summary>
/// Writes an <see cref="int"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteInt32(string name, int value);
/// <summary>
/// Writes a <see cref="long"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteInt64(string name, long value);
/// <summary>
/// Writes a <see cref="byte"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteByte(string name, byte value);
/// <summary>
/// Writes an <see cref="ushort"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteUInt16(string name, ushort value);
/// <summary>
/// Writes an <see cref="uint"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteUInt32(string name, uint value);
/// <summary>
/// Writes an <see cref="ulong"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteUInt64(string name, ulong value);
/// <summary>
/// Writes a <see cref="decimal"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteDecimal(string name, decimal value);
/// <summary>
/// Writes a <see cref="float"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteSingle(string name, float value);
/// <summary>
/// Writes a <see cref="double"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteDouble(string name, double value);
/// <summary>
/// Writes a <see cref="bool"/> value to the stream.
/// </summary>
/// <param name="name">The name of the value. If this is null, no name will be written.</param>
/// <param name="value">The value to write.</param>
void WriteBoolean(string name, bool value);
/// <summary>
/// Tells the writer that a new serialization session is about to begin, and that it should clear all cached values left over from any prior serialization sessions.
/// This method is only relevant when the same writer is used to serialize several different, unrelated values.
/// </summary>
void PrepareNewSerializationSession();
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner HashBucket struct.
/// </content>
public partial class ImmutableHashSet<T>
{
/// <summary>
/// The result of a mutation operation.
/// </summary>
internal enum OperationResult
{
/// <summary>
/// The change required element(s) to be added or removed from the collection.
/// </summary>
SizeChanged,
/// <summary>
/// No change was required (the operation ended in a no-op).
/// </summary>
NoChangeRequired,
}
/// <summary>
/// Contains all the keys in the collection that hash to the same value.
/// </summary>
internal struct HashBucket
{
/// <summary>
/// One of the values in this bucket.
/// </summary>
private readonly T firstValue;
/// <summary>
/// Any other elements that hash to the same value.
/// </summary>
/// <value>
/// This is null if and only if the entire bucket is empty (including <see cref="firstValue"/>).
/// It's empty if <see cref="firstValue"/> has an element but no additional elements.
/// </value>
private readonly ImmutableList<T>.Node additionalElements;
/// <summary>
/// Initializes a new instance of the <see cref="HashBucket"/> struct.
/// </summary>
/// <param name="firstElement">The first element.</param>
/// <param name="additionalElements">The additional elements.</param>
private HashBucket(T firstElement, ImmutableList<T>.Node additionalElements = null)
{
this.firstValue = firstElement;
this.additionalElements = additionalElements ?? ImmutableList<T>.Node.EmptyNode;
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
internal bool IsEmpty
{
get { return this.additionalElements == null; }
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Adds the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="result">A description of the effect was on adding an element to this HashBucket.</param>
/// <returns>A new HashBucket that contains the added value and any values already held by this hashbucket.</returns>
internal HashBucket Add(T value, IEqualityComparer<T> valueComparer, out OperationResult result)
{
if (this.IsEmpty)
{
result = OperationResult.SizeChanged;
return new HashBucket(value);
}
if (valueComparer.Equals(value, this.firstValue) || this.additionalElements.IndexOf(value, valueComparer) >= 0)
{
result = OperationResult.NoChangeRequired;
return this;
}
result = OperationResult.SizeChanged;
return new HashBucket(this.firstValue, this.additionalElements.Add(value));
}
/// <summary>
/// Determines whether the HashBucket contains the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="valueComparer">The value comparer.</param>
internal bool Contains(T value, IEqualityComparer<T> valueComparer)
{
if (this.IsEmpty)
{
return false;
}
return valueComparer.Equals(value, this.firstValue) || this.additionalElements.IndexOf(value, valueComparer) >= 0;
}
/// <summary>
/// Searches the set for a given value and returns the equal value it finds, if any.
/// </summary>
/// <param name="value">The value to search for.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="existingValue">The value from the set that the search found, or the original value if the search yielded no match.</param>
/// <returns>
/// A value indicating whether the search was successful.
/// </returns>
internal bool TryExchange(T value, IEqualityComparer<T> valueComparer, out T existingValue)
{
if (!this.IsEmpty)
{
if (valueComparer.Equals(value, this.firstValue))
{
existingValue = this.firstValue;
return true;
}
int index = this.additionalElements.IndexOf(value, valueComparer);
if (index >= 0)
{
existingValue = this.additionalElements[index];
return true;
}
}
existingValue = value;
return false;
}
/// <summary>
/// Removes the specified value if it exists in the collection.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="equalityComparer">The equality comparer.</param>
/// <param name="result">A description of the effect was on adding an element to this HashBucket.</param>
/// <returns>A new HashBucket that does not contain the removed value and any values already held by this hashbucket.</returns>
internal HashBucket Remove(T value, IEqualityComparer<T> equalityComparer, out OperationResult result)
{
if (this.IsEmpty)
{
result = OperationResult.NoChangeRequired;
return this;
}
if (equalityComparer.Equals(this.firstValue, value))
{
if (this.additionalElements.IsEmpty)
{
result = OperationResult.SizeChanged;
return new HashBucket();
}
else
{
// We can promote any element from the list into the first position, but it's most efficient
// to remove the root node in the binary tree that implements the list.
int indexOfRootNode = this.additionalElements.Left.Count;
result = OperationResult.SizeChanged;
return new HashBucket(this.additionalElements.Key, this.additionalElements.RemoveAt(indexOfRootNode));
}
}
int index = this.additionalElements.IndexOf(value, equalityComparer);
if (index < 0)
{
result = OperationResult.NoChangeRequired;
return this;
}
else
{
result = OperationResult.SizeChanged;
return new HashBucket(this.firstValue, this.additionalElements.RemoveAt(index));
}
}
/// <summary>
/// Freezes this instance so that any further mutations require new memory allocations.
/// </summary>
internal void Freeze()
{
if (this.additionalElements != null)
{
this.additionalElements.Freeze();
}
}
/// <summary>
/// Enumerates all the elements in this instance.
/// </summary>
internal struct Enumerator : IEnumerator<T>, IDisposable
{
/// <summary>
/// The bucket being enumerated.
/// </summary>
private readonly HashBucket bucket;
/// <summary>
/// A value indicating whether this enumerator has been disposed.
/// </summary>
private bool disposed;
/// <summary>
/// The current position of this enumerator.
/// </summary>
private Position currentPosition;
/// <summary>
/// The enumerator that represents the current position over the additionalValues of the HashBucket.
/// </summary>
private ImmutableList<T>.Enumerator additionalEnumerator;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashSet<T>.HashBucket.Enumerator"/> struct.
/// </summary>
/// <param name="bucket">The bucket.</param>
internal Enumerator(HashBucket bucket)
{
this.disposed = false;
this.bucket = bucket;
this.currentPosition = Position.BeforeFirst;
this.additionalEnumerator = default(ImmutableList<T>.Enumerator);
}
/// <summary>
/// Describes the positions the enumerator state machine may be in.
/// </summary>
private enum Position
{
/// <summary>
/// The first element has not yet been moved to.
/// </summary>
BeforeFirst,
/// <summary>
/// We're at the firstValue of the containing bucket.
/// </summary>
First,
/// <summary>
/// We're enumerating the additionalValues in the bucket.
/// </summary>
Additional,
/// <summary>
/// The end of enumeration has been reached.
/// </summary>
End,
}
/// <summary>
/// Gets the current element.
/// </summary>
object IEnumerator.Current
{
get { return this.Current; }
}
/// <summary>
/// Gets the current element.
/// </summary>
public T Current
{
get
{
this.ThrowIfDisposed();
switch (this.currentPosition)
{
case Position.First:
return this.bucket.firstValue;
case Position.Additional:
return this.additionalEnumerator.Current;
default:
throw new InvalidOperationException();
}
}
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception>
public bool MoveNext()
{
this.ThrowIfDisposed();
if (this.bucket.IsEmpty)
{
this.currentPosition = Position.End;
return false;
}
switch (this.currentPosition)
{
case Position.BeforeFirst:
this.currentPosition = Position.First;
return true;
case Position.First:
if (this.bucket.additionalElements.IsEmpty)
{
this.currentPosition = Position.End;
return false;
}
this.currentPosition = Position.Additional;
this.additionalEnumerator = new ImmutableList<T>.Enumerator(this.bucket.additionalElements);
return this.additionalEnumerator.MoveNext();
case Position.Additional:
return this.additionalEnumerator.MoveNext();
case Position.End:
return false;
default:
throw new InvalidOperationException();
}
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception>
public void Reset()
{
this.ThrowIfDisposed();
this.additionalEnumerator.Dispose();
this.currentPosition = Position.BeforeFirst;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.disposed = true;
this.additionalEnumerator.Dispose();
}
/// <summary>
/// Throws an ObjectDisposedException if this enumerator has been disposed.
/// </summary>
private void ThrowIfDisposed()
{
if (this.disposed)
{
Validation.Requires.FailObjectDisposed(this);
}
}
}
}
}
}
| |
using Core.IO;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
#if WINRT
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
#elif WINDOWS_PHONE || SILVERLIGHT
using System.IO.IsolatedStorage;
#endif
namespace Core
{
public class WinVSystem : VSystem
{
#region Preamble
#if TEST || DEBUG
static bool OsTrace = false;
protected static void OSTRACE(string x, params object[] args) { if (OsTrace) Console.WriteLine("b:" + string.Format(x, args)); }
#else
protected static void OSTRACE(string x, params object[] args) { }
#endif
#if TEST
static int io_error_hit = 0; // Total number of I/O Errors
static int io_error_hardhit = 0; // Number of non-benign errors
static int io_error_pending = 0; // Count down to first I/O error
static bool io_error_persist = false; // True if I/O errors persist
static bool io_error_benign = false; // True if errors are benign
static int diskfull_pending = 0;
static bool diskfull = false;
protected static void SimulateIOErrorBenign(bool X) { io_error_benign = X; }
protected static bool SimulateIOError() { if ((io_error_persist && io_error_hit > 0) || io_error_pending-- == 1) { local_ioerr(); return true; } return false; }
protected static void local_ioerr() { OSTRACE("IOERR\n"); io_error_hit++; if (!io_error_benign) io_error_hardhit++; }
protected static bool SimulateDiskfullError() { if (diskfull_pending > 0) { if (diskfull_pending == 1) { local_ioerr(); diskfull = true; io_error_hit = 1; return true; } else diskfull_pending--; } return false; }
#else
protected static void SimulateIOErrorBenign(bool X) { }
protected static bool SimulateIOError() { return false; }
protected static bool SimulateDiskfullError() { return false; }
#endif
// When testing, keep a count of the number of open files.
#if TEST
static int open_file_count = 0;
protected static void OpenCounter(int X) { open_file_count += X; }
#else
protected static void OpenCounter(int X) { }
#endif
#endregion
#region Polyfill
const int INVALID_FILE_ATTRIBUTES = -1;
const int INVALID_SET_FILE_POINTER = -1;
#if OS_WINCE
#elif WINRT
static bool isNT() { return true; }
#else
static bool isNT() { return Environment.OSVersion.Platform >= PlatformID.Win32NT; }
#endif
const long ERROR_FILE_NOT_FOUND = 2L;
const long ERROR_HANDLE_DISK_FULL = 39L;
const long ERROR_NOT_SUPPORTED = 50L;
const long ERROR_DISK_FULL = 112L;
#if WINRT
public static bool FileExists(string path)
{
bool exists = true;
try { Task<StorageFile> fileTask = StorageFile.GetFileFromPathAsync(path).AsTask<StorageFile>(); fileTask.Wait(); }
catch (Exception)
{
var ae = (e as AggregateException);
if (ae != null && ae.InnerException is FileNotFoundException)
exists = false;
}
return exists;
}
#endif
#endregion
#region WinVFile
public class WinShm { }
public partial class WinVFile : VFile
{
public VSystem Vfs; // The VFS used to open this file
#if WINRT
public IRandomAccessStream H; // Filestream access to this file
#else
public FileStream H; // Filestream access to this file
#endif
public LOCK Lock_; // Type of lock currently held on this file
public int SharedLockByte; // Randomly chosen byte used as a shared lock
public uint LastErrno; // The Windows errno from the last I/O error
public uint SectorSize; // Sector size of the device file is on
#if !OMIT_WAL
public WinShm Shm; // Instance of shared memory on this file
#else
public object Shm; // DUMMY Instance of shared memory on this file
#endif
public string Path; // Full pathname of this file
public int SizeChunk; // Chunk size configured by FCNTL_CHUNK_SIZE
public void memset()
{
H = null;
Lock_ = 0;
SharedLockByte = 0;
LastErrno = 0;
SectorSize = 0;
}
};
#endregion
#region OS Errors
static RC getLastErrorMsg(ref string buf)
{
#if SILVERLIGHT || WINRT
buf = "Unknown error";
#else
buf = Marshal.GetLastWin32Error().ToString();
#endif
return RC.OK;
}
static RC winLogError(RC a, string b, string c)
{
#if !WINRT
var st = new StackTrace(new StackFrame(true)); var sf = st.GetFrame(0); return winLogErrorAtLine(a, b, c, sf.GetFileLineNumber());
#else
return winLogErrorAtLine(a, b, c, 0);
#endif
}
static RC winLogErrorAtLine(RC errcode, string func, string path, int line)
{
#if SILVERLIGHT || WINRT
uint errno = (uint)ERROR_NOT_SUPPORTED; // Error code
#else
uint errno = (uint)Marshal.GetLastWin32Error(); // Error code
#endif
string msg = null; // Human readable error text
getLastErrorMsg(ref msg);
Debug.Assert(errcode != RC.OK);
if (path == null) path = string.Empty;
int i;
for (i = 0; i < msg.Length && msg[i] != '\r' && msg[i] != '\n'; i++) { }
msg = msg.Substring(0, i);
SysEx.LOG(errcode, "os_win.c:%d: (%d) %s(%s) - %s", line, errno, func, path, msg);
return errcode;
}
#endregion
#region Locking
public static bool IsRunningMediumTrust()
{
// this is where it needs to check if it's running in an ASP.Net MediumTrust or lower environment
// in order to pick the appropriate locking strategy
#if SILVERLIGHT || WINRT
return true;
#else
return false;
#endif
}
private static LockingStrategy _lockingStrategy = (IsRunningMediumTrust() ? new MediumTrustLockingStrategy() : new LockingStrategy());
/// <summary>
/// Basic locking strategy for Console/Winform applications
/// </summary>
private class LockingStrategy
{
#if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT)
[DllImport("kernel32.dll")]
static extern bool LockFileEx(IntPtr hFile, uint dwFlags, uint dwReserved, uint nNumberOfBytesToLockLow, uint nNumberOfBytesToLockHigh, [In] ref System.Threading.NativeOverlapped lpOverlapped);
const int LOCKFILE_FAIL_IMMEDIATELY = 1;
#endif
public virtual void LockFile(WinVFile file, long offset, long length)
{
#if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT)
file.H.Lock(offset, length);
#endif
}
public virtual int SharedLockFile(WinVFile file, long offset, long length)
{
#if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT)
Debug.Assert(length == VFile.SHARED_SIZE);
Debug.Assert(offset == VFile.SHARED_FIRST);
var ovlp = new NativeOverlapped();
ovlp.OffsetLow = (int)offset;
ovlp.OffsetHigh = 0;
ovlp.EventHandle = IntPtr.Zero;
//SafeFileHandle.DangerousGetHandle().ToInt32()
return (LockFileEx(file.H.Handle, LOCKFILE_FAIL_IMMEDIATELY, 0, (uint)length, 0, ref ovlp) ? 1 : 0);
#else
return 1;
#endif
}
public virtual void UnlockFile(WinVFile file, long offset, long length)
{
#if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT)
file.H.Unlock(offset, length);
#endif
}
}
/// <summary>
/// Locking strategy for Medium Trust. It uses the same trick used in the native code for WIN_CE
/// which doesn't support LockFileEx as well.
/// </summary>
private class MediumTrustLockingStrategy : LockingStrategy
{
public override int SharedLockFile(WinVFile file, long offset, long length)
{
#if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT)
Debug.Assert(length == VFile.SHARED_SIZE);
Debug.Assert(offset == VFile.SHARED_FIRST);
try { file.H.Lock(offset + file.SharedLockByte, 1); }
catch (IOException) { return 0; }
#endif
return 1;
}
}
#endregion
#region WinVFile
public partial class WinVFile : VFile
{
static int seekWinFile(WinVFile file, long offset)
{
try
{
#if WINRT
file.H.Seek((ulong)offset);
#else
file.H.Seek(offset, SeekOrigin.Begin);
#endif
}
catch (Exception)
{
#if SILVERLIGHT || WINRT
file.LastErrno = 1;
#else
file.LastErrno = (uint)Marshal.GetLastWin32Error();
#endif
winLogError(RC.IOERR_SEEK, "seekWinFile", file.Path);
return 1;
}
return 0;
}
public static int MX_CLOSE_ATTEMPT = 3;
public override RC Close()
{
#if !OMIT_WAL
Debug.Assert(Shm == null);
#endif
OSTRACE("CLOSE %d (%s)\n", H.GetHashCode(), H.Name);
bool rc;
int cnt = 0;
do
{
#if WINRT
H.Dispose();
#else
H.Close();
#endif
rc = true;
} while (!rc && ++cnt < MX_CLOSE_ATTEMPT);
OSTRACE("CLOSE %d %s\n", H.GetHashCode(), rc ? "ok" : "failed");
if (rc)
H = null;
OpenCounter(-1);
return (rc ? RC.OK : winLogError(RC.IOERR_CLOSE, "winClose", Path));
}
public override RC Read(byte[] buffer, int amount, long offset)
{
//if (buffer == null)
// buffer = new byte[amount];
if (SimulateIOError())
return RC.IOERR_READ;
OSTRACE("READ %d lock=%d\n", H.GetHashCode(), Lock_);
if (!H.CanRead)
return RC.IOERR_READ;
if (seekWinFile(this, offset) != 0)
return RC.FULL;
int read; // Number of bytes actually read from file
try
{
#if WINRT
var stream = H.AsStreamForRead();
read = stream.Read(buffer, 0, amount);
#else
read = H.Read(buffer, 0, amount);
#endif
}
catch (Exception)
{
#if SILVERLIGHT || WINRT
LastErrno = 1;
#else
LastErrno = (uint)Marshal.GetLastWin32Error();
#endif
return winLogError(RC.IOERR_READ, "winRead", Path);
}
if (read < amount)
{
// Unread parts of the buffer must be zero-filled
Array.Clear(buffer, (int)read, (int)(amount - read));
return RC.IOERR_SHORT_READ;
}
return RC.OK;
}
public override RC Write(byte[] buffer, int amount, long offset)
{
Debug.Assert(amount > 0);
if (SimulateIOError())
return RC.IOERR_WRITE;
if (SimulateDiskfullError())
return RC.FULL;
OSTRACE("WRITE %d lock=%d\n", H.GetHashCode(), Lock_);
int rc = seekWinFile(this, offset); // True if error has occured, else false
#if WINRT
ulong wrote = H.Position;
#else
long wrote = H.Position;
#endif
try
{
Debug.Assert(buffer.Length >= amount);
#if WINRT
var stream = H.AsStreamForWrite();
stream.Write(buffer, 0, amount);
#else
H.Write(buffer, 0, amount);
#endif
rc = 1;
wrote = H.Position - wrote;
}
catch (IOException) { return RC.READONLY; }
if (rc == 0 || amount > (int)wrote)
{
#if SILVERLIGHT || WINRT
LastErrno = 1;
#else
LastErrno = (uint)Marshal.GetLastWin32Error();
#endif
if (LastErrno == ERROR_HANDLE_DISK_FULL || LastErrno == ERROR_DISK_FULL)
return RC.FULL;
else
return winLogError(RC.IOERR_WRITE, "winWrite", Path);
}
return RC.OK;
}
public override RC Truncate(long size)
{
RC rc = RC.OK;
OSTRACE("TRUNCATE %d %lld\n", H.Name, size);
if (SimulateIOError())
return RC.IOERR_TRUNCATE;
// If the user has configured a chunk-size for this file, truncate the file so that it consists of an integer number of chunks (i.e. the
// actual file size after the operation may be larger than the requested size).
if (SizeChunk > 0)
size = ((size + SizeChunk - 1) / SizeChunk) * SizeChunk;
try
{
#if WINRT
H.Size = (ulong)size;
#else
H.SetLength(size);
#endif
rc = RC.OK;
}
catch (IOException)
{
#if SILVERLIGHT || WINRT
LastErrno = 1;
#else
LastErrno = (uint)Marshal.GetLastWin32Error();
#endif
rc = winLogError(RC.IOERR_TRUNCATE, "winTruncate2", Path);
}
OSTRACE("TRUNCATE %d %lld %s\n", H.GetHashCode(), size, rc == RC.OK ? "ok" : "failed");
return rc;
}
#if TEST
// Count the number of fullsyncs and normal syncs. This is used to test that syncs and fullsyncs are occuring at the right times.
#if !TCLSH
static int sync_count = 0;
static int fullsync_count = 0;
#else
static tcl.lang.Var.SQLITE3_GETSET sync_count = new tcl.lang.Var.SQLITE3_GETSET("sync_count");
static tcl.lang.Var.SQLITE3_GETSET fullsync_count = new tcl.lang.Var.SQLITE3_GETSET("fullsync_count");
#endif
#endif
public override RC Sync(SYNC flags)
{
// Check that one of SQLITE_SYNC_NORMAL or FULL was passed
Debug.Assert(((int)flags & 0x0F) == (int)SYNC.NORMAL || ((int)flags & 0x0F) == (int)SYNC.FULL);
OSTRACE("SYNC %d lock=%d\n", H.GetHashCode(), Lock_);
// Unix cannot, but some systems may return SQLITE_FULL from here. This line is to test that doing so does not cause any problems.
if (SimulateDiskfullError())
return RC.FULL;
#if TEST
if (((int)flags & 0x0F) == (int)SYNC.FULL)
#if !TCLSH
fullsync_count++;
sync_count++;
#else
fullsync_count.iValue++;
sync_count.iValue++;
#endif
#endif
#if NO_SYNC // If we compiled with the SQLITE_NO_SYNC flag, then syncing is a no-op
return RC::OK;
#elif WINRT
var stream = H.AsStreamForWrite();
stream.Flush();
return RC.OK;
#else
H.Flush();
return RC.OK;
#endif
}
public override RC get_FileSize(out long size)
{
if (SimulateIOError())
{
size = 0;
return RC.IOERR_FSTAT;
}
#if WINRT
size = (H.CanRead ? (long)H.Size : 0);
#else
size = (H.CanRead ? H.Length : 0);
#endif
return RC.OK;
}
static int getReadLock(WinVFile file)
{
int res = 0;
if (isNT())
res = _lockingStrategy.SharedLockFile(file, SHARED_FIRST, SHARED_SIZE);
// isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
#if !OS_WINCE
else
{
Debugger.Break();
// int lk;
// sqlite3_randomness(lk.Length, lk);
// pFile.sharedLockByte = (u16)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
// res = pFile.fs.Lock( SHARED_FIRST + pFile.sharedLockByte, 0, 1, 0);
}
#endif
if (res == 0)
#if SILVERLIGHT || WINRT
file.LastErrno = 1;
#else
file.LastErrno = (uint)Marshal.GetLastWin32Error();
#endif
// No need to log a failure to lock
return res;
}
static int unlockReadLock(WinVFile file)
{
int res = 1;
if (isNT())
try { _lockingStrategy.UnlockFile(file, SHARED_FIRST, SHARED_SIZE); }
catch (Exception) { res = 0; }
// isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
#if !OS_WINCE
else
Debugger.Break();
#endif
if (res == 0)
{
#if SILVERLIGHT || WINRT
file.LastErrno = 1;
#else
file.LastErrno = (uint)Marshal.GetLastWin32Error();
#endif
winLogError(RC.IOERR_UNLOCK, "unlockReadLock", file.Path);
}
return res;
}
public override RC Lock(LOCK lock_)
{
OSTRACE("LOCK %d %d was %d(%d)\n", H.GetHashCode(), lock_, Lock_, SharedLockByte);
// If there is already a lock of this type or more restrictive on the OsFile, do nothing. Don't use the end_lock: exit path, as
// sqlite3OsEnterMutex() hasn't been called yet.
if (Lock_ >= lock_)
return RC.OK;
// Make sure the locking sequence is correct
Debug.Assert(lock_ != LOCK.NO || lock_ == LOCK.SHARED);
Debug.Assert(lock_ != LOCK.PENDING);
Debug.Assert(lock_ != LOCK.RESERVED || Lock_ == LOCK.SHARED);
// Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
// the PENDING_LOCK byte is temporary.
LOCK newLock = Lock_; // Set pFile.locktype to this value before exiting
int res = 1; // Result of a windows lock call
bool gotPendingLock = false;// True if we acquired a PENDING lock this time
uint lastErrno = 0;
if (Lock_ == LOCK.NO || (lock_ == LOCK.EXCLUSIVE && Lock_ == LOCK.RESERVED))
{
res = 0;
int cnt = 3;
while (cnt-- > 0 && res == 0)
{
try { _lockingStrategy.LockFile(this, PENDING_BYTE, 1); res = 1; }
catch (Exception)
{
// Try 3 times to get the pending lock. The pending lock might be held by another reader process who will release it momentarily.
OSTRACE("could not get a PENDING lock. cnt=%d\n", cnt);
#if WINRT
System.Threading.Tasks.Task.Delay(1).Wait();
#else
Thread.Sleep(1);
#endif
}
}
gotPendingLock = (res != 0);
if (res == 0)
#if SILVERLIGHT || WINRT
lastErrno = 1;
#else
lastErrno = (uint)Marshal.GetLastWin32Error();
#endif
}
// Acquire a SHARED lock
if (lock_ == LOCK.SHARED && res != 0)
{
Debug.Assert(Lock_ == LOCK.NO);
res = getReadLock(this);
if (res != 0)
newLock = LOCK.SHARED;
else
#if SILVERLIGHT || WINRT
lastErrno = 1;
#else
lastErrno = (uint)Marshal.GetLastWin32Error();
#endif
}
// Acquire a RESERVED lock
if (lock_ == LOCK.RESERVED && res != 0)
{
Debug.Assert(Lock_ == LOCK.SHARED);
try { _lockingStrategy.LockFile(this, RESERVED_BYTE, 1); newLock = LOCK.RESERVED; res = 1; }
catch (Exception) { res = 0; }
if (res != 0)
newLock = LOCK.RESERVED;
else
#if SILVERLIGHT
lastErrno = 1;
#else
lastErrno = (uint)Marshal.GetLastWin32Error();
#endif
}
// Acquire a PENDING lock
if (lock_ == LOCK.EXCLUSIVE && res != 0)
{
newLock = LOCK.PENDING;
gotPendingLock = false;
}
// Acquire an EXCLUSIVE lock
if (lock_ == LOCK.EXCLUSIVE && res != 0)
{
Debug.Assert(Lock_ >= LOCK.SHARED);
res = unlockReadLock(this);
OSTRACE("unreadlock = %d\n", res);
try { _lockingStrategy.LockFile(this, SHARED_FIRST, SHARED_SIZE); newLock = LOCK.EXCLUSIVE; res = 1; }
catch (Exception) { res = 0; }
if (res != 0)
newLock = LOCK.EXCLUSIVE;
else
{
#if SILVERLIGHT || WINRT
lastErrno = 1;
#else
lastErrno = (uint)Marshal.GetLastWin32Error();
#endif
OSTRACE("error-code = %d\n", lastErrno);
getReadLock(this);
}
}
// If we are holding a PENDING lock that ought to be released, then release it now.
if (gotPendingLock && lock_ == LOCK.SHARED)
_lockingStrategy.UnlockFile(this, PENDING_BYTE, 1);
// Update the state of the lock has held in the file descriptor then return the appropriate result code.
RC rc;
if (res != 0)
rc = RC.OK;
else
{
OSTRACE("LOCK FAILED %d trying for %d but got %d\n", H.GetHashCode(), lock_, newLock);
LastErrno = lastErrno;
rc = RC.BUSY;
}
Lock_ = newLock;
return rc;
}
public override RC CheckReservedLock(ref int resOut)
{
if (SimulateIOError())
return RC.IOERR_CHECKRESERVEDLOCK;
int rc;
if (Lock_ >= LOCK.RESERVED)
{
rc = 1;
OSTRACE("TEST WR-LOCK %d %d (local)\n", H.Name, rc);
}
else
{
try { _lockingStrategy.LockFile(this, RESERVED_BYTE, 1); _lockingStrategy.UnlockFile(this, RESERVED_BYTE, 1); rc = 1; }
catch (IOException) { rc = 0; }
rc = 1 - rc;
OSTRACE("TEST WR-LOCK %d %d (remote)\n", H.GetHashCode(), rc);
}
resOut = rc;
return RC.OK;
}
public override RC Unlock(LOCK lock_)
{
Debug.Assert(lock_ <= LOCK.SHARED);
OSTRACE("UNLOCK %d to %d was %d(%d)\n", H.GetHashCode(), lock_, Lock_, SharedLockByte);
var rc = RC.OK;
LOCK type = Lock_;
if (type >= LOCK.EXCLUSIVE)
{
_lockingStrategy.UnlockFile(this, SHARED_FIRST, SHARED_SIZE);
if (lock_ == LOCK.SHARED && getReadLock(this) == 0) // This should never happen. We should always be able to reacquire the read lock
rc = winLogError(RC.IOERR_UNLOCK, "winUnlock", Path);
}
if (type >= LOCK.RESERVED)
try { _lockingStrategy.UnlockFile(this, RESERVED_BYTE, 1); }
catch (Exception) { }
if (lock_ == LOCK.NO && type >= LOCK.SHARED)
unlockReadLock(this);
if (type >= LOCK.PENDING)
try { _lockingStrategy.UnlockFile(this, PENDING_BYTE, 1); }
catch (Exception) { }
Lock_ = lock_;
return rc;
}
//static void winModeBit(WinVFile file, char mask, ref long arg)
//{
// if (arg < 0)
// arg = ((file.CtrlFlags & mask) != 0);
// else if (arg == 0)
// file.CtrlFlags &= ~mask;
// else
// file.CtrlFlags |= mask;
//}
public override RC FileControl(FCNTL op, ref long arg)
{
switch (op)
{
case FCNTL.LOCKSTATE:
arg = (int)Lock_;
return RC.OK;
case FCNTL.LAST_ERRNO:
arg = (int)LastErrno;
return RC.OK;
case FCNTL.CHUNK_SIZE:
SizeChunk = (int)arg;
return RC.OK;
case FCNTL.SIZE_HINT:
if (SizeChunk > 0)
{
long oldSize;
var rc = get_FileSize(out oldSize);
if (rc == RC.OK)
{
var newSize = (long)arg;
if (newSize > oldSize)
{
SimulateIOErrorBenign(true);
Truncate(newSize);
SimulateIOErrorBenign(false);
}
}
return rc;
}
return RC.OK;
case FCNTL.PERSIST_WAL:
//winModeBit(this, WINFILE_PERSIST_WAL, ref arg);
return RC.OK;
case FCNTL.POWERSAFE_OVERWRITE:
//winModeBit(this, WINFILE_PSOW, ref arg);
return RC.OK;
//case FCNTL.VFSNAME:
// arg = "win32";
// return RC.OK;
//case FCNTL.WIN32_AV_RETRY:
// int *a = (int*)arg;
// if (a[0] > 0)
// win32IoerrRetry = a[0];
// else
// a[0] = win32IoerrRetry;
// if (a[1] > 0)
// win32IoerrRetryDelay = a[1];
// else
// a[1] = win32IoerrRetryDelay;
// return RC.OK;
//case FCNTL.TEMPFILENAME:
// var tfile = SysEx::Alloc(Vfs->MaxPathname, true);
// if (tfile)
// {
// getTempname(Vfs->MaxPathname, tfile);
// *(char**)arg = tfile;
// }
// return RC.OK;
}
return RC.NOTFOUND;
}
public override uint get_SectorSize()
{
//return DEFAULT_SECTOR_SIZE;
return SectorSize;
}
//public override IOCAP get_DeviceCharacteristics() { return 0; }
#if !OMIT_WAL
public override RC ShmMap(int region, int sizeRegion, bool isWrite, out object pp) { pp = null; return RC.OK; }
public override RC ShmLock(int offset, int count, SHM flags) { return RC.OK; }
public override void ShmBarrier() { }
public override RC ShmUnmap(bool deleteFlag) { return RC.OK; }
#endif
}
#endregion
#region WinVSystem
//static string ConvertUtf8Filename(string filename)
//{
// return filename;
//}
// static RC getTempname(int bufLength, StringBuilder buf)
// {
// const string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
// var random = new StringBuilder(20);
// long randomValue = 0;
// for (int i = 0; i < 15; i++)
// {
// sqlite3_randomness(1, ref randomValue);
// random.Append((char)chars[(int)(randomValue % (chars.Length - 1))]);
// }
//#if WINRT
// buf.Append(Path.Combine(ApplicationData.Current.LocalFolder.Path, TEMP_FILE_PREFIX + random.ToString()));
//#else
// buf.Append(Path.GetTempPath() + TEMP_FILE_PREFIX + random.ToString());
//#endif
// OSTRACE("TEMP FILENAME: %s\n", buf.ToString());
// return RC.OK;
// }
public override RC Open(string name, VFile id, OPEN flags, out OPEN outFlags)
{
// 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
// SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before reaching the VFS.
flags = (OPEN)((uint)flags & 0x87f7f);
outFlags = 0;
var rc = RC.OK;
var type = (OPEN)(int)((int)flags & 0xFFFFFF00); // Type of file to open
var isExclusive = (flags & OPEN.EXCLUSIVE) != 0;
var isDelete = (flags & OPEN.DELETEONCLOSE) != 0;
var isCreate = (flags & OPEN.CREATE) != 0;
var isReadonly = (flags & OPEN.READONLY) != 0;
var isReadWrite = (flags & OPEN.READWRITE) != 0;
var isOpenJournal = (isCreate && (type == OPEN.MASTER_JOURNAL || type == OPEN.MAIN_JOURNAL || type == OPEN.WAL));
// Check the following statements are true:
//
// (a) Exactly one of the READWRITE and READONLY flags must be set, and
// (b) if CREATE is set, then READWRITE must also be set, and
// (c) if EXCLUSIVE is set, then CREATE must also be set.
// (d) if DELETEONCLOSE is set, then CREATE must also be set.
Debug.Assert((!isReadonly || !isReadWrite) && (isReadWrite || isReadonly));
Debug.Assert(!isCreate || isReadWrite);
Debug.Assert(!isExclusive || isCreate);
Debug.Assert(!isDelete || isCreate);
// The main DB, main journal, WAL file and master journal are never automatically deleted. Nor are they ever temporary files.
//Debug.Assert((!isDelete && !string.IsNullOrEmpty(name)) || type != OPEN.MAIN_DB);
Debug.Assert((!isDelete && !string.IsNullOrEmpty(name)) || type != OPEN.MAIN_JOURNAL);
Debug.Assert((!isDelete && !string.IsNullOrEmpty(name)) || type != OPEN.MASTER_JOURNAL);
Debug.Assert((!isDelete && !string.IsNullOrEmpty(name)) || type != OPEN.WAL);
// Assert that the upper layer has set one of the "file-type" flags.
Debug.Assert(type == OPEN.MAIN_DB || type == OPEN.TEMP_DB ||
type == OPEN.MAIN_JOURNAL || type == OPEN.TEMP_JOURNAL ||
type == OPEN.SUBJOURNAL || type == OPEN.MASTER_JOURNAL ||
type == OPEN.TRANSIENT_DB || type == OPEN.WAL);
var file = (WinVFile)id;
Debug.Assert(file != null);
file.H = null;
// If the second argument to this function is NULL, generate a temporary file name to use
if (string.IsNullOrEmpty(name))
{
Debug.Assert(isDelete && !isOpenJournal);
name = Path.GetRandomFileName();
}
// Convert the filename to the system encoding.
if (name.StartsWith("/") && !name.StartsWith("//"))
name = name.Substring(1);
#if !WINRT
FileAccess dwDesiredAccess;
if (isReadWrite)
dwDesiredAccess = FileAccess.Read | FileAccess.Write;
else
dwDesiredAccess = FileAccess.Read;
// SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is created. SQLite doesn't use it to indicate "exclusive access"
// as it is usually understood.
FileMode dwCreationDisposition;
if (isExclusive) // Creates a new file, only if it does not already exist. If the file exists, it fails.
dwCreationDisposition = FileMode.CreateNew;
else if (isCreate) // Open existing file, or create if it doesn't exist
dwCreationDisposition = FileMode.OpenOrCreate;
else // Opens a file, only if it exists.
dwCreationDisposition = FileMode.Open;
FileShare dwShareMode = FileShare.Read | FileShare.Write;
#endif
#if OS_WINCE
uint dwDesiredAccess = 0;
int isTemp = 0;
#else
#if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT)
FileOptions dwFlagsAndAttributes;
#endif
#endif
if (isDelete)
{
#if OS_WINCE
dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
isTemp = 1;
#else
#if !(SILVERLIGHT || WINDOWS_MOBILE || WINRT)
dwFlagsAndAttributes = FileOptions.DeleteOnClose;
#endif
#endif
}
else
{
#if !(SILVERLIGHT || WINDOWS_MOBILE || SQLITE_WINRT)
dwFlagsAndAttributes = FileOptions.None;
#endif
}
// Reports from the internet are that performance is always better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699.
#if OS_WINCE
dwFlagsAndAttributes |= FileOptions.RandomAccess;
#endif
#if WINRT
IRandomAccessStream fs = null;
DWORD dwDesiredAccess = 0;
#else
FileStream fs = null;
#endif
if (isNT())
{
// retry opening the file a few times; this is because of a racing condition between a delete and open call to the FS
int retries = 3;
while (fs == null && retries > 0)
try
{
retries--;
#if WINRT
Task<StorageFile> fileTask = null;
if (isExclusive)
{
if (HelperMethods.FileExists(name)) // Error
throw new IOException("file already exists");
else
{
Task<StorageFolder> folderTask = StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(name)).AsTask<StorageFolder>();
folderTask.Wait();
fileTask = folderTask.Result.CreateFileAsync(Path.GetFileName(name)).AsTask<StorageFile>();
}
}
else if (isCreate)
{
if (HelperMethods.FileExists(name))
fileTask = StorageFile.GetFileFromPathAsync(name).AsTask<StorageFile>();
else
{
Task<StorageFolder> folderTask = StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(name)).AsTask<StorageFolder>();
folderTask.Wait();
fileTask = folderTask.Result.CreateFileAsync(Path.GetFileName(name)).AsTask<StorageFile>();
}
}
else
fileTask = StorageFile.GetFileFromPathAsync(name).AsTask<StorageFile>();
fileTask.Wait();
Task<IRandomAccessStream> streamTask = fileTask.Result.OpenAsync(FileAccessMode.ReadWriteUnsafe).AsTask<IRandomAccessStream>();
streamTask.Wait();
fs = streamTask.Result;
#elif WINDOWS_PHONE || SILVERLIGHT
fs = new IsolatedStorageFileStream(name, dwCreationDisposition, dwDesiredAccess, dwShareMode, IsolatedStorageFile.GetUserStoreForApplication());
#elif !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE)
fs = new FileStream(name, dwCreationDisposition, dwDesiredAccess, dwShareMode, 4096, dwFlagsAndAttributes);
#else
fs = new FileStream(name, dwCreationDisposition, dwDesiredAccess, dwShareMode, 4096);
#endif
OSTRACE("OPEN %d (%s)\n", fs.GetHashCode(), fs.Name);
}
catch (Exception)
{
#if WINRT
System.Threading.Tasks.Task.Delay(100).Wait();
#else
Thread.Sleep(100);
#endif
}
// isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. Since the ASCII version of these Windows API do not exist for WINCE,
// it's important to not reference them for WINCE builds.
#if !OS_WINCE
}
else
{
Debugger.Break();
#endif
}
OSTRACE("OPEN {0} {1} 0x{2:x} {3}\n", file.GetHashCode(), name, dwDesiredAccess, fs == null ? "failed" : "ok");
if (fs == null ||
#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE || SQLITE_WINRT)
fs.SafeFileHandle.IsInvalid
#else
!fs.CanRead
#endif
)
{
#if SILVERLIGHT || WINRT
file.LastErrno = 1;
#else
file.LastErrno = (uint)Marshal.GetLastWin32Error();
#endif
winLogError(RC.CANTOPEN, "winOpen", name);
if (isReadWrite)
return Open(name, file, ((flags | OPEN.READONLY) & ~(OPEN.CREATE | OPEN.READWRITE)), out outFlags);
else
return SysEx.CANTOPEN_BKPT();
}
outFlags = (isReadWrite ? OPEN.READWRITE : OPEN.READONLY);
file.memset();
file.Opened = true;
file.H = fs;
file.LastErrno = 0;
file.Vfs = this;
file.Shm = null;
file.Path = name;
file.SectorSize = (uint)getSectorSize(this, name);
#if OS_WINCE
if (isReadWrite && type == OPEN.MAIN_DB && !winceCreateLock(name, file))
{
CloseHandle(h);
return SysEx.CANTOPEN_BKPT();
}
if (isTemp)
file.DeleteOnClose = name;
#endif
OpenCounter(+1);
return rc;
}
static int MX_DELETION_ATTEMPTS = 5;
public override RC Delete(string filename, bool syncDir)
{
if (SimulateIOError())
return RC.IOERR_DELETE;
int cnt = 0;
RC rc = RC.ERROR;
if (isNT())
do
{
#if WINRT
if(!HelperMethods.FileExists(filename))
#elif WINDOWS_PHONE
if (!System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication().FileExists(filename))
#elif SILVERLIGHT
if (!IsolatedStorageFile.GetUserStoreForApplication().FileExists(filename))
#else
if (!File.Exists(filename))
#endif
{
rc = RC.IOERR;
break;
}
try
{
#if WINRT
Task<StorageFile> fileTask = StorageFile.GetFileFromPathAsync(filename).AsTask<StorageFile>();
fileTask.Wait();
fileTask.Result.DeleteAsync().AsTask().Wait();
#elif WINDOWS_PHONE
System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication().DeleteFile(filename);
#elif SILVERLIGHT
IsolatedStorageFile.GetUserStoreForApplication().DeleteFile(filename);
#else
File.Delete(filename);
#endif
rc = RC.OK;
}
catch (IOException)
{
rc = RC.IOERR;
#if WINRT
System.Threading.Tasks.Task.Delay(100).Wait();
#else
Thread.Sleep(100);
#endif
}
} while (rc != RC.OK && ++cnt < MX_DELETION_ATTEMPTS);
// isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. Since the ASCII version of these Windows API do not exist for WINCE,
// it's important to not reference them for WINCE builds.
#if !OS_WINCE && !WINRT
else
do
{
if (!File.Exists(filename))
{
rc = RC.IOERR;
break;
}
try
{
File.Delete(filename);
rc = RC.OK;
}
catch (IOException)
{
rc = RC.IOERR;
Thread.Sleep(100);
}
} while (rc != RC.OK && cnt++ < MX_DELETION_ATTEMPTS);
#endif
OSTRACE("DELETE \"%s\"\n", filename);
if (rc == RC.OK)
return rc;
int lastErrno;
#if SILVERLIGHT || WINRT
lastErrno = (int)ERROR_NOT_SUPPORTED;
#else
lastErrno = Marshal.GetLastWin32Error();
#endif
return (lastErrno == ERROR_FILE_NOT_FOUND ? RC.OK : winLogError(RC.IOERR_DELETE, "winDelete", filename));
}
public override RC Access(string filename, ACCESS flags, out int resOut)
{
if (SimulateIOError())
{
resOut = -1;
return RC.IOERR_ACCESS;
}
// Do a quick test to prevent the try/catch block
if (flags == ACCESS.EXISTS)
{
#if WINRT
resOut = HelperMethods.FileExists(zFilename) ? 1 : 0;
#elif WINDOWS_PHONE
resOut = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication().FileExists(zFilename) ? 1 : 0;
#elif SILVERLIGHT
resOut = IsolatedStorageFile.GetUserStoreForApplication().FileExists(zFilename) ? 1 : 0;
#else
resOut = File.Exists(filename) ? 1 : 0;
#endif
return RC.OK;
}
FileAttributes attr = 0;
try
{
#if WINRT
attr = FileAttributes.Normal;
}
#else
#if WINDOWS_PHONE || WINDOWS_MOBILE || SILVERLIGHT
if (new DirectoryInfo(filename).Exists)
#else
attr = File.GetAttributes(filename);
if (attr == FileAttributes.Directory)
#endif
{
try
{
var name = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
var fs = File.Create(name);
fs.Close();
File.Delete(name);
attr = FileAttributes.Normal;
}
catch (IOException) { attr = FileAttributes.ReadOnly; }
}
}
// isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. Since the ASCII version of these Windows API do not exist for WINCE,
// it's important to not reference them for WINCE builds.
#if !OS_WINCE
#endif
#endif
catch (IOException) { winLogError(RC.IOERR_ACCESS, "winAccess", filename); }
int rc = 0;
switch (flags)
{
case ACCESS.READ:
case ACCESS.EXISTS:
rc = attr != 0 ? 1 : 0;
break;
case ACCESS.READWRITE:
rc = attr == 0 ? 0 : (int)(attr & FileAttributes.ReadOnly) != 0 ? 0 : 1;
break;
default:
Debug.Assert("Invalid flags argument" == "");
rc = 0;
break;
}
resOut = rc;
return RC.OK;
}
public override RC FullPathname(string relative, out string full)
{
#if OS_WINCE
if (SimulateIOError())
return RC.ERROR;
// WinCE has no concept of a relative pathname, or so I am told.
snprintf(MaxPathname, full, "%s", relative);
return RC.OK;
#endif
#if !OS_WINCE
full = null;
// If this path name begins with "/X:", where "X" is any alphabetic character, discard the initial "/" from the pathname.
if (relative[0] == '/' && Char.IsLetter(relative[1]) && relative[2] == ':')
relative = relative.Substring(1);
if (SimulateIOError())
return RC.ERROR;
if (isNT())
{
try
{
#if WINDOWS_PHONE || SILVERLIGHT || WINRT
full = relative;
#else
full = Path.GetFullPath(relative);
#endif
}
catch (Exception) { full = relative; }
#if !SQLITE_OS_WINCE
}
else
{
Debugger.Break();
#endif
}
if (full.Length > MaxPathname)
full = full.Substring(0, MaxPathname);
return RC.OK;
#endif
}
const int DEFAULT_SECTOR_SIZE = 512;
static int getSectorSize(VSystem vfs, string relative)
{
return DEFAULT_SECTOR_SIZE;
}
#if !OMIT_LOAD_EXTENSION
public override object DlOpen(string filename) { throw new NotSupportedException(); }
public override void DlError(int bufLength, string buf) { throw new NotSupportedException(); }
public override object DlSym(object handle, string symbol) { throw new NotSupportedException(); }
public override void DlClose(object handle) { throw new NotSupportedException(); }
#else
public override object DlOpen(string filename) { return null; }
public override void DlError(int byteLength, string errMsg) { return 0; }
public override object DlSym(object data, string symbol) { return null; }
public override void DlClose(object data) { return 0; }
#endif
public override int Randomness(int bufLength, byte[] buf)
{
int n = 0;
#if TEST
n = bufLength;
Array.Clear(buf, 0, n);
#else
var sBuf = BitConverter.GetBytes(DateTime.Now.Ticks);
buf[0] = sBuf[0];
buf[1] = sBuf[1];
buf[2] = sBuf[2];
buf[3] = sBuf[3];
n += 16;
if (sizeof(uint) <= bufLength - n)
{
uint processId;
#if !(SILVERLIGHT || WINRT)
processId = (uint)Process.GetCurrentProcess().Id;
#else
processId = 28376023;
#endif
ConvertEx.Put4(buf, n, processId);
n += 4;
}
if (sizeof(uint) <= bufLength - n)
{
var dt = new DateTime();
ConvertEx.Put4(buf, n, (uint)dt.Ticks);// memcpy(&zBuf[n], cnt, sizeof(cnt));
n += 4;
}
if (sizeof(long) <= bufLength - n)
{
long i;
i = DateTime.UtcNow.Millisecond;
ConvertEx.Put4(buf, n, (uint)(i & 0xFFFFFFFF));
ConvertEx.Put4(buf, n, (uint)(i >> 32));
n += sizeof(long);
}
#endif
return n;
}
public override int Sleep(int microsec)
{
#if WINRT
System.Threading.Tasks.Task.Delay(((microsec + 999) / 1000)).Wait();
#else
Thread.Sleep(((microsec + 999) / 1000));
#endif
return ((microsec + 999) / 1000) * 1000;
}
#if TEST
#if !TCLSH
static int current_time = 0; // Fake system time in seconds since 1970.
#else
static tcl.lang.Var.SQLITE3_GETSET current_time = new tcl.lang.Var.SQLITE3_GETSET("current_time");
#endif
#endif
public override RC CurrentTimeInt64(ref long now)
{
// FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
#if WINRT
const long winRtEpoc = 17214255 * (long)8640000;
#else
const long winFiletimeEpoch = 23058135 * (long)8640000;
#endif
#if TEST
const long unixEpoch = 24405875 * (long)8640000;
#endif
#if WINRT
now = winRtEpoc + DateTime.UtcNow.Ticks / (long)10000;
#else
now = winFiletimeEpoch + DateTime.UtcNow.ToFileTimeUtc() / (long)10000;
#endif
#if TEST
#if !TCLSH
if (current_time != 0)
now = 1000 * (long)current_time + unixEpoch;
#else
if (current_time.iValue != 0)
now = 1000 * (long)current_time.iValue + unixEpoch;
#endif
#endif
return RC.OK;
}
public override RC CurrentTime(ref double now)
{
long i = 0;
var rc = CurrentTimeInt64(ref i);
if (rc == RC.OK)
now = i / 86400000.0;
return rc;
}
public override RC GetLastError(int bufLength, ref string buf)
{
return getLastErrorMsg(ref buf);
}
#endregion
}
#region Bootstrap VSystem
public abstract partial class VSystem
{
public static RC Initialize()
{
RegisterVfs(new WinVSystem(), true, () => new WinVSystem.WinVFile());
return RC.OK;
}
public static void Shutdown()
{
}
}
#endregion
}
| |
#region License
//L
// 2007 - 2013 Copyright Northwestern University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
//L
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using ClearCanvas.Common;
using NBIAService;
namespace SearchComponent
{
internal partial class RetrieveCoordinator
{
protected class NBIARetrieveCommand : RetrieveCommand
{
public NBIARetrieveCommand(List<RetrieveQueryItem> queryItems) : base()
{
Result.QueryItems.AddRange(queryItems);
}
public override void Execute()
{
List<string> studyUids = new List<string>();
if (Result.QueryItems != null && Result.QueryItems.Count > 0)
{
foreach (RetrieveQueryItem queryItem in Result.QueryItems)
{
if (queryItem.Study != null && !string.IsNullOrEmpty(queryItem.Study.StudyInstanceUid))
studyUids.Add(queryItem.Study.StudyInstanceUid);
}
}
if (studyUids.Count == 0)
{
OnError("No Study Instance UID is specified");
OnCommandExecuted();
return;
}
if (this.IsCancelRequested())
{
OnCancelRequested();
OnCommandExecuted();
return;
}
OnStatusChanged(RetrieveStatus.InProgress, "Quering for studies...");
string url = null;
try
{
NBIARetrieveByStudyUIDs nbiaRetrieveByStudyUIDs = new NBIARetrieveByStudyUIDs();
url = nbiaRetrieveByStudyUIDs.retrieveStudyURL(studyUids.ToArray(), SearchSettings.Default.NBIADataServiceTransferUrl);
}
catch (DataServiceUtil.GridServicerException ex)
{
Platform.Log(LogLevel.Error, ex, "Failed to retrieve images from NBIA");
}
if (this.IsCancelRequested())
{
OnCancelRequested();
OnCommandExecuted();
return;
}
if (string.IsNullOrEmpty(url))
{
OnCommandCompleted("No studies returned by NBIA.");
OnCommandExecuted();
return;
}
string downloadedFilesFolder = this.DownloadQueryResults(url);
if (this.IsCancelRequested())
{
OnCancelRequested();
OnCommandExecuted();
return;
}
if (string.IsNullOrEmpty(downloadedFilesFolder))
{
OnCommandExecuted();
return;
}
OnProgressUpdated("Importing images");
try
{
string[] files = Directory.GetFiles(downloadedFilesFolder, "*.dcm", SearchOption.AllDirectories);
if (files.Length > 0)
this.ImportDicomFiles(files);
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, ex, "Error importing NBIA images");
OnError("Error importing NBIA images");
OnCommandExecuted();
return;
}
OnCommandCompleted("Done");
OnCommandExecuted();
}
private string DownloadQueryResults(string sourceUrl)
{
if (!string.IsNullOrEmpty(sourceUrl))
{
string tempZipDir = Path.Combine(Path.GetTempPath(),
Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
string tempZipFile = tempZipDir + ".zip";
WebClient webClient = null;
bool canceled = false;
try
{
webClient = new WebClient();
bool downloadCompleted = false;
webClient.DownloadProgressChanged +=
delegate(object sender, DownloadProgressChangedEventArgs e)
{
string msg;
if (IsCancelRequested())
{
OnCancelRequested();
if (!canceled)
{
webClient.CancelAsync();
}
canceled = true;
return;
}
if (e.BytesReceived < 1000*1024)
msg = string.Format("Retrieving images ({0:0.00}KB)", ((float) e.BytesReceived)/1024);
else
msg = string.Format("Retrieving images ({0:0.00}MB)", ((float) e.BytesReceived)/1000/1024);
OnProgressUpdated(msg);
};
webClient.DownloadFileCompleted +=
delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
downloadCompleted = true;
};
webClient.DownloadFileAsync(new Uri(sourceUrl), tempZipFile);
while (!downloadCompleted)
System.Threading.Thread.Sleep(500);
if (IsCancelRequested())
{
OnCancelRequested();
canceled = true;
}
if (!canceled)
{
OnProgressUpdated("Processing received images");
try
{
ZipUtil.UnZipFiles(tempZipFile, tempZipDir, "", false, true);
File.Delete(tempZipFile);
}
catch (Exception ex)
{
Platform.Log(LogLevel.Error, "Error processing received images", ex);
OnError("Error processing received images");
return null;
}
return tempZipDir;
}
}
finally
{
if (webClient != null)
{
webClient.Dispose();
}
}
}
return null;
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using ManagedBass;
using osuTK;
using osu.Framework.MathUtils;
using osu.Framework.Audio.Callbacks;
namespace osu.Framework.Audio.Track
{
/// <summary>
/// Procsses audio sample data such that it can then be consumed to generate waveform plots of the audio.
/// </summary>
public class Waveform : IDisposable
{
/// <summary>
/// <see cref="WaveformPoint"/>s are initially generated to a 1ms resolution to cover most use cases.
/// </summary>
private const float resolution = 0.001f;
/// <summary>
/// The data stream is iteratively decoded to provide this many points per iteration so as to not exceed BASS's internal buffer size.
/// </summary>
private const int points_per_iteration = 100000;
private const int bytes_per_sample = 4;
/// <summary>
/// FFT1024 gives ~40hz accuracy.
/// </summary>
private const DataFlags fft_samples = DataFlags.FFT1024;
/// <summary>
/// Number of bins generated by the FFT. Must correspond to <see cref="fft_samples"/>.
/// </summary>
private const int fft_bins = 512;
/// <summary>
/// Minimum frequency for low-range (bass) frequencies. Based on lower range of bass drum fallout.
/// </summary>
private const double low_min = 20;
/// <summary>
/// Minimum frequency for mid-range frequencies. Based on higher range of bass drum fallout.
/// </summary>
private const double mid_min = 100;
/// <summary>
/// Minimum frequency for high-range (treble) frequencies.
/// </summary>
private const double high_min = 2000;
/// <summary>
/// Maximum frequency for high-range (treble) frequencies. A sane value.
/// </summary>
private const double high_max = 12000;
private int channels;
private List<WaveformPoint> points = new List<WaveformPoint>();
private readonly CancellationTokenSource cancelSource = new CancellationTokenSource();
private readonly Task readTask;
private FileCallbacks fileCallbacks;
/// <summary>
/// Constructs a new <see cref="Waveform"/> from provided audio data.
/// </summary>
/// <param name="data">The sample data stream. If null, an empty waveform is constructed.</param>
public Waveform(Stream data)
{
if (data == null) return;
readTask = Task.Run(() =>
{
// for the time being, this code cannot run if there is no bass device available.
if (Bass.CurrentDevice <= 0)
return;
fileCallbacks = new FileCallbacks(new DataStreamFileProcedures(data));
int decodeStream = Bass.CreateStream(StreamSystem.NoBuffer, BassFlags.Decode | BassFlags.Float, fileCallbacks.Callbacks, fileCallbacks.Handle);
Bass.ChannelGetInfo(decodeStream, out ChannelInfo info);
long length = Bass.ChannelGetLength(decodeStream);
// Each "point" is generated from a number of samples, each sample contains a number of channels
int samplesPerPoint = (int)(info.Frequency * resolution * info.Channels);
int bytesPerPoint = samplesPerPoint * bytes_per_sample;
points.Capacity = (int)(length / bytesPerPoint);
// Each iteration pulls in several samples
int bytesPerIteration = bytesPerPoint * points_per_iteration;
var sampleBuffer = new float[bytesPerIteration / bytes_per_sample];
// Read sample data
while (length > 0)
{
length = Bass.ChannelGetData(decodeStream, sampleBuffer, bytesPerIteration);
int samplesRead = (int)(length / bytes_per_sample);
// Each point is composed of multiple samples
for (int i = 0; i < samplesRead; i += samplesPerPoint)
{
// Channels are interleaved in the sample data (data[0] -> channel0, data[1] -> channel1, data[2] -> channel0, etc)
// samplesPerPoint assumes this interleaving behaviour
var point = new WaveformPoint(info.Channels);
for (int j = i; j < i + samplesPerPoint; j += info.Channels)
{
// Find the maximum amplitude for each channel in the point
for (int c = 0; c < info.Channels; c++)
point.Amplitude[c] = Math.Max(point.Amplitude[c], Math.Abs(sampleBuffer[j + c]));
}
// BASS may provide unclipped samples, so clip them ourselves
for (int c = 0; c < info.Channels; c++)
point.Amplitude[c] = Math.Min(1, point.Amplitude[c]);
points.Add(point);
}
}
Bass.ChannelSetPosition(decodeStream, 0);
length = Bass.ChannelGetLength(decodeStream);
// Read FFT data
float[] bins = new float[fft_bins];
int currentPoint = 0;
long currentByte = 0;
while (length > 0)
{
length = Bass.ChannelGetData(decodeStream, bins, (int)fft_samples);
currentByte += length;
double lowIntensity = computeIntensity(info, bins, low_min, mid_min);
double midIntensity = computeIntensity(info, bins, mid_min, high_min);
double highIntensity = computeIntensity(info, bins, high_min, high_max);
// In general, the FFT function will read more data than the amount of data we have in one point
// so we'll be setting intensities for all points whose data fits into the amount read by the FFT
// We know that each data point required sampleDataPerPoint amount of data
for (; currentPoint < points.Count && currentPoint * bytesPerPoint < currentByte; currentPoint++)
{
points[currentPoint].LowIntensity = lowIntensity;
points[currentPoint].MidIntensity = midIntensity;
points[currentPoint].HighIntensity = highIntensity;
}
}
channels = info.Channels;
}, cancelSource.Token);
}
private double computeIntensity(ChannelInfo info, float[] bins, double startFrequency, double endFrequency)
{
int startBin = (int)(fft_bins * 2 * startFrequency / info.Frequency);
int endBin = (int)(fft_bins * 2 * endFrequency / info.Frequency);
startBin = MathHelper.Clamp(startBin, 0, bins.Length);
endBin = MathHelper.Clamp(endBin, 0, bins.Length);
double value = 0;
for (int i = startBin; i < endBin; i++)
value += bins[i];
return value;
}
/// <summary>
/// Creates a new <see cref="Waveform"/> containing a specific number of data points by selecting the average value of each sampled group.
/// </summary>
/// <param name="pointCount">The number of points the resulting <see cref="Waveform"/> should contain.</param>
/// <param name="cancellationToken">The token to cancel the task.</param>
/// <returns>An async task for the generation of the <see cref="Waveform"/>.</returns>
public async Task<Waveform> GenerateResampledAsync(int pointCount, CancellationToken cancellationToken = default)
{
if (pointCount < 0) throw new ArgumentOutOfRangeException(nameof(pointCount));
if (readTask == null)
return new Waveform(null);
await readTask;
return await Task.Run(() =>
{
var generatedPoints = new List<WaveformPoint>();
float pointsPerGeneratedPoint = (float)points.Count / pointCount;
// Determines at which width (relative to the resolution) our smoothing filter is truncated.
// Should not effect overall appearance much, except when the value is too small.
// A gaussian contains almost all its mass within its first 3 standard deviations,
// so a factor of 3 is a very good choice here.
const int kernel_width_factor = 3;
int kernelWidth = (int)(pointsPerGeneratedPoint * kernel_width_factor) + 1;
float[] filter = new float[kernelWidth + 1];
for (int i = 0; i < filter.Length; ++i) {
filter[i] = (float)Blur.EvalGaussian(i, pointsPerGeneratedPoint);
}
for (float i = 0; i < points.Count; i += pointsPerGeneratedPoint)
{
if (cancellationToken.IsCancellationRequested) break;
int startIndex = (int)i - kernelWidth;
int endIndex = (int)i + kernelWidth;
var point = new WaveformPoint(channels);
float totalWeight = 0;
for (int j = startIndex; j < endIndex; j++)
{
if (j < 0 || j >= points.Count) continue;
float weight = filter[Math.Abs(j - startIndex - kernelWidth)];
totalWeight += weight;
for (int c = 0; c < channels; c++)
point.Amplitude[c] += weight * points[j].Amplitude[c];
point.LowIntensity += weight * points[j].LowIntensity;
point.MidIntensity += weight * points[j].MidIntensity;
point.HighIntensity += weight * points[j].HighIntensity;
}
// Means
for (int c = 0; c < channels; c++)
point.Amplitude[c] /= totalWeight;
point.LowIntensity /= totalWeight;
point.MidIntensity /= totalWeight;
point.HighIntensity /= totalWeight;
generatedPoints.Add(point);
}
return new Waveform(null)
{
points = generatedPoints,
channels = channels
};
}, cancellationToken);
}
/// <summary>
/// Gets all the points represented by this <see cref="Waveform"/>.
/// </summary>
public List<WaveformPoint> GetPoints() => GetPointsAsync().Result;
/// <summary>
/// Gets all the points represented by this <see cref="Waveform"/>.
/// </summary>
public async Task<List<WaveformPoint>> GetPointsAsync()
{
if (readTask == null)
return points;
await readTask;
return points;
}
/// <summary>
/// Gets the number of channels represented by each <see cref="WaveformPoint"/>.
/// </summary>
public int GetChannels() => GetChannelsAsync().Result;
/// <summary>
/// Gets the number of channels represented by each <see cref="WaveformPoint"/>.
/// </summary>
public async Task<int> GetChannelsAsync()
{
if (readTask == null)
return channels;
await readTask;
return channels;
}
#region Disposal
~Waveform()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool isDisposed;
protected virtual void Dispose(bool disposing)
{
if (isDisposed)
return;
isDisposed = true;
cancelSource?.Cancel();
cancelSource?.Dispose();
points = null;
fileCallbacks?.Dispose();
fileCallbacks = null;
}
#endregion
}
/// <summary>
/// Represents a singular point of data in a <see cref="Waveform"/>.
/// </summary>
public class WaveformPoint
{
/// <summary>
/// An array of amplitudes, one for each channel.
/// </summary>
public readonly float[] Amplitude;
/// <summary>
/// Unnormalised total intensity of the low-range (bass) frequencies.
/// </summary>
public double LowIntensity;
/// <summary>
/// Unnormalised total intensity of the mid-range frequencies.
/// </summary>
public double MidIntensity;
/// <summary>
/// Unnormalised total intensity of the high-range (treble) frequencies.
/// </summary>
public double HighIntensity;
/// <summary>
/// Cconstructs a <see cref="WaveformPoint"/>.
/// </summary>
/// <param name="channels">The number of channels that contain data.</param>
public WaveformPoint(int channels)
{
Amplitude = new float[channels];
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticache-2015-02-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElastiCache.Model
{
/// <summary>
/// Represents a copy of an entire cache cluster as of the time when the snapshot was
/// taken.
/// </summary>
public partial class Snapshot
{
private bool? _autoMinorVersionUpgrade;
private DateTime? _cacheClusterCreateTime;
private string _cacheClusterId;
private string _cacheNodeType;
private string _cacheParameterGroupName;
private string _cacheSubnetGroupName;
private string _engine;
private string _engineVersion;
private List<NodeSnapshot> _nodeSnapshots = new List<NodeSnapshot>();
private int? _numCacheNodes;
private int? _port;
private string _preferredAvailabilityZone;
private string _preferredMaintenanceWindow;
private string _snapshotName;
private int? _snapshotRetentionLimit;
private string _snapshotSource;
private string _snapshotStatus;
private string _snapshotWindow;
private string _topicArn;
private string _vpcId;
/// <summary>
/// Gets and sets the property AutoMinorVersionUpgrade.
/// <para>
/// This parameter is currently disabled.
/// </para>
/// </summary>
public bool AutoMinorVersionUpgrade
{
get { return this._autoMinorVersionUpgrade.GetValueOrDefault(); }
set { this._autoMinorVersionUpgrade = value; }
}
// Check to see if AutoMinorVersionUpgrade property is set
internal bool IsSetAutoMinorVersionUpgrade()
{
return this._autoMinorVersionUpgrade.HasValue;
}
/// <summary>
/// Gets and sets the property CacheClusterCreateTime.
/// <para>
/// The date and time when the source cache cluster was created.
/// </para>
/// </summary>
public DateTime CacheClusterCreateTime
{
get { return this._cacheClusterCreateTime.GetValueOrDefault(); }
set { this._cacheClusterCreateTime = value; }
}
// Check to see if CacheClusterCreateTime property is set
internal bool IsSetCacheClusterCreateTime()
{
return this._cacheClusterCreateTime.HasValue;
}
/// <summary>
/// Gets and sets the property CacheClusterId.
/// <para>
/// The user-supplied identifier of the source cache cluster.
/// </para>
/// </summary>
public string CacheClusterId
{
get { return this._cacheClusterId; }
set { this._cacheClusterId = value; }
}
// Check to see if CacheClusterId property is set
internal bool IsSetCacheClusterId()
{
return this._cacheClusterId != null;
}
/// <summary>
/// Gets and sets the property CacheNodeType.
/// <para>
/// The name of the compute and memory capacity node type for the source cache cluster.
/// </para>
///
/// <para>
/// Valid node types are as follows:
/// </para>
/// <ul> <li>General purpose: <ul> <li>Current generation: <code>cache.t2.micro</code>,
/// <code>cache.t2.small</code>, <code>cache.t2.medium</code>, <code>cache.m3.medium</code>,
/// <code>cache.m3.large</code>, <code>cache.m3.xlarge</code>, <code>cache.m3.2xlarge</code></li>
/// <li>Previous generation: <code>cache.t1.micro</code>, <code>cache.m1.small</code>,
/// <code>cache.m1.medium</code>, <code>cache.m1.large</code>, <code>cache.m1.xlarge</code></li>
/// </ul></li> <li>Compute optimized: <code>cache.c1.xlarge</code></li> <li>Memory optimized
/// <ul> <li>Current generation: <code>cache.r3.large</code>, <code>cache.r3.xlarge</code>,
/// <code>cache.r3.2xlarge</code>, <code>cache.r3.4xlarge</code>, <code>cache.r3.8xlarge</code></li>
/// <li>Previous generation: <code>cache.m2.xlarge</code>, <code>cache.m2.2xlarge</code>,
/// <code>cache.m2.4xlarge</code></li> </ul></li> </ul>
/// <para>
/// <b>Notes:</b>
/// </para>
/// <ul> <li>All t2 instances are created in an Amazon Virtual Private Cloud (VPC).</li>
/// <li>Redis backup/restore is not supported for t2 instances.</li> <li>Redis Append-only
/// files (AOF) functionality is not supported for t1 or t2 instances.</li> </ul>
/// <para>
/// For a complete listing of cache node types and specifications, see <a href="http://aws.amazon.com/elasticache/details">Amazon
/// ElastiCache Product Features and Details</a> and <a href="http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Memcached.html#CacheParameterGroups.Memcached.NodeSpecific">Cache
/// Node Type-Specific Parameters for Memcached</a> or <a href="http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Redis.html#CacheParameterGroups.Redis.NodeSpecific">Cache
/// Node Type-Specific Parameters for Redis</a>.
/// </para>
/// </summary>
public string CacheNodeType
{
get { return this._cacheNodeType; }
set { this._cacheNodeType = value; }
}
// Check to see if CacheNodeType property is set
internal bool IsSetCacheNodeType()
{
return this._cacheNodeType != null;
}
/// <summary>
/// Gets and sets the property CacheParameterGroupName.
/// <para>
/// The cache parameter group that is associated with the source cache cluster.
/// </para>
/// </summary>
public string CacheParameterGroupName
{
get { return this._cacheParameterGroupName; }
set { this._cacheParameterGroupName = value; }
}
// Check to see if CacheParameterGroupName property is set
internal bool IsSetCacheParameterGroupName()
{
return this._cacheParameterGroupName != null;
}
/// <summary>
/// Gets and sets the property CacheSubnetGroupName.
/// <para>
/// The name of the cache subnet group associated with the source cache cluster.
/// </para>
/// </summary>
public string CacheSubnetGroupName
{
get { return this._cacheSubnetGroupName; }
set { this._cacheSubnetGroupName = value; }
}
// Check to see if CacheSubnetGroupName property is set
internal bool IsSetCacheSubnetGroupName()
{
return this._cacheSubnetGroupName != null;
}
/// <summary>
/// Gets and sets the property Engine.
/// <para>
/// The name of the cache engine (<i>memcached</i> or <i>redis</i>) used by the source
/// cache cluster.
/// </para>
/// </summary>
public string Engine
{
get { return this._engine; }
set { this._engine = value; }
}
// Check to see if Engine property is set
internal bool IsSetEngine()
{
return this._engine != null;
}
/// <summary>
/// Gets and sets the property EngineVersion.
/// <para>
/// The version of the cache engine version that is used by the source cache cluster.
/// </para>
/// </summary>
public string EngineVersion
{
get { return this._engineVersion; }
set { this._engineVersion = value; }
}
// Check to see if EngineVersion property is set
internal bool IsSetEngineVersion()
{
return this._engineVersion != null;
}
/// <summary>
/// Gets and sets the property NodeSnapshots.
/// <para>
/// A list of the cache nodes in the source cache cluster.
/// </para>
/// </summary>
public List<NodeSnapshot> NodeSnapshots
{
get { return this._nodeSnapshots; }
set { this._nodeSnapshots = value; }
}
// Check to see if NodeSnapshots property is set
internal bool IsSetNodeSnapshots()
{
return this._nodeSnapshots != null && this._nodeSnapshots.Count > 0;
}
/// <summary>
/// Gets and sets the property NumCacheNodes.
/// <para>
/// The number of cache nodes in the source cache cluster.
/// </para>
///
/// <para>
/// For clusters running Redis, this value must be 1. For clusters running Memcached,
/// this value must be between 1 and 20.
/// </para>
/// </summary>
public int NumCacheNodes
{
get { return this._numCacheNodes.GetValueOrDefault(); }
set { this._numCacheNodes = value; }
}
// Check to see if NumCacheNodes property is set
internal bool IsSetNumCacheNodes()
{
return this._numCacheNodes.HasValue;
}
/// <summary>
/// Gets and sets the property Port.
/// <para>
/// The port number used by each cache nodes in the source cache cluster.
/// </para>
/// </summary>
public int Port
{
get { return this._port.GetValueOrDefault(); }
set { this._port = value; }
}
// Check to see if Port property is set
internal bool IsSetPort()
{
return this._port.HasValue;
}
/// <summary>
/// Gets and sets the property PreferredAvailabilityZone.
/// <para>
/// The name of the Availability Zone in which the source cache cluster is located.
/// </para>
/// </summary>
public string PreferredAvailabilityZone
{
get { return this._preferredAvailabilityZone; }
set { this._preferredAvailabilityZone = value; }
}
// Check to see if PreferredAvailabilityZone property is set
internal bool IsSetPreferredAvailabilityZone()
{
return this._preferredAvailabilityZone != null;
}
/// <summary>
/// Gets and sets the property PreferredMaintenanceWindow.
/// <para>
/// Specifies the weekly time range during which maintenance on the cache cluster is performed.
/// It is specified as a range in the format ddd:hh24:mi-ddd:hh24:mi (24H Clock UTC).
/// The minimum maintenance window is a 60 minute period. Valid values for <code>ddd</code>
/// are:
/// </para>
/// <ul> <li><code>sun</code></li> <li><code>mon</code></li> <li><code>tue</code></li>
/// <li><code>wed</code></li> <li><code>thu</code></li> <li><code>fri</code></li> <li><code>sat</code></li>
/// </ul>
/// <para>
/// Example: <code>sun:05:00-sun:09:00</code>
/// </para>
/// </summary>
public string PreferredMaintenanceWindow
{
get { return this._preferredMaintenanceWindow; }
set { this._preferredMaintenanceWindow = value; }
}
// Check to see if PreferredMaintenanceWindow property is set
internal bool IsSetPreferredMaintenanceWindow()
{
return this._preferredMaintenanceWindow != null;
}
/// <summary>
/// Gets and sets the property SnapshotName.
/// <para>
/// The name of a snapshot. For an automatic snapshot, the name is system-generated; for
/// a manual snapshot, this is the user-provided name.
/// </para>
/// </summary>
public string SnapshotName
{
get { return this._snapshotName; }
set { this._snapshotName = value; }
}
// Check to see if SnapshotName property is set
internal bool IsSetSnapshotName()
{
return this._snapshotName != null;
}
/// <summary>
/// Gets and sets the property SnapshotRetentionLimit.
/// <para>
/// For an automatic snapshot, the number of days for which ElastiCache will retain the
/// snapshot before deleting it.
/// </para>
///
/// <para>
/// For manual snapshots, this field reflects the <i>SnapshotRetentionLimit</i> for the
/// source cache cluster when the snapshot was created. This field is otherwise ignored:
/// Manual snapshots do not expire, and can only be deleted using the <i>DeleteSnapshot</i>
/// action.
/// </para>
///
/// <para>
/// <b>Important</b>If the value of SnapshotRetentionLimit is set to zero (0), backups
/// are turned off.
/// </para>
/// </summary>
public int SnapshotRetentionLimit
{
get { return this._snapshotRetentionLimit.GetValueOrDefault(); }
set { this._snapshotRetentionLimit = value; }
}
// Check to see if SnapshotRetentionLimit property is set
internal bool IsSetSnapshotRetentionLimit()
{
return this._snapshotRetentionLimit.HasValue;
}
/// <summary>
/// Gets and sets the property SnapshotSource.
/// <para>
/// Indicates whether the snapshot is from an automatic backup (<code>automated</code>)
/// or was created manually (<code>manual</code>).
/// </para>
/// </summary>
public string SnapshotSource
{
get { return this._snapshotSource; }
set { this._snapshotSource = value; }
}
// Check to see if SnapshotSource property is set
internal bool IsSetSnapshotSource()
{
return this._snapshotSource != null;
}
/// <summary>
/// Gets and sets the property SnapshotStatus.
/// <para>
/// The status of the snapshot. Valid values: <code>creating</code> | <code>available</code>
/// | <code>restoring</code> | <code>copying</code> | <code>deleting</code>.
/// </para>
/// </summary>
public string SnapshotStatus
{
get { return this._snapshotStatus; }
set { this._snapshotStatus = value; }
}
// Check to see if SnapshotStatus property is set
internal bool IsSetSnapshotStatus()
{
return this._snapshotStatus != null;
}
/// <summary>
/// Gets and sets the property SnapshotWindow.
/// <para>
/// The daily time range during which ElastiCache takes daily snapshots of the source
/// cache cluster.
/// </para>
/// </summary>
public string SnapshotWindow
{
get { return this._snapshotWindow; }
set { this._snapshotWindow = value; }
}
// Check to see if SnapshotWindow property is set
internal bool IsSetSnapshotWindow()
{
return this._snapshotWindow != null;
}
/// <summary>
/// Gets and sets the property TopicArn.
/// <para>
/// The Amazon Resource Name (ARN) for the topic used by the source cache cluster for
/// publishing notifications.
/// </para>
/// </summary>
public string TopicArn
{
get { return this._topicArn; }
set { this._topicArn = value; }
}
// Check to see if TopicArn property is set
internal bool IsSetTopicArn()
{
return this._topicArn != null;
}
/// <summary>
/// Gets and sets the property VpcId.
/// <para>
/// The Amazon Virtual Private Cloud identifier (VPC ID) of the cache subnet group for
/// the source cache cluster.
/// </para>
/// </summary>
public string VpcId
{
get { return this._vpcId; }
set { this._vpcId = value; }
}
// Check to see if VpcId property is set
internal bool IsSetVpcId()
{
return this._vpcId != null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
using Internal.Runtime.Augments;
using Internal.Runtime.TypeLoader;
using Internal.Runtime.CompilerServices;
using Internal.NativeFormat;
using Internal.TypeSystem;
using Internal.TypeSystem.NativeFormat;
using Internal.TypeSystem.NoMetadata;
namespace Internal.Runtime.TypeLoader
{
public abstract class GenericDictionaryCell
{
abstract internal void Prepare(TypeBuilder builder);
abstract internal IntPtr Create(TypeBuilder builder);
virtual internal IntPtr CreateLazyLookupCell(TypeBuilder builder, out IntPtr auxResult)
{
auxResult = IntPtr.Zero;
return Create(builder);
}
// Helper method for nullable transform. Ideally, we would do the nullable transform upfront before
// the types is build. Unfortunately, there does not seem to be easy way to test for Nullable<> type definition
// without introducing type builder recursion
private static RuntimeTypeHandle GetRuntimeTypeHandleWithNullableTransform(TypeBuilder builder, TypeDesc type)
{
RuntimeTypeHandle th = builder.GetRuntimeTypeHandle(type);
if (RuntimeAugments.IsNullable(th))
th = builder.GetRuntimeTypeHandle(((DefType)type).Instantiation[0]);
return th;
}
public static GenericDictionaryCell CreateTypeHandleCell(TypeDesc type)
{
TypeHandleCell typeCell = new TypeHandleCell();
typeCell.Type = type;
return typeCell;
}
private class TypeHandleCell : GenericDictionaryCell
{
internal TypeDesc Type;
override internal void Prepare(TypeBuilder builder)
{
if (Type.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Canonical types do not have EETypes");
builder.RegisterForPreparation(Type);
}
override internal IntPtr Create(TypeBuilder builder)
{
return builder.GetRuntimeTypeHandle(Type).ToIntPtr();
}
}
private class UnwrapNullableTypeCell : GenericDictionaryCell
{
internal DefType Type;
override internal void Prepare(TypeBuilder builder)
{
if (Type.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Canonical types do not have EETypes");
if (Type.IsNullable)
{
Debug.Assert(Type.Instantiation.Length == 1);
builder.RegisterForPreparation(Type.Instantiation[0]);
}
else
builder.RegisterForPreparation(Type);
}
override internal IntPtr Create(TypeBuilder builder)
{
if (Type.IsNullable)
return builder.GetRuntimeTypeHandle(Type.Instantiation[0]).ToIntPtr();
else
return builder.GetRuntimeTypeHandle(Type).ToIntPtr();
}
}
private class InterfaceCallCell : GenericDictionaryCell
{
internal TypeDesc InterfaceType;
internal int Slot;
override internal void Prepare(TypeBuilder builder)
{
if (InterfaceType.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Unable to compute call information for a canonical interface");
builder.RegisterForPreparation(InterfaceType);
}
override internal IntPtr Create(TypeBuilder builder)
{
return RuntimeAugments.NewInterfaceDispatchCell(builder.GetRuntimeTypeHandle(InterfaceType), Slot);
}
}
/// <summary>
/// Used for non-generic Direct Call Constrained Methods
/// </summary>
private class NonGenericDirectConstrainedMethodCell : GenericDictionaryCell
{
internal TypeDesc ConstraintType;
internal TypeDesc ConstrainedMethodType;
internal int ConstrainedMethodSlot;
override internal void Prepare(TypeBuilder builder)
{
if (ConstraintType.IsCanonicalSubtype(CanonicalFormKind.Any) || ConstrainedMethodType.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Unable to compute call information for a canonical type/method.");
builder.RegisterForPreparation(ConstraintType);
builder.RegisterForPreparation(ConstrainedMethodType);
}
override internal IntPtr Create(TypeBuilder builder)
{
return ConstrainedCallSupport.NonGenericConstrainedCallDesc.GetDirectConstrainedCallPtr(builder.GetRuntimeTypeHandle(ConstraintType),
builder.GetRuntimeTypeHandle(ConstrainedMethodType),
ConstrainedMethodSlot);
}
}
/// <summary>
/// Used for non-generic Constrained Methods
/// </summary>
private class NonGenericConstrainedMethodCell : GenericDictionaryCell
{
internal TypeDesc ConstraintType;
internal TypeDesc ConstrainedMethodType;
internal int ConstrainedMethodSlot;
override internal void Prepare(TypeBuilder builder)
{
if (ConstraintType.IsCanonicalSubtype(CanonicalFormKind.Any) || ConstrainedMethodType.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Unable to compute call information for a canonical type/method.");
builder.RegisterForPreparation(ConstraintType);
builder.RegisterForPreparation(ConstrainedMethodType);
}
override internal IntPtr Create(TypeBuilder builder)
{
return ConstrainedCallSupport.NonGenericConstrainedCallDesc.Get(builder.GetRuntimeTypeHandle(ConstraintType),
builder.GetRuntimeTypeHandle(ConstrainedMethodType),
ConstrainedMethodSlot);
}
}
/// <summary>
/// Used for generic Constrained Methods
/// </summary>
private class GenericConstrainedMethodCell : GenericDictionaryCell
{
internal TypeDesc ConstraintType;
internal MethodDesc ConstrainedMethod;
internal IntPtr MethodName;
internal RuntimeSignature MethodSignature;
override internal void Prepare(TypeBuilder builder)
{
if (ConstraintType.IsCanonicalSubtype(CanonicalFormKind.Any) || ConstrainedMethod.IsCanonicalMethod(CanonicalFormKind.Any))
Environment.FailFast("Unable to compute call information for a canonical type/method.");
builder.RegisterForPreparation(ConstraintType);
// Do not use builder.PrepareMethod here. That
// would prepare the dictionary for the method,
// and if the method is abstract, there is no
// dictionary. Also, the dictionary is not necessary
// to create the ldtoken.
builder.RegisterForPreparation(ConstrainedMethod.OwningType);
foreach (var type in ConstrainedMethod.Instantiation)
builder.RegisterForPreparation(type);
}
override internal IntPtr Create(TypeBuilder builder)
{
RuntimeMethodHandle rmh = TypeLoaderEnvironment.Instance.GetRuntimeMethodHandleForComponents(
builder.GetRuntimeTypeHandle(ConstrainedMethod.OwningType),
MethodName,
MethodSignature,
builder.GetRuntimeTypeHandles(ConstrainedMethod.Instantiation));
return ConstrainedCallSupport.GenericConstrainedCallDesc.Get(builder.GetRuntimeTypeHandle(ConstraintType), rmh);
}
}
private class StaticDataCell : GenericDictionaryCell
{
internal StaticDataKind DataKind;
internal TypeDesc Type;
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
internal bool Direct; // Set this flag if a direct pointer to the static data is requested
// otherwise, an extra indirection will be inserted
#endif
override internal void Prepare(TypeBuilder builder)
{
if (Type.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Unable to compute static field locations for a canonical type.");
builder.RegisterForPreparation(Type);
}
override internal IntPtr Create(TypeBuilder builder)
{
RuntimeTypeHandle typeHandle = builder.GetRuntimeTypeHandle(Type);
switch (DataKind)
{
case StaticDataKind.NonGc:
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
if (Direct)
{
return TypeLoaderEnvironment.Instance.TryGetNonGcStaticFieldDataDirect(typeHandle);
}
else
#endif
{
return TypeLoaderEnvironment.Instance.TryGetNonGcStaticFieldData(typeHandle);
}
case StaticDataKind.Gc:
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
if (Direct)
{
return TypeLoaderEnvironment.Instance.TryGetGcStaticFieldDataDirect(typeHandle);
}
else
#endif
{
return TypeLoaderEnvironment.Instance.TryGetGcStaticFieldData(typeHandle);
}
default:
Debug.Assert(false);
return IntPtr.Zero;
}
}
override internal unsafe IntPtr CreateLazyLookupCell(TypeBuilder builder, out IntPtr auxResult)
{
auxResult = IntPtr.Zero;
return *(IntPtr*)Create(builder);
}
}
private class MethodDictionaryCell : GenericDictionaryCell
{
internal InstantiatedMethod GenericMethod;
internal unsafe override void Prepare(TypeBuilder builder)
{
if (GenericMethod.IsCanonicalMethod(CanonicalFormKind.Any))
Environment.FailFast("Method dictionaries of canonical methods do not exist");
builder.PrepareMethod(GenericMethod);
}
internal override IntPtr Create(TypeBuilder builder)
{
// TODO (USG): What if this method's instantiation is a non-shareable one (from a normal canonical
// perspective) and there's an exact method pointer for the method in question, do we still
// construct a method dictionary to be used with the universal canonical method implementation?
Debug.Assert(GenericMethod.RuntimeMethodDictionary != IntPtr.Zero);
return GenericMethod.RuntimeMethodDictionary;
}
}
private class FieldLdTokenCell : GenericDictionaryCell
{
internal TypeDesc ContainingType;
internal IntPtr FieldName;
internal unsafe override void Prepare(TypeBuilder builder)
{
if (ContainingType.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Ldtoken is not permitted for a canonical field");
builder.RegisterForPreparation(ContainingType);
}
internal override unsafe IntPtr Create(TypeBuilder builder)
{
RuntimeFieldHandle handle = TypeLoaderEnvironment.Instance.GetRuntimeFieldHandleForComponents(
builder.GetRuntimeTypeHandle(ContainingType),
FieldName);
return *(IntPtr*)&handle;
}
}
private class MethodLdTokenCell : GenericDictionaryCell
{
internal MethodDesc Method;
internal IntPtr MethodName;
internal RuntimeSignature MethodSignature;
internal unsafe override void Prepare(TypeBuilder builder)
{
if (Method.IsCanonicalMethod(CanonicalFormKind.Any))
Environment.FailFast("Ldtoken is not permitted for a canonical method");
// Do not use builder.PrepareMethod here. That
// would prepare the dictionary for the method,
// and if the method is abstract, there is no
// dictionary. Also, the dictionary is not necessary
// to create the ldtoken.
builder.RegisterForPreparation(Method.OwningType);
foreach (var type in Method.Instantiation)
builder.RegisterForPreparation(type);
}
internal override unsafe IntPtr Create(TypeBuilder builder)
{
RuntimeMethodHandle handle = TypeLoaderEnvironment.Instance.GetRuntimeMethodHandleForComponents(
builder.GetRuntimeTypeHandle(Method.OwningType),
MethodName,
MethodSignature,
builder.GetRuntimeTypeHandles(Method.Instantiation));
return *(IntPtr*)&handle;
}
}
private class TypeSizeCell : GenericDictionaryCell
{
internal TypeDesc Type;
internal override void Prepare(TypeBuilder builder)
{
if (Type.IsCanonicalSubtype(CanonicalFormKind.Universal))
Environment.FailFast("Universal shared generics do not have a defined size");
builder.RegisterForPreparation(Type);
}
internal override IntPtr Create(TypeBuilder builder)
{
if (Type.IsValueType)
return (IntPtr)RuntimeAugments.GetValueTypeSize(builder.GetRuntimeTypeHandle(Type));
else
return (IntPtr)IntPtr.Size;
}
}
private class FieldOffsetCell : GenericDictionaryCell
{
internal DefType ContainingType;
internal uint Ordinal;
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
internal FieldDesc Field;
#endif
internal int Offset;
internal unsafe override void Prepare(TypeBuilder builder)
{
if (ContainingType.IsCanonicalSubtype(CanonicalFormKind.Universal))
Environment.FailFast("Universal shared generics do not have a defined size");
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
if (Field != null)
Offset = Field.Offset;
else
#endif
Offset = ContainingType.GetFieldByNativeLayoutOrdinal(Ordinal).Offset;
}
internal override unsafe IntPtr Create(TypeBuilder builder)
{
return (IntPtr)Offset;
}
}
private class VTableOffsetCell : GenericDictionaryCell
{
internal TypeDesc ContainingType;
internal uint VTableSlot;
internal unsafe override void Prepare(TypeBuilder builder)
{
builder.RegisterForPreparation(ContainingType);
}
internal override unsafe IntPtr Create(TypeBuilder builder)
{
// Debug sanity check for the size of the EEType structure
// just to ensure nothing of it gets reduced
#if EETYPE_TYPE_MANAGER
Debug.Assert(sizeof(EEType) == (IntPtr.Size == 8 ? 32 : 24));
#else
Debug.Assert(sizeof(EEType) == (IntPtr.Size == 8 ? 24 : 20));
#endif
int result = (int)VTableSlot;
DefType currentType = (DefType)ContainingType;
while (currentType != null)
{
if (currentType.HasInstantiation)
{
// Check if the current type can share code with normal canonical
// generic types. If not, then the vtable layout will not have a
// slot for a dictionary pointer, and we need to adjust the slot number
if (!currentType.CanShareNormalGenericCode())
result--;
}
currentType = currentType.BaseType;
}
Debug.Assert(result >= 0);
return (IntPtr)(sizeof(EEType) + result * IntPtr.Size);
}
}
private class AllocateObjectCell : GenericDictionaryCell
{
internal TypeDesc Type;
override internal void Prepare(TypeBuilder builder)
{
if (Type.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Canonical types cannot be allocated");
builder.RegisterForPreparation(Type);
}
override internal IntPtr Create(TypeBuilder builder)
{
RuntimeTypeHandle th = GetRuntimeTypeHandleWithNullableTransform(builder, Type);
return RuntimeAugments.GetAllocateObjectHelperForType(th);
}
override internal unsafe IntPtr CreateLazyLookupCell(TypeBuilder builder, out IntPtr auxResult)
{
RuntimeTypeHandle th = GetRuntimeTypeHandleWithNullableTransform(builder, Type);
auxResult = th.ToIntPtr();
return *(IntPtr*)RuntimeAugments.GetAllocateObjectHelperForType(th);
}
}
private class DefaultConstructorCell : GenericDictionaryCell
{
internal TypeDesc Type;
override internal void Prepare(TypeBuilder builder)
{
builder.RegisterForPreparation(Type);
}
override internal IntPtr Create(TypeBuilder builder)
{
IntPtr result = TypeLoaderEnvironment.Instance.TryGetDefaultConstructorForType(Type);
if (result == IntPtr.Zero)
result = RuntimeAugments.GetFallbackDefaultConstructor();
return result;
}
}
private class TlsIndexCell : GenericDictionaryCell
{
internal TypeDesc Type;
override internal void Prepare(TypeBuilder builder)
{
if (Type.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Unable to compute static field locations for a canonical type.");
builder.RegisterForPreparation(Type);
}
override unsafe internal IntPtr Create(TypeBuilder builder)
{
return TypeLoaderEnvironment.Instance.TryGetTlsIndexDictionaryCellForType(builder.GetRuntimeTypeHandle(Type));
}
}
private class TlsOffsetCell : GenericDictionaryCell
{
internal TypeDesc Type;
override internal void Prepare(TypeBuilder builder)
{
if (Type.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Unable to compute static field locations for a canonical type.");
builder.RegisterForPreparation(Type);
}
override unsafe internal IntPtr Create(TypeBuilder builder)
{
return TypeLoaderEnvironment.Instance.TryGetTlsOffsetDictionaryCellForType(builder.GetRuntimeTypeHandle(Type));
}
}
public static GenericDictionaryCell CreateIntPtrCell(IntPtr ptrValue)
{
IntPtrCell typeCell = new IntPtrCell();
typeCell.Value = ptrValue;
return typeCell;
}
private class IntPtrCell : GenericDictionaryCell
{
internal IntPtr Value;
internal unsafe override void Prepare(TypeBuilder builder)
{
}
internal unsafe override IntPtr Create(TypeBuilder builder)
{
return Value;
}
}
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
public static GenericDictionaryCell CreateExactCallableMethodCell(MethodDesc method)
{
MethodCell methodCell = new MethodCell();
methodCell.Method = method;
if (!RuntimeSignatureHelper.TryCreate(method, out methodCell.MethodSignature))
{
Environment.FailFast("Unable to create method signature, for method reloc");
}
methodCell.ExactCallableAddressNeeded = true;
return methodCell;
}
#endif
private class MethodCell : GenericDictionaryCell
{
internal MethodDesc Method;
internal RuntimeSignature MethodSignature;
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
internal bool ExactCallableAddressNeeded;
#endif
private bool _universalCanonImplementationOfCanonMethod;
private MethodDesc _methodToUseForInstantiatingParameters;
private IntPtr _exactFunctionPointer;
internal unsafe override void Prepare(TypeBuilder builder)
{
_methodToUseForInstantiatingParameters = Method;
IntPtr exactFunctionPointer;
bool canUseRetrieveExactFunctionPointerIfPossible = false;
// RetrieveExactFunctionPointerIfPossible always gets the unboxing stub if possible
if (Method.UnboxingStub)
canUseRetrieveExactFunctionPointerIfPossible = true;
else if (!Method.OwningType.IsValueType) // If the owning type isn't a valuetype, concerns about unboxing stubs are moot
canUseRetrieveExactFunctionPointerIfPossible = true;
else if (TypeLoaderEnvironment.Instance.IsStaticMethodSignature(MethodSignature)) // Static methods don't have unboxing stub concerns
canUseRetrieveExactFunctionPointerIfPossible = true;
if (canUseRetrieveExactFunctionPointerIfPossible &&
builder.RetrieveExactFunctionPointerIfPossible(Method, out exactFunctionPointer))
{
// If we succeed in finding a non-shareable function pointer for this method, it means
// that we found a method body for it that was statically compiled. We'll use that body
// instead of the universal canonical method pointer
Debug.Assert(exactFunctionPointer != IntPtr.Zero &&
exactFunctionPointer != Method.FunctionPointer &&
exactFunctionPointer != Method.UsgFunctionPointer);
_exactFunctionPointer = exactFunctionPointer;
}
else
{
// There is no exact function pointer available. This means that we'll have to
// build a method dictionary for the method instantiation, and use the shared canonical
// function pointer that was parsed from native layout.
_exactFunctionPointer = IntPtr.Zero;
builder.PrepareMethod(Method);
// Check whether we have already resolved a canonical or universal match
IntPtr addressToUse;
TypeLoaderEnvironment.MethodAddressType foundAddressType;
if (Method.FunctionPointer != IntPtr.Zero)
{
addressToUse = Method.FunctionPointer;
foundAddressType = TypeLoaderEnvironment.MethodAddressType.Canonical;
}
else if (Method.UsgFunctionPointer != IntPtr.Zero)
{
addressToUse = Method.UsgFunctionPointer;
foundAddressType = TypeLoaderEnvironment.MethodAddressType.UniversalCanonical;
}
else
{
// No previous match, new lookup is needed
IntPtr fnptr;
IntPtr unboxingStub;
MethodDesc searchMethod = Method;
if (Method.UnboxingStub)
{
// Find the function that isn't an unboxing stub, note the first parameter which is false
searchMethod = searchMethod.Context.ResolveGenericMethodInstantiation(false, (DefType)Method.OwningType, Method.NameAndSignature, Method.Instantiation, IntPtr.Zero, false);
}
if (!TypeLoaderEnvironment.TryGetMethodAddressFromMethodDesc(searchMethod, out fnptr, out unboxingStub, out foundAddressType))
{
Environment.FailFast("Unable to find method address for method:" + Method.ToString());
}
if (Method.UnboxingStub)
{
addressToUse = unboxingStub;
}
else
{
addressToUse = fnptr;
}
if (foundAddressType == TypeLoaderEnvironment.MethodAddressType.Canonical ||
foundAddressType == TypeLoaderEnvironment.MethodAddressType.UniversalCanonical)
{
// Cache the resolved canonical / universal pointer in the MethodDesc
// Actually it would simplify matters here if the MethodDesc held just one pointer
// and the lookup type enumeration value.
Method.SetFunctionPointer(
addressToUse,
foundAddressType == TypeLoaderEnvironment.MethodAddressType.UniversalCanonical);
}
}
// Look at the resolution type and check whether we can set up the ExactFunctionPointer upfront
switch (foundAddressType)
{
case TypeLoaderEnvironment.MethodAddressType.Exact:
_exactFunctionPointer = addressToUse;
break;
case TypeLoaderEnvironment.MethodAddressType.Canonical:
{
bool methodRequestedIsCanonical = Method.IsCanonicalMethod(CanonicalFormKind.Specific);
bool requestedMethodNeedsDictionaryWhenCalledAsCanonical = NeedsDictionaryParameterToCallCanonicalVersion(Method);
if (!requestedMethodNeedsDictionaryWhenCalledAsCanonical || methodRequestedIsCanonical)
{
_exactFunctionPointer = addressToUse;
}
break;
}
case TypeLoaderEnvironment.MethodAddressType.UniversalCanonical:
{
if (Method.IsCanonicalMethod(CanonicalFormKind.Specific) &&
!NeedsDictionaryParameterToCallCanonicalVersion(Method) &&
!TypeLoaderEnvironment.MethodSignatureHasVarsNeedingCallingConventionConverter_MethodSignature(
Method.GetTypicalMethodDefinition().Signature))
{
_exactFunctionPointer = addressToUse;
}
break;
}
default:
Environment.FailFast("Unexpected method address type");
return;
}
if (_exactFunctionPointer == IntPtr.Zero)
{
// We have exhausted exact resolution options so we must resort to calling
// convention conversion. Prepare the type parameters of the method so that
// the calling convention converter can have RuntimeTypeHandle's to work with.
// For canonical methods, convert paramters to their CanonAlike form
// as the Canonical RuntimeTypeHandle's are not permitted to exist.
Debug.Assert(!Method.IsCanonicalMethod(CanonicalFormKind.Universal));
bool methodRequestedIsCanonical = Method.IsCanonicalMethod(CanonicalFormKind.Specific);
MethodDesc canonAlikeForm;
if (methodRequestedIsCanonical)
{
canonAlikeForm = Method.ReplaceTypesInConstructionOfMethod(Method.Context.CanonTypeArray, Method.Context.CanonAlikeTypeArray);
}
else
{
canonAlikeForm = Method;
}
foreach (TypeDesc t in canonAlikeForm.Instantiation)
{
builder.PrepareType(t);
}
foreach (TypeDesc t in canonAlikeForm.OwningType.Instantiation)
{
builder.PrepareType(t);
}
if (!(Method.GetTypicalMethodDefinition() is RuntimeMethodDesc))
{
// Also, prepare all of the argument types as will be needed by the calling convention converter
MethodSignature signature = canonAlikeForm.Signature;
for (int i = 0; i < signature.Length; i++)
{
TypeDesc t = signature[i];
if (t is ByRefType)
builder.PrepareType(((ByRefType)t).ParameterType);
else
builder.PrepareType(t);
}
if (signature.ReturnType is ByRefType)
builder.PrepareType((ByRefType)signature.ReturnType);
else
builder.PrepareType(signature.ReturnType);
}
_universalCanonImplementationOfCanonMethod = methodRequestedIsCanonical;
_methodToUseForInstantiatingParameters = canonAlikeForm;
}
}
// By the time we reach here, we should always have a function pointer of some form
Debug.Assert((_exactFunctionPointer != IntPtr.Zero) || (Method.FunctionPointer != IntPtr.Zero) || (Method.UsgFunctionPointer != IntPtr.Zero));
}
private bool NeedsDictionaryParameterToCallCanonicalVersion(MethodDesc method)
{
if (Method.HasInstantiation)
return true;
if (!Method.OwningType.HasInstantiation)
return false;
if (Method is NoMetadataMethodDesc)
{
// If the method does not have metadata, use the NameAndSignature property which should work in that case.
if (!TypeLoaderEnvironment.Instance.IsStaticMethodSignature(Method.NameAndSignature.Signature))
return false;
}
else
{
// Otherwise, use the MethodSignature
if (!Method.Signature.IsStatic)
return false;
}
return true;
}
internal unsafe override IntPtr Create(TypeBuilder builder)
{
if (_exactFunctionPointer != IntPtr.Zero)
{
// We are done... we don't need to create any unboxing stubs or calling convertion translation
// thunks for exact non-shareable method instantiations
return _exactFunctionPointer;
}
Debug.Assert(Method.Instantiation.Length > 0 || Method.OwningType.HasInstantiation);
IntPtr methodDictionary = IntPtr.Zero;
if (!_universalCanonImplementationOfCanonMethod)
{
methodDictionary = Method.Instantiation.Length > 0 ?
((InstantiatedMethod)Method).RuntimeMethodDictionary :
builder.GetRuntimeTypeHandle(Method.OwningType).ToIntPtr();
}
if (Method.FunctionPointer != IntPtr.Zero)
{
if (Method.Instantiation.Length > 0 || TypeLoaderEnvironment.Instance.IsStaticMethodSignature(MethodSignature))
{
Debug.Assert(methodDictionary != IntPtr.Zero);
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
if (this.ExactCallableAddressNeeded)
{
// In this case we need to build an instantiating stub
return BuildCallingConventionConverter(builder, Method.FunctionPointer, methodDictionary, false);
}
else
#endif
{
return FunctionPointerOps.GetGenericMethodFunctionPointer(Method.FunctionPointer, methodDictionary);
}
}
else
{
return Method.FunctionPointer;
}
}
else if (Method.UsgFunctionPointer != IntPtr.Zero)
{
return BuildCallingConventionConverter(builder, Method.UsgFunctionPointer, methodDictionary, true);
}
Debug.Assert(false, "UNREACHABLE");
return IntPtr.Zero;
}
private IntPtr BuildCallingConventionConverter(TypeBuilder builder, IntPtr pointerToUse, IntPtr dictionary, bool usgConverter)
{
RuntimeTypeHandle[] typeArgs = Empty<RuntimeTypeHandle>.Array;
RuntimeTypeHandle[] methodArgs = Empty<RuntimeTypeHandle>.Array;
typeArgs = builder.GetRuntimeTypeHandles(_methodToUseForInstantiatingParameters.OwningType.Instantiation);
bool containingTypeIsValueType = _methodToUseForInstantiatingParameters.OwningType.IsValueType;
bool genericMethod = (_methodToUseForInstantiatingParameters.Instantiation.Length > 0);
methodArgs = builder.GetRuntimeTypeHandles(_methodToUseForInstantiatingParameters.Instantiation);
Debug.Assert(!MethodSignature.IsNativeLayoutSignature || (MethodSignature.NativeLayoutSignature() != IntPtr.Zero));
CallConverterThunk.ThunkKind thunkKind;
if (usgConverter)
{
if (genericMethod || containingTypeIsValueType)
{
if (dictionary == IntPtr.Zero)
thunkKind = CallConverterThunk.ThunkKind.StandardToGenericPassthruInstantiating;
else
thunkKind = CallConverterThunk.ThunkKind.StandardToGenericInstantiating;
}
else
{
if (dictionary == IntPtr.Zero)
thunkKind = CallConverterThunk.ThunkKind.StandardToGenericPassthruInstantiatingIfNotHasThis;
else
thunkKind = CallConverterThunk.ThunkKind.StandardToGenericInstantiatingIfNotHasThis;
}
}
else
{
thunkKind = CallConverterThunk.ThunkKind.StandardToStandardInstantiating;
}
IntPtr thunkPtr = CallConverterThunk.MakeThunk(
thunkKind,
Method.UsgFunctionPointer,
MethodSignature,
dictionary,
typeArgs,
methodArgs);
Debug.Assert(thunkPtr != IntPtr.Zero);
return thunkPtr;
}
}
private class CastingCell : GenericDictionaryCell
{
internal TypeDesc Type;
internal bool Throwing;
override internal void Prepare(TypeBuilder builder)
{
if (Type.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Canonical types do not have EETypes");
builder.RegisterForPreparation(Type);
}
override internal IntPtr Create(TypeBuilder builder)
{
RuntimeTypeHandle th = GetRuntimeTypeHandleWithNullableTransform(builder, Type);
return RuntimeAugments.GetCastingHelperForType(th, Throwing);
}
override internal unsafe IntPtr CreateLazyLookupCell(TypeBuilder builder, out IntPtr auxResult)
{
RuntimeTypeHandle th = GetRuntimeTypeHandleWithNullableTransform(builder, Type);
auxResult = th.ToIntPtr();
return *(IntPtr*)RuntimeAugments.GetCastingHelperForType(th, Throwing);
}
}
private class AllocateArrayCell : GenericDictionaryCell
{
internal TypeDesc Type;
override internal void Prepare(TypeBuilder builder)
{
if (Type.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Canonical types do not have EETypes");
builder.RegisterForPreparation(Type);
}
override internal IntPtr Create(TypeBuilder builder)
{
return RuntimeAugments.GetAllocateArrayHelperForType(builder.GetRuntimeTypeHandle(Type));
}
override internal unsafe IntPtr CreateLazyLookupCell(TypeBuilder builder, out IntPtr auxResult)
{
auxResult = builder.GetRuntimeTypeHandle(Type).ToIntPtr();
return *(IntPtr*)Create(builder);
}
}
private class CheckArrayElementTypeCell : GenericDictionaryCell
{
internal TypeDesc Type;
override internal void Prepare(TypeBuilder builder)
{
if (Type.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Canonical types do not have EETypes");
builder.RegisterForPreparation(Type);
}
override internal IntPtr Create(TypeBuilder builder)
{
return RuntimeAugments.GetCheckArrayElementTypeHelperForType(builder.GetRuntimeTypeHandle(Type));
}
override internal unsafe IntPtr CreateLazyLookupCell(TypeBuilder builder, out IntPtr auxResult)
{
auxResult = builder.GetRuntimeTypeHandle(Type).ToIntPtr();
return *(IntPtr*)Create(builder);
}
}
private class CallingConventionConverterCell : GenericDictionaryCell
{
internal NativeFormat.CallingConventionConverterKind Flags;
internal RuntimeSignature Signature;
internal Instantiation MethodArgs;
internal Instantiation TypeArgs;
override internal void Prepare(TypeBuilder builder)
{
if (!MethodArgs.IsNull)
{
foreach (TypeDesc t in MethodArgs)
{
if (t.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Canonical types do not have EETypes");
}
}
if (!TypeArgs.IsNull)
{
foreach (TypeDesc t in TypeArgs)
{
if (t.IsCanonicalSubtype(CanonicalFormKind.Any))
Environment.FailFast("Canonical types do not have EETypes");
}
}
}
override internal IntPtr Create(TypeBuilder builder)
{
RuntimeTypeHandle[] typeArgs = null;
RuntimeTypeHandle[] methodArgs = null;
if (!MethodArgs.IsNull)
{
methodArgs = builder.GetRuntimeTypeHandles(MethodArgs);
}
if (!TypeArgs.IsNull)
{
typeArgs = builder.GetRuntimeTypeHandles(TypeArgs);
}
CallConverterThunk.ThunkKind thunkKind;
switch (Flags)
{
case NativeFormat.CallingConventionConverterKind.NoInstantiatingParam:
thunkKind = CallConverterThunk.ThunkKind.GenericToStandardWithTargetPointerArg;
break;
case NativeFormat.CallingConventionConverterKind.HasInstantiatingParam:
thunkKind = CallConverterThunk.ThunkKind.GenericToStandardWithTargetPointerArgAndParamArg;
break;
case NativeFormat.CallingConventionConverterKind.MaybeInstantiatingParam:
thunkKind = CallConverterThunk.ThunkKind.GenericToStandardWithTargetPointerArgAndMaybeParamArg;
break;
default:
throw new NotSupportedException();
}
IntPtr result = CallConverterThunk.MakeThunk(thunkKind, IntPtr.Zero, Signature, IntPtr.Zero, typeArgs, methodArgs);
return result;
}
}
internal static unsafe GenericDictionaryCell[] BuildDictionary(TypeBuilder typeBuilder, NativeLayoutInfoLoadContext nativeLayoutInfoLoadContext, NativeParser parser)
{
uint parserStartOffset = parser.Offset;
uint count = parser.GetSequenceCount();
Debug.Assert(count > 0);
TypeLoaderLogger.WriteLine("Parsing dictionary layout @ " + parserStartOffset.LowLevelToString() + " (" + count.LowLevelToString() + " entries)");
GenericDictionaryCell[] dictionary = new GenericDictionaryCell[count];
for (uint i = 0; i < count; i++)
{
GenericDictionaryCell cell = ParseAndCreateCell(nativeLayoutInfoLoadContext, ref parser);
cell.Prepare(typeBuilder);
dictionary[i] = cell;
}
return dictionary;
}
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
/// <summary>
/// Build an array of GenericDictionaryCell from a NativeParser stream that has the appropriate metadata
/// Return null if there are no cells to describe
/// </summary>
internal static unsafe GenericDictionaryCell[] BuildDictionaryFromMetadataTokensAndContext(TypeBuilder typeBuilder, NativeParser parser, NativeFormatMetadataUnit nativeMetadataUnit, FixupCellMetadataResolver resolver)
{
uint parserStartOffset = parser.Offset;
uint count = parser.GetSequenceCount();
// An empty dictionary isn't interesting
if (count == 0)
return null;
Debug.Assert(count > 0);
TypeLoaderLogger.WriteLine("Parsing dictionary layout @ " + parserStartOffset.LowLevelToString() + " (" + count.LowLevelToString() + " entries)");
GenericDictionaryCell[] dictionary = new GenericDictionaryCell[count];
for (uint i = 0; i < count; i++)
{
MetadataFixupKind fixupKind = (MetadataFixupKind)parser.GetUInt8();
Internal.Metadata.NativeFormat.Handle token = parser.GetUnsigned().AsHandle();
Internal.Metadata.NativeFormat.Handle token2 = new Internal.Metadata.NativeFormat.Handle();
switch (fixupKind)
{
case MetadataFixupKind.GenericConstrainedMethod:
case MetadataFixupKind.NonGenericConstrainedMethod:
case MetadataFixupKind.NonGenericDirectConstrainedMethod:
token2 = parser.GetUnsigned().AsHandle();
break;
}
GenericDictionaryCell cell = CreateCellFromFixupKindAndToken(fixupKind, resolver, token, token2);
cell.Prepare(typeBuilder);
dictionary[i] = cell;
}
return dictionary;
}
#endif
private static TypeDesc TransformNullable(TypeDesc type)
{
DefType typeAsDefType = type as DefType;
if (typeAsDefType != null && typeAsDefType.Instantiation.Length == 1 && typeAsDefType.GetTypeDefinition().RuntimeTypeHandle.Equals(typeof(Nullable<>).TypeHandle))
return typeAsDefType.Instantiation[0];
return type;
}
private static int ComputeConstrainedMethodSlot(MethodDesc constrainedMethod)
{
if (constrainedMethod.OwningType.IsInterface)
{
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
ushort slot;
if (!LazyVTableResolver.TryGetInterfaceSlotNumberFromMethod(constrainedMethod, out slot))
throw new BadImageFormatException();
return slot;
#else
Environment.FailFast("Unable to resolve constrained call");
return 0;
#endif
}
else if (constrainedMethod.OwningType == constrainedMethod.Context.GetWellKnownType(WellKnownType.Object))
{
if (constrainedMethod.Name == "ToString")
return ConstrainedCallSupport.NonGenericConstrainedCallDesc.s_ToStringSlot;
else if (constrainedMethod.Name == "GetHashCode")
return ConstrainedCallSupport.NonGenericConstrainedCallDesc.s_GetHashCodeSlot;
else if (constrainedMethod.Name == "Equals")
return ConstrainedCallSupport.NonGenericConstrainedCallDesc.s_EqualsSlot;
}
Environment.FailFast("unable to construct constrained method slot from constrained method");
return -1;
}
internal static GenericDictionaryCell CreateMethodCell(MethodDesc method, bool exactCallableAddressNeeded)
{
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
var nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)method.GetTypicalMethodDefinition();
return new MethodCell
{
ExactCallableAddressNeeded = exactCallableAddressNeeded,
Method = method,
MethodSignature = RuntimeSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt())
};
#else
Environment.FailFast("Creating a methodcell from a MethodDesc only supported in the presence of metadata based type loading.");
return null;
#endif
}
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
/// <summary>
/// Create a single cell to resolve based on a MetadataFixupKind, and the matching tokens
/// </summary>
internal static GenericDictionaryCell CreateCellFromFixupKindAndToken(MetadataFixupKind kind, FixupCellMetadataResolver metadata, Internal.Metadata.NativeFormat.Handle token, Internal.Metadata.NativeFormat.Handle token2)
{
GenericDictionaryCell cell;
switch (kind)
{
case MetadataFixupKind.TypeHandle:
{
var type = metadata.GetType(token);
TypeLoaderLogger.WriteLine("TypeHandle: " + type.ToString());
cell = new TypeHandleCell() { Type = type };
}
break;
case MetadataFixupKind.ArrayOfTypeHandle:
{
var type = metadata.GetType(token);
var arrayType = type.Context.GetArrayType(type);
TypeLoaderLogger.WriteLine("TypeHandle: " + arrayType.ToString());
cell = new TypeHandleCell() { Type = arrayType };
}
break;
case MetadataFixupKind.VirtualCallDispatch:
{
var method = metadata.GetMethod(token);
var containingType = method.OwningType;
if (containingType.IsInterface)
{
ushort slot;
if (!LazyVTableResolver.TryGetInterfaceSlotNumberFromMethod(method, out slot))
{
Environment.FailFast("Unable to get interface slot while resolving InterfaceCall dictionary cell");
}
TypeLoaderLogger.WriteLine("InterfaceCall: " + containingType.ToString() + ", slot #" + ((int)slot).LowLevelToString());
cell = new InterfaceCallCell() { InterfaceType = containingType, Slot = (int)slot };
}
else
{
// TODO! Implement virtual dispatch cell creation
throw NotImplemented.ByDesign;
}
}
break;
case MetadataFixupKind.MethodDictionary:
{
var genericMethod = metadata.GetMethod(token);
TypeLoaderLogger.WriteLine("MethodDictionary: " + genericMethod.ToString());
cell = new MethodDictionaryCell { GenericMethod = (InstantiatedMethod)genericMethod };
}
break;
case MetadataFixupKind.GcStaticData:
{
var type = metadata.GetType(token);
var staticDataKind = StaticDataKind.Gc;
TypeLoaderLogger.WriteLine("StaticData (" + (staticDataKind == StaticDataKind.Gc ? "Gc" : "NonGc") + ": " + type.ToString());
cell = new StaticDataCell() { DataKind = staticDataKind, Type = type };
}
break;
case MetadataFixupKind.NonGcStaticData:
{
var type = metadata.GetType(token);
var staticDataKind = StaticDataKind.NonGc;
TypeLoaderLogger.WriteLine("StaticData (" + (staticDataKind == StaticDataKind.Gc ? "Gc" : "NonGc") + ": " + type.ToString());
cell = new StaticDataCell() { DataKind = staticDataKind, Type = type };
}
break;
case MetadataFixupKind.DirectGcStaticData:
{
var type = metadata.GetType(token);
var staticDataKind = StaticDataKind.Gc;
TypeLoaderLogger.WriteLine("Direct StaticData (" + (staticDataKind == StaticDataKind.Gc ? "Gc" : "NonGc") + ": " + type.ToString());
cell = new StaticDataCell() { DataKind = staticDataKind, Type = type, Direct = true };
}
break;
case MetadataFixupKind.DirectNonGcStaticData:
{
var type = metadata.GetType(token);
var staticDataKind = StaticDataKind.NonGc;
TypeLoaderLogger.WriteLine("Direct StaticData (" + (staticDataKind == StaticDataKind.Gc ? "Gc" : "NonGc") + ": " + type.ToString());
cell = new StaticDataCell() { DataKind = staticDataKind, Type = type, Direct = true };
}
break;
case MetadataFixupKind.UnwrapNullableType:
{
var type = metadata.GetType(token);
TypeLoaderLogger.WriteLine("UnwrapNullableType of: " + type.ToString());
cell = new UnwrapNullableTypeCell() { Type = (DefType)type };
}
break;
case MetadataFixupKind.FieldLdToken:
{
var field = metadata.GetField(token);
TypeLoaderLogger.WriteLine("LdToken on: " + field.ToString());
IntPtr fieldName = TypeLoaderEnvironment.Instance.GetNativeFormatStringForString(field.Name);
cell = new FieldLdTokenCell() { FieldName = fieldName, ContainingType = field.OwningType };
}
break;
case MetadataFixupKind.MethodLdToken:
{
var method = metadata.GetMethod(token);
TypeLoaderLogger.WriteLine("LdToken on: " + method.ToString());
var nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)method.GetTypicalMethodDefinition();
cell = new MethodLdTokenCell
{
Method = method,
MethodName = IntPtr.Zero,
MethodSignature = RuntimeSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt())
};
}
break;
case MetadataFixupKind.TypeSize:
{
var type = metadata.GetType(token);
TypeLoaderLogger.WriteLine("TypeSize: " + type.ToString());
cell = new TypeSizeCell() { Type = type };
}
break;
case MetadataFixupKind.FieldOffset:
{
var field = metadata.GetField(token);
TypeLoaderLogger.WriteLine("FieldOffset: " + field.ToString());
cell = new FieldOffsetCell() { Field = field };
}
break;
case MetadataFixupKind.AllocateObject:
{
var type = metadata.GetType(token);
TypeLoaderLogger.WriteLine("AllocateObject on: " + type.ToString());
cell = new AllocateObjectCell { Type = type };
}
break;
case MetadataFixupKind.DefaultConstructor:
{
var type = metadata.GetType(token);
TypeLoaderLogger.WriteLine("DefaultConstructor on: " + type.ToString());
cell = new DefaultConstructorCell { Type = type };
}
break;
case MetadataFixupKind.TlsIndex:
{
var type = metadata.GetType(token);
TypeLoaderLogger.WriteLine("TlsIndex on: " + type.ToString());
cell = new TlsIndexCell { Type = type };
}
break;
case MetadataFixupKind.TlsOffset:
{
var type = metadata.GetType(token);
TypeLoaderLogger.WriteLine("TlsOffset on: " + type.ToString());
cell = new TlsOffsetCell { Type = type };
}
break;
case MetadataFixupKind.UnboxingStubMethod:
{
var method = metadata.GetMethod(token);
TypeLoaderLogger.WriteLine("Unboxing Stub Method: " + method.ToString());
if (method.OwningType.IsValueType)
{
// If an unboxing stub could exists, that's actually what we want
method = method.Context.ResolveGenericMethodInstantiation(true/* get the unboxing stub */, method.OwningType.GetClosestDefType(), method.NameAndSignature, method.Instantiation, IntPtr.Zero, false);
}
var nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)method.GetTypicalMethodDefinition();
cell = new MethodCell
{
Method = method,
MethodSignature = RuntimeSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt())
};
}
break;
case MetadataFixupKind.Method:
{
var method = metadata.GetMethod(token);
TypeLoaderLogger.WriteLine("Method: " + method.ToString());
var nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)method.GetTypicalMethodDefinition();
cell = new MethodCell
{
Method = method,
MethodSignature = RuntimeSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt())
};
}
break;
case MetadataFixupKind.CallableMethod:
{
var method = metadata.GetMethod(token);
TypeLoaderLogger.WriteLine("CallableMethod: " + method.ToString());
var nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)method.GetTypicalMethodDefinition();
cell = new MethodCell
{
ExactCallableAddressNeeded = true,
Method = method,
MethodSignature = RuntimeSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt())
};
}
break;
case MetadataFixupKind.NonGenericDirectConstrainedMethod:
{
var constraintType = metadata.GetType(token);
var method = metadata.GetMethod(token2);
var constrainedMethodType = method.OwningType;
var constrainedMethodSlot = ComputeConstrainedMethodSlot(method);
TypeLoaderLogger.WriteLine("NonGenericDirectConstrainedMethod: " + constraintType.ToString() + " Method:" + method.ToString() + " Consisting of " + constrainedMethodType.ToString() + ", slot #" + constrainedMethodSlot.LowLevelToString());
cell = new NonGenericDirectConstrainedMethodCell()
{
ConstraintType = constraintType,
ConstrainedMethodType = constrainedMethodType,
ConstrainedMethodSlot = (int)constrainedMethodSlot
};
}
break;
case MetadataFixupKind.NonGenericConstrainedMethod:
{
var constraintType = metadata.GetType(token);
var method = metadata.GetMethod(token2);
var constrainedMethodType = method.OwningType;
var constrainedMethodSlot = ComputeConstrainedMethodSlot(method);
TypeLoaderLogger.WriteLine("NonGenericConstrainedMethod: " + constraintType.ToString() + " Method:" + method.ToString() + " Consisting of " + constrainedMethodType.ToString() + ", slot #" + constrainedMethodSlot.LowLevelToString());
cell = new NonGenericConstrainedMethodCell()
{
ConstraintType = constraintType,
ConstrainedMethodType = constrainedMethodType,
ConstrainedMethodSlot = (int)constrainedMethodSlot
};
}
break;
case MetadataFixupKind.GenericConstrainedMethod:
{
var constraintType = metadata.GetType(token);
var method = metadata.GetMethod(token2);
var nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)method.GetTypicalMethodDefinition();
TypeLoaderLogger.WriteLine("GenericConstrainedMethod: " + constraintType.ToString() + " Method " + method.ToString());
cell = new GenericConstrainedMethodCell()
{
ConstraintType = constraintType,
ConstrainedMethod = method,
MethodName = IntPtr.Zero,
MethodSignature = RuntimeSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt())
};
}
break;
case MetadataFixupKind.IsInst:
case MetadataFixupKind.CastClass:
{
var type = metadata.GetType(token);
TypeLoaderLogger.WriteLine("Casting on: " + type.ToString());
cell = new CastingCell { Type = type, Throwing = (kind == MetadataFixupKind.CastClass) };
}
break;
case MetadataFixupKind.AllocateArray:
{
var type = metadata.GetType(token);
TypeLoaderLogger.WriteLine("AllocateArray on: " + type.ToString());
cell = new AllocateArrayCell { Type = type };
}
break;
case MetadataFixupKind.CheckArrayElementType:
{
var type = metadata.GetType(token);
TypeLoaderLogger.WriteLine("CheckArrayElementType on: " + type.ToString());
cell = new CheckArrayElementTypeCell { Type = type };
}
break;
case MetadataFixupKind.CallingConventionConverter_NoInstantiatingParam:
case MetadataFixupKind.CallingConventionConverter_MaybeInstantiatingParam:
case MetadataFixupKind.CallingConventionConverter_HasInstantiatingParam:
{
CallingConventionConverterKind converterKind;
switch (kind)
{
case MetadataFixupKind.CallingConventionConverter_NoInstantiatingParam:
converterKind = CallingConventionConverterKind.NoInstantiatingParam;
break;
case MetadataFixupKind.CallingConventionConverter_MaybeInstantiatingParam:
converterKind = CallingConventionConverterKind.MaybeInstantiatingParam;
break;
case MetadataFixupKind.CallingConventionConverter_HasInstantiatingParam:
converterKind = CallingConventionConverterKind.HasInstantiatingParam;
break;
default:
Environment.FailFast("Unknown converter kind");
throw new BadImageFormatException();
}
cell = new CallingConventionConverterCell
{
Flags = converterKind,
Signature = metadata.GetSignature(token),
MethodArgs = metadata.MethodInstantiation,
TypeArgs = metadata.TypeInstantiation
};
#if TYPE_LOADER_TRACE
TypeLoaderLogger.WriteLine("CallingConventionConverter on: ");
TypeLoaderLogger.WriteLine(" -> Flags: " + ((int)converterKind).LowLevelToString());
TypeLoaderLogger.WriteLine(" -> Signature: " + token.ToInt().LowLevelToString());
for (int i = 0; i < metadata.TypeInstantiation.Length; i++)
TypeLoaderLogger.WriteLine(" -> TypeArg[" + i.LowLevelToString() + "]: " + metadata.TypeInstantiation[i]);
for (int i = 0; i < metadata.MethodInstantiation.Length; i++)
TypeLoaderLogger.WriteLine(" -> MethodArg[" + i.LowLevelToString() + "]: " + metadata.MethodInstantiation[i]);
#endif
}
break;
default:
Environment.FailFast("Unknown fixup kind");
// Throw here so that the compiler won't complain.
throw new BadImageFormatException();
}
return cell;
}
#endif
internal static GenericDictionaryCell ParseAndCreateCell(NativeLayoutInfoLoadContext nativeLayoutInfoLoadContext, ref NativeParser parser)
{
GenericDictionaryCell cell;
var kind = parser.GetFixupSignatureKind();
switch (kind)
{
case FixupSignatureKind.TypeHandle:
{
var type = nativeLayoutInfoLoadContext.GetType(ref parser);
TypeLoaderLogger.WriteLine("TypeHandle: " + type.ToString());
cell = new TypeHandleCell() { Type = type };
}
break;
case FixupSignatureKind.InterfaceCall:
{
var interfaceType = nativeLayoutInfoLoadContext.GetType(ref parser);
var slot = parser.GetUnsigned();
TypeLoaderLogger.WriteLine("InterfaceCall: " + interfaceType.ToString() + ", slot #" + slot.LowLevelToString());
cell = new InterfaceCallCell() { InterfaceType = interfaceType, Slot = (int)slot };
}
break;
case FixupSignatureKind.MethodDictionary:
{
var genericMethod = nativeLayoutInfoLoadContext.GetMethod(ref parser);
Debug.Assert(genericMethod.Instantiation.Length > 0);
TypeLoaderLogger.WriteLine("MethodDictionary: " + genericMethod.ToString());
cell = new MethodDictionaryCell { GenericMethod = (InstantiatedMethod)genericMethod };
}
break;
case FixupSignatureKind.StaticData:
{
var type = nativeLayoutInfoLoadContext.GetType(ref parser);
StaticDataKind staticDataKind = (StaticDataKind)parser.GetUnsigned();
TypeLoaderLogger.WriteLine("StaticData (" + (staticDataKind == StaticDataKind.Gc ? "Gc" : "NonGc") + ": " + type.ToString());
cell = new StaticDataCell() { DataKind = staticDataKind, Type = type };
}
break;
case FixupSignatureKind.UnwrapNullableType:
{
var type = nativeLayoutInfoLoadContext.GetType(ref parser);
TypeLoaderLogger.WriteLine("UnwrapNullableType of: " + type.ToString());
cell = new UnwrapNullableTypeCell() { Type = (DefType)type };
}
break;
case FixupSignatureKind.FieldLdToken:
{
NativeParser ldtokenSigParser = parser.GetParserFromRelativeOffset();
var type = nativeLayoutInfoLoadContext.GetType(ref ldtokenSigParser);
IntPtr fieldNameSig = ldtokenSigParser.Reader.OffsetToAddress(ldtokenSigParser.Offset);
TypeLoaderLogger.WriteLine("LdToken on: " + type.ToString() + "." + ldtokenSigParser.GetString());
cell = new FieldLdTokenCell() { FieldName = fieldNameSig, ContainingType = type };
}
break;
case FixupSignatureKind.MethodLdToken:
{
NativeParser ldtokenSigParser = parser.GetParserFromRelativeOffset();
RuntimeSignature methodNameSig;
RuntimeSignature methodSig;
var method = nativeLayoutInfoLoadContext.GetMethod(ref ldtokenSigParser, out methodNameSig, out methodSig);
TypeLoaderLogger.WriteLine("LdToken on: " + method.OwningType.ToString() + "::" + method.NameAndSignature.Name);
cell = new MethodLdTokenCell
{
Method = method,
MethodName = methodNameSig.NativeLayoutSignature(),
MethodSignature = methodSig
};
}
break;
case FixupSignatureKind.TypeSize:
{
var type = nativeLayoutInfoLoadContext.GetType(ref parser);
TypeLoaderLogger.WriteLine("TypeSize: " + type.ToString());
cell = new TypeSizeCell() { Type = type };
}
break;
case FixupSignatureKind.FieldOffset:
{
var type = (DefType)nativeLayoutInfoLoadContext.GetType(ref parser);
uint ordinal = parser.GetUnsigned();
TypeLoaderLogger.WriteLine("FieldOffset on: " + type.ToString());
cell = new FieldOffsetCell() { Ordinal = ordinal, ContainingType = type };
}
break;
case FixupSignatureKind.VTableOffset:
{
var type = nativeLayoutInfoLoadContext.GetType(ref parser);
var vtableSlot = parser.GetUnsigned();
TypeLoaderLogger.WriteLine("VTableOffset on: " + type.ToString() + ", slot: " + vtableSlot.LowLevelToString());
cell = new VTableOffsetCell() { ContainingType = type, VTableSlot = vtableSlot };
}
break;
case FixupSignatureKind.AllocateObject:
{
var type = nativeLayoutInfoLoadContext.GetType(ref parser);
TypeLoaderLogger.WriteLine("AllocateObject on: " + type.ToString());
cell = new AllocateObjectCell { Type = type };
}
break;
case FixupSignatureKind.DefaultConstructor:
{
var type = nativeLayoutInfoLoadContext.GetType(ref parser);
TypeLoaderLogger.WriteLine("DefaultConstructor on: " + type.ToString());
cell = new DefaultConstructorCell { Type = type };
}
break;
case FixupSignatureKind.TlsIndex:
{
var type = nativeLayoutInfoLoadContext.GetType(ref parser);
TypeLoaderLogger.WriteLine("TlsIndex on: " + type.ToString());
cell = new TlsIndexCell { Type = type };
}
break;
case FixupSignatureKind.TlsOffset:
{
var type = nativeLayoutInfoLoadContext.GetType(ref parser);
TypeLoaderLogger.WriteLine("TlsOffset on: " + type.ToString());
cell = new TlsOffsetCell { Type = type };
}
break;
case FixupSignatureKind.Method:
{
RuntimeSignature methodSig;
RuntimeSignature methodNameSig;
var method = nativeLayoutInfoLoadContext.GetMethod(ref parser, out methodNameSig, out methodSig);
TypeLoaderLogger.WriteLine("Method: " + method.ToString());
cell = new MethodCell
{
Method = method,
MethodSignature = methodSig
};
}
break;
case FixupSignatureKind.NonGenericDirectConstrainedMethod:
{
var constraintType = nativeLayoutInfoLoadContext.GetType(ref parser);
var constrainedMethodType = nativeLayoutInfoLoadContext.GetType(ref parser);
var constrainedMethodSlot = parser.GetUnsigned();
TypeLoaderLogger.WriteLine("NonGenericDirectConstrainedMethod: " + constraintType.ToString() + " Method " + constrainedMethodType.ToString() + ", slot #" + constrainedMethodSlot.LowLevelToString());
cell = new NonGenericDirectConstrainedMethodCell()
{
ConstraintType = constraintType,
ConstrainedMethodType = constrainedMethodType,
ConstrainedMethodSlot = (int)constrainedMethodSlot
};
}
break;
case FixupSignatureKind.NonGenericConstrainedMethod:
{
var constraintType = nativeLayoutInfoLoadContext.GetType(ref parser);
var constrainedMethodType = nativeLayoutInfoLoadContext.GetType(ref parser);
var constrainedMethodSlot = parser.GetUnsigned();
TypeLoaderLogger.WriteLine("NonGenericConstrainedMethod: " + constraintType.ToString() + " Method " + constrainedMethodType.ToString() + ", slot #" + constrainedMethodSlot.LowLevelToString());
cell = new NonGenericConstrainedMethodCell()
{
ConstraintType = constraintType,
ConstrainedMethodType = constrainedMethodType,
ConstrainedMethodSlot = (int)constrainedMethodSlot
};
}
break;
case FixupSignatureKind.GenericConstrainedMethod:
{
var constraintType = nativeLayoutInfoLoadContext.GetType(ref parser);
NativeParser ldtokenSigParser = parser.GetParserFromRelativeOffset();
RuntimeSignature methodNameSig;
RuntimeSignature methodSig;
var method = nativeLayoutInfoLoadContext.GetMethod(ref ldtokenSigParser, out methodNameSig, out methodSig);
TypeLoaderLogger.WriteLine("GenericConstrainedMethod: " + constraintType.ToString() + " Method " + method.OwningType.ToString() + "::" + method.NameAndSignature.Name);
cell = new GenericConstrainedMethodCell()
{
ConstraintType = constraintType,
ConstrainedMethod = method,
MethodName = methodNameSig.NativeLayoutSignature(),
MethodSignature = methodSig
};
}
break;
case FixupSignatureKind.IsInst:
case FixupSignatureKind.CastClass:
{
var type = nativeLayoutInfoLoadContext.GetType(ref parser);
TypeLoaderLogger.WriteLine("Casting on: " + type.ToString());
cell = new CastingCell { Type = type, Throwing = (kind == FixupSignatureKind.CastClass) };
}
break;
case FixupSignatureKind.AllocateArray:
{
var type = nativeLayoutInfoLoadContext.GetType(ref parser);
TypeLoaderLogger.WriteLine("AllocateArray on: " + type.ToString());
cell = new AllocateArrayCell { Type = type };
}
break;
case FixupSignatureKind.CheckArrayElementType:
{
var type = nativeLayoutInfoLoadContext.GetType(ref parser);
TypeLoaderLogger.WriteLine("CheckArrayElementType on: " + type.ToString());
cell = new CheckArrayElementTypeCell { Type = type };
}
break;
case FixupSignatureKind.CallingConventionConverter:
{
CallingConventionConverterKind flags = (CallingConventionConverterKind)parser.GetUnsigned();
NativeParser sigParser = parser.GetParserFromRelativeOffset();
RuntimeSignature signature = RuntimeSignature.CreateFromNativeLayoutSignature(nativeLayoutInfoLoadContext._module.Handle, sigParser.Offset);
#if TYPE_LOADER_TRACE
TypeLoaderLogger.WriteLine("CallingConventionConverter on: ");
TypeLoaderLogger.WriteLine(" -> Flags: " + ((int)flags).LowLevelToString());
TypeLoaderLogger.WriteLine(" -> Signature: " + signature.NativeLayoutSignature().LowLevelToString());
for (int i = 0; !nativeLayoutInfoLoadContext._typeArgumentHandles.IsNull && i < nativeLayoutInfoLoadContext._typeArgumentHandles.Length; i++)
TypeLoaderLogger.WriteLine(" -> TypeArg[" + i.LowLevelToString() + "]: " + nativeLayoutInfoLoadContext._typeArgumentHandles[i]);
for (int i = 0; !nativeLayoutInfoLoadContext._methodArgumentHandles.IsNull && i < nativeLayoutInfoLoadContext._methodArgumentHandles.Length; i++)
TypeLoaderLogger.WriteLine(" -> MethodArg[" + i.LowLevelToString() + "]: " + nativeLayoutInfoLoadContext._methodArgumentHandles[i]);
#endif
cell = new CallingConventionConverterCell
{
Flags = flags,
Signature = signature,
MethodArgs = nativeLayoutInfoLoadContext._methodArgumentHandles,
TypeArgs = nativeLayoutInfoLoadContext._typeArgumentHandles
};
}
break;
case FixupSignatureKind.NotYetSupported:
TypeLoaderLogger.WriteLine("Valid dictionary entry, but not yet supported by the TypeLoader!");
throw new TypeBuilder.MissingTemplateException();
default:
parser.ThrowBadImageFormatException();
cell = null;
break;
}
return cell;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias WORKSPACES;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.FileSystem;
using Microsoft.CodeAnalysis.Editor.Implementation.Interactive;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Interactive;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Roslyn.Utilities;
using DesktopMetadataReferenceResolver = WORKSPACES::Microsoft.CodeAnalysis.Scripting.DesktopMetadataReferenceResolver;
using GacFileResolver = WORKSPACES::Microsoft.CodeAnalysis.Scripting.GacFileResolver;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
public abstract class InteractiveEvaluator : IInteractiveEvaluator, ICurrentWorkingDirectoryDiscoveryService
{
// full path or null
private readonly string _responseFilePath;
private readonly InteractiveHost _interactiveHost;
private string _initialWorkingDirectory;
private ImmutableArray<CommandLineSourceFile> _rspSourceFiles;
private readonly IContentType _contentType;
private readonly InteractiveWorkspace _workspace;
private IInteractiveWindow _currentWindow;
private ImmutableHashSet<MetadataReference> _references;
private MetadataFileReferenceResolver _metadataReferenceResolver;
private ImmutableArray<string> _sourceSearchPaths;
private ProjectId _previousSubmissionProjectId;
private ProjectId _currentSubmissionProjectId;
private readonly IViewClassifierAggregatorService _classifierAggregator;
private readonly IInteractiveWindowCommandsFactory _commandsFactory;
private readonly ImmutableArray<IInteractiveWindowCommand> _commands;
private IInteractiveWindowCommands _interactiveCommands;
private ITextView _currentTextView;
private ITextBuffer _currentSubmissionBuffer;
private readonly ISet<ValueTuple<ITextView, ITextBuffer>> _submissionBuffers = new HashSet<ValueTuple<ITextView, ITextBuffer>>();
private int _submissionCount = 0;
private readonly EventHandler<ContentTypeChangedEventArgs> _contentTypeChangedHandler;
internal InteractiveEvaluator(
IContentType contentType,
HostServices hostServices,
IViewClassifierAggregatorService classifierAggregator,
IInteractiveWindowCommandsFactory commandsFactory,
ImmutableArray<IInteractiveWindowCommand> commands,
string responseFilePath,
string initialWorkingDirectory,
string interactiveHostPath,
Type replType)
{
Debug.Assert(responseFilePath == null || PathUtilities.IsAbsolute(responseFilePath));
_contentType = contentType;
_responseFilePath = responseFilePath;
_workspace = new InteractiveWorkspace(this, hostServices);
_contentTypeChangedHandler = new EventHandler<ContentTypeChangedEventArgs>(LanguageBufferContentTypeChanged);
_classifierAggregator = classifierAggregator;
_initialWorkingDirectory = initialWorkingDirectory;
_commandsFactory = commandsFactory;
_commands = commands;
var hostPath = interactiveHostPath;
_interactiveHost = new InteractiveHost(replType, hostPath, initialWorkingDirectory);
_interactiveHost.ProcessStarting += ProcessStarting;
}
public IContentType ContentType
{
get
{
return _contentType;
}
}
public IInteractiveWindow CurrentWindow
{
get
{
return _currentWindow;
}
set
{
if (_currentWindow != value)
{
_interactiveHost.Output = value.OutputWriter;
_interactiveHost.ErrorOutput = value.ErrorOutputWriter;
if (_currentWindow != null)
{
_currentWindow.SubmissionBufferAdded -= SubmissionBufferAdded;
}
_currentWindow = value;
}
_currentWindow.SubmissionBufferAdded += SubmissionBufferAdded;
_interactiveCommands = _commandsFactory.CreateInteractiveCommands(_currentWindow, "#", _commands);
}
}
protected IInteractiveWindowCommands InteractiveCommands
{
get
{
return _interactiveCommands;
}
}
protected abstract string LanguageName { get; }
protected abstract CompilationOptions GetSubmissionCompilationOptions(string name, MetadataReferenceResolver metadataReferenceResolver);
protected abstract ParseOptions ParseOptions { get; }
protected abstract CommandLineParser CommandLineParser { get; }
#region Initialization
public string GetConfiguration()
{
return null;
}
private IInteractiveWindow GetInteractiveWindow()
{
var window = CurrentWindow;
if (window == null)
{
throw new InvalidOperationException(EditorFeaturesResources.EngineMustBeAttachedToAnInteractiveWindow);
}
return window;
}
public Task<ExecutionResult> InitializeAsync()
{
var window = GetInteractiveWindow();
_interactiveHost.Output = window.OutputWriter;
_interactiveHost.ErrorOutput = window.ErrorOutputWriter;
return ResetAsyncWorker();
}
public void Dispose()
{
_workspace.Dispose();
_interactiveHost.Dispose();
}
/// <summary>
/// Invoked by <see cref="InteractiveHost"/> when a new process is being started.
/// </summary>
private void ProcessStarting(InteractiveHostOptions options)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.BeginInvoke(new Action(() => ProcessStarting(options)));
return;
}
// Freeze all existing classifications and then clear the list of
// submission buffers we have.
FreezeClassifications();
_submissionBuffers.Clear();
// We always start out empty
_workspace.ClearSolution();
_currentSubmissionProjectId = null;
_previousSubmissionProjectId = null;
var metadataService = _workspace.CurrentSolution.Services.MetadataService;
ImmutableArray<string> referencePaths;
// reset configuration:
if (File.Exists(_responseFilePath))
{
// The base directory for relative paths is the directory that contains the .rsp file.
// Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
var rspArguments = this.CommandLineParser.Parse(new[] { "@" + _responseFilePath }, Path.GetDirectoryName(_responseFilePath), RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/);
referencePaths = rspArguments.ReferencePaths;
// the base directory for references specified in the .rsp file is the .rsp file directory:
var rspMetadataReferenceResolver = CreateFileResolver(referencePaths, rspArguments.BaseDirectory);
var metadataProvider = metadataService.GetProvider();
// ignore unresolved references, they will be reported in the interactive window:
var rspReferences = rspArguments.ResolveMetadataReferences(new AssemblyReferenceResolver(rspMetadataReferenceResolver, metadataProvider))
.Where(r => !(r is UnresolvedMetadataReference));
var interactiveHelpersRef = metadataService.GetReference(typeof(Script).Assembly.Location, MetadataReferenceProperties.Assembly);
var interactiveHostObjectRef = metadataService.GetReference(typeof(InteractiveHostObject).Assembly.Location, MetadataReferenceProperties.Assembly);
_references = ImmutableHashSet.Create<MetadataReference>(
interactiveHelpersRef,
interactiveHostObjectRef)
.Union(rspReferences);
// we need to create projects for these:
_rspSourceFiles = rspArguments.SourceFiles;
}
else
{
var mscorlibRef = metadataService.GetReference(typeof(object).Assembly.Location, MetadataReferenceProperties.Assembly);
_references = ImmutableHashSet.Create<MetadataReference>(mscorlibRef);
_rspSourceFiles = ImmutableArray.Create<CommandLineSourceFile>();
referencePaths = ScriptOptions.Default.SearchPaths;
}
// reset search paths, working directory:
_metadataReferenceResolver = CreateFileResolver(referencePaths, _initialWorkingDirectory);
_sourceSearchPaths = InteractiveHost.Service.DefaultSourceSearchPaths;
// create the first submission project in the workspace after reset:
if (_currentSubmissionBuffer != null)
{
AddSubmission(_currentTextView, _currentSubmissionBuffer, this.LanguageName);
}
}
private Dispatcher Dispatcher
{
get { return ((FrameworkElement)GetInteractiveWindow().TextView).Dispatcher; }
}
private static MetadataFileReferenceResolver CreateFileResolver(ImmutableArray<string> referencePaths, string baseDirectory)
{
var userProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var packagesDirectory = (userProfilePath == null) ?
null :
PathUtilities.CombineAbsoluteAndRelativePaths(userProfilePath, PathUtilities.CombinePossiblyRelativeAndRelativePaths(".nuget", "packages"));
return new DesktopMetadataReferenceResolver(
new RelativePathReferenceResolver(referencePaths, baseDirectory),
string.IsNullOrEmpty(packagesDirectory) ? null : new NuGetPackageResolverImpl(packagesDirectory),
new GacFileResolver(
architectures: GacFileResolver.Default.Architectures, // TODO (tomat)
preferredCulture: System.Globalization.CultureInfo.CurrentCulture)); // TODO (tomat)
}
#endregion
#region Workspace
private void SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs args)
{
AddSubmission(_currentWindow.TextView, args.NewBuffer, this.LanguageName);
}
// The REPL window might change content type to host command content type (when a host command is typed at the beginning of the buffer).
private void LanguageBufferContentTypeChanged(object sender, ContentTypeChangedEventArgs e)
{
// It's not clear whether this situation will ever happen, but just in case.
if (e.BeforeContentType == e.AfterContentType)
{
return;
}
var buffer = e.Before.TextBuffer;
var contentTypeName = this.ContentType.TypeName;
var afterIsLanguage = e.AfterContentType.IsOfType(contentTypeName);
var afterIsInteractiveCommand = e.AfterContentType.IsOfType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName);
var beforeIsLanguage = e.BeforeContentType.IsOfType(contentTypeName);
var beforeIsInteractiveCommand = e.BeforeContentType.IsOfType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName);
Debug.Assert((afterIsLanguage && beforeIsInteractiveCommand)
|| (beforeIsLanguage && afterIsInteractiveCommand));
// We're switching between the target language and the Interactive Command "language".
// First, remove the current submission from the solution.
var oldSolution = _workspace.CurrentSolution;
var newSolution = oldSolution;
foreach (var documentId in _workspace.GetRelatedDocumentIds(buffer.AsTextContainer()))
{
Debug.Assert(documentId != null);
newSolution = newSolution.RemoveDocument(documentId);
// TODO (tomat): Is there a better way to remove mapping between buffer and document in REPL?
// Perhaps TrackingWorkspace should implement RemoveDocumentAsync?
_workspace.ClearOpenDocument(documentId);
}
// Next, remove the previous submission project and update the workspace.
newSolution = newSolution.RemoveProject(_currentSubmissionProjectId);
_workspace.SetCurrentSolution(newSolution);
// Add a new submission with the correct language for the current buffer.
var languageName = afterIsLanguage
? this.LanguageName
: InteractiveLanguageNames.InteractiveCommand;
AddSubmission(_currentTextView, buffer, languageName);
}
private void AddSubmission(ITextView textView, ITextBuffer subjectBuffer, string languageName)
{
var solution = _workspace.CurrentSolution;
Project project;
if (_previousSubmissionProjectId == null)
{
// insert projects for initialization files listed in .rsp:
// If we have separate files, then those are implicitly #loaded. For this, we'll
// create a submission chain
foreach (var file in _rspSourceFiles)
{
project = CreateSubmissionProject(solution, languageName);
var documentId = DocumentId.CreateNewId(project.Id, debugName: file.Path);
solution = project.Solution.AddDocument(documentId, Path.GetFileName(file.Path), new FileTextLoader(file.Path, defaultEncoding: null));
_previousSubmissionProjectId = project.Id;
}
}
// project for the new submission:
project = CreateSubmissionProject(solution, languageName);
// Keep track of this buffer so we can freeze the classifications for it in the future.
var viewAndBuffer = ValueTuple.Create(textView, subjectBuffer);
if (!_submissionBuffers.Contains(viewAndBuffer))
{
_submissionBuffers.Add(ValueTuple.Create(textView, subjectBuffer));
}
SetSubmissionDocument(subjectBuffer, project);
_currentSubmissionProjectId = project.Id;
if (_currentSubmissionBuffer != null)
{
_currentSubmissionBuffer.ContentTypeChanged -= _contentTypeChangedHandler;
}
subjectBuffer.ContentTypeChanged += _contentTypeChangedHandler;
subjectBuffer.Properties[typeof(ICurrentWorkingDirectoryDiscoveryService)] = this;
_currentSubmissionBuffer = subjectBuffer;
_currentTextView = textView;
}
private Project CreateSubmissionProject(Solution solution, string languageName)
{
var name = "Submission#" + (_submissionCount++);
// Grab a local copy so we aren't closing over the field that might change. The
// collection itself is an immutable collection.
var localReferences = _references;
// TODO (tomat): needs implementation in InteractiveHostService as well
// var localCompilationOptions = (rspArguments != null) ? rspArguments.CompilationOptions : CompilationOptions.Default;
var localCompilationOptions = GetSubmissionCompilationOptions(name,
new AssemblyReferenceResolver(_metadataReferenceResolver, solution.Services.MetadataService.GetProvider()));
var localParseOptions = ParseOptions;
var projectId = ProjectId.CreateNewId(debugName: name);
solution = solution.AddProject(
ProjectInfo.Create(
projectId,
VersionStamp.Create(),
name: name,
assemblyName: name,
language: languageName,
compilationOptions: localCompilationOptions,
parseOptions: localParseOptions,
documents: null,
projectReferences: null,
metadataReferences: localReferences,
hostObjectType: typeof(InteractiveHostObject),
isSubmission: true));
if (_previousSubmissionProjectId != null)
{
solution = solution.AddProjectReference(projectId, new ProjectReference(_previousSubmissionProjectId));
}
return solution.GetProject(projectId);
}
private void SetSubmissionDocument(ITextBuffer buffer, Project project)
{
var documentId = DocumentId.CreateNewId(project.Id, debugName: project.Name);
var solution = project.Solution
.AddDocument(documentId, project.Name, buffer.CurrentSnapshot.AsText());
_workspace.SetCurrentSolution(solution);
// opening document will start workspace listening to changes in this text container
_workspace.OpenDocument(documentId, buffer.AsTextContainer());
}
private void FreezeClassifications()
{
foreach (var textViewAndBuffer in _submissionBuffers)
{
var textView = textViewAndBuffer.Item1;
var textBuffer = textViewAndBuffer.Item2;
if (textBuffer != _currentSubmissionBuffer)
{
InertClassifierProvider.CaptureExistingClassificationSpans(_classifierAggregator, textView, textBuffer);
}
}
}
#endregion
#region IInteractiveEngine
public virtual bool CanExecuteCode(string text)
{
if (_interactiveCommands != null && _interactiveCommands.InCommand)
{
return true;
}
return false;
}
public Task<ExecutionResult> ResetAsync(bool initialize = true)
{
GetInteractiveWindow().AddInput(_interactiveCommands.CommandPrefix + "reset");
GetInteractiveWindow().WriteLine("Resetting execution engine.");
GetInteractiveWindow().FlushOutput();
return ResetAsyncWorker(initialize);
}
private async Task<ExecutionResult> ResetAsyncWorker(bool initialize = true)
{
try
{
var options = InteractiveHostOptions.Default.WithInitializationFile(initialize ? _responseFilePath : null);
// async as this can load references, run initialization code, etc.
var result = await _interactiveHost.ResetAsync(options).ConfigureAwait(false);
// TODO: set up options
//if (result.Success)
//{
// UpdateLocalPaths(result.NewReferencePaths, result.NewSourcePaths, result.NewWorkingDirectory);
//}
return new ExecutionResult(result.Success);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public async Task<ExecutionResult> ExecuteCodeAsync(string text)
{
try
{
if (InteractiveCommands.InCommand)
{
var cmdResult = InteractiveCommands.TryExecuteCommand();
if (cmdResult != null)
{
return await cmdResult.ConfigureAwait(false);
}
}
var result = await _interactiveHost.ExecuteAsync(text).ConfigureAwait(false);
if (result.Success)
{
// We are not executing a command (the current content type is not "Interactive Command"),
// so the source document should not have been removed.
Debug.Assert(_workspace.CurrentSolution.GetProject(_currentSubmissionProjectId).HasDocuments);
SubmissionSuccessfullyExecuted(result);
}
return new ExecutionResult(result.Success);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void SubmissionSuccessfullyExecuted(RemoteExecutionResult result)
{
// only remember the submission if we compiled successfully, otherwise we
// ignore it's id so we don't reference it in the next submission.
_previousSubmissionProjectId = _currentSubmissionProjectId;
// Grab any directive references from it
var compilation = _workspace.CurrentSolution.GetProject(_previousSubmissionProjectId).GetCompilationAsync().Result;
_references = _references.Union(compilation.DirectiveReferences);
// update local search paths - remote paths has already been updated
UpdateLocalPaths(result.NewReferencePaths, result.NewSourcePaths, result.NewWorkingDirectory);
}
public void AbortExecution()
{
// TODO: abort execution
}
public string FormatClipboard()
{
// keep the clipboard content as is
return null;
}
#endregion
#region Paths
public ImmutableArray<string> ReferenceSearchPaths { get { return _metadataReferenceResolver.SearchPaths; } }
public ImmutableArray<string> SourceSearchPaths { get { return _sourceSearchPaths; } }
public string CurrentDirectory { get { return _metadataReferenceResolver.BaseDirectory; } }
public void UpdateLocalPaths(string[] newReferenceSearchPaths, string[] newSourceSearchPaths, string newBaseDirectory)
{
var changed = false;
if (newReferenceSearchPaths != null || newBaseDirectory != null)
{
_metadataReferenceResolver = CreateFileResolver(
(newReferenceSearchPaths == null) ? _metadataReferenceResolver.SearchPaths : newReferenceSearchPaths.AsImmutable(),
newBaseDirectory ?? _metadataReferenceResolver.BaseDirectory);
changed = true;
}
if (newSourceSearchPaths != null)
{
_sourceSearchPaths = newSourceSearchPaths.AsImmutable();
changed = true;
}
if (changed)
{
var solution = _workspace.CurrentSolution;
var metadataProvider = _workspace.CurrentSolution.Services.MetadataService.GetProvider();
var oldOptions = solution.GetProjectState(_currentSubmissionProjectId).CompilationOptions;
var newOptions = oldOptions.WithMetadataReferenceResolver(new AssemblyReferenceResolver(_metadataReferenceResolver, metadataProvider));
_workspace.SetCurrentSolution(solution.WithProjectCompilationOptions(_currentSubmissionProjectId, newOptions));
}
}
public void SetInitialPaths(string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory)
{
_initialWorkingDirectory = baseDirectory;
UpdateLocalPaths(referenceSearchPaths, sourceSearchPaths, baseDirectory);
_interactiveHost.SetPathsAsync(referenceSearchPaths, sourceSearchPaths, baseDirectory);
}
public string GetPrompt()
{
if (CurrentWindow.CurrentLanguageBuffer != null &&
CurrentWindow.CurrentLanguageBuffer.CurrentSnapshot.LineCount > 1)
{
return ". ";
}
return "> ";
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace AttendanceServices.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// ----------------------------------------------------------------------------
// <copyright file="PhotonView.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH
// </copyright>
// <summary>
//
// </summary>
// <author>[email protected]</author>
// ----------------------------------------------------------------------------
using System;
using UnityEngine;
using System.Reflection;
using System.Collections.Generic;
using ExitGames.Client.Photon;
#if UNITY_EDITOR
using UnityEditor;
#endif
public enum ViewSynchronization { Off, ReliableDeltaCompressed, Unreliable, UnreliableOnChange }
public enum OnSerializeTransform { OnlyPosition, OnlyRotation, OnlyScale, PositionAndRotation, All }
public enum OnSerializeRigidBody { OnlyVelocity, OnlyAngularVelocity, All }
/// <summary>
/// Options to define how Ownership Transfer is handled per PhotonView.
/// </summary>
/// <remarks>
/// This setting affects how RequestOwnership and TransferOwnership work at runtime.
/// </remarks>
public enum OwnershipOption
{
/// <summary>
/// Ownership is fixed. Instantiated objects stick with their creator, scene objects always belong to the Master Client.
/// </summary>
Fixed,
/// <summary>
/// Ownership can be taken away from the current owner who can't object.
/// </summary>
Takeover,
/// <summary>
/// Ownership can be requested with PhotonView.RequestOwnership but the current owner has to agree to give up ownership.
/// </summary>
/// <remarks>The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.</remarks>
Request
}
/// <summary>
/// PUN's NetworkView replacement class for networking. Use it like a NetworkView.
/// </summary>
/// \ingroup publicApi
[AddComponentMenu("Photon Networking/Photon View &v")]
public class PhotonView : Photon.MonoBehaviour
{
#if UNITY_EDITOR
[ContextMenu("Open PUN Wizard")]
void OpenPunWizard()
{
EditorApplication.ExecuteMenuItem("Window/Photon Unity Networking");
}
#endif
public int ownerId;
public byte group = 0;
protected internal bool mixedModeIsReliable = false;
/// <summary>
/// Flag to check if ownership of this photonView was set during the lifecycle. Used for checking when joining late if event with mismatched owner and sender needs addressing.
/// </summary>
/// <value><c>true</c> if owner ship was transfered; otherwise, <c>false</c>.</value>
public bool OwnerShipWasTransfered;
// NOTE: this is now an integer because unity won't serialize short (needed for instantiation). we SEND only a short though!
// NOTE: prefabs have a prefixBackup of -1. this is replaced with any currentLevelPrefix that's used at runtime. instantiated GOs get their prefix set pre-instantiation (so those are not -1 anymore)
public int prefix
{
get
{
if (this.prefixBackup == -1 && PhotonNetwork.networkingPeer != null)
{
this.prefixBackup = PhotonNetwork.networkingPeer.currentLevelPrefix;
}
return this.prefixBackup;
}
set { this.prefixBackup = value; }
}
// this field is serialized by unity. that means it is copied when instantiating a persistent obj into the scene
public int prefixBackup = -1;
/// <summary>
/// This is the instantiationData that was passed when calling PhotonNetwork.Instantiate* (if that was used to spawn this prefab)
/// </summary>
public object[] instantiationData
{
get
{
if (!this.didAwake)
{
// even though viewID and instantiationID are setup before the GO goes live, this data can't be set. as workaround: fetch it if needed
this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId);
}
return this.instantiationDataField;
}
set { this.instantiationDataField = value; }
}
internal object[] instantiationDataField;
/// <summary>
/// For internal use only, don't use
/// </summary>
protected internal object[] lastOnSerializeDataSent = null;
/// <summary>
/// For internal use only, don't use
/// </summary>
protected internal object[] lastOnSerializeDataReceived = null;
public ViewSynchronization synchronization;
public OnSerializeTransform onSerializeTransformOption = OnSerializeTransform.PositionAndRotation;
public OnSerializeRigidBody onSerializeRigidBodyOption = OnSerializeRigidBody.All;
/// <summary>Defines if ownership of this PhotonView is fixed, can be requested or simply taken.</summary>
/// <remarks>
/// Note that you can't edit this value at runtime.
/// The options are described in enum OwnershipOption.
/// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
/// </remarks>
public OwnershipOption ownershipTransfer = OwnershipOption.Fixed;
public List<Component> ObservedComponents;
Dictionary<Component, MethodInfo> m_OnSerializeMethodInfos = new Dictionary<Component, MethodInfo>(3);
#if UNITY_EDITOR
// Suppressing compiler warning "this variable is never used". Only used in the CustomEditor, only in Editor
#pragma warning disable 0414
[SerializeField]
bool ObservedComponentsFoldoutOpen = true;
#pragma warning restore 0414
#endif
[SerializeField]
private int viewIdField = 0;
/// <summary>
/// The ID of the PhotonView. Identifies it in a networked game (per room).
/// </summary>
/// <remarks>See: [Network Instantiation](@ref instantiateManual)</remarks>
public int viewID
{
get { return this.viewIdField; }
set
{
// if ID was 0 for an awakened PhotonView, the view should add itself into the networkingPeer.photonViewList after setup
bool viewMustRegister = this.didAwake && this.viewIdField == 0;
// TODO: decide if a viewID can be changed once it wasn't 0. most likely that is not a good idea
// check if this view is in networkingPeer.photonViewList and UPDATE said list (so we don't keep the old viewID with a reference to this object)
// PhotonNetwork.networkingPeer.RemovePhotonView(this, true);
this.ownerId = value / PhotonNetwork.MAX_VIEW_IDS;
this.viewIdField = value;
if (viewMustRegister)
{
PhotonNetwork.networkingPeer.RegisterPhotonView(this);
}
//Debug.Log("Set viewID: " + value + " -> owner: " + this.ownerId + " subId: " + this.subId);
}
}
public int instantiationId; // if the view was instantiated with a GO, this GO has a instantiationID (first view's viewID)
/// <summary>True if the PhotonView was loaded with the scene (game object) or instantiated with InstantiateSceneObject.</summary>
/// <remarks>
/// Scene objects are not owned by a particular player but belong to the scene. Thus they don't get destroyed when their
/// creator leaves the game and the current Master Client can control them (whoever that is).
/// The ownerId is 0 (player IDs are 1 and up).
/// </remarks>
public bool isSceneView
{
get { return this.CreatorActorNr == 0; }
}
/// <summary>
/// The owner of a PhotonView is the player who created the GameObject with that view. Objects in the scene don't have an owner.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
///
/// Ownership can be transferred to another player with PhotonView.TransferOwnership or any player can request
/// ownership by calling the PhotonView's RequestOwnership method.
/// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
/// </remarks>
public PhotonPlayer owner
{
get
{
return PhotonPlayer.Find(this.ownerId);
}
}
public int OwnerActorNr
{
get { return this.ownerId; }
}
public bool isOwnerActive
{
get { return this.ownerId != 0 && PhotonNetwork.networkingPeer.mActors.ContainsKey(this.ownerId); }
}
public int CreatorActorNr
{
get { return this.viewIdField / PhotonNetwork.MAX_VIEW_IDS; }
}
/// <summary>
/// True if the PhotonView is "mine" and can be controlled by this client.
/// </summary>
/// <remarks>
/// PUN has an ownership concept that defines who can control and destroy each PhotonView.
/// True in case the owner matches the local PhotonPlayer.
/// True if this is a scene photonview on the Master client.
/// </remarks>
public bool isMine
{
get
{
return (this.ownerId == PhotonNetwork.player.ID) || (!this.isOwnerActive && PhotonNetwork.isMasterClient);
}
}
/// <summary>
/// The current master ID so that we can compare when we receive OnMasterClientSwitched() callback
/// It's public so that we can check it during ownerId assignments in networkPeer script
/// TODO: Maybe we can have the networkPeer always aware of the previous MasterClient?
/// </summary>
public int currentMasterID = -1;
protected internal bool didAwake;
[SerializeField]
protected internal bool isRuntimeInstantiated;
protected internal bool removedFromLocalViewList;
internal MonoBehaviour[] RpcMonoBehaviours;
private MethodInfo OnSerializeMethodInfo;
private bool failedToFindOnSerialize;
/// <summary>Called by Unity on start of the application and does a setup the PhotonView.</summary>
protected internal void Awake()
{
if (this.viewID != 0)
{
// registration might be too late when some script (on this GO) searches this view BUT GetPhotonView() can search ALL in that case
PhotonNetwork.networkingPeer.RegisterPhotonView(this);
this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId);
}
this.didAwake = true;
}
/// <summary>
/// Depending on the PhotonView's ownershipTransfer setting, any client can request to become owner of the PhotonView.
/// </summary>
/// <remarks>
/// Requesting ownership can give you control over a PhotonView, if the ownershipTransfer setting allows that.
/// The current owner might have to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
///
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void RequestOwnership()
{
PhotonNetwork.networkingPeer.RequestOwnership(this.viewID, this.ownerId);
}
/// <summary>
/// Transfers the ownership of this PhotonView (and GameObject) to another player.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void TransferOwnership(PhotonPlayer newOwner)
{
this.TransferOwnership(newOwner.ID);
}
/// <summary>
/// Transfers the ownership of this PhotonView (and GameObject) to another player.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void TransferOwnership(int newOwnerId)
{
PhotonNetwork.networkingPeer.TransferOwnership(this.viewID, newOwnerId);
this.ownerId = newOwnerId; // immediately switch ownership locally, to avoid more updates sent from this client.
}
/// <summary>
///Check ownerId assignment for sceneObjects to keep being owned by the MasterClient.
/// </summary>
/// <param name="newMasterClient">New master client.</param>
public void OnMasterClientSwitched(PhotonPlayer newMasterClient)
{
if (this.CreatorActorNr == 0 && !this.OwnerShipWasTransfered && (this.currentMasterID== -1 || this.ownerId==this.currentMasterID))
{
this.ownerId = newMasterClient.ID;
}
this.currentMasterID = newMasterClient.ID;
}
protected internal void OnDestroy()
{
if (!this.removedFromLocalViewList)
{
bool wasInList = PhotonNetwork.networkingPeer.LocalCleanPhotonView(this);
bool loading = false;
#if (!UNITY_5 || UNITY_5_0 || UNITY_5_1) && !UNITY_5_3_OR_NEWER
loading = Application.isLoadingLevel;
#endif
if (wasInList && !loading && this.instantiationId > 0 && !PhotonHandler.AppQuits && PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
{
Debug.Log("PUN-instantiated '" + this.gameObject.name + "' got destroyed by engine. This is OK when loading levels. Otherwise use: PhotonNetwork.Destroy().");
}
}
}
public void SerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (this.ObservedComponents != null && this.ObservedComponents.Count > 0)
{
for (int i = 0; i < this.ObservedComponents.Count; ++i)
{
SerializeComponent(this.ObservedComponents[i], stream, info);
}
}
}
public void DeserializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (this.ObservedComponents != null && this.ObservedComponents.Count > 0)
{
for (int i = 0; i < this.ObservedComponents.Count; ++i)
{
DeserializeComponent(this.ObservedComponents[i], stream, info);
}
}
}
protected internal void DeserializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info)
{
if (component == null)
{
return;
}
// Use incoming data according to observed type
if (component is MonoBehaviour)
{
ExecuteComponentOnSerialize(component, stream, info);
}
else if (component is Transform)
{
Transform trans = (Transform) component;
switch (this.onSerializeTransformOption)
{
case OnSerializeTransform.All:
trans.localPosition = (Vector3) stream.ReceiveNext();
trans.localRotation = (Quaternion) stream.ReceiveNext();
trans.localScale = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyPosition:
trans.localPosition = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyRotation:
trans.localRotation = (Quaternion) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyScale:
trans.localScale = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.PositionAndRotation:
trans.localPosition = (Vector3) stream.ReceiveNext();
trans.localRotation = (Quaternion) stream.ReceiveNext();
break;
}
}
else if (component is Rigidbody)
{
Rigidbody rigidB = (Rigidbody) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
rigidB.velocity = (Vector3) stream.ReceiveNext();
rigidB.angularVelocity = (Vector3) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
rigidB.angularVelocity = (Vector3) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyVelocity:
rigidB.velocity = (Vector3) stream.ReceiveNext();
break;
}
}
else if (component is Rigidbody2D)
{
Rigidbody2D rigidB = (Rigidbody2D) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
rigidB.velocity = (Vector2) stream.ReceiveNext();
rigidB.angularVelocity = (float) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
rigidB.angularVelocity = (float) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyVelocity:
rigidB.velocity = (Vector2) stream.ReceiveNext();
break;
}
}
else
{
Debug.LogError("Type of observed is unknown when receiving.");
}
}
protected internal void SerializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info)
{
if (component == null)
{
return;
}
if (component is MonoBehaviour)
{
ExecuteComponentOnSerialize(component, stream, info);
}
else if (component is Transform)
{
Transform trans = (Transform) component;
switch (this.onSerializeTransformOption)
{
case OnSerializeTransform.All:
stream.SendNext(trans.localPosition);
stream.SendNext(trans.localRotation);
stream.SendNext(trans.localScale);
break;
case OnSerializeTransform.OnlyPosition:
stream.SendNext(trans.localPosition);
break;
case OnSerializeTransform.OnlyRotation:
stream.SendNext(trans.localRotation);
break;
case OnSerializeTransform.OnlyScale:
stream.SendNext(trans.localScale);
break;
case OnSerializeTransform.PositionAndRotation:
stream.SendNext(trans.localPosition);
stream.SendNext(trans.localRotation);
break;
}
}
else if (component is Rigidbody)
{
Rigidbody rigidB = (Rigidbody) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
stream.SendNext(rigidB.velocity);
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyVelocity:
stream.SendNext(rigidB.velocity);
break;
}
}
else if (component is Rigidbody2D)
{
Rigidbody2D rigidB = (Rigidbody2D) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
stream.SendNext(rigidB.velocity);
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyVelocity:
stream.SendNext(rigidB.velocity);
break;
}
}
else
{
Debug.LogError("Observed type is not serializable: " + component.GetType());
}
}
protected internal void ExecuteComponentOnSerialize(Component component, PhotonStream stream, PhotonMessageInfo info)
{
IPunObservable observable = component as IPunObservable;
if (observable != null)
{
observable.OnPhotonSerializeView(stream, info);
}
else if (component != null)
{
MethodInfo method = null;
bool found = this.m_OnSerializeMethodInfos.TryGetValue(component, out method);
if (!found)
{
bool foundMethod = NetworkingPeer.GetMethod(component as MonoBehaviour, PhotonNetworkingMessage.OnPhotonSerializeView.ToString(), out method);
if (foundMethod == false)
{
Debug.LogError("The observed monobehaviour (" + component.name + ") of this PhotonView does not implement OnPhotonSerializeView()!");
method = null;
}
this.m_OnSerializeMethodInfos.Add(component, method);
}
if (method != null)
{
method.Invoke(component, new object[] {stream, info});
}
}
}
/// <summary>
/// Can be used to refesh the list of MonoBehaviours on this GameObject while PhotonNetwork.UseRpcMonoBehaviourCache is true.
/// </summary>
/// <remarks>
/// Set PhotonNetwork.UseRpcMonoBehaviourCache to true to enable the caching.
/// Uses this.GetComponents<MonoBehaviour>() to get a list of MonoBehaviours to call RPCs on (potentially).
///
/// While PhotonNetwork.UseRpcMonoBehaviourCache is false, this method has no effect,
/// because the list is refreshed when a RPC gets called.
/// </remarks>
public void RefreshRpcMonoBehaviourCache()
{
this.RpcMonoBehaviours = this.GetComponents<MonoBehaviour>();
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// RPC calls can target "All" or the "Others".
/// Usually, the target "All" gets executed locally immediately after sending the RPC.
/// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
/// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
/// <param name="target">The group of targets and the way the RPC gets sent.</param>
/// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RPC(string methodName, PhotonTargets target, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, target, false, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// RPC calls can target "All" or the "Others".
/// Usually, the target "All" gets executed locally immediately after sending the RPC.
/// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
///<param name="target">The group of targets and the way the RPC gets sent.</param>
///<param name="encrypt"> </param>
///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RpcSecure(string methodName, PhotonTargets target, bool encrypt, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, target, encrypt, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// This method allows you to make an RPC calls on a specific player's client.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
/// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
/// <param name="targetPlayer">The group of targets and the way the RPC gets sent.</param>
/// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RPC(string methodName, PhotonPlayer targetPlayer, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, targetPlayer, false, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// This method allows you to make an RPC calls on a specific player's client.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
///<param name="targetPlayer">The group of targets and the way the RPC gets sent.</param>
///<param name="encrypt"> </param>
///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RpcSecure(string methodName, PhotonPlayer targetPlayer, bool encrypt, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, targetPlayer, encrypt, parameters);
}
public static PhotonView Get(Component component)
{
return component.GetComponent<PhotonView>();
}
public static PhotonView Get(GameObject gameObj)
{
return gameObj.GetComponent<PhotonView>();
}
public static PhotonView Find(int viewID)
{
return PhotonNetwork.networkingPeer.GetPhotonView(viewID);
}
public override string ToString()
{
return string.Format("View ({3}){0} on {1} {2}", this.viewID, (this.gameObject != null) ? this.gameObject.name : "GO==null", (this.isSceneView) ? "(scene)" : string.Empty, this.prefix);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace System.IO.MemoryMappedFiles
{
public partial class MemoryMappedFile
{
/// <summary>
/// Used by the 2 Create factory method groups. A null fileHandle specifies that the
/// memory mapped file should not be associated with an exsiting file on disk (ie start
/// out empty).
/// </summary>
private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
[SecurityCritical]
private static SafeMemoryMappedFileHandle CreateCore(
FileStream fileStream, string mapName, HandleInheritability inheritability,
MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity)
{
SafeFileHandle fileHandle = fileStream != null ? fileStream.SafeFileHandle : null;
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability);
// split the long into two ints
int capacityLow = unchecked((int)(capacity & 0x00000000FFFFFFFFL));
int capacityHigh = unchecked((int)(capacity >> 32));
SafeMemoryMappedFileHandle handle = fileHandle != null ?
Interop.mincore.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName) :
Interop.mincore.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName);
int errorCode = Marshal.GetLastWin32Error();
if (!handle.IsInvalid)
{
if (errorCode == Interop.mincore.Errors.ERROR_ALREADY_EXISTS)
{
handle.Dispose();
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
else // handle.IsInvalid
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
return handle;
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, bool createOrOpen)
{
return OpenCore(mapName, inheritability, GetFileMapAccess(access), createOrOpen);
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileRights rights, bool createOrOpen)
{
return OpenCore(mapName, inheritability, GetFileMapAccess(rights), createOrOpen);
}
/// <summary>
/// Used by the CreateOrOpen factory method groups.
/// </summary>
[SecurityCritical]
private static SafeMemoryMappedFileHandle CreateOrOpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access,
MemoryMappedFileOptions options, long capacity)
{
/// Try to open the file if it exists -- this requires a bit more work. Loop until we can
/// either create or open a memory mapped file up to a timeout. CreateFileMapping may fail
/// if the file exists and we have non-null security attributes, in which case we need to
/// use OpenFileMapping. But, there exists a race condition because the memory mapped file
/// may have closed inbetween the two calls -- hence the loop.
///
/// The retry/timeout logic increases the wait time each pass through the loop and times
/// out in approximately 1.4 minutes. If after retrying, a MMF handle still hasn't been opened,
/// throw an InvalidOperationException.
Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf");
SafeMemoryMappedFileHandle handle = null;
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability);
// split the long into two ints
int capacityLow = unchecked((int)(capacity & 0x00000000FFFFFFFFL));
int capacityHigh = unchecked((int)(capacity >> 32));
int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins
int waitSleep = 0;
// keep looping until we've exhausted retries or break as soon we we get valid handle
while (waitRetries > 0)
{
// try to create
handle = Interop.mincore.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs,
GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName);
if (!handle.IsInvalid)
{
break;
}
else
{
int createErrorCode = Marshal.GetLastWin32Error();
if (createErrorCode != Interop.mincore.Errors.ERROR_ACCESS_DENIED)
{
throw Win32Marshal.GetExceptionForWin32Error(createErrorCode);
}
}
// try to open
handle = Interop.mincore.OpenFileMapping(GetFileMapAccess(access), (inheritability &
HandleInheritability.Inheritable) != 0, mapName);
// valid handle
if (!handle.IsInvalid)
{
break;
}
// didn't get valid handle; have to retry
else
{
int openErrorCode = Marshal.GetLastWin32Error();
if (openErrorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
{
throw Win32Marshal.GetExceptionForWin32Error(openErrorCode);
}
// increase wait time
--waitRetries;
if (waitSleep == 0)
{
waitSleep = 10;
}
else
{
ThreadSleep(waitSleep);
waitSleep *= 2;
}
}
}
// finished retrying but couldn't create or open
if (handle == null || handle.IsInvalid)
{
throw new InvalidOperationException(SR.InvalidOperation_CantCreateFileMapping);
}
return handle;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>
/// This converts a MemoryMappedFileRights to its corresponding native FILE_MAP_XXX value to be used when
/// creating new views.
/// </summary>
private static int GetFileMapAccess(MemoryMappedFileRights rights)
{
return (int)rights;
}
/// <summary>
/// This converts a MemoryMappedFileAccess to its corresponding native FILE_MAP_XXX value to be used when
/// creating new views.
/// </summary>
internal static int GetFileMapAccess(MemoryMappedFileAccess access)
{
switch (access)
{
case MemoryMappedFileAccess.Read: return Interop.mincore.FileMapOptions.FILE_MAP_READ;
case MemoryMappedFileAccess.Write: return Interop.mincore.FileMapOptions.FILE_MAP_WRITE;
case MemoryMappedFileAccess.ReadWrite: return Interop.mincore.FileMapOptions.FILE_MAP_READ | Interop.mincore.FileMapOptions.FILE_MAP_WRITE;
case MemoryMappedFileAccess.CopyOnWrite: return Interop.mincore.FileMapOptions.FILE_MAP_COPY;
case MemoryMappedFileAccess.ReadExecute: return Interop.mincore.FileMapOptions.FILE_MAP_EXECUTE | Interop.mincore.FileMapOptions.FILE_MAP_READ;
default:
Debug.Assert(access == MemoryMappedFileAccess.ReadWriteExecute);
return Interop.mincore.FileMapOptions.FILE_MAP_EXECUTE | Interop.mincore.FileMapOptions.FILE_MAP_READ | Interop.mincore.FileMapOptions.FILE_MAP_WRITE;
}
}
/// <summary>
/// This converts a MemoryMappedFileAccess to it's corresponding native PAGE_XXX value to be used by the
/// factory methods that construct a new memory mapped file object. MemoryMappedFileAccess.Write is not
/// valid here since there is no corresponding PAGE_XXX value.
/// </summary>
internal static int GetPageAccess(MemoryMappedFileAccess access)
{
switch (access)
{
case MemoryMappedFileAccess.Read: return Interop.mincore.PageOptions.PAGE_READONLY;
case MemoryMappedFileAccess.ReadWrite: return Interop.mincore.PageOptions.PAGE_READWRITE;
case MemoryMappedFileAccess.CopyOnWrite: return Interop.mincore.PageOptions.PAGE_WRITECOPY;
case MemoryMappedFileAccess.ReadExecute: return Interop.mincore.PageOptions.PAGE_EXECUTE_READ;
default:
Debug.Assert(access == MemoryMappedFileAccess.ReadWriteExecute);
return Interop.mincore.PageOptions.PAGE_EXECUTE_READWRITE;
}
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
[SecurityCritical]
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, int desiredAccessRights, bool createOrOpen)
{
SafeMemoryMappedFileHandle handle = Interop.mincore.OpenFileMapping(
desiredAccessRights, (inheritability & HandleInheritability.Inheritable) != 0, mapName);
int lastError = Marshal.GetLastWin32Error();
if (handle.IsInvalid)
{
if (createOrOpen && (lastError == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND))
{
throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access");
}
else
{
throw Win32Marshal.GetExceptionForWin32Error(lastError);
}
}
return handle;
}
/// <summary>
/// Helper method used to extract the native binary security descriptor from the MemoryMappedFileSecurity
/// type. If pinningHandle is not null, caller must free it AFTER the call to CreateFile has returned.
/// </summary>
[SecurityCritical]
private unsafe static Interop.mincore.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability)
{
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES);
if ((inheritability & HandleInheritability.Inheritable) != 0)
{
secAttrs = new Interop.mincore.SECURITY_ATTRIBUTES();
secAttrs.nLength = (uint)Marshal.SizeOf(secAttrs);
secAttrs.bInheritHandle = true;
}
return secAttrs;
}
/// <summary>
/// Replacement for Thread.Sleep(milliseconds), which isn't available.
/// </summary>
internal static void ThreadSleep(int milliseconds)
{
new ManualResetEventSlim(initialState: false).Wait(milliseconds);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
namespace ICSimulator
{
public class BitValuePair
{
public int bits;
public ulong val
{
get { return ((ulong)1) << bits; }
set
{
bits = (int)Math.Ceiling(Math.Log(value, 2));
if ((int)Math.Floor(Math.Log(value, 2)) != bits)
throw new Exception("Only settable to powers of two!");
}
}
public BitValuePair(int bits)
{
this.bits = bits;
}
}
public abstract class ConfigGroup
{
/// <summary>
/// Special switch for complex parameter initialization
/// </summary>
protected abstract bool setSpecialParameter(string param, string val);
/// <summary>
/// Verify member parameters; called after all options are parsed.
/// </summary>
public abstract void finalize();
public void setParameter(string param, string val)
{
if (setSpecialParameter(param, val))
return;
try
{
FieldInfo fi = GetType().GetField(param);
Type t = fi.FieldType;
if (t == typeof(int))
fi.SetValue(this, int.Parse(val));
else if (t == typeof(ulong))
fi.SetValue(this, ulong.Parse(val));
else if (t == typeof(double))
fi.SetValue(this, double.Parse(val));
else if (t == typeof(bool))
fi.SetValue(this, bool.Parse(val));
else if (t == typeof(string))
fi.SetValue(this, val);
else if (t.BaseType == typeof(Enum))
fi.SetValue(this, Enum.Parse(t, val));
else if (t == typeof(BitValuePair))
((BitValuePair)fi.GetValue(this)).bits = int.Parse(val);
else
throw new Exception(String.Format("Unhandled parameter type {0}", t));
}
catch (NullReferenceException e)
{
Console.WriteLine("Parameter {0} not found!", param);
throw e;
}
}
}
public enum BinningMethod
{
NONE,
KMEANS,
EQUAL_PER,
DELTA
}
public enum SynthTrafficPattern
{
UR,
BC,
TR,
}
public class Config : ConfigGroup
{
public static ProcessorConfig proc = new ProcessorConfig();
public static MemoryConfig memory = new MemoryConfig();
public static RouterConfig router = new RouterConfig();
public static bool synthGen = false;
public static double synthRate = 0.1;
public static int synthQueueLimit = 1000;
public static SynthTrafficPattern synthPattern = SynthTrafficPattern.UR;
// ---- MICRO'11
// -- AFC
public static int afc_buf_per_vnet = 8;
public static int afc_vnets = 8;
public static bool afc_real_classes = false; // otherwise, randomize for even distribution
public static int afc_avg_window = 4;
public static double afc_ewma_history = 0.05;
public static double afc_buf_threshold = 0.6;
public static double afc_bless_threshold = 0.5;
public static bool afc_force = false; // force bufferless or buffered mode?
public static bool afc_force_buffered = true; // if force, force buffered or bufferless?
// -- self-tuned congestion control (simple netutil-based throttler)
public static int selftuned_quantum = 128; // update once per quantum
public static int selftuned_netutil_window = 64;
public static bool selftuned_bangbang = false; // true = bang-bang control, false = adj. throt rate
public static double selftuned_rate_delta = 0.01; // throt-rate delta
public static double selftuned_netutil_tolerance = 0.05; // tolerance on either side of target (hysteresis)
public static double selftuned_init_netutil_target = 0.7;
// -- self-tuned congestion control: hillclimbing based on above netutil-target-seeking
public static bool selftuned_seek_higher_ground = false; // hillclimb on IPC? (off by default)
public static int selftuned_ipc_window = 100000;
public static int selftuned_ipc_quantum = 100000;
public static double selftuned_drop_threshold = 0.9; //0.75;
public static double selftuned_target_decrease = 0.02;
public static double selftuned_target_increase = 0.02;
// ---- Global RR throttling
public static bool cluster_prios = false;
public static bool cluster_prios_injq = false; // extend prios into inj Q
public static double MPKI_max_thresh = 50;
public static double MPKI_min_thresh = 35;
public static double MPKI_high_node = 50;
public static int num_epoch = 3;
public static double thresholdWeight = 0.1;
public static bool canAddEmptyCluster = false;
public static int interval_length = 50;
public static int short_life_interval = 10;
public static double throttling_threshold = 2.0;
public static double netutil_throttling_threshold = 0.5;
//# of cycles for each sampling period to determine whether to throttle
public static int throttle_sampling_period = 1000;
public static double RR_throttle_rate = 0.94;
// ---- Global RR Batch controller
public static double cluster_MPKI_threshold = 100;
public static bool adaptive_cluster_mpki = false;
public static bool alpha = false;
public static bool adaptive_rate = false;
// ---- Global RR Adaptive controller
public static double free_total_MPKI = 100;
// ---- Cluster will try to map far node to the same cluster
public static bool distanceAwareCluster = true;
// ---- Static Controller
// static throttle rate
public static double sweep_th_rate = 0;
// specify which node to throttle when using static throttle controller
public static string throttle_node = "1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1";
// ---- Three level throttling controller
// # of sampling periods for each applications test.
public static int apps_test_freq = 1;
public static double sampling_period_freq = 10;
public static double sensitivity_threshold = 0.05;
// apps with high mpki that exceeds cluster threshold will be always throttled
public static bool use_cluster_threshold = true;
// ---- Three level throttling controller
public static bool use_absolute = true;
public static double ipc_hurt_co = 1;
// ---- SIGCOMM'11
//
public static int workload_number = 0;
public static string lambdas = "";
public static string misses = "";
public static bool simplemap_mem = false;
public static int simple_MC_think = 200;
public static ControllerType controller = ControllerType.NONE;
public static string controller_mix = "";
// STC:
// Every 'reprioritizePeriod', counters are calculated for each app as
// numerator/denom, factoring into past values based on historyWeight,
// packets are then put into bins for injection and routing decisions
public static double STC_history = 0;
public static ulong STC_period = 300000;
public static BinningMethod STC_binMethod = BinningMethod.KMEANS;
public static int STC_binCount = 8;
public static ulong STC_batchPeriod = 16000;
public static ulong STC_batchCount = 8;
// throttling:
// params for HotNets
public static int throttle_epoch = 1000;
public static int throttle_averaging_window = 128;
// also throt_min, throt_max, throt_scale, congested_alpha, congested_beta, congested_gamma below
// simple mapping (distribution):
public static double simplemap_lambda = 2.0;
public static int bounded_locality = -1;
public static int neighborhood_locality = -1;
public static int overlapping_squares = -1;
// ----
public static bool histogram_bins = true;
public static int barrier = 1;
// ---- ISCA'11
public static int ideal_router_width = 8;
public static int ideal_router_length = 4;
// ---
public static bool bochs_fe = false;
// ---- synth traces
public static double synth_reads_fraction = 0.8;
public static double synth_rate = 0.1;
// ----
// ---- sampling methodology
public static int rand_seed = 0; // controlled seed for deterministic runs
public static ulong randomize_trace = 0; // range of starting counts (in insns)
public static int warmup_cyc = 0;
public static bool trace_wraparound = false;
public static ulong insns = 1000000000000; // insns for which stats are collected on each CPU
// for Weighted Speedup
public static string readlog = ""; // retire-time annotation log (one per trace, space-separated)
public static string writelog = ""; // name of single annotation log to write
public static int writelog_node = -1; // node from which to take annotation log
public static string logpath = "."; // path in which to find annotation logs
public static int writelog_delta = 100; // instruction delta at which to write retire-time annotations
// ----
// ---- golden packet / injection token
public static bool calf_new_inj_ej = false;
public static int gp_levels = 1;
public static double gp_epoch = 1.0;
public static int gp_rescuers = 0;
public static bool gp_rescuers_dummy = false;
public static bool gp_adaptive = false;
public static bool dor_only = false; // dimension-ordered routing only
public static bool edge_loop = true;
public static bool torus = false;
public static bool sortnet_twist = true;
public static bool sortnet_full = false;
// ----
// ---- promises
public static bool promise_wb_only = false;
public static bool coherence_noPromises = false; // promises not used; writebacks bypass NoC
// ----
// ---- new cache architecture
public static bool simple_nocoher = false; // simple no-coherence, no-memory (low overhead) model?
public static int cache_block = 5; // cache block size is universal
public static int coherent_cache_size = 14; // power of two
public static int coherent_cache_assoc = 2; // power of two
public static bool sh_cache = true; // have a shared cache layer?
public static int sh_cache_size = 18; // power of two: per slice
public static int sh_cache_assoc = 4; // power of two
public static bool sh_cache_perfect = true; // perfect shared cache?
public static int shcache_buf = 16; // reassembly buffer slots per shared cache slice
public static int shcache_lat = 15; // cycles
public static int cohcache_lat = 2; // cycles
public static int cacheop_lat = 1; // cycles -- passthrough lat for in-progress operations
// ----
// ---- CAL paper (true bufferless)
public static int cheap_of = 1; // oldest-first age divisor
public static int cheap_of_cap = -1; // if not -1, livelock limit at which we flush
public static bool naive_rx_buf = false;
public static bool naive_rx_buf_evict = false;
public static RxBufMode rxbuf_mode = RxBufMode.NONE;
public static int rxbuf_size = 8;
public static bool split_queues = true; // for validation with orig sim
public static int mshrs = 16;
public static bool rxbuf_cache_only = true;
public static bool ctrl_data_split = false;
public static bool ignore_livelock = true;
public static ulong livelock_thresh = 1000000;
// ----
// ---- SIGCOMM'10 paper (starvation congestion-control)
public static bool starve_control = false;
public static bool speriod_control = false;
public static bool net_age_arbitration = false;
public static bool tier1_disabled = false;
public static bool tier2_disabled = true;
public static bool tier3_disabled = false;
public static double srate_thresh = 0.45;
public static int srate_win = 1000;
public static bool srate_log = false;
public static bool starve_log = false;
public static bool netu_log = false;
public static bool nthrot_log = false;
public static int interleave_bits = 0;
public static bool valiant = false;
public static bool stnetu_log = false;
public static bool irate_log = false;
public static bool qlen_log = false;
public static bool aqlen_log = false;
public static bool sstate_log = false;
public static double static_throttle = 0.0;
public static bool starvehigh_new = true;
public static bool throt_ideal = false;
public static bool throt_starvee = false;
public static bool throt_stree = false;
public static int throt_stree_t = 0;
public static bool starvee_distributed = false;
public static bool ttime_log = false;
public static bool tier1_prob = true;
public static bool biasing_inject = false;
public static bool sources_log = false;
public static bool nbutil_log = false;
public static double bias_prob = 0.333;
public static bool bias_single = true;
public static string socket = "";
public static bool idealnet = false;
public static int ideallat = 10;
public static int idealcap = 16;
public static bool idealrr = false;
public static double throt_rate = 0.75;
public static double congested_alpha = 0.35;
public static double congested_omega = 15;
public static double congested_max = 0.9;
public static double throt_min = 0.45;
public static double throt_max = 0.75;
public static double throt_scale = 30;
public static double avg_scale = 1;
public static bool always_obey_tier3 = true;
public static bool use_qlen = true;
public static int l1count_Q = 100000;
// ----
// ---- SCARAB impl
public static int nack_linkLatency = 2;
public static int nack_nr = 16;
public static bool address_is_node = false;
public static bool opp_buffering = false;
public static bool nack_epoch = false;
// ----
public static bool progress = true;
public static string output = "output.txt";
public static string matlab = "";
public static string fairdata = "";
public static int simulationDuration = 1000;
public static bool stopOnEnd = false;
public static int network_nrX = 2;
public static int network_nrY = 2;
public static bool randomize_defl = true;
public static int network_loopback = -1;
public static int network_quantum = -1;
public static int entropy_quantum = 1000; // in cycles
// 741: BLESS-CC Congestion Avoidance Variables
public static int BLESSCC_DeflectionAvgRounds = 10;
public static double BLESSCC_DeflectionThreshold = 35.0;
// 741: BLESS-CC variables for distinguishing congestion from hot-spots
public static int BLESSCC_BitsForCongestion = 3;
public static double BLESSCC_CongestionDecrease = 0.1;
public static double BLESSCC_CongestionIncrease = 0.01;
public static int BLESSCC_MinimumRoundsBetween = 5;
// 741: BLESS-CC Valiant routing variables
public static int BLESSCC_ValiantRounds = 50;
public static int BLESSCC_ValiantProcessors = 4;
// 741: BLESS-CC Fairness variables
public static int BLESSCC_RateHistoryRounds = 20;
public static int BLESSCC_RateHistorySources = 1;
public static bool BLESSCC_FairnessInputOnly = false;
// 741: Link monitoring variables to prevent starvation
public static int BLESSCC_StarvationRounds = 1000;
// ------ CIF: experiment parameters, new version -----------------
public static string sources = "all uniformRandom";
public static string finish = "cycle 10000000";
public static string solo = "";
// ------ CHIPPER experiments --------------
public static int ejectCount = 2;
// -- Hard Potato --
public static bool hardPotato = false;
public static double hardPotatoConstant = 65.2387639;
// -- Silver flit --
public static string silverMode = "none";
public static bool alwaysSilver = true;
// -- App aware buffering --
public static bool app_aware_buffer = false;
public static bool largest_mpki = false;
public static bool smallest_mpki = false;
public static bool reverse_mpki = false;
// ------ Resubmit Buffer ------------
public static bool resubmitBuffer = true;
public static bool resubmitLineBuffers = false; // One buffer for each input line (4)
public static bool middleResubmit = false;
public static bool inputResubmitBuffers = false;
public static int pipelineCount = 1;
// Buffer size
public static int sizeOfRSBuffer = 16; // 16 not 8 for chipper, 2 for BLESS
public static bool isInfiniteRSBuffer = false; // Overrides size
// Buffer sorting algorithms
public static string RSBuffer_sort = "fifo"; // Will replace the bools below
public static bool RSBuffer_randomVariant = false;
/*public static bool RSBuffer_fifo = false; // Easiest to design and most consistant
public static bool RSBuffer_oldestFirst = false;
public static bool RSBuffer_mostDeflected = false;
public static bool RSBuffer_mostInRebuf = false;
public static bool RSBuffer_highestPriority = false;
*/
// LEGACY OPTIONS The number of allowed flits to be injected and removed at a time
public static int rebufInjectCount = 1; // More than 1 doesn't seem to help
public static int rebufRemovalCount = 1; // Anything higher than 1 will cause problems
// Sets all outgoing packets to false for wasInRebuf
public static bool wasInRebufCycleRefresh = false;
/* Resubmit eject options */
// Resubmit ejection priority sorts
public static string resubmitBy = "Random"; // will replace the bools below
public static bool resubmitByRandomVariant = false;
public static bool flip_resubmitPrio = true;
/*
public static bool resubmitByInjectionTime = false; // Sometimes does the best job but not with prioritization over normal flits
public static bool resubmitByDeflections = false; // Wasn't better than random, plus then a deflection counter would have to be in each flit
public static bool resubmitByRandom = false; // Cheap, easy to implement, and better than arbitrary
public static bool resubmitByArbitraryOrder = false;
public static bool resubmitByPriority = false; // Need to test
*/
// Tweaks to not eject flits
public static bool noResubmitProductive = false; // Only one that provides any significant difference for BLESS
public static bool noResubmitLocalDest = true;
public static bool noResubmitTwice = false;
public static bool resubmitBlocksInjection = false; // Causes a major performance hit in all loads
// Number of flits to skip before allowing one into the buffer
public static bool noResubmitSkip = false;
public static ulong noResubmitSkipCount = 4; // For bless 4/6 is optimum. 0 is optimum for chipper, but if there is a delay 4 is still optimum.
// Distance away from target to not put in resubmit buffer
public static bool noResubmitClose = false;
public static ulong noResubmitDist = 2; // 2 is optimum for both but its not a significant difference
public static bool noResubmitGolden = true; // No significant change
public static bool noResubmitRedirection = true; // need to test
/* End of resubmit eject options */
// Resubmit injection options
public static bool redirection = true; // Doesn't seem to make a big difference even after optimizing
public static ulong redirection_threshold = 1; // Must be blocked for threshold + 1 cycles
public static ulong redirectCount = 1;
// Prioritization Options
public static bool resubmitFlitWins = false; // Increases performance in most situations
public static bool resubmitFlitOneWins = false; // Best choice for both chipper and bless
public static bool resubmitFlitNrWins = false;
public static bool resubmitPrioWins = false;
public static bool deprioritize = true;
public static bool prioByDefl = false;
//public static bool prioTypes = false;
public static bool packetPrio = false;
public static bool initFlitPrio = false;
public static bool deflPrio = false;
public static bool rebufPrio = false;
public static bool infectPrio = false;
public static bool deflectOverInitPrio = false;
public static bool distancePrio = false;
public static int randomPacketPrioPercent = 50;
public static int randomFlitPrioPercent = 50;
//public static bool prioRandomAndDefl = false;
//public static bool prioFlipExperiment = false;
//public static bool prioRandomExperiment = false;
//public static bool prioSkipExperiment = false;
//public static int prioSkipCount = 0;
public static bool prioFlipOnEpoch = false;
public static bool wasDeflectCycleRefresh = false; // Destroys performance gain by prio
public static bool noDeflectProductive = false; // Causes small gains
//public static bool prioByRandom = false;
//public static bool prioByArbitrary = false; // Works better and is cheaper to make
public static bool prioComplexDist = false;
/* input buffer chipper */
public static bool inputBuffer = false;
public static bool inputBuffer_retry = false;
/* End input buffer chipper */
// Output Buffers
public static bool outputBuffers = false;
public static int nrOutputRemove = 1;
public static int nrOutputInject = 4;
/* XY RINGS */
public static bool xy_rings = false;
public static bool injectOnlyX = false;
/* END XY RINGS */
/* Linked Rings */
public static bool DisjointRings = false;
public static int nrPlaceholders = 2;
public static int injectHoldThreshold = 3;
public static int blockInjectCount = 3;
public static bool injectedCountReset = false;
public static bool SeperateConnect = false;
public static int ringSize = 4; // Number of nodes in a ring
public static bool sameDir = false;
public static bool disjointRings = false;
public static string disjointConnection = "mesh";
public static bool RingRouter = false;
public static int ringWidth = 2; // Don't change unless I fix the code
public static int ringHeight = 2;
public static int nrConnections = 1;
public static bool alternateDir = false;
/* Deflection Infection */
public static bool prioByInfection = false;
public static int infectionRate = 100;
public static int cureRate = 0;
public static int initialInfectionRate = 50;
/* End Deflection Infection */
public static int N
{ get { return network_nrX * network_nrY; } }
//TODO: CATEGORIZE
public static string[] traceFilenames;
public static string TraceDirs = ""; ///<summary> Comma delimited list of dirs potentially containing traces </summary>
public static bool PerfectLastLevelCache = false;
public static bool RouterEvaluation = false;
public static ulong RouterEvaluationIterations = 1;
public void read(string[] args)
{
string[] traceArgs = null;
int traceArgOffset = 0;
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-workload")
{
string worksetFile = args[i + 1];
int index = int.Parse(args[i + 2]);
workload_number = index;
if (!File.Exists(args[i + 1]))
throw new Exception("Could not locate workset file " + worksetFile);
string[] lines = File.ReadAllLines(worksetFile);
if (TraceDirs == "")
TraceDirs = lines[0];
traceArgs = lines[index].Split();
traceArgOffset = 0;
i += 2;
}
else if (args[i] == "-traces")
{
traceArgs = args;
traceArgOffset = i + 1;
break;
}
else
{
setSystemParameter(args[i].Substring(1), args[i + 1]);
i++;
}
}
traceFilenames = new string[N];
if (traceArgs.Length - traceArgOffset < N)
throw new Exception(
String.Format("Not enough trace files given (got {0}, wanted {1})", traceArgs.Length - traceArgOffset, N));
for (int a = 0; a < N; a++)
{
traceFilenames[a] = traceArgs[traceArgOffset + a];
}
Simulator.stats = new Stats(Config.N);
finalize();
proc.finalize();
memory.finalize();
router.finalize();
}
public void readConfig(string filename)
{
Char[] delims = new Char[] { '=' }; //took out ' ' for better listing capabilities
StreamReader configReader = File.OpenText(filename);
if (configReader == null)
return;
string buf;
for (; ; )
{
buf = configReader.ReadLine();
if (buf == null)
break;
int comment = buf.IndexOf("//");
if (comment != -1)
buf = buf.Remove(comment).Trim();
if (buf == "")
continue;
string[] flags = buf.Split(delims, 2);
if (flags.Length < 2) continue;
setSystemParameter(flags[0].Trim(), flags[1].Trim());
}
}
public void setSystemParameter(string param, string val)
{
Console.WriteLine("{0} <= {1}", param, val);
if (param.Contains("."))
{
string name = param.Substring(0, param.IndexOf('.'));
string subparam = param.Substring(param.IndexOf('.') + 1);
FieldInfo fi = GetType().GetField(name);
if (!(fi.GetValue(this) is ConfigGroup))
{
throw new Exception(String.Format("Non-ConfigGroup indexed, of type {0}", fi.FieldType.ToString()));
}
((ConfigGroup)fi.GetValue(this)).setParameter(subparam, val);
}
else
setParameter(param, val);
}
protected override bool setSpecialParameter(string param, string val)
{
switch (param)
{
case "config":
readConfig(val); break;
default:
return false;
}
return true;
}
public static string ConfigHash()
{
System.Security.Cryptography.MD5CryptoServiceProvider md5 =
new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] checksum = md5.ComputeHash(new System.Text.ASCIIEncoding().GetBytes(
Config.sources +
Config.router.algorithm +
Config.router.options +
Config.network_nrX + Config.network_nrY));
return BitConverter.ToString(checksum).Replace("-", "");
}
public override void finalize()
{
if (output == "" && matlab == "")
{
throw new Exception("No output specified.");
}
if (STC_binCount == 0)
STC_binCount = N;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.