context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// CartSummary
/// </summary>
[DataContract]
public partial class CartSummary : IEquatable<CartSummary>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="CartSummary" /> class.
/// </summary>
/// <param name="arbitraryShippingHandlingTotal">arbitraryShippingHandlingTotal.</param>
/// <param name="arbitraryTax">arbitraryTax.</param>
/// <param name="arbitraryTaxRate">arbitraryTaxRate.</param>
/// <param name="arbitraryTaxableSubtotal">arbitraryTaxableSubtotal.</param>
/// <param name="shippingHandling">shippingHandling.</param>
/// <param name="shippingHandlingDiscount">shippingHandlingDiscount.</param>
/// <param name="shippingHandlingWithDiscount">shippingHandlingWithDiscount.</param>
/// <param name="subtotal">subtotal.</param>
/// <param name="subtotalDiscount">subtotalDiscount.</param>
/// <param name="subtotalWithDiscount">subtotalWithDiscount.</param>
/// <param name="surcharge">surcharge.</param>
/// <param name="tax">tax.</param>
/// <param name="taxableSubtotal">taxableSubtotal.</param>
/// <param name="taxableSubtotalDiscount">taxableSubtotalDiscount.</param>
/// <param name="taxableSubtotalWithDiscount">taxableSubtotalWithDiscount.</param>
/// <param name="total">total.</param>
public CartSummary(Currency arbitraryShippingHandlingTotal = default(Currency), Currency arbitraryTax = default(Currency), Currency arbitraryTaxRate = default(Currency), Currency arbitraryTaxableSubtotal = default(Currency), Currency shippingHandling = default(Currency), Currency shippingHandlingDiscount = default(Currency), Currency shippingHandlingWithDiscount = default(Currency), Currency subtotal = default(Currency), Currency subtotalDiscount = default(Currency), Currency subtotalWithDiscount = default(Currency), Currency surcharge = default(Currency), Currency tax = default(Currency), Currency taxableSubtotal = default(Currency), Currency taxableSubtotalDiscount = default(Currency), Currency taxableSubtotalWithDiscount = default(Currency), Currency total = default(Currency))
{
this.ArbitraryShippingHandlingTotal = arbitraryShippingHandlingTotal;
this.ArbitraryTax = arbitraryTax;
this.ArbitraryTaxRate = arbitraryTaxRate;
this.ArbitraryTaxableSubtotal = arbitraryTaxableSubtotal;
this.ShippingHandling = shippingHandling;
this.ShippingHandlingDiscount = shippingHandlingDiscount;
this.ShippingHandlingWithDiscount = shippingHandlingWithDiscount;
this.Subtotal = subtotal;
this.SubtotalDiscount = subtotalDiscount;
this.SubtotalWithDiscount = subtotalWithDiscount;
this.Surcharge = surcharge;
this.Tax = tax;
this.TaxableSubtotal = taxableSubtotal;
this.TaxableSubtotalDiscount = taxableSubtotalDiscount;
this.TaxableSubtotalWithDiscount = taxableSubtotalWithDiscount;
this.Total = total;
}
/// <summary>
/// Gets or Sets ArbitraryShippingHandlingTotal
/// </summary>
[DataMember(Name="arbitrary_shipping_handling_total", EmitDefaultValue=false)]
public Currency ArbitraryShippingHandlingTotal { get; set; }
/// <summary>
/// Gets or Sets ArbitraryTax
/// </summary>
[DataMember(Name="arbitrary_tax", EmitDefaultValue=false)]
public Currency ArbitraryTax { get; set; }
/// <summary>
/// Gets or Sets ArbitraryTaxRate
/// </summary>
[DataMember(Name="arbitrary_tax_rate", EmitDefaultValue=false)]
public Currency ArbitraryTaxRate { get; set; }
/// <summary>
/// Gets or Sets ArbitraryTaxableSubtotal
/// </summary>
[DataMember(Name="arbitrary_taxable_subtotal", EmitDefaultValue=false)]
public Currency ArbitraryTaxableSubtotal { get; set; }
/// <summary>
/// Gets or Sets ShippingHandling
/// </summary>
[DataMember(Name="shipping_handling", EmitDefaultValue=false)]
public Currency ShippingHandling { get; set; }
/// <summary>
/// Gets or Sets ShippingHandlingDiscount
/// </summary>
[DataMember(Name="shipping_handling_discount", EmitDefaultValue=false)]
public Currency ShippingHandlingDiscount { get; set; }
/// <summary>
/// Gets or Sets ShippingHandlingWithDiscount
/// </summary>
[DataMember(Name="shipping_handling_with_discount", EmitDefaultValue=false)]
public Currency ShippingHandlingWithDiscount { get; set; }
/// <summary>
/// Gets or Sets Subtotal
/// </summary>
[DataMember(Name="subtotal", EmitDefaultValue=false)]
public Currency Subtotal { get; set; }
/// <summary>
/// Gets or Sets SubtotalDiscount
/// </summary>
[DataMember(Name="subtotal_discount", EmitDefaultValue=false)]
public Currency SubtotalDiscount { get; set; }
/// <summary>
/// Gets or Sets SubtotalWithDiscount
/// </summary>
[DataMember(Name="subtotal_with_discount", EmitDefaultValue=false)]
public Currency SubtotalWithDiscount { get; set; }
/// <summary>
/// Gets or Sets Surcharge
/// </summary>
[DataMember(Name="surcharge", EmitDefaultValue=false)]
public Currency Surcharge { get; set; }
/// <summary>
/// Gets or Sets Tax
/// </summary>
[DataMember(Name="tax", EmitDefaultValue=false)]
public Currency Tax { get; set; }
/// <summary>
/// Gets or Sets TaxableSubtotal
/// </summary>
[DataMember(Name="taxable_subtotal", EmitDefaultValue=false)]
public Currency TaxableSubtotal { get; set; }
/// <summary>
/// Gets or Sets TaxableSubtotalDiscount
/// </summary>
[DataMember(Name="taxable_subtotal_discount", EmitDefaultValue=false)]
public Currency TaxableSubtotalDiscount { get; set; }
/// <summary>
/// Gets or Sets TaxableSubtotalWithDiscount
/// </summary>
[DataMember(Name="taxable_subtotal_with_discount", EmitDefaultValue=false)]
public Currency TaxableSubtotalWithDiscount { get; set; }
/// <summary>
/// Gets or Sets Total
/// </summary>
[DataMember(Name="total", EmitDefaultValue=false)]
public Currency Total { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class CartSummary {\n");
sb.Append(" ArbitraryShippingHandlingTotal: ").Append(ArbitraryShippingHandlingTotal).Append("\n");
sb.Append(" ArbitraryTax: ").Append(ArbitraryTax).Append("\n");
sb.Append(" ArbitraryTaxRate: ").Append(ArbitraryTaxRate).Append("\n");
sb.Append(" ArbitraryTaxableSubtotal: ").Append(ArbitraryTaxableSubtotal).Append("\n");
sb.Append(" ShippingHandling: ").Append(ShippingHandling).Append("\n");
sb.Append(" ShippingHandlingDiscount: ").Append(ShippingHandlingDiscount).Append("\n");
sb.Append(" ShippingHandlingWithDiscount: ").Append(ShippingHandlingWithDiscount).Append("\n");
sb.Append(" Subtotal: ").Append(Subtotal).Append("\n");
sb.Append(" SubtotalDiscount: ").Append(SubtotalDiscount).Append("\n");
sb.Append(" SubtotalWithDiscount: ").Append(SubtotalWithDiscount).Append("\n");
sb.Append(" Surcharge: ").Append(Surcharge).Append("\n");
sb.Append(" Tax: ").Append(Tax).Append("\n");
sb.Append(" TaxableSubtotal: ").Append(TaxableSubtotal).Append("\n");
sb.Append(" TaxableSubtotalDiscount: ").Append(TaxableSubtotalDiscount).Append("\n");
sb.Append(" TaxableSubtotalWithDiscount: ").Append(TaxableSubtotalWithDiscount).Append("\n");
sb.Append(" Total: ").Append(Total).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as CartSummary);
}
/// <summary>
/// Returns true if CartSummary instances are equal
/// </summary>
/// <param name="input">Instance of CartSummary to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CartSummary input)
{
if (input == null)
return false;
return
(
this.ArbitraryShippingHandlingTotal == input.ArbitraryShippingHandlingTotal ||
(this.ArbitraryShippingHandlingTotal != null &&
this.ArbitraryShippingHandlingTotal.Equals(input.ArbitraryShippingHandlingTotal))
) &&
(
this.ArbitraryTax == input.ArbitraryTax ||
(this.ArbitraryTax != null &&
this.ArbitraryTax.Equals(input.ArbitraryTax))
) &&
(
this.ArbitraryTaxRate == input.ArbitraryTaxRate ||
(this.ArbitraryTaxRate != null &&
this.ArbitraryTaxRate.Equals(input.ArbitraryTaxRate))
) &&
(
this.ArbitraryTaxableSubtotal == input.ArbitraryTaxableSubtotal ||
(this.ArbitraryTaxableSubtotal != null &&
this.ArbitraryTaxableSubtotal.Equals(input.ArbitraryTaxableSubtotal))
) &&
(
this.ShippingHandling == input.ShippingHandling ||
(this.ShippingHandling != null &&
this.ShippingHandling.Equals(input.ShippingHandling))
) &&
(
this.ShippingHandlingDiscount == input.ShippingHandlingDiscount ||
(this.ShippingHandlingDiscount != null &&
this.ShippingHandlingDiscount.Equals(input.ShippingHandlingDiscount))
) &&
(
this.ShippingHandlingWithDiscount == input.ShippingHandlingWithDiscount ||
(this.ShippingHandlingWithDiscount != null &&
this.ShippingHandlingWithDiscount.Equals(input.ShippingHandlingWithDiscount))
) &&
(
this.Subtotal == input.Subtotal ||
(this.Subtotal != null &&
this.Subtotal.Equals(input.Subtotal))
) &&
(
this.SubtotalDiscount == input.SubtotalDiscount ||
(this.SubtotalDiscount != null &&
this.SubtotalDiscount.Equals(input.SubtotalDiscount))
) &&
(
this.SubtotalWithDiscount == input.SubtotalWithDiscount ||
(this.SubtotalWithDiscount != null &&
this.SubtotalWithDiscount.Equals(input.SubtotalWithDiscount))
) &&
(
this.Surcharge == input.Surcharge ||
(this.Surcharge != null &&
this.Surcharge.Equals(input.Surcharge))
) &&
(
this.Tax == input.Tax ||
(this.Tax != null &&
this.Tax.Equals(input.Tax))
) &&
(
this.TaxableSubtotal == input.TaxableSubtotal ||
(this.TaxableSubtotal != null &&
this.TaxableSubtotal.Equals(input.TaxableSubtotal))
) &&
(
this.TaxableSubtotalDiscount == input.TaxableSubtotalDiscount ||
(this.TaxableSubtotalDiscount != null &&
this.TaxableSubtotalDiscount.Equals(input.TaxableSubtotalDiscount))
) &&
(
this.TaxableSubtotalWithDiscount == input.TaxableSubtotalWithDiscount ||
(this.TaxableSubtotalWithDiscount != null &&
this.TaxableSubtotalWithDiscount.Equals(input.TaxableSubtotalWithDiscount))
) &&
(
this.Total == input.Total ||
(this.Total != null &&
this.Total.Equals(input.Total))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.ArbitraryShippingHandlingTotal != null)
hashCode = hashCode * 59 + this.ArbitraryShippingHandlingTotal.GetHashCode();
if (this.ArbitraryTax != null)
hashCode = hashCode * 59 + this.ArbitraryTax.GetHashCode();
if (this.ArbitraryTaxRate != null)
hashCode = hashCode * 59 + this.ArbitraryTaxRate.GetHashCode();
if (this.ArbitraryTaxableSubtotal != null)
hashCode = hashCode * 59 + this.ArbitraryTaxableSubtotal.GetHashCode();
if (this.ShippingHandling != null)
hashCode = hashCode * 59 + this.ShippingHandling.GetHashCode();
if (this.ShippingHandlingDiscount != null)
hashCode = hashCode * 59 + this.ShippingHandlingDiscount.GetHashCode();
if (this.ShippingHandlingWithDiscount != null)
hashCode = hashCode * 59 + this.ShippingHandlingWithDiscount.GetHashCode();
if (this.Subtotal != null)
hashCode = hashCode * 59 + this.Subtotal.GetHashCode();
if (this.SubtotalDiscount != null)
hashCode = hashCode * 59 + this.SubtotalDiscount.GetHashCode();
if (this.SubtotalWithDiscount != null)
hashCode = hashCode * 59 + this.SubtotalWithDiscount.GetHashCode();
if (this.Surcharge != null)
hashCode = hashCode * 59 + this.Surcharge.GetHashCode();
if (this.Tax != null)
hashCode = hashCode * 59 + this.Tax.GetHashCode();
if (this.TaxableSubtotal != null)
hashCode = hashCode * 59 + this.TaxableSubtotal.GetHashCode();
if (this.TaxableSubtotalDiscount != null)
hashCode = hashCode * 59 + this.TaxableSubtotalDiscount.GetHashCode();
if (this.TaxableSubtotalWithDiscount != null)
hashCode = hashCode * 59 + this.TaxableSubtotalWithDiscount.GetHashCode();
if (this.Total != null)
hashCode = hashCode * 59 + this.Total.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// This file makes use of the LeMP 'unroll' macro to avoid copy-pasting code.
// See http://ecsharp.net/lemp/avoid-tedium-with-LeMP.html for an explanation.
#importMacros(LeMP);
using System.Text;
using System.Threading;
namespace System.IO
{
/// <summary>
/// A writer that writes sequences of characters.
/// </summary>
public abstract class TextWriter : IDisposable
{
protected TextWriter()
{
CoreNewLineStr = Environment.NewLine;
CoreNewLine = CoreNewLineStr.ToCharArray();
}
~TextWriter()
{
if (!isDisposed)
{
Dispose(false);
}
}
protected char[] CoreNewLine;
private string CoreNewLineStr;
private bool isDisposed;
/// <summary>
/// Gets the encoding used by this text writer.
/// </summary>
/// <returns>The encoding.</returns>
public abstract Encoding Encoding { get; }
public virtual string NewLine
{
get { return CoreNewLineStr; }
set
{
if (value == null)
{
value = Environment.NewLine;
}
CoreNewLineStr = value;
CoreNewLine = value.ToCharArray();
}
}
public virtual void Close()
{
Dispose();
}
public void Dispose()
{
isDisposed = true;
Dispose(true);
}
protected virtual void Dispose(bool disposing) { }
public virtual void Flush() { }
public static readonly TextWriter Null = new NullTextWriter();
public static TextWriter Synchronized(TextWriter writer)
{
return new SynchronizedTextWriter(writer);
}
/// <summary>
/// Prints out a character.
/// </summary>
/// <param name="value">The value to write.</param>
public virtual void Write(char value)
{
// Do nothing. This is our "root" function. Ideally,
// this would've been abstract.
}
/// <summary>
/// Prints out a character, followed by an end-of-line sequence.
/// </summary>
/// <param name="value">The value to write.</param>
public virtual void WriteLine(char value)
{
Write(value);
WriteLine();
}
/// <summary>
/// Prints out the characters in a buffer.
/// </summary>
/// <param name="buffer">A buffer containing the characters to write.</param>
public virtual void Write(char[] buffer)
{
Write(buffer, 0, buffer.Length);
}
/// <summary>
/// Prints out the characters in a buffer, followed by an end-of-line sequence.
/// </summary>
/// <param name="buffer">A buffer containing the characters to write.</param>
public virtual void WriteLine(char[] buffer)
{
Write(buffer);
WriteLine();
}
/// <summary>
/// Prints out a range of characters in a buffer.
/// </summary>
/// <param name="buffer">A buffer containing the characters to write.</param>
/// <param name="index">The index of the first character to write.</param>
/// <param name="count">The number of characters to write.</param>
public virtual void Write(char[] buffer, int index, int count)
{
for (int i = 0; i < count; i++)
{
Write(buffer[index + i]);
}
}
/// <summary>
/// Prints out a range of characters in a buffer, followed by an end-of-line sequence.
/// </summary>
/// <param name="buffer">A buffer containing the characters to write.</param>
/// <param name="index">The index of the first character to write.</param>
/// <param name="count">The number of characters to write.</param>
public virtual void WriteLine(char[] buffer, int index, int count)
{
Write(buffer, index, count);
WriteLine();
}
/// <summary>
/// Prints out a string.
/// </summary>
/// <param name="value">The string to write.</param>
public virtual void Write(string value)
{
if (value != null)
{
Write(value.ToCharArray());
}
}
/// <summary>
/// Prints out a string, followed by an end-of-line sequence.
/// </summary>
/// <param name="value">The string to write.</param>
public virtual void WriteLine(string value)
{
Write(value);
WriteLine();
}
/// <summary>
/// Prints out an object.
/// </summary>
/// <param name="value">The object to write.</param>
public virtual void Write(object value)
{
if (value != null)
{
Write(value.ToString());
}
}
/// <summary>
/// Prints out an object, followed by an end-of-line sequence.
/// </summary>
/// <param name="value">The object to write.</param>
public virtual void WriteLine(object value)
{
Write(value);
WriteLine();
}
unroll ((TYPE) in (
bool,
sbyte, byte, short, ushort, int, uint, long, ulong,
float, double))
{
/// <summary>
/// Prints out a value.
/// </summary>
/// <param name="value">The value to write.</param>
public virtual void Write(TYPE value)
{
Write(value.ToString());
}
/// <summary>
/// Prints out a value, followed by an end-of-line sequence.
/// </summary>
/// <param name="value">The value to write.</param>
public virtual void WriteLine(TYPE value)
{
Write(value);
WriteLine();
}
}
/// <summary>
/// Prints out an end-of-line sequence.
/// </summary>
public virtual void WriteLine()
{
Write(CoreNewLine);
}
}
internal sealed class NullTextWriter : TextWriter
{
public NullTextWriter()
{ }
/// <inheritdoc/>
public override Encoding Encoding => null;
/// <inheritdoc/>
public override void Write(char value)
{
// Do nothing.
}
/// <inheritdoc/>
public override void Write(string value)
{
// Do nothing.
}
/// <inheritdoc/>
public override void Write(char[] buffer, int index, int count)
{
// Do nothing.
}
}
internal sealed class SynchronizedTextWriter : TextWriter
{
public SynchronizedTextWriter(TextWriter writer)
{
this.writer = writer;
this.mutex = new Mutex();
}
private TextWriter writer;
private Mutex mutex;
private void AcquireLock()
{
mutex.WaitOne();
}
private void ReleaseLock()
{
mutex.ReleaseMutex();
}
/// <inheritdoc/>
public override Encoding Encoding => writer.Encoding;
/// <inheritdoc/>
public override string NewLine
{
get => writer.NewLine;
set
{
AcquireLock();
try
{
writer.NewLine = value;
}
finally
{
ReleaseLock();
}
}
}
/// <inheritdoc/>
public override void Close()
{
AcquireLock();
try
{
writer.Close();
}
finally
{
ReleaseLock();
}
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (disposing)
{
writer.Dispose();
}
mutex.Dispose();
}
/// <inheritdoc/>
public override void Flush()
{
AcquireLock();
try
{
writer.Flush();
}
finally
{
ReleaseLock();
}
}
/// <inheritdoc/>
public override void Write(char[] buffer)
{
AcquireLock();
try
{
writer.Write(buffer);
}
finally
{
ReleaseLock();
}
}
/// <inheritdoc/>
public override void WriteLine(char[] buffer)
{
AcquireLock();
try
{
writer.WriteLine(buffer);
}
finally
{
ReleaseLock();
}
}
/// <inheritdoc/>
public override void Write(char[] buffer, int index, int count)
{
AcquireLock();
try
{
writer.Write(buffer, index, count);
}
finally
{
ReleaseLock();
}
}
/// <inheritdoc/>
public override void WriteLine(char[] buffer, int index, int count)
{
AcquireLock();
try
{
writer.WriteLine(buffer, index, count);
}
finally
{
ReleaseLock();
}
}
unroll ((TYPE) in (
char, bool, string, object,
sbyte, byte, short, ushort, int, uint, long, ulong,
float, double))
{
/// <inheritdoc/>
public override void Write(TYPE value)
{
AcquireLock();
try
{
writer.Write(value);
}
finally
{
ReleaseLock();
}
}
/// <inheritdoc/>
public override void WriteLine(TYPE value)
{
AcquireLock();
try
{
writer.WriteLine(value);
}
finally
{
ReleaseLock();
}
}
}
/// <inheritdoc/>
public override void WriteLine()
{
AcquireLock();
try
{
writer.WriteLine();
}
finally
{
ReleaseLock();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Webrtc {
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='StatsReport']"
[global::Android.Runtime.Register ("org/webrtc/StatsReport", DoNotGenerateAcw=true)]
public partial class StatsReport : global::Java.Lang.Object {
static IntPtr id_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='StatsReport']/field[@name='id']"
[Register ("id")]
public string Id {
get {
if (id_jfieldId == IntPtr.Zero)
id_jfieldId = JNIEnv.GetFieldID (class_ref, "id", "Ljava/lang/String;");
IntPtr __ret = JNIEnv.GetObjectField (Handle, id_jfieldId);
return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (id_jfieldId == IntPtr.Zero)
id_jfieldId = JNIEnv.GetFieldID (class_ref, "id", "Ljava/lang/String;");
IntPtr native_value = JNIEnv.NewString (value);
try {
JNIEnv.SetField (Handle, id_jfieldId, native_value);
} finally {
JNIEnv.DeleteLocalRef (native_value);
}
}
}
static IntPtr timestamp_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='StatsReport']/field[@name='timestamp']"
[Register ("timestamp")]
public double Timestamp {
get {
if (timestamp_jfieldId == IntPtr.Zero)
timestamp_jfieldId = JNIEnv.GetFieldID (class_ref, "timestamp", "D");
return JNIEnv.GetDoubleField (Handle, timestamp_jfieldId);
}
set {
if (timestamp_jfieldId == IntPtr.Zero)
timestamp_jfieldId = JNIEnv.GetFieldID (class_ref, "timestamp", "D");
try {
JNIEnv.SetField (Handle, timestamp_jfieldId, value);
} finally {
}
}
}
static IntPtr type_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='StatsReport']/field[@name='type']"
[Register ("type")]
public string Type {
get {
if (type_jfieldId == IntPtr.Zero)
type_jfieldId = JNIEnv.GetFieldID (class_ref, "type", "Ljava/lang/String;");
IntPtr __ret = JNIEnv.GetObjectField (Handle, type_jfieldId);
return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (type_jfieldId == IntPtr.Zero)
type_jfieldId = JNIEnv.GetFieldID (class_ref, "type", "Ljava/lang/String;");
IntPtr native_value = JNIEnv.NewString (value);
try {
JNIEnv.SetField (Handle, type_jfieldId, native_value);
} finally {
JNIEnv.DeleteLocalRef (native_value);
}
}
}
static IntPtr values_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='StatsReport']/field[@name='values']"
[Register ("values")]
public IList<Org.Webrtc.StatsReport.Value> Values {
get {
if (values_jfieldId == IntPtr.Zero)
values_jfieldId = JNIEnv.GetFieldID (class_ref, "values", "[Lorg/webrtc/StatsReport$Value;");
return JavaArray<global::Org.Webrtc.StatsReport.Value>.FromJniHandle (JNIEnv.GetObjectField (Handle, values_jfieldId), JniHandleOwnership.TransferLocalRef);
}
set {
if (values_jfieldId == IntPtr.Zero)
values_jfieldId = JNIEnv.GetFieldID (class_ref, "values", "[Lorg/webrtc/StatsReport$Value;");
IntPtr native_value = JavaArray<global::Org.Webrtc.StatsReport.Value>.ToLocalJniHandle (value);
try {
JNIEnv.SetField (Handle, values_jfieldId, native_value);
} finally {
JNIEnv.DeleteLocalRef (native_value);
}
}
}
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='StatsReport.Value']"
[global::Android.Runtime.Register ("org/webrtc/StatsReport$Value", DoNotGenerateAcw=true)]
public partial class Value : global::Java.Lang.Object {
static IntPtr name_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='StatsReport.Value']/field[@name='name']"
[Register ("name")]
public string Name {
get {
if (name_jfieldId == IntPtr.Zero)
name_jfieldId = JNIEnv.GetFieldID (class_ref, "name", "Ljava/lang/String;");
IntPtr __ret = JNIEnv.GetObjectField (Handle, name_jfieldId);
return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (name_jfieldId == IntPtr.Zero)
name_jfieldId = JNIEnv.GetFieldID (class_ref, "name", "Ljava/lang/String;");
IntPtr native_value = JNIEnv.NewString (value);
try {
JNIEnv.SetField (Handle, name_jfieldId, native_value);
} finally {
JNIEnv.DeleteLocalRef (native_value);
}
}
}
static IntPtr value_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='StatsReport.Value']/field[@name='value']"
[Register ("value")]
public string value {
get {
if (value_jfieldId == IntPtr.Zero)
value_jfieldId = JNIEnv.GetFieldID (class_ref, "value", "Ljava/lang/String;");
IntPtr __ret = JNIEnv.GetObjectField (Handle, value_jfieldId);
return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (value_jfieldId == IntPtr.Zero)
value_jfieldId = JNIEnv.GetFieldID (class_ref, "value", "Ljava/lang/String;");
IntPtr native_value = JNIEnv.NewString (value);
try {
JNIEnv.SetField (Handle, value_jfieldId, native_value);
} finally {
JNIEnv.DeleteLocalRef (native_value);
}
}
}
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/webrtc/StatsReport$Value", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (Value); }
}
protected Value (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Ljava_lang_String_Ljava_lang_String_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='StatsReport.Value']/constructor[@name='StatsReport.Value' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String']]"
[Register (".ctor", "(Ljava/lang/String;Ljava/lang/String;)V", "")]
public unsafe Value (string p0, string p1)
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
IntPtr native_p0 = JNIEnv.NewString (p0);
IntPtr native_p1 = JNIEnv.NewString (p1);
try {
JValue* __args = stackalloc JValue [2];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (native_p1);
if (GetType () != typeof (Value)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/lang/String;Ljava/lang/String;)V", __args),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/lang/String;Ljava/lang/String;)V", __args);
return;
}
if (id_ctor_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero)
id_ctor_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_Ljava_lang_String_, __args),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_lang_String_Ljava_lang_String_, __args);
} finally {
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p1);
}
}
}
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/webrtc/StatsReport", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (StatsReport); }
}
protected StatsReport (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Ljava_lang_String_Ljava_lang_String_DarrayLorg_webrtc_StatsReport_Value_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='StatsReport']/constructor[@name='StatsReport' and count(parameter)=4 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='double'] and parameter[4][@type='org.webrtc.StatsReport.Value[]']]"
[Register (".ctor", "(Ljava/lang/String;Ljava/lang/String;D[Lorg/webrtc/StatsReport$Value;)V", "")]
public unsafe StatsReport (string p0, string p1, double p2, global::Org.Webrtc.StatsReport.Value[] p3)
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
IntPtr native_p0 = JNIEnv.NewString (p0);
IntPtr native_p1 = JNIEnv.NewString (p1);
IntPtr native_p3 = JNIEnv.NewArray (p3);
try {
JValue* __args = stackalloc JValue [4];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (native_p1);
__args [2] = new JValue (p2);
__args [3] = new JValue (native_p3);
if (GetType () != typeof (StatsReport)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/lang/String;Ljava/lang/String;D[Lorg/webrtc/StatsReport$Value;)V", __args),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/lang/String;Ljava/lang/String;D[Lorg/webrtc/StatsReport$Value;)V", __args);
return;
}
if (id_ctor_Ljava_lang_String_Ljava_lang_String_DarrayLorg_webrtc_StatsReport_Value_ == IntPtr.Zero)
id_ctor_Ljava_lang_String_Ljava_lang_String_DarrayLorg_webrtc_StatsReport_Value_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;Ljava/lang/String;D[Lorg/webrtc/StatsReport$Value;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_Ljava_lang_String_DarrayLorg_webrtc_StatsReport_Value_, __args),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_lang_String_Ljava_lang_String_DarrayLorg_webrtc_StatsReport_Value_, __args);
} finally {
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p1);
if (p3 != null) {
JNIEnv.CopyArray (native_p3, p3);
JNIEnv.DeleteLocalRef (native_p3);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
public partial class SiteRecoveryManagementClient : ServiceClient<SiteRecoveryManagementClient>, ISiteRecoveryManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The subscription Id.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// The name of the resource group where the recovery services vault is
/// present.
/// </summary>
public string ResourceGroupName { get; set; }
/// <summary>
/// The name of the recovery services vault.
/// </summary>
public string ResourceName { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IReplicationProtectedItemsOperations.
/// </summary>
public virtual IReplicationProtectedItemsOperations ReplicationProtectedItems { get; private set; }
/// <summary>
/// Gets the IReplicationNetworkMappingsOperations.
/// </summary>
public virtual IReplicationNetworkMappingsOperations ReplicationNetworkMappings { get; private set; }
/// <summary>
/// Gets the IReplicationFabricsOperations.
/// </summary>
public virtual IReplicationFabricsOperations ReplicationFabrics { get; private set; }
/// <summary>
/// Gets the IReplicationvCentersOperations.
/// </summary>
public virtual IReplicationvCentersOperations ReplicationvCenters { get; private set; }
/// <summary>
/// Gets the IReplicationStorageClassificationMappingsOperations.
/// </summary>
public virtual IReplicationStorageClassificationMappingsOperations ReplicationStorageClassificationMappings { get; private set; }
/// <summary>
/// Gets the IReplicationStorageClassificationsOperations.
/// </summary>
public virtual IReplicationStorageClassificationsOperations ReplicationStorageClassifications { get; private set; }
/// <summary>
/// Gets the IReplicationRecoveryServicesProvidersOperations.
/// </summary>
public virtual IReplicationRecoveryServicesProvidersOperations ReplicationRecoveryServicesProviders { get; private set; }
/// <summary>
/// Gets the IRecoveryPointsOperations.
/// </summary>
public virtual IRecoveryPointsOperations RecoveryPoints { get; private set; }
/// <summary>
/// Gets the IReplicationRecoveryPlansOperations.
/// </summary>
public virtual IReplicationRecoveryPlansOperations ReplicationRecoveryPlans { get; private set; }
/// <summary>
/// Gets the IReplicationProtectionContainersOperations.
/// </summary>
public virtual IReplicationProtectionContainersOperations ReplicationProtectionContainers { get; private set; }
/// <summary>
/// Gets the IReplicationProtectionContainerMappingsOperations.
/// </summary>
public virtual IReplicationProtectionContainerMappingsOperations ReplicationProtectionContainerMappings { get; private set; }
/// <summary>
/// Gets the IReplicationProtectableItemsOperations.
/// </summary>
public virtual IReplicationProtectableItemsOperations ReplicationProtectableItems { get; private set; }
/// <summary>
/// Gets the IReplicationPoliciesOperations.
/// </summary>
public virtual IReplicationPoliciesOperations ReplicationPolicies { get; private set; }
/// <summary>
/// Gets the IOperations.
/// </summary>
public virtual IOperations Operations { get; private set; }
/// <summary>
/// Gets the IReplicationNetworksOperations.
/// </summary>
public virtual IReplicationNetworksOperations ReplicationNetworks { get; private set; }
/// <summary>
/// Gets the IReplicationLogicalNetworksOperations.
/// </summary>
public virtual IReplicationLogicalNetworksOperations ReplicationLogicalNetworks { get; private set; }
/// <summary>
/// Gets the IReplicationJobsOperations.
/// </summary>
public virtual IReplicationJobsOperations ReplicationJobs { get; private set; }
/// <summary>
/// Gets the IReplicationEventsOperations.
/// </summary>
public virtual IReplicationEventsOperations ReplicationEvents { get; private set; }
/// <summary>
/// Gets the IReplicationAlertSettingsOperations.
/// </summary>
public virtual IReplicationAlertSettingsOperations ReplicationAlertSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SiteRecoveryManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SiteRecoveryManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SiteRecoveryManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SiteRecoveryManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SiteRecoveryManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SiteRecoveryManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SiteRecoveryManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SiteRecoveryManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
ReplicationProtectedItems = new ReplicationProtectedItemsOperations(this);
ReplicationNetworkMappings = new ReplicationNetworkMappingsOperations(this);
ReplicationFabrics = new ReplicationFabricsOperations(this);
ReplicationvCenters = new ReplicationvCentersOperations(this);
ReplicationStorageClassificationMappings = new ReplicationStorageClassificationMappingsOperations(this);
ReplicationStorageClassifications = new ReplicationStorageClassificationsOperations(this);
ReplicationRecoveryServicesProviders = new ReplicationRecoveryServicesProvidersOperations(this);
RecoveryPoints = new RecoveryPointsOperations(this);
ReplicationRecoveryPlans = new ReplicationRecoveryPlansOperations(this);
ReplicationProtectionContainers = new ReplicationProtectionContainersOperations(this);
ReplicationProtectionContainerMappings = new ReplicationProtectionContainerMappingsOperations(this);
ReplicationProtectableItems = new ReplicationProtectableItemsOperations(this);
ReplicationPolicies = new ReplicationPoliciesOperations(this);
Operations = new Operations(this);
ReplicationNetworks = new ReplicationNetworksOperations(this);
ReplicationLogicalNetworks = new ReplicationLogicalNetworksOperations(this);
ReplicationJobs = new ReplicationJobsOperations(this);
ReplicationEvents = new ReplicationEventsOperations(this);
ReplicationAlertSettings = new ReplicationAlertSettingsOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
ApiVersion = "2016-08-10";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<EventProviderSpecificDetails>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<EventProviderSpecificDetails>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<EventSpecificDetails>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<EventSpecificDetails>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<FabricSpecificDetails>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<FabricSpecificDetails>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<FabricSpecificCreationInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<FabricSpecificCreationInput>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<TaskTypeDetails>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<TaskTypeDetails>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<GroupTaskDetails>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<GroupTaskDetails>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<JobDetails>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<JobDetails>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<NetworkMappingFabricSpecificSettings>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<NetworkMappingFabricSpecificSettings>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<FabricSpecificCreateNetworkMappingInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<FabricSpecificCreateNetworkMappingInput>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<FabricSpecificUpdateNetworkMappingInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<FabricSpecificUpdateNetworkMappingInput>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<PolicyProviderSpecificDetails>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<PolicyProviderSpecificDetails>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<PolicyProviderSpecificInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<PolicyProviderSpecificInput>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ConfigurationSettings>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ConfigurationSettings>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ReplicationProviderSpecificContainerCreationInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ReplicationProviderSpecificContainerCreationInput>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<SwitchProtectionProviderSpecificInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<SwitchProtectionProviderSpecificInput>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RecoveryPlanActionDetails>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RecoveryPlanActionDetails>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RecoveryPlanProviderSpecificFailoverInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RecoveryPlanProviderSpecificFailoverInput>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ReplicationProviderSpecificSettings>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ReplicationProviderSpecificSettings>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<EnableProtectionProviderSpecificInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<EnableProtectionProviderSpecificInput>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<UpdateReplicationProtectedItemProviderInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<UpdateReplicationProtectedItemProviderInput>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<DisableProtectionProviderSpecificInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<DisableProtectionProviderSpecificInput>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ProviderSpecificFailoverInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ProviderSpecificFailoverInput>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ReverseReplicationProviderSpecificInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ReverseReplicationProviderSpecificInput>("instanceType"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ApplyRecoveryPointProviderSpecificInput>("instanceType"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ApplyRecoveryPointProviderSpecificInput>("instanceType"));
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
namespace android.app
{
[global::MonoJavaBridge.JavaClass()]
public partial class AlertDialog : android.app.Dialog, android.content.DialogInterface
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected AlertDialog(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public partial class Builder : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Builder(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual global::android.app.AlertDialog create()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "create", "()Landroid/app/AlertDialog;", ref global::android.app.AlertDialog.Builder._m0) as android.app.AlertDialog;
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual global::android.app.AlertDialog.Builder setTitle(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setTitle", "(I)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual global::android.app.AlertDialog.Builder setTitle(java.lang.CharSequence arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setTitle", "(Ljava/lang/CharSequence;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setTitle(string arg0)
{
return setTitle((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
public new global::android.content.DialogInterface_OnKeyListener OnKeyListener
{
set
{
setOnKeyListener(value);
}
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual global::android.app.AlertDialog.Builder setOnKeyListener(android.content.DialogInterface_OnKeyListener arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setOnKeyListener", "(Landroid/content/DialogInterface$OnKeyListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setOnKeyListener(global::android.content.DialogInterface_OnKeyListenerDelegate arg0)
{
return setOnKeyListener((global::android.content.DialogInterface_OnKeyListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual global::android.app.AlertDialog.Builder setIcon(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setIcon", "(I)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual global::android.app.AlertDialog.Builder setIcon(android.graphics.drawable.Drawable arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setIcon", "(Landroid/graphics/drawable/Drawable;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual global::android.app.AlertDialog show()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "show", "()Landroid/app/AlertDialog;", ref global::android.app.AlertDialog.Builder._m6) as android.app.AlertDialog;
}
public new bool Cancelable
{
set
{
setCancelable(value);
}
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual global::android.app.AlertDialog.Builder setCancelable(bool arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setCancelable", "(Z)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
public new global::android.content.DialogInterface_OnCancelListener OnCancelListener
{
set
{
setOnCancelListener(value);
}
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual global::android.app.AlertDialog.Builder setOnCancelListener(android.content.DialogInterface_OnCancelListener arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setOnCancelListener", "(Landroid/content/DialogInterface$OnCancelListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setOnCancelListener(global::android.content.DialogInterface_OnCancelListenerDelegate arg0)
{
return setOnCancelListener((global::android.content.DialogInterface_OnCancelListenerDelegateWrapper)arg0);
}
public new global::android.view.View CustomTitle
{
set
{
setCustomTitle(value);
}
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual global::android.app.AlertDialog.Builder setCustomTitle(android.view.View arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setCustomTitle", "(Landroid/view/View;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual global::android.app.AlertDialog.Builder setMessage(java.lang.CharSequence arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setMessage", "(Ljava/lang/CharSequence;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setMessage(string arg0)
{
return setMessage((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual global::android.app.AlertDialog.Builder setMessage(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setMessage", "(I)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual global::android.app.AlertDialog.Builder setPositiveButton(java.lang.CharSequence arg0, android.content.DialogInterface_OnClickListener arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setPositiveButton", "(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setPositiveButton(string arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1)
{
return setPositiveButton((global::java.lang.CharSequence)(global::java.lang.String)arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual global::android.app.AlertDialog.Builder setPositiveButton(int arg0, android.content.DialogInterface_OnClickListener arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setPositiveButton", "(ILandroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setPositiveButton(int arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1)
{
return setPositiveButton(arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual global::android.app.AlertDialog.Builder setNegativeButton(java.lang.CharSequence arg0, android.content.DialogInterface_OnClickListener arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setNegativeButton", "(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setNegativeButton(string arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1)
{
return setNegativeButton((global::java.lang.CharSequence)(global::java.lang.String)arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual global::android.app.AlertDialog.Builder setNegativeButton(int arg0, android.content.DialogInterface_OnClickListener arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setNegativeButton", "(ILandroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setNegativeButton(int arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1)
{
return setNegativeButton(arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual global::android.app.AlertDialog.Builder setNeutralButton(java.lang.CharSequence arg0, android.content.DialogInterface_OnClickListener arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setNeutralButton", "(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setNeutralButton(string arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1)
{
return setNeutralButton((global::java.lang.CharSequence)(global::java.lang.String)arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual global::android.app.AlertDialog.Builder setNeutralButton(int arg0, android.content.DialogInterface_OnClickListener arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setNeutralButton", "(ILandroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setNeutralButton(int arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1)
{
return setNeutralButton(arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual global::android.app.AlertDialog.Builder setItems(int arg0, android.content.DialogInterface_OnClickListener arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setItems", "(ILandroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setItems(int arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1)
{
return setItems(arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual global::android.app.AlertDialog.Builder setItems(java.lang.CharSequence[] arg0, android.content.DialogInterface_OnClickListener arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setItems", "([Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setItems(java.lang.CharSequence[] arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1)
{
return setItems(arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual global::android.app.AlertDialog.Builder setAdapter(android.widget.ListAdapter arg0, android.content.DialogInterface_OnClickListener arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setAdapter", "(Landroid/widget/ListAdapter;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setAdapter(android.widget.ListAdapter arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1)
{
return setAdapter(arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual global::android.app.AlertDialog.Builder setCursor(android.database.Cursor arg0, android.content.DialogInterface_OnClickListener arg1, java.lang.String arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setCursor", "(Landroid/database/Cursor;Landroid/content/DialogInterface$OnClickListener;Ljava/lang/String;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setCursor(android.database.Cursor arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1, java.lang.String arg2)
{
return setCursor(arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1, arg2);
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual global::android.app.AlertDialog.Builder setMultiChoiceItems(android.database.Cursor arg0, java.lang.String arg1, java.lang.String arg2, android.content.DialogInterface_OnMultiChoiceClickListener arg3)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setMultiChoiceItems", "(Landroid/database/Cursor;Ljava/lang/String;Ljava/lang/String;Landroid/content/DialogInterface$OnMultiChoiceClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setMultiChoiceItems(android.database.Cursor arg0, java.lang.String arg1, java.lang.String arg2, global::android.content.DialogInterface_OnMultiChoiceClickListenerDelegate arg3)
{
return setMultiChoiceItems(arg0, arg1, arg2, (global::android.content.DialogInterface_OnMultiChoiceClickListenerDelegateWrapper)arg3);
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual global::android.app.AlertDialog.Builder setMultiChoiceItems(java.lang.CharSequence[] arg0, bool[] arg1, android.content.DialogInterface_OnMultiChoiceClickListener arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setMultiChoiceItems", "([Ljava/lang/CharSequence;[ZLandroid/content/DialogInterface$OnMultiChoiceClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setMultiChoiceItems(java.lang.CharSequence[] arg0, bool[] arg1, global::android.content.DialogInterface_OnMultiChoiceClickListenerDelegate arg2)
{
return setMultiChoiceItems(arg0, arg1, (global::android.content.DialogInterface_OnMultiChoiceClickListenerDelegateWrapper)arg2);
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual global::android.app.AlertDialog.Builder setMultiChoiceItems(int arg0, bool[] arg1, android.content.DialogInterface_OnMultiChoiceClickListener arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setMultiChoiceItems", "(I[ZLandroid/content/DialogInterface$OnMultiChoiceClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setMultiChoiceItems(int arg0, bool[] arg1, global::android.content.DialogInterface_OnMultiChoiceClickListenerDelegate arg2)
{
return setMultiChoiceItems(arg0, arg1, (global::android.content.DialogInterface_OnMultiChoiceClickListenerDelegateWrapper)arg2);
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual global::android.app.AlertDialog.Builder setSingleChoiceItems(int arg0, int arg1, android.content.DialogInterface_OnClickListener arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setSingleChoiceItems", "(IILandroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setSingleChoiceItems(int arg0, int arg1, global::android.content.DialogInterface_OnClickListenerDelegate arg2)
{
return setSingleChoiceItems(arg0, arg1, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg2);
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual global::android.app.AlertDialog.Builder setSingleChoiceItems(android.widget.ListAdapter arg0, int arg1, android.content.DialogInterface_OnClickListener arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setSingleChoiceItems", "(Landroid/widget/ListAdapter;ILandroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setSingleChoiceItems(android.widget.ListAdapter arg0, int arg1, global::android.content.DialogInterface_OnClickListenerDelegate arg2)
{
return setSingleChoiceItems(arg0, arg1, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg2);
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual global::android.app.AlertDialog.Builder setSingleChoiceItems(java.lang.CharSequence[] arg0, int arg1, android.content.DialogInterface_OnClickListener arg2)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setSingleChoiceItems", "([Ljava/lang/CharSequence;ILandroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setSingleChoiceItems(java.lang.CharSequence[] arg0, int arg1, global::android.content.DialogInterface_OnClickListenerDelegate arg2)
{
return setSingleChoiceItems(arg0, arg1, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg2);
}
private static global::MonoJavaBridge.MethodId _m28;
public virtual global::android.app.AlertDialog.Builder setSingleChoiceItems(android.database.Cursor arg0, int arg1, java.lang.String arg2, android.content.DialogInterface_OnClickListener arg3)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setSingleChoiceItems", "(Landroid/database/Cursor;ILjava/lang/String;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)) as android.app.AlertDialog.Builder;
}
public android.app.AlertDialog.Builder setSingleChoiceItems(android.database.Cursor arg0, int arg1, java.lang.String arg2, global::android.content.DialogInterface_OnClickListenerDelegate arg3)
{
return setSingleChoiceItems(arg0, arg1, arg2, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg3);
}
public new global::android.widget.AdapterView.OnItemSelectedListener OnItemSelectedListener
{
set
{
setOnItemSelectedListener(value);
}
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual global::android.app.AlertDialog.Builder setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setOnItemSelectedListener", "(Landroid/widget/AdapterView$OnItemSelectedListener;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
public new global::android.view.View View
{
set
{
setView(value);
}
}
private static global::MonoJavaBridge.MethodId _m30;
public virtual global::android.app.AlertDialog.Builder setView(android.view.View arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setView", "(Landroid/view/View;)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
public new bool InverseBackgroundForced
{
set
{
setInverseBackgroundForced(value);
}
}
private static global::MonoJavaBridge.MethodId _m31;
public virtual global::android.app.AlertDialog.Builder setInverseBackgroundForced(bool arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.Builder.staticClass, "setInverseBackgroundForced", "(Z)Landroid/app/AlertDialog$Builder;", ref global::android.app.AlertDialog.Builder._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.AlertDialog.Builder;
}
private static global::MonoJavaBridge.MethodId _m32;
public Builder(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.AlertDialog.Builder._m32.native == global::System.IntPtr.Zero)
global::android.app.AlertDialog.Builder._m32 = @__env.GetMethodIDNoThrow(global::android.app.AlertDialog.Builder.staticClass, "<init>", "(Landroid/content/Context;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.AlertDialog.Builder.staticClass, global::android.app.AlertDialog.Builder._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
static Builder()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.app.AlertDialog.Builder.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/AlertDialog$Builder"));
}
}
private static global::MonoJavaBridge.MethodId _m0;
protected override void onCreate(android.os.Bundle arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "onCreate", "(Landroid/os/Bundle;)V", ref global::android.app.AlertDialog._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public override bool onKeyDown(int arg0, android.view.KeyEvent arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.AlertDialog.staticClass, "onKeyDown", "(ILandroid/view/KeyEvent;)Z", ref global::android.app.AlertDialog._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m2;
public override bool onKeyUp(int arg0, android.view.KeyEvent arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.app.AlertDialog.staticClass, "onKeyUp", "(ILandroid/view/KeyEvent;)Z", ref global::android.app.AlertDialog._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public new global::java.lang.CharSequence Title
{
set
{
setTitle(value);
}
}
private static global::MonoJavaBridge.MethodId _m3;
public override void setTitle(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setTitle", "(Ljava/lang/CharSequence;)V", ref global::android.app.AlertDialog._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setTitle(string arg0)
{
setTitle((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual void setIcon(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setIcon", "(I)V", ref global::android.app.AlertDialog._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual void setIcon(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setIcon", "(Landroid/graphics/drawable/Drawable;)V", ref global::android.app.AlertDialog._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::android.view.View CustomTitle
{
set
{
setCustomTitle(value);
}
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual void setCustomTitle(android.view.View arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setCustomTitle", "(Landroid/view/View;)V", ref global::android.app.AlertDialog._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.lang.CharSequence Message
{
set
{
setMessage(value);
}
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void setMessage(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setMessage", "(Ljava/lang/CharSequence;)V", ref global::android.app.AlertDialog._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setMessage(string arg0)
{
setMessage((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual void setView(android.view.View arg0, int arg1, int arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setView", "(Landroid/view/View;IIII)V", ref global::android.app.AlertDialog._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
public new global::android.view.View View
{
set
{
setView(value);
}
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual void setView(android.view.View arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setView", "(Landroid/view/View;)V", ref global::android.app.AlertDialog._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new bool InverseBackgroundForced
{
set
{
setInverseBackgroundForced(value);
}
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual void setInverseBackgroundForced(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setInverseBackgroundForced", "(Z)V", ref global::android.app.AlertDialog._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual global::android.widget.Button getButton(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.staticClass, "getButton", "(I)Landroid/widget/Button;", ref global::android.app.AlertDialog._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.widget.Button;
}
public new global::android.widget.ListView ListView
{
get
{
return getListView();
}
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual global::android.widget.ListView getListView()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.app.AlertDialog.staticClass, "getListView", "()Landroid/widget/ListView;", ref global::android.app.AlertDialog._m12) as android.widget.ListView;
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual void setButton(java.lang.CharSequence arg0, android.content.DialogInterface_OnClickListener arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setButton", "(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)V", ref global::android.app.AlertDialog._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public void setButton(string arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1)
{
setButton((global::java.lang.CharSequence)(global::java.lang.String)arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual void setButton(java.lang.CharSequence arg0, android.os.Message arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setButton", "(Ljava/lang/CharSequence;Landroid/os/Message;)V", ref global::android.app.AlertDialog._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public void setButton(string arg0, android.os.Message arg1)
{
setButton((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1);
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void setButton(int arg0, java.lang.CharSequence arg1, android.content.DialogInterface_OnClickListener arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setButton", "(ILjava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)V", ref global::android.app.AlertDialog._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
public void setButton(int arg0, string arg1, global::android.content.DialogInterface_OnClickListenerDelegate arg2)
{
setButton(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg2);
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void setButton(int arg0, java.lang.CharSequence arg1, android.os.Message arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setButton", "(ILjava/lang/CharSequence;Landroid/os/Message;)V", ref global::android.app.AlertDialog._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
public void setButton(int arg0, string arg1, android.os.Message arg2)
{
setButton(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1, arg2);
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void setButton2(java.lang.CharSequence arg0, android.content.DialogInterface_OnClickListener arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setButton2", "(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)V", ref global::android.app.AlertDialog._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public void setButton2(string arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1)
{
setButton2((global::java.lang.CharSequence)(global::java.lang.String)arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual void setButton2(java.lang.CharSequence arg0, android.os.Message arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setButton2", "(Ljava/lang/CharSequence;Landroid/os/Message;)V", ref global::android.app.AlertDialog._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public void setButton2(string arg0, android.os.Message arg1)
{
setButton2((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1);
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual void setButton3(java.lang.CharSequence arg0, android.content.DialogInterface_OnClickListener arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setButton3", "(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)V", ref global::android.app.AlertDialog._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public void setButton3(string arg0, global::android.content.DialogInterface_OnClickListenerDelegate arg1)
{
setButton3((global::java.lang.CharSequence)(global::java.lang.String)arg0, (global::android.content.DialogInterface_OnClickListenerDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void setButton3(java.lang.CharSequence arg0, android.os.Message arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.AlertDialog.staticClass, "setButton3", "(Ljava/lang/CharSequence;Landroid/os/Message;)V", ref global::android.app.AlertDialog._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public void setButton3(string arg0, android.os.Message arg1)
{
setButton3((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1);
}
private static global::MonoJavaBridge.MethodId _m21;
protected AlertDialog(android.content.Context arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.AlertDialog._m21.native == global::System.IntPtr.Zero)
global::android.app.AlertDialog._m21 = @__env.GetMethodIDNoThrow(global::android.app.AlertDialog.staticClass, "<init>", "(Landroid/content/Context;I)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.AlertDialog.staticClass, global::android.app.AlertDialog._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m22;
protected AlertDialog(android.content.Context arg0, bool arg1, android.content.DialogInterface_OnCancelListener arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.AlertDialog._m22.native == global::System.IntPtr.Zero)
global::android.app.AlertDialog._m22 = @__env.GetMethodIDNoThrow(global::android.app.AlertDialog.staticClass, "<init>", "(Landroid/content/Context;ZLandroid/content/DialogInterface$OnCancelListener;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.AlertDialog.staticClass, global::android.app.AlertDialog._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m23;
protected AlertDialog(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.app.AlertDialog._m23.native == global::System.IntPtr.Zero)
global::android.app.AlertDialog._m23 = @__env.GetMethodIDNoThrow(global::android.app.AlertDialog.staticClass, "<init>", "(Landroid/content/Context;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.AlertDialog.staticClass, global::android.app.AlertDialog._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
static AlertDialog()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.app.AlertDialog.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/AlertDialog"));
}
}
}
| |
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using NuPattern.VisualStudio.Solution;
namespace NuPattern.Runtime.Guidance.Extensions
{
/// <summary>
/// BlackboardManager provides a single, global, key/string value pair API available to all
/// guidance extension instances.
/// Updated 2010-05-19 to not persist until IsPersistent is set to true
/// <para/>
/// Note: It is *not* threadsafe (at least not yet) so do not WRITE to the Blackboard in background threads
/// </summary>
[Export]
public class BlackboardManager
{
/// <summary>
/// Local static to keep the singleton instance
/// </summary>
private static BlackboardManager current;
/// <summary>
/// Name of the solution folder in which to store the Blackboard
/// </summary>
private static string solutionFolderName = @"Solution Items";
/// <summary>
/// Name of the file in which the Blackboard data is stored
/// </summary>
private static string defaultBlackboardFileNameBase = @".guidancestate";
/// <summary>
/// Empty dictionary contents with which we pre-populate the Blackboard on creation
/// </summary>
private static string emptyDictionary = @"<?xml version=""1.0"" encoding=""utf-8""?><ArrayOfKeyValueOfstringstring xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.microsoft.com/2003/10/Serialization/Arrays""></ArrayOfKeyValueOfstringstring>";
/// <summary>
/// The calculated absolute path to the blackboard file (for serialization)
/// </summary>
private string blackboardFileName = string.Empty;
/// <summary>
/// The live "in-memory" instance of the blackboard
/// </summary>
private Dictionary<string, string> blackboard = null;
private bool isPersisted;
/// <summary>
/// Initializes a new instance of the BlackboardManager class.
/// Used by MEF to instantiate BlackboardManager in GuidanceExtension.cs
/// </summary>
public BlackboardManager()
{
current = this;
isPersisted = false;
}
/// <summary>
/// Gets the singleton instance of the Blackboard
/// Static property returning singleton instance of BlackboardManager.
/// Note: We do it this way instead of accessing the instance of BlackboardManager
/// saved in GuidanceExtension.cs because commands can't directly reference the specific guidance extension
/// type since they are in a referred-to assembly.
/// </summary>
public static BlackboardManager Current
{
get { return current; }
}
/// <summary>
/// Gets or sets an indicator of whether or not the data is
/// stored on disk.
/// </summary>
public bool IsPersistent
{
get { return this.isPersisted; }
set
{
this.isPersisted = value;
if (value)
{
// Note: processSolutionFolder both creates the GuidanceExtensionData solution folder (if necessary)
// and returns the path to the Blackboard File
this.blackboardFileName = this.ProcessSolutionFolder(this.Solution);
this.WriteBlackboardDataToFile();
}
}
}
/// <summary>
/// Gets or sets the current Visual Studio solution
/// </summary>
[Import]
private ISolution Solution { get; set; }
/// <summary>
/// Creates the FeatureExtensionData solution folder (if necessary) and
/// reads in the current state of the Blackboard
/// </summary>
public void Initialize()
{
//
// Make multiple calls to Initialize safe
//
if (this.blackboard == null)
this.blackboard = new Dictionary<string, string>();
//
// If the file exists, we must read it on initialize
//
try
{
string bbFileName = Path.Combine(Path.GetDirectoryName(Solution.PhysicalPath), Solution.Name + defaultBlackboardFileNameBase);
if (File.Exists(bbFileName))
{
using (XmlReader reader = XmlReader.Create(bbFileName))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, string>));
this.blackboard = (Dictionary<string, string>)serializer.ReadObject(reader);
}
}
}
catch
{
}
}
/// <summary>
/// Reinitializes the Blackboard to an empty state.
/// Called by the GuidanceManager.Close method.
/// </summary>
public void Clear()
{
this.blackboard = new Dictionary<string, string>();
}
/// <summary>
/// Retrieve a string from the global Blackboard
/// </summary>
/// <param name="key">Key to retrieve</param>
/// <returns>Value for the specified key or null if key not present</returns>
public string Get(string key)
{
this.blackboard = this.GetBlackboardDataFromFile();
string value;
this.blackboard.TryGetValue(key, out value);
return value;
}
/// <summary>
/// Stores a new or updated value on the global Blackboard
/// </summary>
/// <param name="key">Key under which value should be saved</param>
/// <param name="value">Data to store under the specified key</param>
public void Set(string key, string value)
{
// Delete existing content for this key, if present
// so we can "overwrite"
if (this.blackboard.ContainsKey(key))
{
// Don't change it if it's the same value.
// Makes it easier to leave the XML file open in the editor while
// the workflow is running.
if (this.blackboard[key].Equals(value))
{
return;
}
}
this.blackboard[key] = value;
this.WriteBlackboardDataToFile();
}
/// <summary>
/// Loads the Blackboard from the global XML file
/// </summary>
/// <returns>A <string,string> dictionary deserialized from the file</returns>
private Dictionary<string, string> GetBlackboardDataFromFile()
{
Dictionary<string, string> result;
if (!IsPersistent)
return this.blackboard;
//
// Check it out if it's under source control
//
VsHelper.CheckOut(blackboardFileName);
if (!File.Exists(this.blackboardFileName))
{
this.blackboard = new Dictionary<string, string>();
this.WriteBlackboardDataToFile();
}
using (XmlReader reader = XmlReader.Create(this.blackboardFileName))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, string>));
result = (Dictionary<string, string>)serializer.ReadObject(reader);
}
return result;
}
/// <summary>
/// Saves the Blackboard to the global XML file
/// </summary>
private void WriteBlackboardDataToFile()
{
if (!IsPersistent)
return;
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(this.blackboardFileName, settings))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, string>));
serializer.WriteObject(writer, this.blackboard);
}
}
/// <summary>
/// Create, if necessary, the solution folder for the Blackboard
/// Adds an empty Blackboard data file when the folder is created
/// </summary>
/// <param name="solution">The current VS Solution abstraction from import</param>
/// <returns>Path to Solution</returns>
private string ProcessSolutionFolder(ISolution solution)
{
ISolutionFolder blackboardFolder = null;
bool solutionFolderExists = false;
foreach (var item in solution.Items)
{
if (item.Name == solutionFolderName)
{
solutionFolderExists = true;
blackboardFolder = item as ISolutionFolder;
break;
}
}
if (!solutionFolderExists)
{
blackboardFolder = solution.CreateSolutionFolder(solutionFolderName);
blackboardFolder.AddContent(emptyDictionary, solution.Name + defaultBlackboardFileNameBase, false, false);
}
else
{
//
// Ok, the solution folder exists, let's see if our file exists
//
string bbFileName = Path.Combine(Path.GetDirectoryName(solution.PhysicalPath), solution.Name + defaultBlackboardFileNameBase);
if (!File.Exists(bbFileName))
{
blackboardFolder.AddContent(emptyDictionary, solution.Name + defaultBlackboardFileNameBase, false, false);
}
}
return Path.Combine(Path.GetDirectoryName(solution.PhysicalPath), solution.Name + defaultBlackboardFileNameBase);
}
}
}
| |
// 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 core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using EnvDTE;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell.Interop;
using VSLangProj;
using Project = EnvDTE.Project;
using System.Collections.Immutable;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.CodeAnalysis.Text;
using System.Linq;
using core::Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.VisualStudio.LanguageServices.Interactive
{
internal sealed class VsResetInteractive : ResetInteractive
{
private readonly DTE _dte;
private readonly IComponentModel _componentModel;
private readonly IVsMonitorSelection _monitorSelection;
private readonly IVsSolutionBuildManager _buildManager;
internal VsResetInteractive(
DTE dte,
IComponentModel componentModel,
IVsMonitorSelection monitorSelection,
IVsSolutionBuildManager buildManager,
Func<string, string> createReference,
Func<string, string> createImport)
: base(componentModel.GetService<IEditorOptionsFactoryService>(), createReference, createImport)
{
_dte = dte;
_componentModel = componentModel;
_monitorSelection = monitorSelection;
_buildManager = buildManager;
}
/// <summary>
/// Gets the properties of the currently selected projects necessary for reset.
/// </summary>
protected override bool GetProjectProperties(
out ImmutableArray<string> references,
out ImmutableArray<string> referenceSearchPaths,
out ImmutableArray<string> sourceSearchPaths,
out ImmutableArray<string> projectNamespaces,
out string projectDirectory)
{
var hierarchyPointer = default(IntPtr);
var selectionContainerPointer = default(IntPtr);
references = ImmutableArray<string>.Empty;
referenceSearchPaths = ImmutableArray<string>.Empty;
sourceSearchPaths = ImmutableArray<string>.Empty;
projectNamespaces = ImmutableArray<string>.Empty;
projectDirectory = null;
try
{
uint itemid;
IVsMultiItemSelect multiItemSelectPointer;
Marshal.ThrowExceptionForHR(_monitorSelection.GetCurrentSelection(
out hierarchyPointer, out itemid, out multiItemSelectPointer, out selectionContainerPointer));
if (hierarchyPointer != IntPtr.Zero)
{
GetProjectProperties(hierarchyPointer, out references, out referenceSearchPaths, out sourceSearchPaths, out projectNamespaces, out projectDirectory);
return true;
}
}
finally
{
SafeRelease(hierarchyPointer);
SafeRelease(selectionContainerPointer);
}
return false;
}
private static void GetProjectProperties(
IntPtr hierarchyPointer,
out ImmutableArray<string> references,
out ImmutableArray<string> referenceSearchPaths,
out ImmutableArray<string> sourceSearchPaths,
out ImmutableArray<string> projectNamespaces,
out string projectDirectory)
{
var hierarchy = (IVsHierarchy)Marshal.GetObjectForIUnknown(hierarchyPointer);
object extensibilityObject;
Marshal.ThrowExceptionForHR(
hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out extensibilityObject));
// TODO: Revert this back to using dynamic for web projects, since they have copies of these interfaces.
var project = (Project)extensibilityObject;
var vsProject = (VSProject)project.Object;
var referencesBuilder = ImmutableArray.CreateBuilder<string>();
var referenceSearchPathsBuilder = ImmutableArray.CreateBuilder<string>();
var sourceSearchPathsBuilder = ImmutableArray.CreateBuilder<string>();
var namespacesToImportBuilder = ImmutableArray.CreateBuilder<string>();
var projectDir = (string)project.Properties.Item("FullPath").Value;
var outputFileName = (string)project.Properties.Item("OutputFileName").Value;
var defaultNamespace = (string)project.Properties.Item("DefaultNamespace").Value;
var relativeOutputPath = (string)project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value;
Debug.Assert(!string.IsNullOrEmpty(projectDir));
Debug.Assert(!string.IsNullOrEmpty(outputFileName));
Debug.Assert(!string.IsNullOrEmpty(relativeOutputPath));
var scriptsDir = Path.Combine(projectDir, "Scripts");
var outputDir = Path.Combine(projectDir, relativeOutputPath);
projectDirectory = projectDir;
referenceSearchPathsBuilder.Add(outputDir);
referenceSearchPathsBuilder.Add(RuntimeEnvironment.GetRuntimeDirectory());
foreach (Reference reference in vsProject.References)
{
var str = GetReferenceString(reference);
if (str != null)
{
referencesBuilder.Add(str);
}
}
referencesBuilder.Add(outputFileName);
// TODO (tomat): project Scripts dir
sourceSearchPathsBuilder.Add(Directory.Exists(scriptsDir) ? scriptsDir : projectDir);
if (!string.IsNullOrEmpty(defaultNamespace))
{
namespacesToImportBuilder.Add(defaultNamespace);
}
references = referencesBuilder.ToImmutableArray();
referenceSearchPaths = referenceSearchPathsBuilder.ToImmutableArray();
sourceSearchPaths = sourceSearchPathsBuilder.ToImmutableArray();
projectNamespaces = namespacesToImportBuilder.ToImmutableArray();
}
private static string GetReferenceString(Reference reference)
{
if (!reference.StrongName)
{
return reference.Path;
}
string name = reference.Name;
if (name == "mscorlib")
{
// mscorlib is always loaded
return null;
}
return reference.Path;
#if TODO // TODO: This shouldn't directly depend on GAC, rather we should have some kind of "reference simplifier".
var possibleGacNames = GlobalAssemblyCache.GetAssemblyIdentities(name).ToArray();
if (possibleGacNames.Length == 0)
{
// no assembly with simple "name" found in GAC, use path to identify the reference:
return reference.Path;
}
string version = reference.Version;
string culture = reference.Culture;
string publicKeyToken = reference.PublicKeyToken;
var fullName = string.Concat(
name,
", Version=",
version,
", Culture=",
(culture == "") ? "neutral" : culture,
", PublicKeyToken=",
publicKeyToken.ToLowerInvariant());
AssemblyIdentity identity;
if (!AssemblyIdentity.TryParseDisplayName(fullName, out identity))
{
// ignore invalid names:
return null;
}
var foundEquivalent = false;
var foundNonEquivalent = false;
foreach (var possibleGacName in possibleGacNames)
{
if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, possibleGacName))
{
foundEquivalent = true;
}
else
{
foundNonEquivalent = true;
}
if (foundEquivalent && foundNonEquivalent)
{
break;
}
}
if (!foundEquivalent)
{
// The reference name isn't equivalent to any GAC name.
// The assembly is strong named but not GAC'd, so we need to load it from path:
return reference.Path;
}
if (foundNonEquivalent)
{
// We found some equivalent assemblies but also some non-equivalent.
// So simple name doesn't identify the reference uniquely.
return fullName;
}
// We found a single simple name match that is equivalent to the given reference.
// We can use the simple name to load the GAC'd assembly.
return name;
#endif
}
private static void SafeRelease(IntPtr pointer)
{
if (pointer != IntPtr.Zero)
{
Marshal.Release(pointer);
}
}
protected override Task<bool> BuildProject()
{
var taskSource = new TaskCompletionSource<bool>();
var updateSolutionEvents = new VsUpdateSolutionEvents(_buildManager, taskSource);
// Build the project. When project build is done, set the task source as being done.
// (Either succeeded, cancelled, or failed).
_dte.ExecuteCommand("Build.BuildSelection");
return taskSource.Task;
}
protected override void CancelBuildProject()
{
_dte.ExecuteCommand("Build.Cancel");
}
protected override IWaitIndicator GetWaitIndicator()
{
return _componentModel.GetService<IWaitIndicator>();
}
/// <summary>
/// Return namespaces that can be resolved in the latest interactive compilation.
/// </summary>
protected override async Task<IEnumerable<string>> GetNamespacesToImportAsync(IEnumerable<string> namespacesToImport, IInteractiveWindow interactiveWindow)
{
var document = interactiveWindow.CurrentLanguageBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
var compilation = await document.Project.GetCompilationAsync().ConfigureAwait(true);
return namespacesToImport.Where(ns => compilation.GlobalNamespace.GetQualifiedNamespace(ns) != null);
}
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Engines
{
/**
* Wrap keys according to
* <a href="http://www.ietf.org/internet-drafts/draft-ietf-smime-key-wrap-01.txt">
* draft-ietf-smime-key-wrap-01.txt</a>.
* <p>
* Note:
* <ul>
* <li>this is based on a draft, and as such is subject to change - don't use this class for anything requiring long term storage.</li>
* <li>if you are using this to wrap triple-des keys you need to set the
* parity bits on the key and, if it's a two-key triple-des key, pad it
* yourself.</li>
* </ul>
* </p>
*/
public class DesEdeWrapEngine
: IWrapper
{
/** Field engine */
private CbcBlockCipher engine;
/** Field param */
private KeyParameter param;
/** Field paramPlusIV */
private ParametersWithIV paramPlusIV;
/** Field iv */
private byte[] iv;
/** Field forWrapping */
private bool forWrapping;
/** Field IV2 */
private static readonly byte[] IV2 = { (byte) 0x4a, (byte) 0xdd, (byte) 0xa2,
(byte) 0x2c, (byte) 0x79, (byte) 0xe8,
(byte) 0x21, (byte) 0x05 };
//
// checksum digest
//
private readonly IDigest sha1 = new Sha1Digest();
private readonly byte[] digest = new byte[20];
/**
* Method init
*
* @param forWrapping
* @param param
*/
public void Init(
bool forWrapping,
ICipherParameters parameters)
{
this.forWrapping = forWrapping;
this.engine = new CbcBlockCipher(new DesEdeEngine());
SecureRandom sr;
if (parameters is ParametersWithRandom)
{
ParametersWithRandom pr = (ParametersWithRandom) parameters;
parameters = pr.Parameters;
sr = pr.Random;
}
else
{
sr = new SecureRandom();
}
if (parameters is KeyParameter)
{
this.param = (KeyParameter) parameters;
if (this.forWrapping)
{
// Hm, we have no IV but we want to wrap ?!?
// well, then we have to create our own IV.
this.iv = new byte[8];
sr.NextBytes(iv);
this.paramPlusIV = new ParametersWithIV(this.param, this.iv);
}
}
else if (parameters is ParametersWithIV)
{
if (!forWrapping)
throw new ArgumentException("You should not supply an IV for unwrapping");
this.paramPlusIV = (ParametersWithIV) parameters;
this.iv = this.paramPlusIV.GetIV();
this.param = (KeyParameter) this.paramPlusIV.Parameters;
if (this.iv.Length != 8)
throw new ArgumentException("IV is not 8 octets", "parameters");
}
}
/**
* Method GetAlgorithmName
*
* @return
*/
public string AlgorithmName
{
get { return "DESede"; }
}
/**
* Method wrap
*
* @param in
* @param inOff
* @param inLen
* @return
*/
public byte[] Wrap(
byte[] input,
int inOff,
int length)
{
if (!forWrapping)
{
throw new InvalidOperationException("Not initialized for wrapping");
}
byte[] keyToBeWrapped = new byte[length];
Array.Copy(input, inOff, keyToBeWrapped, 0, length);
// Compute the CMS Key Checksum, (section 5.6.1), call this CKS.
byte[] CKS = CalculateCmsKeyChecksum(keyToBeWrapped);
// Let WKCKS = WK || CKS where || is concatenation.
byte[] WKCKS = new byte[keyToBeWrapped.Length + CKS.Length];
Array.Copy(keyToBeWrapped, 0, WKCKS, 0, keyToBeWrapped.Length);
Array.Copy(CKS, 0, WKCKS, keyToBeWrapped.Length, CKS.Length);
// Encrypt WKCKS in CBC mode using KEK as the key and IV as the
// initialization vector. Call the results TEMP1.
byte [] TEMP1 = new byte[WKCKS.Length];
Array.Copy(WKCKS, 0, TEMP1, 0, WKCKS.Length);
int noOfBlocks = WKCKS.Length / engine.GetBlockSize();
int extraBytes = WKCKS.Length % engine.GetBlockSize();
if (extraBytes != 0) {
throw new InvalidOperationException("Not multiple of block length");
}
engine.Init(true, paramPlusIV);
for (int i = 0; i < noOfBlocks; i++) {
int currentBytePos = i * engine.GetBlockSize();
engine.ProcessBlock(TEMP1, currentBytePos, TEMP1, currentBytePos);
}
// Left TEMP2 = IV || TEMP1.
byte[] TEMP2 = new byte[this.iv.Length + TEMP1.Length];
Array.Copy(this.iv, 0, TEMP2, 0, this.iv.Length);
Array.Copy(TEMP1, 0, TEMP2, this.iv.Length, TEMP1.Length);
// Reverse the order of the octets in TEMP2 and call the result TEMP3.
byte[] TEMP3 = new byte[TEMP2.Length];
for (int i = 0; i < TEMP2.Length; i++) {
TEMP3[i] = TEMP2[TEMP2.Length - (i + 1)];
}
// Encrypt TEMP3 in CBC mode using the KEK and an initialization vector
// of 0x 4a dd a2 2c 79 e8 21 05. The resulting cipher text is the desired
// result. It is 40 octets long if a 168 bit key is being wrapped.
ParametersWithIV param2 = new ParametersWithIV(this.param, IV2);
this.engine.Init(true, param2);
for (int i = 0; i < noOfBlocks + 1; i++) {
int currentBytePos = i * engine.GetBlockSize();
engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
}
return TEMP3;
}
/**
* Method unwrap
*
* @param in
* @param inOff
* @param inLen
* @return
* @throws InvalidCipherTextException
*/
public byte[] Unwrap(
byte[] input,
int inOff,
int length)
{
if (forWrapping)
{
throw new InvalidOperationException("Not set for unwrapping");
}
if (input == null)
{
throw new InvalidCipherTextException("Null pointer as ciphertext");
}
if (length % engine.GetBlockSize() != 0)
{
throw new InvalidCipherTextException(
"Ciphertext not multiple of " + engine.GetBlockSize());
}
/*
// Check if the length of the cipher text is reasonable given the key
// type. It must be 40 bytes for a 168 bit key and either 32, 40, or
// 48 bytes for a 128, 192, or 256 bit key. If the length is not supported
// or inconsistent with the algorithm for which the key is intended,
// return error.
//
// we do not accept 168 bit keys. it has to be 192 bit.
int lengthA = (estimatedKeyLengthInBit / 8) + 16;
int lengthB = estimatedKeyLengthInBit % 8;
if ((lengthA != keyToBeUnwrapped.Length) || (lengthB != 0)) {
throw new XMLSecurityException("empty");
}
*/
// Decrypt the cipher text with TRIPLedeS in CBC mode using the KEK
// and an initialization vector (IV) of 0x4adda22c79e82105. Call the output TEMP3.
ParametersWithIV param2 = new ParametersWithIV(this.param, IV2);
this.engine.Init(false, param2);
byte [] TEMP3 = new byte[length];
Array.Copy(input, inOff, TEMP3, 0, length);
for (int i = 0; i < (TEMP3.Length / engine.GetBlockSize()); i++) {
int currentBytePos = i * engine.GetBlockSize();
engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
}
// Reverse the order of the octets in TEMP3 and call the result TEMP2.
byte[] TEMP2 = new byte[TEMP3.Length];
for (int i = 0; i < TEMP3.Length; i++) {
TEMP2[i] = TEMP3[TEMP3.Length - (i + 1)];
}
// Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets.
this.iv = new byte[8];
byte[] TEMP1 = new byte[TEMP2.Length - 8];
Array.Copy(TEMP2, 0, this.iv, 0, 8);
Array.Copy(TEMP2, 8, TEMP1, 0, TEMP2.Length - 8);
// Decrypt TEMP1 using TRIPLedeS in CBC mode using the KEK and the IV
// found in the previous step. Call the result WKCKS.
this.paramPlusIV = new ParametersWithIV(this.param, this.iv);
this.engine.Init(false, this.paramPlusIV);
byte[] WKCKS = new byte[TEMP1.Length];
Array.Copy(TEMP1, 0, WKCKS, 0, TEMP1.Length);
for (int i = 0; i < (WKCKS.Length / engine.GetBlockSize()); i++) {
int currentBytePos = i * engine.GetBlockSize();
engine.ProcessBlock(WKCKS, currentBytePos, WKCKS, currentBytePos);
}
// Decompose WKCKS. CKS is the last 8 octets and WK, the wrapped key, are
// those octets before the CKS.
byte[] result = new byte[WKCKS.Length - 8];
byte[] CKStoBeVerified = new byte[8];
Array.Copy(WKCKS, 0, result, 0, WKCKS.Length - 8);
Array.Copy(WKCKS, WKCKS.Length - 8, CKStoBeVerified, 0, 8);
// Calculate a CMS Key Checksum, (section 5.6.1), over the WK and compare
// with the CKS extracted in the above step. If they are not equal, return error.
if (!CheckCmsKeyChecksum(result, CKStoBeVerified)) {
throw new InvalidCipherTextException(
"Checksum inside ciphertext is corrupted");
}
// WK is the wrapped key, now extracted for use in data decryption.
return result;
}
/**
* Some key wrap algorithms make use of the Key Checksum defined
* in CMS [CMS-Algorithms]. This is used to provide an integrity
* check value for the key being wrapped. The algorithm is
*
* - Compute the 20 octet SHA-1 hash on the key being wrapped.
* - Use the first 8 octets of this hash as the checksum value.
*
* @param key
* @return
* @throws Exception
* @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
*/
private byte[] CalculateCmsKeyChecksum(
byte[] key)
{
byte[] result = new byte[8];
sha1.BlockUpdate(key, 0, key.Length);
sha1.DoFinal(digest, 0);
Array.Copy(digest, 0, result, 0, 8);
return result;
}
/**
* @param key
* @param checksum
* @return
* @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
*/
private bool CheckCmsKeyChecksum(
byte[] key,
byte[] checksum)
{
return Arrays.AreEqual(CalculateCmsKeyChecksum(key), checksum);
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Teacher Absences Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class TCTBDataSet : EduHubDataSet<TCTB>
{
/// <inheritdoc />
public override string Name { get { return "TCTB"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal TCTBDataSet(EduHubContext Context)
: base(Context)
{
Index_ABSENCE_TYPE = new Lazy<NullDictionary<string, IReadOnlyList<TCTB>>>(() => this.ToGroupedNullDictionary(i => i.ABSENCE_TYPE));
Index_ROOM = new Lazy<NullDictionary<string, IReadOnlyList<TCTB>>>(() => this.ToGroupedNullDictionary(i => i.ROOM));
Index_SUBJ = new Lazy<NullDictionary<string, IReadOnlyList<TCTB>>>(() => this.ToGroupedNullDictionary(i => i.SUBJ));
Index_TCTBKEY = new Lazy<Dictionary<DateTime, IReadOnlyList<TCTB>>>(() => this.ToGroupedDictionary(i => i.TCTBKEY));
Index_TEACHER = new Lazy<NullDictionary<string, IReadOnlyList<TCTB>>>(() => this.ToGroupedNullDictionary(i => i.TEACHER));
Index_TID = new Lazy<Dictionary<int, TCTB>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="TCTB" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="TCTB" /> fields for each CSV column header</returns>
internal override Action<TCTB, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<TCTB, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "TCTBKEY":
mapper[i] = (e, v) => e.TCTBKEY = DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "SUBJ":
mapper[i] = (e, v) => e.SUBJ = v;
break;
case "CLASS":
mapper[i] = (e, v) => e.CLASS = v == null ? (short?)null : short.Parse(v);
break;
case "TEACHER":
mapper[i] = (e, v) => e.TEACHER = v;
break;
case "ROOM":
mapper[i] = (e, v) => e.ROOM = v;
break;
case "TEACHER_AVAILABLE":
mapper[i] = (e, v) => e.TEACHER_AVAILABLE = v;
break;
case "ROOM_AVAILABLE":
mapper[i] = (e, v) => e.ROOM_AVAILABLE = v;
break;
case "TIME_FROM":
mapper[i] = (e, v) => e.TIME_FROM = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "TIME_TO":
mapper[i] = (e, v) => e.TIME_TO = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "COMMENT_A":
mapper[i] = (e, v) => e.COMMENT_A = v;
break;
case "ABSENCE_TYPE":
mapper[i] = (e, v) => e.ABSENCE_TYPE = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="TCTB" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="TCTB" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="TCTB" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{TCTB}"/> of entities</returns>
internal override IEnumerable<TCTB> ApplyDeltaEntities(IEnumerable<TCTB> Entities, List<TCTB> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.TCTBKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.TCTBKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<TCTB>>> Index_ABSENCE_TYPE;
private Lazy<NullDictionary<string, IReadOnlyList<TCTB>>> Index_ROOM;
private Lazy<NullDictionary<string, IReadOnlyList<TCTB>>> Index_SUBJ;
private Lazy<Dictionary<DateTime, IReadOnlyList<TCTB>>> Index_TCTBKEY;
private Lazy<NullDictionary<string, IReadOnlyList<TCTB>>> Index_TEACHER;
private Lazy<Dictionary<int, TCTB>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find TCTB by ABSENCE_TYPE field
/// </summary>
/// <param name="ABSENCE_TYPE">ABSENCE_TYPE value used to find TCTB</param>
/// <returns>List of related TCTB entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTB> FindByABSENCE_TYPE(string ABSENCE_TYPE)
{
return Index_ABSENCE_TYPE.Value[ABSENCE_TYPE];
}
/// <summary>
/// Attempt to find TCTB by ABSENCE_TYPE field
/// </summary>
/// <param name="ABSENCE_TYPE">ABSENCE_TYPE value used to find TCTB</param>
/// <param name="Value">List of related TCTB entities</param>
/// <returns>True if the list of related TCTB entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByABSENCE_TYPE(string ABSENCE_TYPE, out IReadOnlyList<TCTB> Value)
{
return Index_ABSENCE_TYPE.Value.TryGetValue(ABSENCE_TYPE, out Value);
}
/// <summary>
/// Attempt to find TCTB by ABSENCE_TYPE field
/// </summary>
/// <param name="ABSENCE_TYPE">ABSENCE_TYPE value used to find TCTB</param>
/// <returns>List of related TCTB entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTB> TryFindByABSENCE_TYPE(string ABSENCE_TYPE)
{
IReadOnlyList<TCTB> value;
if (Index_ABSENCE_TYPE.Value.TryGetValue(ABSENCE_TYPE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find TCTB by ROOM field
/// </summary>
/// <param name="ROOM">ROOM value used to find TCTB</param>
/// <returns>List of related TCTB entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTB> FindByROOM(string ROOM)
{
return Index_ROOM.Value[ROOM];
}
/// <summary>
/// Attempt to find TCTB by ROOM field
/// </summary>
/// <param name="ROOM">ROOM value used to find TCTB</param>
/// <param name="Value">List of related TCTB entities</param>
/// <returns>True if the list of related TCTB entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByROOM(string ROOM, out IReadOnlyList<TCTB> Value)
{
return Index_ROOM.Value.TryGetValue(ROOM, out Value);
}
/// <summary>
/// Attempt to find TCTB by ROOM field
/// </summary>
/// <param name="ROOM">ROOM value used to find TCTB</param>
/// <returns>List of related TCTB entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTB> TryFindByROOM(string ROOM)
{
IReadOnlyList<TCTB> value;
if (Index_ROOM.Value.TryGetValue(ROOM, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find TCTB by SUBJ field
/// </summary>
/// <param name="SUBJ">SUBJ value used to find TCTB</param>
/// <returns>List of related TCTB entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTB> FindBySUBJ(string SUBJ)
{
return Index_SUBJ.Value[SUBJ];
}
/// <summary>
/// Attempt to find TCTB by SUBJ field
/// </summary>
/// <param name="SUBJ">SUBJ value used to find TCTB</param>
/// <param name="Value">List of related TCTB entities</param>
/// <returns>True if the list of related TCTB entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySUBJ(string SUBJ, out IReadOnlyList<TCTB> Value)
{
return Index_SUBJ.Value.TryGetValue(SUBJ, out Value);
}
/// <summary>
/// Attempt to find TCTB by SUBJ field
/// </summary>
/// <param name="SUBJ">SUBJ value used to find TCTB</param>
/// <returns>List of related TCTB entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTB> TryFindBySUBJ(string SUBJ)
{
IReadOnlyList<TCTB> value;
if (Index_SUBJ.Value.TryGetValue(SUBJ, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find TCTB by TCTBKEY field
/// </summary>
/// <param name="TCTBKEY">TCTBKEY value used to find TCTB</param>
/// <returns>List of related TCTB entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTB> FindByTCTBKEY(DateTime TCTBKEY)
{
return Index_TCTBKEY.Value[TCTBKEY];
}
/// <summary>
/// Attempt to find TCTB by TCTBKEY field
/// </summary>
/// <param name="TCTBKEY">TCTBKEY value used to find TCTB</param>
/// <param name="Value">List of related TCTB entities</param>
/// <returns>True if the list of related TCTB entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTCTBKEY(DateTime TCTBKEY, out IReadOnlyList<TCTB> Value)
{
return Index_TCTBKEY.Value.TryGetValue(TCTBKEY, out Value);
}
/// <summary>
/// Attempt to find TCTB by TCTBKEY field
/// </summary>
/// <param name="TCTBKEY">TCTBKEY value used to find TCTB</param>
/// <returns>List of related TCTB entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTB> TryFindByTCTBKEY(DateTime TCTBKEY)
{
IReadOnlyList<TCTB> value;
if (Index_TCTBKEY.Value.TryGetValue(TCTBKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find TCTB by TEACHER field
/// </summary>
/// <param name="TEACHER">TEACHER value used to find TCTB</param>
/// <returns>List of related TCTB entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTB> FindByTEACHER(string TEACHER)
{
return Index_TEACHER.Value[TEACHER];
}
/// <summary>
/// Attempt to find TCTB by TEACHER field
/// </summary>
/// <param name="TEACHER">TEACHER value used to find TCTB</param>
/// <param name="Value">List of related TCTB entities</param>
/// <returns>True if the list of related TCTB entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTEACHER(string TEACHER, out IReadOnlyList<TCTB> Value)
{
return Index_TEACHER.Value.TryGetValue(TEACHER, out Value);
}
/// <summary>
/// Attempt to find TCTB by TEACHER field
/// </summary>
/// <param name="TEACHER">TEACHER value used to find TCTB</param>
/// <returns>List of related TCTB entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<TCTB> TryFindByTEACHER(string TEACHER)
{
IReadOnlyList<TCTB> value;
if (Index_TEACHER.Value.TryGetValue(TEACHER, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find TCTB by TID field
/// </summary>
/// <param name="TID">TID value used to find TCTB</param>
/// <returns>Related TCTB entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public TCTB FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find TCTB by TID field
/// </summary>
/// <param name="TID">TID value used to find TCTB</param>
/// <param name="Value">Related TCTB entity</param>
/// <returns>True if the related TCTB entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out TCTB Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find TCTB by TID field
/// </summary>
/// <param name="TID">TID value used to find TCTB</param>
/// <returns>Related TCTB entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public TCTB TryFindByTID(int TID)
{
TCTB value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a TCTB table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TCTB]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[TCTB](
[TID] int IDENTITY NOT NULL,
[TCTBKEY] datetime NOT NULL,
[SUBJ] varchar(5) NULL,
[CLASS] smallint NULL,
[TEACHER] varchar(4) NULL,
[ROOM] varchar(4) NULL,
[TEACHER_AVAILABLE] varchar(1) NULL,
[ROOM_AVAILABLE] varchar(1) NULL,
[TIME_FROM] datetime NULL,
[TIME_TO] datetime NULL,
[COMMENT_A] varchar(MAX) NULL,
[ABSENCE_TYPE] varchar(10) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [TCTB_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE NONCLUSTERED INDEX [TCTB_Index_ABSENCE_TYPE] ON [dbo].[TCTB]
(
[ABSENCE_TYPE] ASC
);
CREATE NONCLUSTERED INDEX [TCTB_Index_ROOM] ON [dbo].[TCTB]
(
[ROOM] ASC
);
CREATE NONCLUSTERED INDEX [TCTB_Index_SUBJ] ON [dbo].[TCTB]
(
[SUBJ] ASC
);
CREATE CLUSTERED INDEX [TCTB_Index_TCTBKEY] ON [dbo].[TCTB]
(
[TCTBKEY] ASC
);
CREATE NONCLUSTERED INDEX [TCTB_Index_TEACHER] ON [dbo].[TCTB]
(
[TEACHER] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTB]') AND name = N'TCTB_Index_ABSENCE_TYPE')
ALTER INDEX [TCTB_Index_ABSENCE_TYPE] ON [dbo].[TCTB] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTB]') AND name = N'TCTB_Index_ROOM')
ALTER INDEX [TCTB_Index_ROOM] ON [dbo].[TCTB] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTB]') AND name = N'TCTB_Index_SUBJ')
ALTER INDEX [TCTB_Index_SUBJ] ON [dbo].[TCTB] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTB]') AND name = N'TCTB_Index_TEACHER')
ALTER INDEX [TCTB_Index_TEACHER] ON [dbo].[TCTB] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTB]') AND name = N'TCTB_Index_TID')
ALTER INDEX [TCTB_Index_TID] ON [dbo].[TCTB] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTB]') AND name = N'TCTB_Index_ABSENCE_TYPE')
ALTER INDEX [TCTB_Index_ABSENCE_TYPE] ON [dbo].[TCTB] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTB]') AND name = N'TCTB_Index_ROOM')
ALTER INDEX [TCTB_Index_ROOM] ON [dbo].[TCTB] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTB]') AND name = N'TCTB_Index_SUBJ')
ALTER INDEX [TCTB_Index_SUBJ] ON [dbo].[TCTB] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTB]') AND name = N'TCTB_Index_TEACHER')
ALTER INDEX [TCTB_Index_TEACHER] ON [dbo].[TCTB] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TCTB]') AND name = N'TCTB_Index_TID')
ALTER INDEX [TCTB_Index_TID] ON [dbo].[TCTB] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="TCTB"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="TCTB"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<TCTB> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[TCTB] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the TCTB data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the TCTB data set</returns>
public override EduHubDataSetDataReader<TCTB> GetDataSetDataReader()
{
return new TCTBDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the TCTB data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the TCTB data set</returns>
public override EduHubDataSetDataReader<TCTB> GetDataSetDataReader(List<TCTB> Entities)
{
return new TCTBDataReader(new EduHubDataSetLoadedReader<TCTB>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class TCTBDataReader : EduHubDataSetDataReader<TCTB>
{
public TCTBDataReader(IEduHubDataSetReader<TCTB> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 15; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // TCTBKEY
return Current.TCTBKEY;
case 2: // SUBJ
return Current.SUBJ;
case 3: // CLASS
return Current.CLASS;
case 4: // TEACHER
return Current.TEACHER;
case 5: // ROOM
return Current.ROOM;
case 6: // TEACHER_AVAILABLE
return Current.TEACHER_AVAILABLE;
case 7: // ROOM_AVAILABLE
return Current.ROOM_AVAILABLE;
case 8: // TIME_FROM
return Current.TIME_FROM;
case 9: // TIME_TO
return Current.TIME_TO;
case 10: // COMMENT_A
return Current.COMMENT_A;
case 11: // ABSENCE_TYPE
return Current.ABSENCE_TYPE;
case 12: // LW_DATE
return Current.LW_DATE;
case 13: // LW_TIME
return Current.LW_TIME;
case 14: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // SUBJ
return Current.SUBJ == null;
case 3: // CLASS
return Current.CLASS == null;
case 4: // TEACHER
return Current.TEACHER == null;
case 5: // ROOM
return Current.ROOM == null;
case 6: // TEACHER_AVAILABLE
return Current.TEACHER_AVAILABLE == null;
case 7: // ROOM_AVAILABLE
return Current.ROOM_AVAILABLE == null;
case 8: // TIME_FROM
return Current.TIME_FROM == null;
case 9: // TIME_TO
return Current.TIME_TO == null;
case 10: // COMMENT_A
return Current.COMMENT_A == null;
case 11: // ABSENCE_TYPE
return Current.ABSENCE_TYPE == null;
case 12: // LW_DATE
return Current.LW_DATE == null;
case 13: // LW_TIME
return Current.LW_TIME == null;
case 14: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // TCTBKEY
return "TCTBKEY";
case 2: // SUBJ
return "SUBJ";
case 3: // CLASS
return "CLASS";
case 4: // TEACHER
return "TEACHER";
case 5: // ROOM
return "ROOM";
case 6: // TEACHER_AVAILABLE
return "TEACHER_AVAILABLE";
case 7: // ROOM_AVAILABLE
return "ROOM_AVAILABLE";
case 8: // TIME_FROM
return "TIME_FROM";
case 9: // TIME_TO
return "TIME_TO";
case 10: // COMMENT_A
return "COMMENT_A";
case 11: // ABSENCE_TYPE
return "ABSENCE_TYPE";
case 12: // LW_DATE
return "LW_DATE";
case 13: // LW_TIME
return "LW_TIME";
case 14: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "TCTBKEY":
return 1;
case "SUBJ":
return 2;
case "CLASS":
return 3;
case "TEACHER":
return 4;
case "ROOM":
return 5;
case "TEACHER_AVAILABLE":
return 6;
case "ROOM_AVAILABLE":
return 7;
case "TIME_FROM":
return 8;
case "TIME_TO":
return 9;
case "COMMENT_A":
return 10;
case "ABSENCE_TYPE":
return 11;
case "LW_DATE":
return 12;
case "LW_TIME":
return 13;
case "LW_USER":
return 14;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Umbraco.Core.Events;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Security;
namespace Umbraco.Core.Services
{
/// <summary>
/// Represents the UserService, which is an easy access to operations involving <see cref="IProfile"/>, <see cref="IMembershipUser"/> and eventually Backoffice Users.
/// </summary>
public class UserService : IUserService
{
private readonly RepositoryFactory _repositoryFactory;
private readonly IDatabaseUnitOfWorkProvider _uowProvider;
public UserService(RepositoryFactory repositoryFactory)
: this(new PetaPocoUnitOfWorkProvider(), repositoryFactory)
{ }
public UserService(IDatabaseUnitOfWorkProvider provider)
: this(provider, new RepositoryFactory())
{ }
public UserService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory)
{
_repositoryFactory = repositoryFactory;
_uowProvider = provider;
}
#region Implementation of IMembershipUserService
/// <summary>
/// By default we'll return the 'writer', but we need to check it exists. If it doesn't we'll return the first type that is not an admin, otherwise if there's only one
/// we will return that one.
/// </summary>
/// <returns></returns>
public string GetDefaultMemberType()
{
using (var repository = _repositoryFactory.CreateUserTypeRepository(_uowProvider.GetUnitOfWork()))
{
var types = repository.GetAll().Select(x => x.Alias).ToArray();
if (types.Any() == false)
{
throw new EntityNotFoundException("No member types could be resolved");
}
if (types.InvariantContains("writer"))
{
return types.First(x => x.InvariantEquals("writer"));
}
if (types.Length == 1)
{
return types.First();
}
//first that is not admin
return types.First(x => x.InvariantEquals("admin") == false);
}
}
public bool Exists(string username)
{
using (var repository = _repositoryFactory.CreateUserRepository(_uowProvider.GetUnitOfWork()))
{
return repository.Exists(username);
}
}
public IUser CreateUserWithIdentity(string username, string email, IUserType userType)
{
return CreateUserWithIdentity(username, email, "", userType);
}
IUser IMembershipMemberService<IUser>.CreateWithIdentity(string username, string email, string rawPasswordValue, string memberTypeAlias)
{
var userType = GetUserTypeByAlias(memberTypeAlias);
if (userType == null)
{
throw new EntityNotFoundException("The user type " + memberTypeAlias + " could not be resolved");
}
return CreateUserWithIdentity(username, email, rawPasswordValue, userType);
}
private IUser CreateUserWithIdentity(string username, string email, string rawPasswordValue, IUserType userType)
{
if (userType == null) throw new ArgumentNullException("userType");
//TODO: PUT lock here!!
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserRepository(uow))
{
var loginExists = uow.Database.ExecuteScalar<int>("SELECT COUNT(id) FROM umbracoUser WHERE userLogin = @Login", new { Login = username }) != 0;
if (loginExists)
throw new ArgumentException("Login already exists");
var user = new User(userType)
{
DefaultToLiveEditing = false,
Email = email,
Language = Configuration.GlobalSettings.DefaultUILanguage,
Name = username,
RawPasswordValue = rawPasswordValue,
Username = username,
StartContentId = -1,
StartMediaId = -1,
IsLockedOut = false,
IsApproved = true
};
if (SavingUser.IsRaisedEventCancelled(new SaveEventArgs<IUser>(user), this))
return user;
repository.AddOrUpdate(user);
uow.Commit();
SavedUser.RaiseEvent(new SaveEventArgs<IUser>(user, false), this);
return user;
}
}
public IUser GetById(int id)
{
using (var repository = _repositoryFactory.CreateUserRepository(_uowProvider.GetUnitOfWork()))
{
var user = repository.Get((int)id);
return user;
}
}
public IUser GetByProviderKey(object id)
{
var asInt = id.TryConvertTo<int>();
if (asInt.Success)
{
return GetById((int)id);
}
return null;
}
public IUser GetByEmail(string email)
{
using (var repository = _repositoryFactory.CreateUserRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IUser>.Builder.Where(x => x.Email.Equals(email));
var user = repository.GetByQuery(query).FirstOrDefault();
return user;
}
}
public IUser GetByUsername(string login)
{
using (var repository = _repositoryFactory.CreateUserRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IUser>.Builder.Where(x => x.Username.Equals(login));
return repository.GetByQuery(query).FirstOrDefault();
}
}
/// <summary>
/// This disables and renames the user, it does not delete them, use the overload to delete them
/// </summary>
/// <param name="membershipUser"></param>
public void Delete(IUser membershipUser)
{
//disable
membershipUser.IsApproved = false;
//can't rename if it's going to take up too many chars
if (membershipUser.Username.Length + 9 <= 125)
{
membershipUser.Username = DateTime.Now.ToString("yyyyMMdd") + "_" + membershipUser.Username;
}
Save(membershipUser);
//clear out the user logins!
var uow = _uowProvider.GetUnitOfWork();
uow.Database.Execute("delete from umbracoUserLogins where userID = @id", new {id = membershipUser.Id});
}
/// <summary>
/// This is simply a helper method which essentially just wraps the MembershipProvider's ChangePassword method
/// </summary>
/// <param name="user">The user to save the password for</param>
/// <param name="password"></param>
/// <remarks>
/// This method exists so that Umbraco developers can use one entry point to create/update users if they choose to.
/// </remarks>
public void SavePassword(IUser user, string password)
{
if (user == null) throw new ArgumentNullException("user");
var provider = MembershipProviderExtensions.GetUsersMembershipProvider();
if (provider.IsUmbracoMembershipProvider() == false)
throw new NotSupportedException("When using a non-Umbraco membership provider you must change the user password by using the MembershipProvider.ChangePassword method");
provider.ChangePassword(user.Username, "", password);
//go re-fetch the member and update the properties that may have changed
var result = GetByUsername(user.Username);
if (result != null)
{
//should never be null but it could have been deleted by another thread.
user.RawPasswordValue = result.RawPasswordValue;
user.LastPasswordChangeDate = result.LastPasswordChangeDate;
user.UpdateDate = user.UpdateDate;
}
}
/// <summary>
/// To permanently delete the user pass in true, otherwise they will just be disabled
/// </summary>
/// <param name="user"></param>
/// <param name="deletePermanently"></param>
public void Delete(IUser user, bool deletePermanently)
{
if (deletePermanently == false)
{
Delete(user);
}
else
{
if (DeletingUser.IsRaisedEventCancelled(new DeleteEventArgs<IUser>(user), this))
return;
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserRepository(uow))
{
repository.Delete(user);
uow.Commit();
}
DeletedUser.RaiseEvent(new DeleteEventArgs<IUser>(user, false), this);
}
}
public void Save(IUser entity, bool raiseEvents = true)
{
if (raiseEvents)
{
if (SavingUser.IsRaisedEventCancelled(new SaveEventArgs<IUser>(entity), this))
return;
}
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserRepository(uow))
{
repository.AddOrUpdate(entity);
uow.Commit();
}
if (raiseEvents)
SavedUser.RaiseEvent(new SaveEventArgs<IUser>(entity, false), this);
}
public void Save(IEnumerable<IUser> entities, bool raiseEvents = true)
{
if (raiseEvents)
{
if (SavingUser.IsRaisedEventCancelled(new SaveEventArgs<IUser>(entities), this))
return;
}
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserRepository(uow))
{
foreach (var member in entities)
{
repository.AddOrUpdate(member);
}
//commit the whole lot in one go
uow.Commit();
}
if (raiseEvents)
SavedUser.RaiseEvent(new SaveEventArgs<IUser>(entities, false), this);
}
public IEnumerable<IUser> FindByEmail(string emailStringToMatch, int pageIndex, int pageSize, out int totalRecords, StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith)
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserRepository(uow))
{
var query = new Query<IUser>();
switch (matchType)
{
case StringPropertyMatchType.Exact:
query.Where(member => member.Email.Equals(emailStringToMatch));
break;
case StringPropertyMatchType.Contains:
query.Where(member => member.Email.Contains(emailStringToMatch));
break;
case StringPropertyMatchType.StartsWith:
query.Where(member => member.Email.StartsWith(emailStringToMatch));
break;
case StringPropertyMatchType.EndsWith:
query.Where(member => member.Email.EndsWith(emailStringToMatch));
break;
case StringPropertyMatchType.Wildcard:
query.Where(member => member.Email.SqlWildcard(emailStringToMatch, TextColumnType.NVarchar));
break;
default:
throw new ArgumentOutOfRangeException("matchType");
}
return repository.GetPagedResultsByQuery(query, pageIndex, pageSize, out totalRecords, dto => dto.Email);
}
}
public IEnumerable<IUser> FindByUsername(string login, int pageIndex, int pageSize, out int totalRecords, StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith)
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserRepository(uow))
{
var query = new Query<IUser>();
switch (matchType)
{
case StringPropertyMatchType.Exact:
query.Where(member => member.Username.Equals(login));
break;
case StringPropertyMatchType.Contains:
query.Where(member => member.Username.Contains(login));
break;
case StringPropertyMatchType.StartsWith:
query.Where(member => member.Username.StartsWith(login));
break;
case StringPropertyMatchType.EndsWith:
query.Where(member => member.Username.EndsWith(login));
break;
case StringPropertyMatchType.Wildcard:
query.Where(member => member.Email.SqlWildcard(login, TextColumnType.NVarchar));
break;
default:
throw new ArgumentOutOfRangeException("matchType");
}
return repository.GetPagedResultsByQuery(query, pageIndex, pageSize, out totalRecords, dto => dto.Username);
}
}
public int GetCount(MemberCountType countType)
{
using (var repository = _repositoryFactory.CreateUserRepository(_uowProvider.GetUnitOfWork()))
{
IQuery<IUser> query;
switch (countType)
{
case MemberCountType.All:
query = new Query<IUser>();
return repository.Count(query);
case MemberCountType.Online:
throw new NotImplementedException();
//var fromDate = DateTime.Now.AddMinutes(-Membership.UserIsOnlineTimeWindow);
//query =
// Query<IMember>.Builder.Where(
// x =>
// ((Member)x).PropertyTypeAlias == Constants.Conventions.Member.LastLoginDate &&
// ((Member)x).DateTimePropertyValue > fromDate);
//return repository.GetCountByQuery(query);
case MemberCountType.LockedOut:
query =
Query<IUser>.Builder.Where(
x => x.IsLockedOut);
return repository.GetCountByQuery(query);
case MemberCountType.Approved:
query =
Query<IUser>.Builder.Where(
x => x.IsApproved);
return repository.GetCountByQuery(query);
default:
throw new ArgumentOutOfRangeException("countType");
}
}
}
public IEnumerable<IUser> GetAll(int pageIndex, int pageSize, out int totalRecords)
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserRepository(uow))
{
return repository.GetPagedResultsByQuery(null, pageIndex, pageSize, out totalRecords, member => member.Username);
}
}
#endregion
#region Implementation of IUserService
/// <summary>
/// Gets an IProfile by User Id.
/// </summary>
/// <param name="id">Id of the User to retrieve</param>
/// <returns><see cref="IProfile"/></returns>
public IProfile GetProfileById(int id)
{
var user = GetUserById(id);
return user.ProfileData;
}
public IProfile GetProfileByUserName(string login)
{
var user = GetByUsername(login);
return user.ProfileData;
}
public IUser GetUserById(int id)
{
using (var repository = _repositoryFactory.CreateUserRepository(_uowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Replaces the same permission set for a single user to any number of entities
/// </summary>
/// <param name="userId"></param>
/// <param name="permissions"></param>
/// <param name="entityIds"></param>
public void ReplaceUserPermissions(int userId, IEnumerable<char> permissions, params int[] entityIds)
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserRepository(uow))
{
repository.ReplaceUserPermissions(userId, permissions, entityIds);
}
}
public IEnumerable<IUserType> GetAllUserTypes(params int[] ids)
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserTypeRepository(uow))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets an IUserType by its Alias
/// </summary>
/// <param name="alias">Alias of the UserType to retrieve</param>
/// <returns><see cref="IUserType"/></returns>
public IUserType GetUserTypeByAlias(string alias)
{
using (var repository = _repositoryFactory.CreateUserTypeRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IUserType>.Builder.Where(x => x.Alias == alias);
var contents = repository.GetByQuery(query);
return contents.SingleOrDefault();
}
}
public IUserType GetUserTypeById(int id)
{
using (var repository = _repositoryFactory.CreateUserTypeRepository(_uowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets an IUserType by its Name
/// </summary>
/// <param name="name">Name of the UserType to retrieve</param>
/// <returns><see cref="IUserType"/></returns>
public IUserType GetUserTypeByName(string name)
{
using (var repository = _repositoryFactory.CreateUserTypeRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IUserType>.Builder.Where(x => x.Name == name);
var contents = repository.GetByQuery(query);
return contents.SingleOrDefault();
}
}
public void SaveUserType(IUserType userType, bool raiseEvents = true)
{
if (raiseEvents)
{
if (SavingUserType.IsRaisedEventCancelled(new SaveEventArgs<IUserType>(userType), this))
return;
}
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserTypeRepository(uow))
{
repository.AddOrUpdate(userType);
uow.Commit();
}
if (raiseEvents)
SavedUserType.RaiseEvent(new SaveEventArgs<IUserType>(userType, false), this);
}
public void DeleteUserType(IUserType userType)
{
if (DeletingUserType.IsRaisedEventCancelled(new DeleteEventArgs<IUserType>(userType), this))
return;
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserTypeRepository(uow))
{
repository.Delete(userType);
uow.Commit();
}
DeletedUserType.RaiseEvent(new DeleteEventArgs<IUserType>(userType, false), this);
}
/// <summary>
/// This is useful for when a section is removed from config
/// </summary>
/// <param name="sectionAlias"></param>
public void DeleteSectionFromAllUsers(string sectionAlias)
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserRepository(uow))
{
var assignedUsers = repository.GetUsersAssignedToSection(sectionAlias);
foreach (var user in assignedUsers)
{
//now remove the section for each user and commit
user.RemoveAllowedSection(sectionAlias);
repository.AddOrUpdate(user);
}
uow.Commit();
}
}
/// <summary>
/// Returns permissions for a given user for any number of nodes
/// </summary>
/// <param name="user"></param>
/// <param name="nodeIds"></param>
/// <returns></returns>
/// <remarks>
/// If no permissions are found for a particular entity then the user's default permissions will be applied
/// </remarks>
public IEnumerable<EntityPermission> GetPermissions(IUser user, params int[] nodeIds)
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserRepository(uow))
{
var explicitPermissions = repository.GetUserPermissionsForEntities(user.Id, nodeIds);
//if no permissions are assigned to a particular node then we will fill in those permissions with the user's defaults
var result = new List<EntityPermission>(explicitPermissions);
var missingIds = nodeIds.Except(result.Select(x => x.EntityId));
foreach (var id in missingIds)
{
result.Add(
new EntityPermission(
user.Id,
id,
user.DefaultPermissions.ToArray()));
}
return result;
}
}
#endregion
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IUserService, SaveEventArgs<IUser>> SavingUser;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IUserService, SaveEventArgs<IUser>> SavedUser;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IUserService, DeleteEventArgs<IUser>> DeletingUser;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IUserService, DeleteEventArgs<IUser>> DeletedUser;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IUserService, SaveEventArgs<IUserType>> SavingUserType;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IUserService, SaveEventArgs<IUserType>> SavedUserType;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IUserService, DeleteEventArgs<IUserType>> DeletingUserType;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IUserService, DeleteEventArgs<IUserType>> DeletedUserType;
}
}
| |
// 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.Resources;
using System.Runtime.CompilerServices;
#if !FEATURE_SERIALIZATION_UAPAOT
namespace System.Xml.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Xml;
using System.Xml.Serialization.Configuration;
using System.Reflection;
using System.Reflection.Emit;
using System.IO;
using System.Security;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Xml.Extensions;
internal class CodeGenerator
{
internal static BindingFlags InstancePublicBindingFlags = BindingFlags.Instance | BindingFlags.Public;
internal static BindingFlags InstanceBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
internal static BindingFlags StaticBindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
internal static MethodAttributes PublicMethodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig;
internal static MethodAttributes PublicOverrideMethodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;
internal static MethodAttributes ProtectedOverrideMethodAttributes = MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig;
internal static MethodAttributes PrivateMethodAttributes = MethodAttributes.Private | MethodAttributes.HideBySig;
private TypeBuilder _typeBuilder;
private MethodBuilder _methodBuilder;
private ILGenerator _ilGen;
private Dictionary<string, ArgBuilder> _argList;
private LocalScope _currentScope;
// Stores a queue of free locals available in the context of the method, keyed by
// type and name of the local
private Dictionary<Tuple<Type, string>, Queue<LocalBuilder>> _freeLocals;
private Stack _blockStack;
private Label _methodEndLabel;
internal CodeGenerator(TypeBuilder typeBuilder)
{
System.Diagnostics.Debug.Assert(typeBuilder != null);
_typeBuilder = typeBuilder;
}
internal static bool IsNullableGenericType(Type type)
{
return type.Name == "Nullable`1";
}
internal static void AssertHasInterface(Type type, Type iType)
{
#if DEBUG
Debug.Assert(iType.IsInterface);
foreach (Type iFace in type.GetInterfaces())
{
if (iFace == iType)
return;
}
Debug.Assert(false);
#endif
}
internal void BeginMethod(Type returnType, string methodName, Type[] argTypes, string[] argNames, MethodAttributes methodAttributes)
{
_methodBuilder = _typeBuilder.DefineMethod(methodName, methodAttributes, returnType, argTypes);
_ilGen = _methodBuilder.GetILGenerator();
InitILGeneration(argTypes, argNames, (_methodBuilder.Attributes & MethodAttributes.Static) == MethodAttributes.Static);
}
internal void BeginMethod(Type returnType, MethodBuilderInfo methodBuilderInfo, Type[] argTypes, string[] argNames, MethodAttributes methodAttributes)
{
#if DEBUG
methodBuilderInfo.Validate(returnType, argTypes, methodAttributes);
#endif
_methodBuilder = methodBuilderInfo.MethodBuilder;
_ilGen = _methodBuilder.GetILGenerator();
InitILGeneration(argTypes, argNames, (_methodBuilder.Attributes & MethodAttributes.Static) == MethodAttributes.Static);
}
private void InitILGeneration(Type[] argTypes, string[] argNames, bool isStatic)
{
_methodEndLabel = _ilGen.DefineLabel();
this.retLabel = _ilGen.DefineLabel();
_blockStack = new Stack();
_whileStack = new Stack();
_currentScope = new LocalScope();
_freeLocals = new Dictionary<Tuple<Type, string>, Queue<LocalBuilder>>();
_argList = new Dictionary<string, ArgBuilder>();
// this ptr is arg 0 for non static, assuming ref type (not value type)
if (!isStatic)
_argList.Add("this", new ArgBuilder("this", 0, _typeBuilder.BaseType));
for (int i = 0; i < argTypes.Length; i++)
{
ArgBuilder arg = new ArgBuilder(argNames[i], _argList.Count, argTypes[i]);
_argList.Add(arg.Name, arg);
_methodBuilder.DefineParameter(arg.Index, ParameterAttributes.None, arg.Name);
}
}
internal MethodBuilder EndMethod()
{
MarkLabel(_methodEndLabel);
Ret();
MethodBuilder retVal = null;
retVal = _methodBuilder;
_methodBuilder = null;
_ilGen = null;
_freeLocals = null;
_blockStack = null;
_whileStack = null;
_argList = null;
_currentScope = null;
retLocal = null;
return retVal;
}
internal MethodBuilder MethodBuilder
{
get { return _methodBuilder; }
}
internal ArgBuilder GetArg(string name)
{
System.Diagnostics.Debug.Assert(_argList != null && _argList.ContainsKey(name));
return (ArgBuilder)_argList[name];
}
internal LocalBuilder GetLocal(string name)
{
System.Diagnostics.Debug.Assert(_currentScope != null && _currentScope.ContainsKey(name));
return _currentScope[name];
}
internal LocalBuilder retLocal;
internal Label retLabel;
internal LocalBuilder ReturnLocal
{
get
{
if (retLocal == null)
retLocal = DeclareLocal(_methodBuilder.ReturnType, "_ret");
return retLocal;
}
}
internal Label ReturnLabel
{
get { return retLabel; }
}
private Dictionary<Type, LocalBuilder> _tmpLocals = new Dictionary<Type, LocalBuilder>();
internal LocalBuilder GetTempLocal(Type type)
{
LocalBuilder localTmp;
if (!_tmpLocals.TryGetValue(type, out localTmp))
{
localTmp = DeclareLocal(type, "_tmp" + _tmpLocals.Count);
_tmpLocals.Add(type, localTmp);
}
return localTmp;
}
internal Type GetVariableType(object var)
{
if (var is ArgBuilder)
return ((ArgBuilder)var).ArgType;
else if (var is LocalBuilder)
return ((LocalBuilder)var).LocalType;
else
return var.GetType();
}
internal object GetVariable(string name)
{
object var;
if (TryGetVariable(name, out var))
return var;
System.Diagnostics.Debug.Assert(false);
return null;
}
internal bool TryGetVariable(string name, out object variable)
{
LocalBuilder loc;
if (_currentScope != null && _currentScope.TryGetValue(name, out loc))
{
variable = loc;
return true;
}
ArgBuilder arg;
if (_argList != null && _argList.TryGetValue(name, out arg))
{
variable = arg;
return true;
}
int val;
if (int.TryParse(name, out val))
{
variable = val;
return true;
}
variable = null;
return false;
}
internal void EnterScope()
{
LocalScope newScope = new LocalScope(_currentScope);
_currentScope = newScope;
}
internal void ExitScope()
{
Debug.Assert(_currentScope.parent != null);
_currentScope.AddToFreeLocals(_freeLocals);
_currentScope = _currentScope.parent;
}
private bool TryDequeueLocal(Type type, string name, out LocalBuilder local)
{
// This method can only be called between BeginMethod and EndMethod (i.e.
// while we are emitting code for a method
Debug.Assert(_freeLocals != null);
Queue<LocalBuilder> freeLocalQueue;
Tuple<Type, string> key = new Tuple<Type, string>(type, name);
if (_freeLocals.TryGetValue(key, out freeLocalQueue))
{
local = freeLocalQueue.Dequeue();
// If the queue is empty, remove this key from the dictionary
// of free locals
if (freeLocalQueue.Count == 0)
{
_freeLocals.Remove(key);
}
return true;
}
local = null;
return false;
}
internal LocalBuilder DeclareLocal(Type type, string name)
{
Debug.Assert(!_currentScope.ContainsKey(name));
LocalBuilder local;
if (!TryDequeueLocal(type, name, out local))
{
local = _ilGen.DeclareLocal(type, false);
}
_currentScope[name] = local;
return local;
}
internal LocalBuilder DeclareOrGetLocal(Type type, string name)
{
LocalBuilder local;
if (!_currentScope.TryGetValue(name, out local))
local = DeclareLocal(type, name);
else
Debug.Assert(local.LocalType == type);
return local;
}
internal object For(LocalBuilder local, object start, object end)
{
ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end);
if (forState.Index != null)
{
Load(start);
Stloc(forState.Index);
Br(forState.TestLabel);
}
MarkLabel(forState.BeginLabel);
_blockStack.Push(forState);
return forState;
}
internal void EndFor()
{
object stackTop = _blockStack.Pop();
ForState forState = stackTop as ForState;
Debug.Assert(forState != null);
if (forState.Index != null)
{
Ldloc(forState.Index);
Ldc(1);
Add();
Stloc(forState.Index);
MarkLabel(forState.TestLabel);
Ldloc(forState.Index);
Load(forState.End);
Type varType = GetVariableType(forState.End);
if (varType.IsArray)
{
Ldlen();
}
else
{
#if DEBUG
CodeGenerator.AssertHasInterface(varType, typeof(ICollection));
#endif
MethodInfo ICollection_get_Count = typeof(ICollection).GetMethod(
"get_Count",
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
Call(ICollection_get_Count);
}
Blt(forState.BeginLabel);
}
else
Br(forState.BeginLabel);
}
internal void If()
{
InternalIf(false);
}
internal void IfNot()
{
InternalIf(true);
}
private static OpCode[] s_branchCodes = new OpCode[] {
OpCodes.Bge,
OpCodes.Bne_Un,
OpCodes.Bgt,
OpCodes.Ble,
OpCodes.Beq,
OpCodes.Blt,
};
private OpCode GetBranchCode(Cmp cmp)
{
return s_branchCodes[(int)cmp];
}
internal void If(Cmp cmpOp)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void If(object value1, Cmp cmpOp, object value2)
{
Load(value1);
Load(value2);
If(cmpOp);
}
internal void Else()
{
IfState ifState = PopIfState();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
ifState.ElseBegin = ifState.EndIf;
_blockStack.Push(ifState);
}
internal void EndIf()
{
IfState ifState = PopIfState();
if (!ifState.ElseBegin.Equals(ifState.EndIf))
MarkLabel(ifState.ElseBegin);
MarkLabel(ifState.EndIf);
}
private Stack _leaveLabels = new Stack();
internal void BeginExceptionBlock()
{
_leaveLabels.Push(DefineLabel());
_ilGen.BeginExceptionBlock();
}
internal void BeginCatchBlock(Type exception)
{
_ilGen.BeginCatchBlock(exception);
}
internal void EndExceptionBlock()
{
_ilGen.EndExceptionBlock();
_ilGen.MarkLabel((Label)_leaveLabels.Pop());
}
internal void Leave()
{
_ilGen.Emit(OpCodes.Leave, (Label)_leaveLabels.Peek());
}
internal void Call(MethodInfo methodInfo)
{
Debug.Assert(methodInfo != null);
if (methodInfo.IsVirtual && !methodInfo.DeclaringType.IsValueType)
_ilGen.Emit(OpCodes.Callvirt, methodInfo);
else
_ilGen.Emit(OpCodes.Call, methodInfo);
}
internal void Call(ConstructorInfo ctor)
{
Debug.Assert(ctor != null);
_ilGen.Emit(OpCodes.Call, ctor);
}
internal void New(ConstructorInfo constructorInfo)
{
Debug.Assert(constructorInfo != null);
_ilGen.Emit(OpCodes.Newobj, constructorInfo);
}
internal void InitObj(Type valueType)
{
_ilGen.Emit(OpCodes.Initobj, valueType);
}
internal void NewArray(Type elementType, object len)
{
Load(len);
_ilGen.Emit(OpCodes.Newarr, elementType);
}
internal void LoadArrayElement(object obj, object arrayIndex)
{
Type objType = GetVariableType(obj).GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
{
Ldelema(objType);
Ldobj(objType);
}
else
Ldelem(objType);
}
internal void StoreArrayElement(object obj, object arrayIndex, object value)
{
Type arrayType = GetVariableType(obj);
if (arrayType == typeof(Array))
{
Load(obj);
Call(typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) }));
}
else
{
Type objType = arrayType.GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
Ldelema(objType);
Load(value);
ConvertValue(GetVariableType(value), objType);
if (IsStruct(objType))
Stobj(objType);
else
Stelem(objType);
}
}
private static bool IsStruct(Type objType)
{
return objType.IsValueType && !objType.IsPrimitive;
}
internal Type LoadMember(object obj, MemberInfo memberInfo)
{
if (GetVariableType(obj).IsValueType)
LoadAddress(obj);
else
Load(obj);
return LoadMember(memberInfo);
}
private static MethodInfo GetPropertyMethodFromBaseType(PropertyInfo propertyInfo, bool isGetter)
{
// we only invoke this when the propertyInfo does not have a GET or SET method on it
Type currentType = propertyInfo.DeclaringType.BaseType;
PropertyInfo currentProperty;
string propertyName = propertyInfo.Name;
MethodInfo result = null;
while (currentType != null)
{
currentProperty = currentType.GetProperty(propertyName);
if (currentProperty != null)
{
if (isGetter)
{
result = currentProperty.GetMethod;
}
else
{
result = currentProperty.SetMethod;
}
if (result != null)
{
// we found the GetMethod/SetMethod on the type closest to the current declaring type
break;
}
}
// keep looking at the base type like compiler does
currentType = currentType.BaseType;
}
return result;
}
internal Type LoadMember(MemberInfo memberInfo)
{
Type memberType = null;
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
memberType = fieldInfo.FieldType;
if (fieldInfo.IsStatic)
{
_ilGen.Emit(OpCodes.Ldsfld, fieldInfo);
}
else
{
_ilGen.Emit(OpCodes.Ldfld, fieldInfo);
}
}
else
{
System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo);
PropertyInfo property = (PropertyInfo)memberInfo;
memberType = property.PropertyType;
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null)
{
getMethod = GetPropertyMethodFromBaseType(property, true);
}
System.Diagnostics.Debug.Assert(getMethod != null);
Call(getMethod);
}
}
return memberType;
}
internal Type LoadMemberAddress(MemberInfo memberInfo)
{
Type memberType = null;
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
memberType = fieldInfo.FieldType;
if (fieldInfo.IsStatic)
{
_ilGen.Emit(OpCodes.Ldsflda, fieldInfo);
}
else
{
_ilGen.Emit(OpCodes.Ldflda, fieldInfo);
}
}
else
{
System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo);
PropertyInfo property = (PropertyInfo)memberInfo;
memberType = property.PropertyType;
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null)
{
getMethod = GetPropertyMethodFromBaseType(property, true);
}
System.Diagnostics.Debug.Assert(getMethod != null);
Call(getMethod);
LocalBuilder tmpLoc = GetTempLocal(memberType);
Stloc(tmpLoc);
Ldloca(tmpLoc);
}
}
return memberType;
}
internal void StoreMember(MemberInfo memberInfo)
{
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
if (fieldInfo.IsStatic)
{
_ilGen.Emit(OpCodes.Stsfld, fieldInfo);
}
else
{
_ilGen.Emit(OpCodes.Stfld, fieldInfo);
}
}
else
{
System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo);
PropertyInfo property = (PropertyInfo)memberInfo;
if (property != null)
{
MethodInfo setMethod = property.SetMethod;
if (setMethod == null)
{
setMethod = GetPropertyMethodFromBaseType(property, false);
}
System.Diagnostics.Debug.Assert(setMethod != null);
Call(setMethod);
}
}
}
internal void Load(object obj)
{
if (obj == null)
_ilGen.Emit(OpCodes.Ldnull);
else if (obj is ArgBuilder)
Ldarg((ArgBuilder)obj);
else if (obj is LocalBuilder)
Ldloc((LocalBuilder)obj);
else
Ldc(obj);
}
internal void LoadAddress(object obj)
{
if (obj is ArgBuilder)
LdargAddress((ArgBuilder)obj);
else if (obj is LocalBuilder)
LdlocAddress((LocalBuilder)obj);
else
Load(obj);
}
internal void ConvertAddress(Type source, Type target)
{
InternalConvert(source, target, true);
}
internal void ConvertValue(Type source, Type target)
{
InternalConvert(source, target, false);
}
internal void Castclass(Type target)
{
_ilGen.Emit(OpCodes.Castclass, target);
}
internal void Box(Type type)
{
_ilGen.Emit(OpCodes.Box, type);
}
internal void Unbox(Type type)
{
_ilGen.Emit(OpCodes.Unbox, type);
}
private static OpCode[] s_ldindOpCodes = new OpCode[] {
OpCodes.Nop,//Empty = 0,
OpCodes.Nop,//Object = 1,
OpCodes.Nop,//DBNull = 2,
OpCodes.Ldind_I1,//Boolean = 3,
OpCodes.Ldind_I2,//Char = 4,
OpCodes.Ldind_I1,//SByte = 5,
OpCodes.Ldind_U1,//Byte = 6,
OpCodes.Ldind_I2,//Int16 = 7,
OpCodes.Ldind_U2,//UInt16 = 8,
OpCodes.Ldind_I4,//Int32 = 9,
OpCodes.Ldind_U4,//UInt32 = 10,
OpCodes.Ldind_I8,//Int64 = 11,
OpCodes.Ldind_I8,//UInt64 = 12,
OpCodes.Ldind_R4,//Single = 13,
OpCodes.Ldind_R8,//Double = 14,
OpCodes.Nop,//Decimal = 15,
OpCodes.Nop,//DateTime = 16,
OpCodes.Nop,//17
OpCodes.Ldind_Ref,//String = 18,
};
private OpCode GetLdindOpCode(TypeCode typeCode)
{
return s_ldindOpCodes[(int)typeCode];
}
internal void Ldobj(Type type)
{
OpCode opCode = GetLdindOpCode(type.GetTypeCode());
if (!opCode.Equals(OpCodes.Nop))
{
_ilGen.Emit(opCode);
}
else
{
_ilGen.Emit(OpCodes.Ldobj, type);
}
}
internal void Stobj(Type type)
{
_ilGen.Emit(OpCodes.Stobj, type);
}
internal void Ceq()
{
_ilGen.Emit(OpCodes.Ceq);
}
internal void Clt()
{
_ilGen.Emit(OpCodes.Clt);
}
internal void Cne()
{
Ceq();
Ldc(0);
Ceq();
}
internal void Ble(Label label)
{
_ilGen.Emit(OpCodes.Ble, label);
}
internal void Throw()
{
_ilGen.Emit(OpCodes.Throw);
}
internal void Ldtoken(Type t)
{
_ilGen.Emit(OpCodes.Ldtoken, t);
}
internal void Ldc(object o)
{
Type valueType = o.GetType();
if (o is Type)
{
Ldtoken((Type)o);
Call(typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(RuntimeTypeHandle) }));
}
else if (valueType.IsEnum)
{
Ldc(Convert.ChangeType(o, Enum.GetUnderlyingType(valueType), null));
}
else
{
switch (valueType.GetTypeCode())
{
case TypeCode.Boolean:
Ldc((bool)o);
break;
case TypeCode.Char:
Debug.Assert(false, "Char is not a valid schema primitive and should be treated as int in DataContract");
throw new NotSupportedException(SR.XmlInvalidCharSchemaPrimitive);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
Ldc(Convert.ToInt32(o, CultureInfo.InvariantCulture));
break;
case TypeCode.Int32:
Ldc((int)o);
break;
case TypeCode.UInt32:
Ldc((int)(uint)o);
break;
case TypeCode.UInt64:
Ldc((long)(ulong)o);
break;
case TypeCode.Int64:
Ldc((long)o);
break;
case TypeCode.Single:
Ldc((float)o);
break;
case TypeCode.Double:
Ldc((double)o);
break;
case TypeCode.String:
Ldstr((string)o);
break;
case TypeCode.Decimal:
ConstructorInfo Decimal_ctor = typeof(Decimal).GetConstructor(
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) }
);
int[] bits = decimal.GetBits((decimal)o);
Ldc(bits[0]); // digit
Ldc(bits[1]); // digit
Ldc(bits[2]); // digit
Ldc((bits[3] & 0x80000000) == 0x80000000); // sign
Ldc((byte)((bits[3] >> 16) & 0xFF)); // decimal location
New(Decimal_ctor);
break;
case TypeCode.DateTime:
ConstructorInfo DateTime_ctor = typeof(DateTime).GetConstructor(
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(long) }
);
Ldc(((DateTime)o).Ticks); // ticks
New(DateTime_ctor);
break;
case TypeCode.Object:
case TypeCode.Empty:
case TypeCode.DBNull:
default:
if (valueType == typeof(TimeSpan))
{
ConstructorInfo TimeSpan_ctor = typeof(TimeSpan).GetConstructor(
CodeGenerator.InstanceBindingFlags,
null,
new Type[] { typeof(long) },
null
);
Ldc(((TimeSpan)o).Ticks); // ticks
New(TimeSpan_ctor);
break;
}
else
{
throw new NotSupportedException(SR.Format(SR.UnknownConstantType, valueType.AssemblyQualifiedName));
}
}
}
}
internal void Ldc(bool boolVar)
{
if (boolVar)
{
_ilGen.Emit(OpCodes.Ldc_I4_1);
}
else
{
_ilGen.Emit(OpCodes.Ldc_I4_0);
}
}
internal void Ldc(int intVar)
{
switch (intVar)
{
case -1:
_ilGen.Emit(OpCodes.Ldc_I4_M1);
break;
case 0:
_ilGen.Emit(OpCodes.Ldc_I4_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldc_I4_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldc_I4_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldc_I4_3);
break;
case 4:
_ilGen.Emit(OpCodes.Ldc_I4_4);
break;
case 5:
_ilGen.Emit(OpCodes.Ldc_I4_5);
break;
case 6:
_ilGen.Emit(OpCodes.Ldc_I4_6);
break;
case 7:
_ilGen.Emit(OpCodes.Ldc_I4_7);
break;
case 8:
_ilGen.Emit(OpCodes.Ldc_I4_8);
break;
default:
_ilGen.Emit(OpCodes.Ldc_I4, intVar);
break;
}
}
internal void Ldc(long l)
{
_ilGen.Emit(OpCodes.Ldc_I8, l);
}
internal void Ldc(float f)
{
_ilGen.Emit(OpCodes.Ldc_R4, f);
}
internal void Ldc(double d)
{
_ilGen.Emit(OpCodes.Ldc_R8, d);
}
internal void Ldstr(string strVar)
{
if (strVar == null)
_ilGen.Emit(OpCodes.Ldnull);
else
_ilGen.Emit(OpCodes.Ldstr, strVar);
}
internal void LdlocAddress(LocalBuilder localBuilder)
{
if (localBuilder.LocalType.IsValueType)
Ldloca(localBuilder);
else
Ldloc(localBuilder);
}
internal void Ldloc(LocalBuilder localBuilder)
{
_ilGen.Emit(OpCodes.Ldloc, localBuilder);
}
internal void Ldloc(string name)
{
Debug.Assert(_currentScope.ContainsKey(name));
LocalBuilder local = _currentScope[name];
Ldloc(local);
}
internal void Stloc(Type type, string name)
{
LocalBuilder local = null;
if (!_currentScope.TryGetValue(name, out local))
{
local = DeclareLocal(type, name);
}
Debug.Assert(local.LocalType == type);
Stloc(local);
}
internal void Stloc(LocalBuilder local)
{
_ilGen.Emit(OpCodes.Stloc, local);
}
internal void Ldloc(Type type, string name)
{
Debug.Assert(_currentScope.ContainsKey(name));
LocalBuilder local = _currentScope[name];
Debug.Assert(local.LocalType == type);
Ldloc(local);
}
internal void Ldloca(LocalBuilder localBuilder)
{
_ilGen.Emit(OpCodes.Ldloca, localBuilder);
}
internal void LdargAddress(ArgBuilder argBuilder)
{
if (argBuilder.ArgType.IsValueType)
Ldarga(argBuilder);
else
Ldarg(argBuilder);
}
internal void Ldarg(string arg)
{
Ldarg(GetArg(arg));
}
internal void Ldarg(ArgBuilder arg)
{
Ldarg(arg.Index);
}
internal void Ldarg(int slot)
{
switch (slot)
{
case 0:
_ilGen.Emit(OpCodes.Ldarg_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldarg_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldarg_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldarg_3);
break;
default:
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarg_S, slot);
else
_ilGen.Emit(OpCodes.Ldarg, slot);
break;
}
}
internal void Ldarga(ArgBuilder argBuilder)
{
Ldarga(argBuilder.Index);
}
internal void Ldarga(int slot)
{
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarga_S, slot);
else
_ilGen.Emit(OpCodes.Ldarga, slot);
}
internal void Ldlen()
{
_ilGen.Emit(OpCodes.Ldlen);
_ilGen.Emit(OpCodes.Conv_I4);
}
private static OpCode[] s_ldelemOpCodes = new OpCode[] {
OpCodes.Nop,//Empty = 0,
OpCodes.Ldelem_Ref,//Object = 1,
OpCodes.Ldelem_Ref,//DBNull = 2,
OpCodes.Ldelem_I1,//Boolean = 3,
OpCodes.Ldelem_I2,//Char = 4,
OpCodes.Ldelem_I1,//SByte = 5,
OpCodes.Ldelem_U1,//Byte = 6,
OpCodes.Ldelem_I2,//Int16 = 7,
OpCodes.Ldelem_U2,//UInt16 = 8,
OpCodes.Ldelem_I4,//Int32 = 9,
OpCodes.Ldelem_U4,//UInt32 = 10,
OpCodes.Ldelem_I8,//Int64 = 11,
OpCodes.Ldelem_I8,//UInt64 = 12,
OpCodes.Ldelem_R4,//Single = 13,
OpCodes.Ldelem_R8,//Double = 14,
OpCodes.Nop,//Decimal = 15,
OpCodes.Nop,//DateTime = 16,
OpCodes.Nop,//17
OpCodes.Ldelem_Ref,//String = 18,
};
private OpCode GetLdelemOpCode(TypeCode typeCode)
{
return s_ldelemOpCodes[(int)typeCode];
}
internal void Ldelem(Type arrayElementType)
{
if (arrayElementType.IsEnum)
{
Ldelem(Enum.GetUnderlyingType(arrayElementType));
}
else
{
OpCode opCode = GetLdelemOpCode(arrayElementType.GetTypeCode());
Debug.Assert(!opCode.Equals(OpCodes.Nop));
if (opCode.Equals(OpCodes.Nop))
throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.AssemblyQualifiedName));
_ilGen.Emit(opCode);
}
}
internal void Ldelema(Type arrayElementType)
{
OpCode opCode = OpCodes.Ldelema;
_ilGen.Emit(opCode, arrayElementType);
}
private static OpCode[] s_stelemOpCodes = new OpCode[] {
OpCodes.Nop,//Empty = 0,
OpCodes.Stelem_Ref,//Object = 1,
OpCodes.Stelem_Ref,//DBNull = 2,
OpCodes.Stelem_I1,//Boolean = 3,
OpCodes.Stelem_I2,//Char = 4,
OpCodes.Stelem_I1,//SByte = 5,
OpCodes.Stelem_I1,//Byte = 6,
OpCodes.Stelem_I2,//Int16 = 7,
OpCodes.Stelem_I2,//UInt16 = 8,
OpCodes.Stelem_I4,//Int32 = 9,
OpCodes.Stelem_I4,//UInt32 = 10,
OpCodes.Stelem_I8,//Int64 = 11,
OpCodes.Stelem_I8,//UInt64 = 12,
OpCodes.Stelem_R4,//Single = 13,
OpCodes.Stelem_R8,//Double = 14,
OpCodes.Nop,//Decimal = 15,
OpCodes.Nop,//DateTime = 16,
OpCodes.Nop,//17
OpCodes.Stelem_Ref,//String = 18,
};
private OpCode GetStelemOpCode(TypeCode typeCode)
{
return s_stelemOpCodes[(int)typeCode];
}
internal void Stelem(Type arrayElementType)
{
if (arrayElementType.IsEnum)
Stelem(Enum.GetUnderlyingType(arrayElementType));
else
{
OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.AssemblyQualifiedName));
_ilGen.Emit(opCode);
}
}
internal Label DefineLabel()
{
return _ilGen.DefineLabel();
}
internal void MarkLabel(Label label)
{
_ilGen.MarkLabel(label);
}
internal void Nop()
{
_ilGen.Emit(OpCodes.Nop);
}
internal void Add()
{
_ilGen.Emit(OpCodes.Add);
}
internal void Ret()
{
_ilGen.Emit(OpCodes.Ret);
}
internal void Br(Label label)
{
_ilGen.Emit(OpCodes.Br, label);
}
internal void Br_S(Label label)
{
_ilGen.Emit(OpCodes.Br_S, label);
}
internal void Blt(Label label)
{
_ilGen.Emit(OpCodes.Blt, label);
}
internal void Brfalse(Label label)
{
_ilGen.Emit(OpCodes.Brfalse, label);
}
internal void Brtrue(Label label)
{
_ilGen.Emit(OpCodes.Brtrue, label);
}
internal void Pop()
{
_ilGen.Emit(OpCodes.Pop);
}
internal void Dup()
{
_ilGen.Emit(OpCodes.Dup);
}
private void InternalIf(bool negate)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
if (negate)
Brtrue(ifState.ElseBegin);
else
Brfalse(ifState.ElseBegin);
_blockStack.Push(ifState);
}
private static OpCode[] s_convOpCodes = new OpCode[] {
OpCodes.Nop,//Empty = 0,
OpCodes.Nop,//Object = 1,
OpCodes.Nop,//DBNull = 2,
OpCodes.Conv_I1,//Boolean = 3,
OpCodes.Conv_I2,//Char = 4,
OpCodes.Conv_I1,//SByte = 5,
OpCodes.Conv_U1,//Byte = 6,
OpCodes.Conv_I2,//Int16 = 7,
OpCodes.Conv_U2,//UInt16 = 8,
OpCodes.Conv_I4,//Int32 = 9,
OpCodes.Conv_U4,//UInt32 = 10,
OpCodes.Conv_I8,//Int64 = 11,
OpCodes.Conv_U8,//UInt64 = 12,
OpCodes.Conv_R4,//Single = 13,
OpCodes.Conv_R8,//Double = 14,
OpCodes.Nop,//Decimal = 15,
OpCodes.Nop,//DateTime = 16,
OpCodes.Nop,//17
OpCodes.Nop,//String = 18,
};
private OpCode GetConvOpCode(TypeCode typeCode)
{
return s_convOpCodes[(int)typeCode];
}
private void InternalConvert(Type source, Type target, bool isAddress)
{
if (target == source)
return;
if (target.IsValueType)
{
if (source.IsValueType)
{
OpCode opCode = GetConvOpCode(target.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
{
throw new CodeGeneratorConversionException(source, target, isAddress, "NoConversionPossibleTo");
}
else
{
_ilGen.Emit(opCode);
}
}
else if (source.IsAssignableFrom(target))
{
Unbox(target);
if (!isAddress)
Ldobj(target);
}
else
{
throw new CodeGeneratorConversionException(source, target, isAddress, "IsNotAssignableFrom");
}
}
else if (target.IsAssignableFrom(source))
{
if (source.IsValueType)
{
if (isAddress)
Ldobj(source);
Box(source);
}
}
else if (source.IsAssignableFrom(target))
{
Castclass(target);
}
else if (target.IsInterface || source.IsInterface)
{
Castclass(target);
}
else
{
throw new CodeGeneratorConversionException(source, target, isAddress, "IsNotAssignableFrom");
}
}
private IfState PopIfState()
{
object stackTop = _blockStack.Pop();
IfState ifState = stackTop as IfState;
Debug.Assert(ifState != null);
return ifState;
}
internal static AssemblyBuilder CreateAssemblyBuilder(string name)
{
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = name;
assemblyName.Version = new Version(1, 0, 0, 0);
return AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
}
internal static ModuleBuilder CreateModuleBuilder(AssemblyBuilder assemblyBuilder, string name)
{
return assemblyBuilder.DefineDynamicModule(name);
}
internal static TypeBuilder CreateTypeBuilder(ModuleBuilder moduleBuilder, string name, TypeAttributes attributes, Type parent, Type[] interfaces)
{
// parent is nullable if no base class
return moduleBuilder.DefineType(TempAssembly.GeneratedAssemblyNamespace + "." + name,
attributes, parent, interfaces);
}
private int _initElseIfStack = -1;
private IfState _elseIfState;
internal void InitElseIf()
{
Debug.Assert(_initElseIfStack == -1);
_elseIfState = (IfState)_blockStack.Pop();
_initElseIfStack = _blockStack.Count;
Br(_elseIfState.EndIf);
MarkLabel(_elseIfState.ElseBegin);
}
private int _initIfStack = -1;
internal void InitIf()
{
Debug.Assert(_initIfStack == -1);
_initIfStack = _blockStack.Count;
}
internal void AndIf(Cmp cmpOp)
{
if (_initIfStack == _blockStack.Count)
{
_initIfStack = -1;
If(cmpOp);
return;
}
if (_initElseIfStack == _blockStack.Count)
{
_initElseIfStack = -1;
_elseIfState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), _elseIfState.ElseBegin);
_blockStack.Push(_elseIfState);
return;
}
Debug.Assert(_initIfStack == -1 && _initElseIfStack == -1);
IfState ifState = (IfState)_blockStack.Peek();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
}
internal void AndIf()
{
if (_initIfStack == _blockStack.Count)
{
_initIfStack = -1;
If();
return;
}
if (_initElseIfStack == _blockStack.Count)
{
_initElseIfStack = -1;
_elseIfState.ElseBegin = DefineLabel();
Brfalse(_elseIfState.ElseBegin);
_blockStack.Push(_elseIfState);
return;
}
Debug.Assert(_initIfStack == -1 && _initElseIfStack == -1);
IfState ifState = (IfState)_blockStack.Peek();
Brfalse(ifState.ElseBegin);
}
internal void IsInst(Type type)
{
_ilGen.Emit(OpCodes.Isinst, type);
}
internal void Beq(Label label)
{
_ilGen.Emit(OpCodes.Beq, label);
}
internal void Bne(Label label)
{
_ilGen.Emit(OpCodes.Bne_Un, label);
}
internal void GotoMethodEnd()
{
//limit to only short forward (127 CIL instruction)
//Br_S(this.methodEndLabel);
Br(_methodEndLabel);
}
internal class WhileState
{
public Label StartLabel;
public Label CondLabel;
public Label EndLabel;
public WhileState(CodeGenerator ilg)
{
StartLabel = ilg.DefineLabel();
CondLabel = ilg.DefineLabel();
EndLabel = ilg.DefineLabel();
}
}
// Usage:
// WhileBegin()
// WhileBreak()
// WhileContinue()
// WhileBeginCondition()
// (bool on stack)
// WhileEndCondition()
// WhileEnd()
private Stack _whileStack;
internal void WhileBegin()
{
WhileState whileState = new WhileState(this);
Br(whileState.CondLabel);
MarkLabel(whileState.StartLabel);
_whileStack.Push(whileState);
}
internal void WhileEnd()
{
WhileState whileState = (WhileState)_whileStack.Pop();
MarkLabel(whileState.EndLabel);
}
internal void WhileContinue()
{
WhileState whileState = (WhileState)_whileStack.Peek();
Br(whileState.CondLabel);
}
internal void WhileBeginCondition()
{
WhileState whileState = (WhileState)_whileStack.Peek();
// If there are two MarkLabel ILs consecutively, Labels will converge to one label.
// This could cause the code to look different. We insert Nop here specifically
// that the While label stands out.
Nop();
MarkLabel(whileState.CondLabel);
}
internal void WhileEndCondition()
{
WhileState whileState = (WhileState)_whileStack.Peek();
Brtrue(whileState.StartLabel);
}
}
internal class ArgBuilder
{
internal string Name;
internal int Index;
internal Type ArgType;
internal ArgBuilder(string name, int index, Type argType)
{
this.Name = name;
this.Index = index;
this.ArgType = argType;
}
}
internal class ForState
{
private LocalBuilder _indexVar;
private Label _beginLabel;
private Label _testLabel;
private object _end;
internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end)
{
_indexVar = indexVar;
_beginLabel = beginLabel;
_testLabel = testLabel;
_end = end;
}
internal LocalBuilder Index
{
get
{
return _indexVar;
}
}
internal Label BeginLabel
{
get
{
return _beginLabel;
}
}
internal Label TestLabel
{
get
{
return _testLabel;
}
}
internal object End
{
get
{
return _end;
}
}
}
internal enum Cmp : int
{
LessThan = 0,
EqualTo,
LessThanOrEqualTo,
GreaterThan,
NotEqualTo,
GreaterThanOrEqualTo
}
internal class IfState
{
private Label _elseBegin;
private Label _endIf;
internal Label EndIf
{
get
{
return _endIf;
}
set
{
_endIf = value;
}
}
internal Label ElseBegin
{
get
{
return _elseBegin;
}
set
{
_elseBegin = value;
}
}
}
internal class LocalScope
{
public readonly LocalScope parent;
private readonly Dictionary<string, LocalBuilder> _locals;
// Root scope
public LocalScope()
{
_locals = new Dictionary<string, LocalBuilder>();
}
public LocalScope(LocalScope parent) : this()
{
this.parent = parent;
}
public bool ContainsKey(string key)
{
return _locals.ContainsKey(key) || (parent != null && parent.ContainsKey(key));
}
public bool TryGetValue(string key, out LocalBuilder value)
{
if (_locals.TryGetValue(key, out value))
{
return true;
}
else if (parent != null)
{
return parent.TryGetValue(key, out value);
}
else
{
value = null;
return false;
}
}
public LocalBuilder this[string key]
{
get
{
LocalBuilder value;
TryGetValue(key, out value);
return value;
}
set
{
_locals[key] = value;
}
}
public void AddToFreeLocals(Dictionary<Tuple<Type, string>, Queue<LocalBuilder>> freeLocals)
{
foreach (var item in _locals)
{
Tuple<Type, string> key = new Tuple<Type, string>(item.Value.LocalType, item.Key);
Queue<LocalBuilder> freeLocalQueue;
if (freeLocals.TryGetValue(key, out freeLocalQueue))
{
// Add to end of the queue so that it will be re-used in
// FIFO manner
freeLocalQueue.Enqueue(item.Value);
}
else
{
freeLocalQueue = new Queue<LocalBuilder>();
freeLocalQueue.Enqueue(item.Value);
freeLocals.Add(key, freeLocalQueue);
}
}
}
}
internal class MethodBuilderInfo
{
public readonly MethodBuilder MethodBuilder;
public readonly Type[] ParameterTypes;
public MethodBuilderInfo(MethodBuilder methodBuilder, Type[] parameterTypes)
{
this.MethodBuilder = methodBuilder;
this.ParameterTypes = parameterTypes;
}
public void Validate(Type returnType, Type[] parameterTypes, MethodAttributes attributes)
{
#if DEBUG
Debug.Assert(this.MethodBuilder.ReturnType == returnType);
Debug.Assert(this.MethodBuilder.Attributes == attributes);
Debug.Assert(this.ParameterTypes.Length == parameterTypes.Length);
for (int i = 0; i < parameterTypes.Length; ++i)
{
Debug.Assert(this.ParameterTypes[i] == parameterTypes[i]);
}
#endif
}
}
internal class CodeGeneratorConversionException : Exception
{
private Type _sourceType;
private Type _targetType;
private bool _isAddress;
private string _reason;
public CodeGeneratorConversionException(Type sourceType, Type targetType, bool isAddress, string reason)
: base()
{
_sourceType = sourceType;
_targetType = targetType;
_isAddress = isAddress;
_reason = reason;
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.CodeGeneration;
using Orleans.Configuration;
using Orleans.Core;
using Orleans.GrainDirectory;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Scheduler;
using Orleans.Storage;
namespace Orleans.Runtime
{
/// <summary>
/// Maintains additional per-activation state that is required for Orleans internal operations.
/// MUST lock this object for any concurrent access
/// Consider: compartmentalize by usage, e.g., using separate interfaces for data for catalog, etc.
/// </summary>
internal class ActivationData : IGrainActivationContext, IActivationData, IInvokable, IDisposable
{
// This class is used for activations that have extension invokers. It keeps a dictionary of
// invoker objects to use with the activation, and extend the default invoker
// defined for the grain class.
// Note that in all cases we never have more than one copy of an actual invoker;
// we may have a ExtensionInvoker per activation, in the worst case.
private class ExtensionInvoker : IGrainMethodInvoker, IGrainExtensionMap
{
// Because calls to ExtensionInvoker are allways made within the activation context,
// we rely on the single-threading guarantee of the runtime and do not protect the map with a lock.
private Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>> extensionMap; // key is the extension interface ID
/// <summary>
/// Try to add an extension for the specific interface ID.
/// Fail and return false if there is already an extension for that interface ID.
/// Note that if an extension invoker handles multiple interface IDs, it can only be associated
/// with one of those IDs when added, and so only conflicts on that one ID will be detected and prevented.
/// </summary>
/// <param name="invoker"></param>
/// <param name="handler"></param>
/// <returns></returns>
internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension handler)
{
if (extensionMap == null)
{
extensionMap = new Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>>(1);
}
if (extensionMap.ContainsKey(invoker.InterfaceId)) return false;
extensionMap.Add(invoker.InterfaceId, new Tuple<IGrainExtension, IGrainExtensionMethodInvoker>(handler, invoker));
return true;
}
/// <summary>
/// Removes all extensions for the specified interface id.
/// Returns true if the chained invoker no longer has any extensions and may be safely retired.
/// </summary>
/// <param name="extension"></param>
/// <returns>true if the chained invoker is now empty, false otherwise</returns>
public bool Remove(IGrainExtension extension)
{
int interfaceId = 0;
foreach(int iface in extensionMap.Keys)
if (extensionMap[iface].Item1 == extension)
{
interfaceId = iface;
break;
}
if (interfaceId == 0) // not found
throw new InvalidOperationException(String.Format("Extension {0} is not installed",
extension.GetType().FullName));
extensionMap.Remove(interfaceId);
return extensionMap.Count == 0;
}
public bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result)
{
result = null;
if (extensionMap == null) return false;
foreach (var ext in extensionMap.Values)
if (extensionType == ext.Item1.GetType())
{
result = ext.Item1;
return true;
}
return false;
}
/// <summary>
/// Invokes the appropriate grain or extension method for the request interface ID and method ID.
/// First each extension invoker is tried; if no extension handles the request, then the base
/// invoker is used to handle the request.
/// The base invoker will throw an appropriate exception if the request is not recognized.
/// </summary>
/// <param name="grain"></param>
/// <param name="request"></param>
/// <returns></returns>
public Task<object> Invoke(IAddressable grain, InvokeMethodRequest request)
{
if (extensionMap == null || !extensionMap.ContainsKey(request.InterfaceId))
throw new InvalidOperationException(
String.Format("Extension invoker invoked with an unknown inteface ID:{0}.", request.InterfaceId));
var invoker = extensionMap[request.InterfaceId].Item2;
var extension = extensionMap[request.InterfaceId].Item1;
return invoker.Invoke(extension, request);
}
public bool IsExtensionInstalled(int interfaceId)
{
return extensionMap != null && extensionMap.ContainsKey(interfaceId);
}
public int InterfaceId
{
get { return 0; } // 0 indicates an extension invoker that may have multiple intefaces inplemented by extensions.
}
public ushort InterfaceVersion
{
get { return 0; }
}
/// <summary>
/// Gets the extension from this instance if it is available.
/// </summary>
/// <param name="interfaceId">The interface id.</param>
/// <param name="extension">The extension.</param>
/// <returns>
/// <see langword="true"/> if the extension is found, <see langword="false"/> otherwise.
/// </returns>
public bool TryGetExtension(int interfaceId, out IGrainExtension extension)
{
Tuple<IGrainExtension, IGrainExtensionMethodInvoker> value;
if (extensionMap != null && extensionMap.TryGetValue(interfaceId, out value))
{
extension = value.Item1;
}
else
{
extension = null;
}
return extension != null;
}
}
internal class GrainActivationContextFactory
{
public IGrainActivationContext Context { get; set; }
}
// This is the maximum amount of time we expect a request to continue processing
private readonly TimeSpan maxRequestProcessingTime;
private readonly TimeSpan maxWarningRequestProcessingTime;
private readonly SiloMessagingOptions messagingOptions;
public readonly TimeSpan CollectionAgeLimit;
private readonly ILogger logger;
private IGrainMethodInvoker lastInvoker;
private IServiceScope serviceScope;
private HashSet<IGrainTimer> timers;
public ActivationData(
ActivationAddress addr,
string genericArguments,
PlacementStrategy placedUsing,
IMultiClusterRegistrationStrategy registrationStrategy,
IActivationCollector collector,
TimeSpan ageLimit,
IOptions<SiloMessagingOptions> messagingOptions,
TimeSpan maxWarningRequestProcessingTime,
TimeSpan maxRequestProcessingTime,
IRuntimeClient runtimeClient,
ILoggerFactory loggerFactory)
{
if (null == addr) throw new ArgumentNullException(nameof(addr));
if (null == placedUsing) throw new ArgumentNullException(nameof(placedUsing));
if (null == collector) throw new ArgumentNullException(nameof(collector));
logger = loggerFactory.CreateLogger<ActivationData>();
this.lifecycle = new GrainLifecycle(loggerFactory.CreateLogger<LifecycleSubject>());
this.maxRequestProcessingTime = maxRequestProcessingTime;
this.maxWarningRequestProcessingTime = maxWarningRequestProcessingTime;
this.messagingOptions = messagingOptions.Value;
ResetKeepAliveRequest();
Address = addr;
State = ActivationState.Create;
PlacedUsing = placedUsing;
RegistrationStrategy = registrationStrategy;
if (!Grain.IsSystemTarget)
{
this.collector = collector;
}
CollectionAgeLimit = ageLimit;
GrainReference = GrainReference.FromGrainId(addr.Grain, runtimeClient.GrainReferenceRuntime, genericArguments, Grain.IsSystemTarget ? addr.Silo : null);
this.SchedulingContext = new SchedulingContext(this);
}
public Type GrainType => GrainTypeData.Type;
public IGrainIdentity GrainIdentity => this.Identity;
public IServiceProvider ActivationServices => this.serviceScope.ServiceProvider;
private ExtensionInvoker extensionInvoker;
public IGrainMethodInvoker GetInvoker(GrainTypeManager typeManager, int interfaceId, string genericGrainType = null)
{
// Return previous cached invoker, if applicable
if (lastInvoker != null && interfaceId == lastInvoker.InterfaceId) // extension invoker returns InterfaceId==0, so this condition will never be true if an extension is installed
return lastInvoker;
if (extensionInvoker != null && extensionInvoker.IsExtensionInstalled(interfaceId))
{
// Shared invoker for all extensions installed on this grain
lastInvoker = extensionInvoker;
}
else
{
// Find the specific invoker for this interface / grain type
lastInvoker = typeManager.GetInvoker(interfaceId, genericGrainType);
}
return lastInvoker;
}
internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension extension)
{
this.lastInvoker = null;
if (extensionInvoker == null)
extensionInvoker = new ExtensionInvoker();
return extensionInvoker.TryAddExtension(invoker, extension);
}
internal void RemoveExtension(IGrainExtension extension)
{
this.lastInvoker = null;
if (extensionInvoker != null)
{
if (extensionInvoker.Remove(extension))
extensionInvoker = null;
}
else
throw new InvalidOperationException("Grain extensions not installed.");
}
internal bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result)
{
result = null;
return extensionInvoker != null && extensionInvoker.TryGetExtensionHandler(extensionType, out result);
}
public ISchedulingContext SchedulingContext { get; }
public string GrainTypeName
{
get
{
if (GrainInstanceType == null)
{
throw new ArgumentNullException("GrainInstanceType", "GrainInstanceType has not been set.");
}
return GrainInstanceType.FullName;
}
}
internal Type GrainInstanceType => GrainTypeData?.Type;
internal void SetGrainInstance(Grain grainInstance)
{
GrainInstance = grainInstance;
}
internal void SetupContext(GrainTypeData typeData, IServiceProvider grainServices)
{
this.GrainTypeData = typeData;
this.Items = new Dictionary<object, object>();
this.serviceScope = grainServices.CreateScope();
SetGrainActivationContextInScopedServices(this.ActivationServices, this);
if (typeData != null)
{
var grainType = typeData.Type;
// Don't ever collect system grains or reminder table grain or memory store grains.
bool doNotCollect = typeof(IReminderTableGrain).IsAssignableFrom(grainType) || typeof(IMemoryStorageGrain).IsAssignableFrom(grainType);
if (doNotCollect)
{
this.collector = null;
}
}
}
private static void SetGrainActivationContextInScopedServices(IServiceProvider sp, IGrainActivationContext context)
{
var contextFactory = sp.GetRequiredService<GrainActivationContextFactory>();
contextFactory.Context = context;
}
private Streams.StreamDirectory streamDirectory;
internal Streams.StreamDirectory GetStreamDirectory()
{
return streamDirectory ?? (streamDirectory = new Streams.StreamDirectory());
}
internal bool IsUsingStreams
{
get { return streamDirectory != null; }
}
internal async Task DeactivateStreamResources()
{
if (streamDirectory == null) return; // No streams - Nothing to do.
if (extensionInvoker == null) return; // No installed extensions - Nothing to do.
if (StreamResourceTestControl.TestOnlySuppressStreamCleanupOnDeactivate)
{
logger.Warn(0, "Suppressing cleanup of stream resources during tests for {0}", this);
return;
}
await streamDirectory.Cleanup(true, false);
}
GrainReference IActivationData.GrainReference
{
get { return GrainReference; }
}
public GrainId Identity
{
get { return Grain; }
}
public GrainTypeData GrainTypeData { get; private set; }
public Grain GrainInstance { get; private set; }
public ActivationId ActivationId { get { return Address.Activation; } }
public ActivationAddress Address { get; private set; }
public IServiceProvider ServiceProvider => this.serviceScope?.ServiceProvider;
public IDictionary<object, object> Items { get; private set; }
private readonly GrainLifecycle lifecycle;
public IGrainLifecycle ObservableLifecycle => lifecycle;
internal ILifecycleObserver Lifecycle => lifecycle;
public void OnTimerCreated(IGrainTimer timer)
{
AddTimer(timer);
}
internal readonly GrainReference GrainReference;
public SiloAddress Silo { get { return Address.Silo; } }
public GrainId Grain { get { return Address.Grain; } }
public ActivationState State { get; private set; }
public void SetState(ActivationState state)
{
State = state;
}
// Don't accept any new messages and stop all timers.
public void PrepareForDeactivation()
{
SetState(ActivationState.Deactivating);
deactivationStartTime = DateTime.UtcNow;
StopAllTimers();
}
/// <summary>
/// If State == Invalid, this may contain a forwarding address for incoming messages
/// </summary>
public ActivationAddress ForwardingAddress { get; set; }
private IActivationCollector collector;
internal bool IsExemptFromCollection
{
get { return collector == null; }
}
public DateTime CollectionTicket { get; private set; }
private bool collectionCancelledFlag;
public bool TrySetCollectionCancelledFlag()
{
lock (this)
{
if (default(DateTime) == CollectionTicket || collectionCancelledFlag) return false;
collectionCancelledFlag = true;
return true;
}
}
public void ResetCollectionCancelledFlag()
{
lock (this)
{
collectionCancelledFlag = false;
}
}
public void ResetCollectionTicket()
{
CollectionTicket = default(DateTime);
}
public void SetCollectionTicket(DateTime ticket)
{
if (ticket == default(DateTime)) throw new ArgumentException("default(DateTime) is disallowed", "ticket");
if (CollectionTicket != default(DateTime))
{
throw new InvalidOperationException("call ResetCollectionTicket before calling SetCollectionTicket.");
}
CollectionTicket = ticket;
}
public PlacementStrategy PlacedUsing { get; private set; }
public IMultiClusterRegistrationStrategy RegistrationStrategy { get; private set; }
// Currently, the only supported multi-activation grain is one using the StatelessWorkerPlacement strategy.
internal bool IsStatelessWorker { get { return PlacedUsing is StatelessWorkerPlacement; } }
// Currently, the only grain type that is not registered in the Grain Directory is StatelessWorker.
internal bool IsUsingGrainDirectory { get { return !IsStatelessWorker; } }
public Message Running { get; private set; }
// the number of requests that are currently executing on this activation.
// includes reentrant and non-reentrant requests.
private int numRunning;
private DateTime currentRequestStartTime;
private DateTime becameIdle;
private DateTime deactivationStartTime;
public void RecordRunning(Message message)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
numRunning++;
if (Running != null) return;
// This logic only works for non-reentrant activations
// Consider: Handle long request detection for reentrant activations.
Running = message;
currentRequestStartTime = DateTime.UtcNow;
}
public void ResetRunning(Message message)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
numRunning--;
if (numRunning == 0)
{
becameIdle = DateTime.UtcNow;
if (!IsExemptFromCollection)
{
collector.TryRescheduleCollection(this);
}
}
// The below logic only works for non-reentrant activations.
if (Running != null && !message.Equals(Running)) return;
Running = null;
currentRequestStartTime = DateTime.MinValue;
}
private long inFlightCount;
private long enqueuedOnDispatcherCount;
/// <summary>
/// Number of messages that are actively being processed [as opposed to being in the Waiting queue].
/// In most cases this will be 0 or 1, but for Reentrant grains can be >1.
/// </summary>
public long InFlightCount { get { return Interlocked.Read(ref inFlightCount); } }
/// <summary>
/// Number of messages that are being received [as opposed to being in the scheduler queue or actively processed].
/// </summary>
public long EnqueuedOnDispatcherCount { get { return Interlocked.Read(ref enqueuedOnDispatcherCount); } }
/// <summary>Increment the number of in-flight messages currently being processed.</summary>
public void IncrementInFlightCount() { Interlocked.Increment(ref inFlightCount); }
/// <summary>Decrement the number of in-flight messages currently being processed.</summary>
public void DecrementInFlightCount() { Interlocked.Decrement(ref inFlightCount); }
/// <summary>Increment the number of messages currently in the prcess of being received.</summary>
public void IncrementEnqueuedOnDispatcherCount() { Interlocked.Increment(ref enqueuedOnDispatcherCount); }
/// <summary>Decrement the number of messages currently in the prcess of being received.</summary>
public void DecrementEnqueuedOnDispatcherCount() { Interlocked.Decrement(ref enqueuedOnDispatcherCount); }
/// <summary>
/// grouped by sending activation: responses first, then sorted by id
/// </summary>
private List<Message> waiting;
public int WaitingCount
{
get
{
return waiting == null ? 0 : waiting.Count;
}
}
public enum EnqueueMessageResult
{
Success,
ErrorInvalidActivation,
ErrorStuckActivation,
}
/// <summary>
/// Insert in a FIFO order
/// </summary>
/// <param name="message"></param>
public EnqueueMessageResult EnqueueMessage(Message message)
{
lock (this)
{
if (State == ActivationState.Invalid)
{
logger.Warn(ErrorCode.Dispatcher_InvalidActivation,
"Cannot enqueue message to invalid activation {0} : {1}", this.ToDetailedString(), message);
return EnqueueMessageResult.ErrorInvalidActivation;
}
if (State == ActivationState.Deactivating)
{
var deactivatingTime = DateTime.UtcNow - deactivationStartTime;
if (deactivatingTime > maxRequestProcessingTime)
{
logger.Error(ErrorCode.Dispatcher_StuckActivation,
$"Current activation {ToDetailedString()} marked as Deactivating for {deactivatingTime}. Trying to enqueue {message}.");
return EnqueueMessageResult.ErrorStuckActivation;
}
}
if (Running != null)
{
var currentRequestActiveTime = DateTime.UtcNow - currentRequestStartTime;
if (currentRequestActiveTime > maxRequestProcessingTime)
{
logger.Error(ErrorCode.Dispatcher_StuckActivation,
$"Current request has been active for {currentRequestActiveTime} for activation {ToDetailedString()}. Currently executing {Running}. Trying to enqueue {message}.");
return EnqueueMessageResult.ErrorStuckActivation;
}
// Consider: Handle long request detection for reentrant activations -- this logic only works for non-reentrant activations
else if (currentRequestActiveTime > maxWarningRequestProcessingTime)
{
logger.Warn(ErrorCode.Dispatcher_ExtendedMessageProcessing,
"Current request has been active for {0} for activation {1}. Currently executing {2}. Trying to enqueue {3}.",
currentRequestActiveTime, this.ToDetailedString(), Running, message);
}
}
waiting = waiting ?? new List<Message>();
waiting.Add(message);
return EnqueueMessageResult.Success;
}
}
/// <summary>
/// Check whether this activation is overloaded.
/// Returns LimitExceededException if overloaded, otherwise <c>null</c>c>
/// </summary>
/// <param name="log">Logger to use for reporting any overflow condition</param>
/// <returns>Returns LimitExceededException if overloaded, otherwise <c>null</c>c></returns>
public LimitExceededException CheckOverloaded(ILogger log)
{
string limitName = LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS;
int maxRequestsHardLimit = this.messagingOptions.MaxEnqueuedRequestsHardLimit;
int maxRequestsSoftLimit = this.messagingOptions.MaxEnqueuedRequestsSoftLimit;
if (IsStatelessWorker)
{
limitName = LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER;
maxRequestsHardLimit = this.messagingOptions.MaxEnqueuedRequestsHardLimit_StatelessWorker;
maxRequestsSoftLimit = this.messagingOptions.MaxEnqueuedRequestsSoftLimit_StatelessWorker;
}
if (maxRequestsHardLimit <= 0 && maxRequestsSoftLimit <= 0) return null; // No limits are set
int count = GetRequestCount();
if (maxRequestsHardLimit > 0 && count > maxRequestsHardLimit) // Hard limit
{
log.Warn(ErrorCode.Catalog_Reject_ActivationTooManyRequests,
String.Format("Overload - {0} enqueued requests for activation {1}, exceeding hard limit rejection threshold of {2}",
count, this, maxRequestsHardLimit));
return new LimitExceededException(limitName, count, maxRequestsHardLimit, this.ToString());
}
if (maxRequestsSoftLimit > 0 && count > maxRequestsSoftLimit) // Soft limit
{
log.Warn(ErrorCode.Catalog_Warn_ActivationTooManyRequests,
String.Format("Hot - {0} enqueued requests for activation {1}, exceeding soft limit warning threshold of {2}",
count, this, maxRequestsSoftLimit));
return null;
}
return null;
}
internal int GetRequestCount()
{
lock (this)
{
long numInDispatcher = EnqueuedOnDispatcherCount;
long numActive = InFlightCount;
long numWaiting = WaitingCount;
return (int)(numInDispatcher + numActive + numWaiting);
}
}
public Message PeekNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0) return waiting[0];
return null;
}
public void DequeueNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0)
waiting.RemoveAt(0);
}
internal List<Message> DequeueAllWaitingMessages()
{
lock (this)
{
if (waiting == null) return null;
List<Message> tmp = waiting;
waiting = null;
return tmp;
}
}
public bool IsInactive
{
get
{
return !IsCurrentlyExecuting && (waiting == null || waiting.Count == 0);
}
}
public bool IsCurrentlyExecuting
{
get
{
return numRunning > 0 ;
}
}
/// <summary>
/// Returns how long this activation has been idle.
/// </summary>
public TimeSpan GetIdleness(DateTime now)
{
if (now == default(DateTime))
throw new ArgumentException("default(DateTime) is not allowed; Use DateTime.UtcNow instead.", "now");
return now - becameIdle;
}
/// <summary>
/// Returns whether this activation has been idle long enough to be collected.
/// </summary>
public bool IsStale(DateTime now)
{
return GetIdleness(now) >= CollectionAgeLimit;
}
private DateTime keepAliveUntil;
public bool ShouldBeKeptAlive { get { return keepAliveUntil >= DateTime.UtcNow; } }
public void DelayDeactivation(TimeSpan timespan)
{
if (timespan <= TimeSpan.Zero)
{
// reset any current keepAliveUntill
ResetKeepAliveRequest();
}
else if (timespan == TimeSpan.MaxValue)
{
// otherwise creates negative time.
keepAliveUntil = DateTime.MaxValue;
}
else
{
keepAliveUntil = DateTime.UtcNow + timespan;
}
}
public void ResetKeepAliveRequest()
{
keepAliveUntil = DateTime.MinValue;
}
public List<Action> OnInactive { get; set; } // ActivationData
public void AddOnInactive(Action action) // ActivationData
{
lock (this)
{
if (OnInactive == null)
{
OnInactive = new List<Action>();
}
OnInactive.Add(action);
}
}
public void RunOnInactive()
{
lock (this)
{
if (OnInactive == null) return;
var actions = OnInactive;
OnInactive = null;
foreach (var action in actions)
{
action();
}
}
}
internal void AddTimer(IGrainTimer timer)
{
lock(this)
{
if (timers == null)
{
timers = new HashSet<IGrainTimer>();
}
timers.Add(timer);
}
}
private void StopAllTimers()
{
lock (this)
{
if (timers == null) return;
foreach (var timer in timers)
{
timer.Stop();
}
}
}
public void OnTimerDisposed(IGrainTimer orleansTimerInsideGrain)
{
lock (this) // need to lock since dispose can be called on finalizer thread, outside garin context (not single threaded).
{
timers.Remove(orleansTimerInsideGrain);
}
}
internal Task WaitForAllTimersToFinish()
{
lock(this)
{
if (timers == null)
{
return Task.CompletedTask;
}
var tasks = new List<Task>();
var timerCopy = timers.ToList(); // need to copy since OnTimerDisposed will change the timers set.
foreach (var timer in timerCopy)
{
// first call dispose, then wait to finish.
Utils.SafeExecute(timer.Dispose, logger, "timer.Dispose has thrown");
tasks.Add(timer.GetCurrentlyExecutingTickTask());
}
return Task.WhenAll(tasks);
}
}
public string DumpStatus()
{
var sb = new StringBuilder();
lock (this)
{
sb.AppendFormat(" {0}", ToDetailedString());
if (Running != null)
{
sb.AppendFormat(" Processing message: {0}", Running);
}
if (waiting!=null && waiting.Count > 0)
{
sb.AppendFormat(" Messages queued within ActivationData: {0}", PrintWaitingQueue());
}
}
return sb.ToString();
}
public override string ToString()
{
return String.Format("[Activation: {0}{1}{2}{3} State={4}]",
Silo,
Grain,
ActivationId,
GetActivationInfoString(),
State);
}
internal string ToDetailedString(bool includeExtraDetails = false)
{
return
String.Format(
"[Activation: {0}{1}{2}{3} State={4} NonReentrancyQueueSize={5} EnqueuedOnDispatcher={6} InFlightCount={7} NumRunning={8} IdlenessTimeSpan={9} CollectionAgeLimit={10}{11}]",
Silo.ToLongString(),
Grain.ToDetailedString(),
ActivationId,
GetActivationInfoString(),
State, // 4
WaitingCount, // 5 NonReentrancyQueueSize
EnqueuedOnDispatcherCount, // 6 EnqueuedOnDispatcher
InFlightCount, // 7 InFlightCount
numRunning, // 8 NumRunning
GetIdleness(DateTime.UtcNow), // 9 IdlenessTimeSpan
CollectionAgeLimit, // 10 CollectionAgeLimit
(includeExtraDetails && Running != null) ? " CurrentlyExecuting=" + Running : ""); // 11: Running
}
public string Name
{
get
{
return String.Format("[Activation: {0}{1}{2}{3}]",
Silo,
Grain,
ActivationId,
GetActivationInfoString());
}
}
/// <summary>
/// Return string containing dump of the queue of waiting work items
/// </summary>
/// <returns></returns>
/// <remarks>Note: Caller must be holding lock on this activation while calling this method.</remarks>
internal string PrintWaitingQueue()
{
return Utils.EnumerableToString(waiting);
}
private string GetActivationInfoString()
{
var placement = PlacedUsing != null ? PlacedUsing.GetType().Name : String.Empty;
return GrainInstanceType == null ? placement :
String.Format(" #GrainType={0} Placement={1}", GrainInstanceType.FullName, placement);
}
public void Dispose()
{
IDisposable disposable = serviceScope;
if (disposable != null) disposable.Dispose();
this.serviceScope = null;
}
}
internal static class StreamResourceTestControl
{
internal static bool TestOnlySuppressStreamCleanupOnDeactivate;
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// Specialized producer/consumer queues.
//
//
// ************<IMPORTANT NOTE>*************
//
// src\ndp\clr\src\bcl\system\threading\tasks\producerConsumerQueue.cs
// src\ndp\fx\src\dataflow\system\threading\tasks\dataflow\internal\producerConsumerQueue.cs
// Keep both of them consistent by changing the other file when you change this one, also avoid:
// 1- To reference interneal types in mscorlib
// 2- To reference any dataflow specific types
// This should be fixed post Dev11 when this class becomes public.
//
// ************</IMPORTANT NOTE>*************
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
namespace System.Threading.Tasks
{
/// <summary>Represents a producer/consumer queue used internally by dataflow blocks.</summary>
/// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam>
internal interface IProducerConsumerQueue<T> : IEnumerable<T>
{
/// <summary>Enqueues an item into the queue.</summary>
/// <param name="item">The item to enqueue.</param>
/// <remarks>This method is meant to be thread-safe subject to the particular nature of the implementation.</remarks>
void Enqueue(T item);
/// <summary>Attempts to dequeue an item from the queue.</summary>
/// <param name="result">The dequeued item.</param>
/// <returns>true if an item could be dequeued; otherwise, false.</returns>
/// <remarks>This method is meant to be thread-safe subject to the particular nature of the implementation.</remarks>
bool TryDequeue(out T result);
/// <summary>Gets whether the collection is currently empty.</summary>
/// <remarks>This method may or may not be thread-safe.</remarks>
bool IsEmpty { get; }
/// <summary>Gets the number of items in the collection.</summary>
/// <remarks>In many implementations, this method will not be thread-safe.</remarks>
int Count { get; }
/// <summary>A thread-safe way to get the number of items in the collection. May synchronize access by locking the provided synchronization object.</summary>
/// <param name="syncObj">The sync object used to lock</param>
/// <returns>The collection count</returns>
int GetCountSafe(object syncObj);
}
/// <summary>
/// Provides a producer/consumer queue safe to be used by any number of producers and consumers concurrently.
/// </summary>
/// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam>
[DebuggerDisplay("Count = {Count}")]
internal sealed class MultiProducerMultiConsumerQueue<T> : ConcurrentQueue<T>, IProducerConsumerQueue<T>
{
/// <summary>Enqueues an item into the queue.</summary>
/// <param name="item">The item to enqueue.</param>
void IProducerConsumerQueue<T>.Enqueue(T item) { base.Enqueue(item); }
/// <summary>Attempts to dequeue an item from the queue.</summary>
/// <param name="result">The dequeued item.</param>
/// <returns>true if an item could be dequeued; otherwise, false.</returns>
bool IProducerConsumerQueue<T>.TryDequeue(out T result) { return base.TryDequeue(out result); }
/// <summary>Gets whether the collection is currently empty.</summary>
bool IProducerConsumerQueue<T>.IsEmpty { get { return base.IsEmpty; } }
/// <summary>Gets the number of items in the collection.</summary>
int IProducerConsumerQueue<T>.Count { get { return base.Count; } }
/// <summary>A thread-safe way to get the number of items in the collection. May synchronize access by locking the provided synchronization object.</summary>
/// <remarks>ConcurrentQueue.Count is thread safe, no need to acquire the lock.</remarks>
int IProducerConsumerQueue<T>.GetCountSafe(object syncObj) { return base.Count; }
}
/// <summary>
/// Provides a producer/consumer queue safe to be used by only one producer and one consumer concurrently.
/// </summary>
/// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(SingleProducerSingleConsumerQueue<>.SingleProducerSingleConsumerQueue_DebugView))]
internal sealed class SingleProducerSingleConsumerQueue<T> : IProducerConsumerQueue<T>
{
// Design:
//
// SingleProducerSingleConsumerQueue (SPSCQueue) is a concurrent queue designed to be used
// by one producer thread and one consumer thread. SPSCQueue does not work correctly when used by
// multiple producer threads concurrently or multiple consumer threads concurrently.
//
// SPSCQueue is based on segments that behave like circular buffers. Each circular buffer is represented
// as an array with two indexes: m_first and m_last. m_first is the index of the array slot for the consumer
// to read next, and m_last is the slot for the producer to write next. The circular buffer is empty when
// (m_first == m_last), and full when ((m_last+1) % m_array.Length == m_first).
//
// Since m_first is only ever modified by the consumer thread and m_last by the producer, the two indices can
// be updated without interlocked operations. As long as the queue size fits inside a single circular buffer,
// enqueues and dequeues simply advance the corresponding indices around the circular buffer. If an enqueue finds
// that there is no room in the existing buffer, however, a new circular buffer is allocated that is twice as big
// as the old buffer. From then on, the producer will insert values into the new buffer. The consumer will first
// empty out the old buffer and only then follow the producer into the new (larger) buffer.
//
// As described above, the enqueue operation on the fast path only modifies the m_first field of the current segment.
// However, it also needs to read m_last in order to verify that there is room in the current segment. Similarly, the
// dequeue operation on the fast path only needs to modify m_last, but also needs to read m_first to verify that the
// queue is non-empty. This results in true cache line sharing between the producer and the consumer.
//
// The cache line sharing issue can be mitigating by having a possibly stale copy of m_first that is owned by the producer,
// and a possibly stale copy of m_last that is owned by the consumer. So, the consumer state is described using
// (m_first, m_lastCopy) and the producer state using (m_firstCopy, m_last). The consumer state is separated from
// the producer state by padding, which allows fast-path enqueues and dequeues from hitting shared cache lines.
// m_lastCopy is the consumer's copy of m_last. Whenever the consumer can tell that there is room in the buffer
// simply by observing m_lastCopy, the consumer thread does not need to read m_last and thus encounter a cache miss. Only
// when the buffer appears to be empty will the consumer refresh m_lastCopy from m_last. m_firstCopy is used by the producer
// in the same way to avoid reading m_first on the hot path.
/// <summary>The initial size to use for segments (in number of elements).</summary>
private const int INIT_SEGMENT_SIZE = 32; // must be a power of 2
/// <summary>The maximum size to use for segments (in number of elements).</summary>
private const int MAX_SEGMENT_SIZE = 0x1000000; // this could be made as large as Int32.MaxValue / 2
/// <summary>The head of the linked list of segments.</summary>
private volatile Segment m_head;
/// <summary>The tail of the linked list of segments.</summary>
private volatile Segment m_tail;
/// <summary>Initializes the queue.</summary>
internal SingleProducerSingleConsumerQueue()
{
// Validate constants in ctor rather than in an explicit cctor that would cause perf degradation
Contract.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0.");
Contract.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2");
Contract.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum.");
Contract.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur.");
// Initialize the queue
m_head = m_tail = new Segment(INIT_SEGMENT_SIZE);
}
/// <summary>Enqueues an item into the queue.</summary>
/// <param name="item">The item to enqueue.</param>
public void Enqueue(T item)
{
Segment segment = m_tail;
var array = segment.m_array;
int last = segment.m_state.m_last; // local copy to avoid multiple volatile reads
// Fast path: there's obviously room in the current segment
int tail2 = (last + 1) & (array.Length - 1);
if (tail2 != segment.m_state.m_firstCopy)
{
array[last] = item;
segment.m_state.m_last = tail2;
}
// Slow path: there may not be room in the current segment.
else EnqueueSlow(item, ref segment);
}
/// <summary>Enqueues an item into the queue.</summary>
/// <param name="item">The item to enqueue.</param>
/// <param name="segment">The segment in which to first attempt to store the item.</param>
private void EnqueueSlow(T item, ref Segment segment)
{
Contract.Requires(segment != null, "Expected a non-null segment.");
if (segment.m_state.m_firstCopy != segment.m_state.m_first)
{
segment.m_state.m_firstCopy = segment.m_state.m_first;
Enqueue(item); // will only recur once for this enqueue operation
return;
}
int newSegmentSize = m_tail.m_array.Length << 1; // double size
Contract.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow.");
if (newSegmentSize > MAX_SEGMENT_SIZE) newSegmentSize = MAX_SEGMENT_SIZE;
var newSegment = new Segment(newSegmentSize);
newSegment.m_array[0] = item;
newSegment.m_state.m_last = 1;
newSegment.m_state.m_lastCopy = 1;
try { } finally
{
// Finally block to protect against corruption due to a thread abort
// between setting m_next and setting m_tail.
Volatile.Write(ref m_tail.m_next, newSegment); // ensure segment not published until item is fully stored
m_tail = newSegment;
}
}
/// <summary>Attempts to dequeue an item from the queue.</summary>
/// <param name="result">The dequeued item.</param>
/// <returns>true if an item could be dequeued; otherwise, false.</returns>
public bool TryDequeue(out T result)
{
Segment segment = m_head;
var array = segment.m_array;
int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads
// Fast path: there's obviously data available in the current segment
if (first != segment.m_state.m_lastCopy)
{
result = array[first];
array[first] = default(T); // Clear the slot to release the element
segment.m_state.m_first = (first + 1) & (array.Length - 1);
return true;
}
// Slow path: there may not be data available in the current segment
else return TryDequeueSlow(ref segment, ref array, out result);
}
/// <summary>Attempts to dequeue an item from the queue.</summary>
/// <param name="array">The array from which the item was dequeued.</param>
/// <param name="segment">The segment from which the item was dequeued.</param>
/// <param name="result">The dequeued item.</param>
/// <returns>true if an item could be dequeued; otherwise, false.</returns>
private bool TryDequeueSlow(ref Segment segment, ref T[] array, out T result)
{
Contract.Requires(segment != null, "Expected a non-null segment.");
Contract.Requires(array != null, "Expected a non-null item array.");
if (segment.m_state.m_last != segment.m_state.m_lastCopy)
{
segment.m_state.m_lastCopy = segment.m_state.m_last;
return TryDequeue(out result); // will only recur once for this dequeue operation
}
if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last)
{
segment = segment.m_next;
array = segment.m_array;
m_head = segment;
}
var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads
if (first == segment.m_state.m_last)
{
result = default(T);
return false;
}
result = array[first];
array[first] = default(T); // Clear the slot to release the element
segment.m_state.m_first = (first + 1) & (segment.m_array.Length - 1);
segment.m_state.m_lastCopy = segment.m_state.m_last; // Refresh m_lastCopy to ensure that m_first has not passed m_lastCopy
return true;
}
/// <summary>Attempts to peek at an item in the queue.</summary>
/// <param name="result">The peeked item.</param>
/// <returns>true if an item could be peeked; otherwise, false.</returns>
public bool TryPeek(out T result)
{
Segment segment = m_head;
var array = segment.m_array;
int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads
// Fast path: there's obviously data available in the current segment
if (first != segment.m_state.m_lastCopy)
{
result = array[first];
return true;
}
// Slow path: there may not be data available in the current segment
else return TryPeekSlow(ref segment, ref array, out result);
}
/// <summary>Attempts to peek at an item in the queue.</summary>
/// <param name="array">The array from which the item is peeked.</param>
/// <param name="segment">The segment from which the item is peeked.</param>
/// <param name="result">The peeked item.</param>
/// <returns>true if an item could be peeked; otherwise, false.</returns>
private bool TryPeekSlow(ref Segment segment, ref T[] array, out T result)
{
Contract.Requires(segment != null, "Expected a non-null segment.");
Contract.Requires(array != null, "Expected a non-null item array.");
if (segment.m_state.m_last != segment.m_state.m_lastCopy)
{
segment.m_state.m_lastCopy = segment.m_state.m_last;
return TryPeek(out result); // will only recur once for this peek operation
}
if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last)
{
segment = segment.m_next;
array = segment.m_array;
m_head = segment;
}
var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads
if (first == segment.m_state.m_last)
{
result = default(T);
return false;
}
result = array[first];
return true;
}
/// <summary>Attempts to dequeue an item from the queue.</summary>
/// <param name="predicate">The predicate that must return true for the item to be dequeued. If null, all items implicitly return true.</param>
/// <param name="result">The dequeued item.</param>
/// <returns>true if an item could be dequeued; otherwise, false.</returns>
public bool TryDequeueIf(Predicate<T> predicate, out T result)
{
Segment segment = m_head;
var array = segment.m_array;
int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads
// Fast path: there's obviously data available in the current segment
if (first != segment.m_state.m_lastCopy)
{
result = array[first];
if (predicate == null || predicate(result))
{
array[first] = default(T); // Clear the slot to release the element
segment.m_state.m_first = (first + 1) & (array.Length - 1);
return true;
}
else
{
result = default(T);
return false;
}
}
// Slow path: there may not be data available in the current segment
else return TryDequeueIfSlow(predicate, ref segment, ref array, out result);
}
/// <summary>Attempts to dequeue an item from the queue.</summary>
/// <param name="predicate">The predicate that must return true for the item to be dequeued. If null, all items implicitly return true.</param>
/// <param name="array">The array from which the item was dequeued.</param>
/// <param name="segment">The segment from which the item was dequeued.</param>
/// <param name="result">The dequeued item.</param>
/// <returns>true if an item could be dequeued; otherwise, false.</returns>
private bool TryDequeueIfSlow(Predicate<T> predicate, ref Segment segment, ref T[] array, out T result)
{
Contract.Requires(segment != null, "Expected a non-null segment.");
Contract.Requires(array != null, "Expected a non-null item array.");
if (segment.m_state.m_last != segment.m_state.m_lastCopy)
{
segment.m_state.m_lastCopy = segment.m_state.m_last;
return TryDequeueIf(predicate, out result); // will only recur once for this dequeue operation
}
if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last)
{
segment = segment.m_next;
array = segment.m_array;
m_head = segment;
}
var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads
if (first == segment.m_state.m_last)
{
result = default(T);
return false;
}
result = array[first];
if (predicate == null || predicate(result))
{
array[first] = default(T); // Clear the slot to release the element
segment.m_state.m_first = (first + 1) & (segment.m_array.Length - 1);
segment.m_state.m_lastCopy = segment.m_state.m_last; // Refresh m_lastCopy to ensure that m_first has not passed m_lastCopy
return true;
}
else
{
result = default(T);
return false;
}
}
public void Clear()
{
T ignored;
while (TryDequeue(out ignored)) ;
}
/// <summary>Gets whether the collection is currently empty.</summary>
/// <remarks>WARNING: This should not be used concurrently without further vetting.</remarks>
public bool IsEmpty
{
// This implementation is optimized for calls from the consumer.
get
{
var head = m_head;
if (head.m_state.m_first != head.m_state.m_lastCopy) return false; // m_first is volatile, so the read of m_lastCopy cannot get reordered
if (head.m_state.m_first != head.m_state.m_last) return false;
return head.m_next == null;
}
}
/// <summary>Gets an enumerable for the collection.</summary>
/// <remarks>WARNING: This should only be used for debugging purposes. It is not safe to be used concurrently.</remarks>
public IEnumerator<T> GetEnumerator()
{
for (Segment segment = m_head; segment != null; segment = segment.m_next)
{
for (int pt = segment.m_state.m_first;
pt != segment.m_state.m_last;
pt = (pt + 1) & (segment.m_array.Length - 1))
{
yield return segment.m_array[pt];
}
}
}
/// <summary>Gets an enumerable for the collection.</summary>
/// <remarks>WARNING: This should only be used for debugging purposes. It is not safe to be used concurrently.</remarks>
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
/// <summary>Gets the number of items in the collection.</summary>
/// <remarks>WARNING: This should only be used for debugging purposes. It is not meant to be used concurrently.</remarks>
public int Count
{
get
{
int count = 0;
for (Segment segment = m_head; segment != null; segment = segment.m_next)
{
int arraySize = segment.m_array.Length;
int first, last;
while (true) // Count is not meant to be used concurrently, but this helps to avoid issues if it is
{
first = segment.m_state.m_first;
last = segment.m_state.m_last;
if (first == segment.m_state.m_first) break;
}
count += (last - first) & (arraySize - 1);
}
return count;
}
}
/// <summary>A thread-safe way to get the number of items in the collection. May synchronize access by locking the provided synchronization object.</summary>
/// <remarks>The Count is not thread safe, so we need to acquire the lock.</remarks>
int IProducerConsumerQueue<T>.GetCountSafe(object syncObj)
{
Contract.Assert(syncObj != null, "The syncObj parameter is null.");
lock (syncObj)
{
return Count;
}
}
/// <summary>A segment in the queue containing one or more items.</summary>
[StructLayout(LayoutKind.Sequential)]
private sealed class Segment
{
/// <summary>The next segment in the linked list of segments.</summary>
internal Segment m_next;
/// <summary>The data stored in this segment.</summary>
internal readonly T[] m_array;
/// <summary>Details about the segment.</summary>
internal SegmentState m_state; // separated out to enable StructLayout attribute to take effect
/// <summary>Initializes the segment.</summary>
/// <param name="size">The size to use for this segment.</param>
internal Segment(int size)
{
Contract.Requires((size & (size - 1)) == 0, "Size must be a power of 2");
m_array = new T[size];
}
}
/// <summary>Stores information about a segment.</summary>
[StructLayout(LayoutKind.Sequential)] // enforce layout so that padding reduces false sharing
private struct SegmentState
{
/// <summary>Padding to reduce false sharing between the segment's array and m_first.</summary>
internal PaddingFor32 m_pad0;
/// <summary>The index of the current head in the segment.</summary>
internal volatile int m_first;
/// <summary>A copy of the current tail index.</summary>
internal int m_lastCopy; // not volatile as read and written by the producer, except for IsEmpty, and there m_lastCopy is only read after reading the volatile m_first
/// <summary>Padding to reduce false sharing between the first and last.</summary>
internal PaddingFor32 m_pad1;
/// <summary>A copy of the current head index.</summary>
internal int m_firstCopy; // not voliatle as only read and written by the consumer thread
/// <summary>The index of the current tail in the segment.</summary>
internal volatile int m_last;
/// <summary>Padding to reduce false sharing with the last and what's after the segment.</summary>
internal PaddingFor32 m_pad2;
}
/// <summary>Debugger type proxy for a SingleProducerSingleConsumerQueue of T.</summary>
private sealed class SingleProducerSingleConsumerQueue_DebugView
{
/// <summary>The queue being visualized.</summary>
private readonly SingleProducerSingleConsumerQueue<T> m_queue;
/// <summary>Initializes the debug view.</summary>
/// <param name="enumerable">The queue being debugged.</param>
public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue<T> queue)
{
Contract.Requires(queue != null, "Expected a non-null queue.");
m_queue = queue;
}
/// <summary>Gets the contents of the list.</summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] Items
{
get
{
List<T> list = new List<T>();
foreach (T item in m_queue)
list.Add(item);
return list.ToArray();
}
}
}
}
/// <summary>A placeholder class for common padding constants and eventually routines.</summary>
static class PaddingHelpers
{
/// <summary>A size greater than or equal to the size of the most common CPU cache lines.</summary>
internal const int CACHE_LINE_SIZE = 128;
}
/// <summary>Padding structure used to minimize false sharing in SingleProducerSingleConsumerQueue{T}.</summary>
[StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(Int32))] // Based on common case of 64-byte cache lines
struct PaddingFor32
{
}
}
| |
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.ConsumePipeSpecifications
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Configuration;
using ConsumeConfigurators;
using Context;
using GreenPipes;
using GreenPipes.Builders;
using GreenPipes.Filters;
using Metadata;
using Observables;
using Pipeline;
using Pipeline.Pipes;
using Saga;
using Saga.SubscriptionConfigurators;
public class ConsumePipeSpecification :
IConsumePipeConfigurator,
IConsumePipeSpecification
{
readonly ConsumerConfigurationObservable _consumerObservers;
readonly object _lock = new object();
readonly ConcurrentDictionary<Type, IMessageConsumePipeSpecification> _messageSpecifications;
readonly ConsumePipeSpecificationObservable _observers;
readonly SagaConfigurationObservable _sagaObservers;
readonly IList<IPipeSpecification<ConsumeContext>> _specifications;
readonly IList<IPipeSpecification<ConsumeContext>> _consumeContextSpecifications;
public ConsumePipeSpecification()
{
_specifications = new List<IPipeSpecification<ConsumeContext>>();
_consumeContextSpecifications = new List<IPipeSpecification<ConsumeContext>>();
_messageSpecifications = new ConcurrentDictionary<Type, IMessageConsumePipeSpecification>();
_observers = new ConsumePipeSpecificationObservable();
_consumerObservers = new ConsumerConfigurationObservable();
_sagaObservers = new SagaConfigurationObservable();
}
public void AddPipeSpecification(IPipeSpecification<ConsumeContext> specification)
{
lock (_lock)
{
_specifications.Add(specification);
foreach (var messageSpecification in _messageSpecifications.Values)
{
messageSpecification.AddPipeSpecification(specification);
}
}
}
public ConnectHandle ConnectConsumerConfigurationObserver(IConsumerConfigurationObserver observer)
{
return _consumerObservers.Connect(observer);
}
public ConnectHandle ConnectSagaConfigurationObserver(ISagaConfigurationObserver observer)
{
return _sagaObservers.Connect(observer);
}
public void AddPipeSpecification<T>(IPipeSpecification<ConsumeContext<T>> specification)
where T : class
{
IMessageConsumePipeSpecification<T> messageSpecification = GetMessageSpecification<T>();
messageSpecification.AddPipeSpecification(specification);
}
public void AddPrePipeSpecification(IPipeSpecification<ConsumeContext> specification)
{
_consumeContextSpecifications.Add(specification);
}
public void ConsumerConfigured<TConsumer>(IConsumerConfigurator<TConsumer> configurator)
where TConsumer : class
{
_consumerObservers.ConsumerConfigured(configurator);
}
public void ConsumerMessageConfigured<TConsumer, TMessage>(IConsumerMessageConfigurator<TConsumer, TMessage> configurator)
where TConsumer : class
where TMessage : class
{
_consumerObservers.ConsumerMessageConfigured(configurator);
}
public void SagaConfigured<TSaga>(ISagaConfigurator<TSaga> configurator) where TSaga : class, ISaga
{
_sagaObservers.SagaConfigured(configurator);
}
public void SagaMessageConfigured<TSaga, TMessage>(ISagaMessageConfigurator<TSaga, TMessage> configurator)
where TSaga : class, ISaga
where TMessage : class
{
_sagaObservers.SagaMessageConfigured(configurator);
}
public IEnumerable<ValidationResult> Validate()
{
return _specifications.SelectMany(x => x.Validate())
.Concat(_messageSpecifications.Values.SelectMany(x => x.Validate()));
}
public IMessageConsumePipeSpecification<T> GetMessageSpecification<T>()
where T : class
{
var specification = _messageSpecifications.GetOrAdd(typeof(T), CreateMessageSpecification<T>);
return specification.GetMessageSpecification<T>();
}
public ConnectHandle Connect(IConsumePipeSpecificationObserver observer)
{
return _observers.Connect(observer);
}
public IConsumePipe BuildConsumePipe()
{
var filter = new DynamicFilter<ConsumeContext, Guid>(new ConsumeContextConverterFactory(), GetRequestId);
foreach (var specification in _messageSpecifications.Values)
{
specification.Connect(filter);
}
var builder = new PipeBuilder<ConsumeContext>();
foreach (var specification in _consumeContextSpecifications)
{
specification.Apply(builder);
}
builder.AddFilter(filter);
return new ConsumePipe(filter, builder.Build());
}
static Guid GetRequestId(ConsumeContext context)
{
return context.RequestId ?? Guid.Empty;
}
IMessageConsumePipeSpecification CreateMessageSpecification<T>(Type type)
where T : class
{
var specification = new MessageConsumePipeSpecification<T>();
foreach (var pipeSpecification in _specifications)
{
specification.AddPipeSpecification(pipeSpecification);
}
_observers.MessageSpecificationCreated(specification);
var connector = new ImplementedMessageTypeConnector<T>(this, specification);
ImplementedMessageTypeCache<T>.EnumerateImplementedTypes(connector);
return specification;
}
class ImplementedMessageTypeConnector<TMessage> :
IImplementedMessageType
where TMessage : class
{
readonly MessageConsumePipeSpecification<TMessage> _messageSpecification;
readonly IConsumePipeSpecification _specification;
public ImplementedMessageTypeConnector(IConsumePipeSpecification specification, MessageConsumePipeSpecification<TMessage> messageSpecification)
{
_specification = specification;
_messageSpecification = messageSpecification;
}
public void ImplementsMessageType<T>(bool direct)
where T : class
{
IMessageConsumePipeSpecification<T> implementedTypeSpecification = _specification.GetMessageSpecification<T>();
_messageSpecification.AddImplementedMessageSpecification(implementedTypeSpecification);
}
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules
{
public class SunModule : ISunModule
{
/// <summary>
/// Note: Sun Hour can be a little deceaving. Although it's based on a 24 hour clock
/// it is not based on ~06:00 == Sun Rise. Rather it is based on 00:00 being sun-rise.
/// </summary>
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//
// Global Constants used to determine where in the sky the sun is
//
private const double m_SeasonalTilt = 0.03 * Math.PI; // A daily shift of approximately 1.7188 degrees
private const double m_AverageTilt = -0.25 * Math.PI; // A 45 degree tilt
private const double m_SunCycle = 2.0D * Math.PI; // A perfect circle measured in radians
private const double m_SeasonalCycle = 2.0D * Math.PI; // Ditto
//
// Per Region Values
//
private bool ready = false;
// This solves a chick before the egg problem
// the local SunFixedHour and SunFixed variables MUST be updated
// at least once with the proper Region Settings before we start
// updating those region settings in GenSunPos()
private bool receivedEstateToolsSunUpdate = false;
// Configurable values
private string m_RegionMode = "SL";
// Sun's position information is updated and sent to clients every m_UpdateInterval frames
private int m_UpdateInterval = 0;
// Number of real time hours per virtual day
private double m_DayLengthHours = 0;
// Number of virtual days to a virtual year
private int m_YearLengthDays = 0;
// Ratio of Daylight hours to Night time hours. This is accomplished by shifting the
// sun's orbit above the horizon
private double m_HorizonShift = 0;
// Used to scale current and positional time to adjust length of an hour during day vs night.
private double m_DayTimeSunHourScale;
// private double m_longitude = 0;
// private double m_latitude = 0;
// Configurable defaults Defaults close to SL
private string d_mode = "SL";
private int d_frame_mod = 100; // Every 10 seconds (actually less)
private double d_day_length = 4; // A VW day is 4 RW hours long
private int d_year_length = 60; // There are 60 VW days in a VW year
private double d_day_night = 0.5; // axis offset: Default Hoizon shift to try and closely match the sun model in LL Viewer
private double d_DayTimeSunHourScale = 0.5; // Day/Night hours are equal
// private double d_longitude = -73.53;
// private double d_latitude = 41.29;
// Frame counter
private uint m_frame = 0;
// Cached Scene reference
private Scene m_scene = null;
// Calculated Once in the lifetime of a region
private long TicksToEpoch; // Elapsed time for 1/1/1970
private uint SecondsPerSunCycle; // Length of a virtual day in RW seconds
private uint SecondsPerYear; // Length of a virtual year in RW seconds
private double SunSpeed; // Rate of passage in radians/second
private double SeasonSpeed; // Rate of change for seasonal effects
// private double HoursToRadians; // Rate of change for seasonal effects
private long TicksUTCOffset = 0; // seconds offset from UTC
// Calculated every update
private float OrbitalPosition; // Orbital placement at a point in time
private double HorizonShift; // Axis offset to skew day and night
private double TotalDistanceTravelled; // Distance since beginning of time (in radians)
private double SeasonalOffset; // Seaonal variation of tilt
private float Magnitude; // Normal tilt
// private double VWTimeRatio; // VW time as a ratio of real time
// Working values
private Vector3 Position = Vector3.Zero;
private Vector3 Velocity = Vector3.Zero;
private Quaternion Tilt = new Quaternion(1.0f, 0.0f, 0.0f, 0.0f);
// Used to fix the sun in the sky so it doesn't move based on current time
private bool m_SunFixed = false;
private float m_SunFixedHour = 0f;
private const int TICKS_PER_SECOND = 10000000;
// Current time in elapsed seconds since Jan 1st 1970
private ulong CurrentTime
{
get
{
return (ulong)(((DateTime.UtcNow.Ticks) - TicksToEpoch + TicksUTCOffset) / TICKS_PER_SECOND);
}
}
// Time in seconds since UTC to use to calculate sun position.
ulong PosTime = 0;
/// <summary>
/// Calculate the sun's orbital position and its velocity.
/// </summary>
private void GenSunPos()
{
// Time in seconds since UTC to use to calculate sun position.
PosTime = CurrentTime;
if (m_SunFixed)
{
// SunFixedHour represents the "hour of day" we would like
// It's represented in 24hr time, with 0 hour being sun-rise
// Because our day length is probably not 24hrs {LL is 6} we need to do a bit of math
// Determine the current "day" from current time, so we can use "today"
// to determine Seasonal Tilt and what'not
// Integer math rounded is on purpose to drop fractional day, determines number
// of virtual days since Epoch
PosTime = CurrentTime / SecondsPerSunCycle;
// Since we want number of seconds since Epoch, multiply back up
PosTime *= SecondsPerSunCycle;
// Then offset by the current Fixed Sun Hour
// Fixed Sun Hour needs to be scaled to reflect the user configured Seconds Per Sun Cycle
PosTime += (ulong)((m_SunFixedHour / 24.0) * (ulong)SecondsPerSunCycle);
}
else
{
if (m_DayTimeSunHourScale != 0.5f)
{
ulong CurDaySeconds = CurrentTime % SecondsPerSunCycle;
double CurDayPercentage = (double)CurDaySeconds / SecondsPerSunCycle;
ulong DayLightSeconds = (ulong)(m_DayTimeSunHourScale * SecondsPerSunCycle);
ulong NightSeconds = SecondsPerSunCycle - DayLightSeconds;
PosTime = CurrentTime / SecondsPerSunCycle;
PosTime *= SecondsPerSunCycle;
if (CurDayPercentage < 0.5)
{
PosTime += (ulong)((CurDayPercentage / .5) * DayLightSeconds);
}
else
{
PosTime += DayLightSeconds;
PosTime += (ulong)(((CurDayPercentage - 0.5) / .5) * NightSeconds);
}
}
}
TotalDistanceTravelled = SunSpeed * PosTime; // distance measured in radians
OrbitalPosition = (float)(TotalDistanceTravelled % m_SunCycle); // position measured in radians
// TotalDistanceTravelled += HoursToRadians-(0.25*Math.PI)*Math.Cos(HoursToRadians)-OrbitalPosition;
// OrbitalPosition = (float) (TotalDistanceTravelled%SunCycle);
SeasonalOffset = SeasonSpeed * PosTime; // Present season determined as total radians travelled around season cycle
Tilt.W = (float)(m_AverageTilt + (m_SeasonalTilt * Math.Sin(SeasonalOffset))); // Calculate seasonal orbital N/S tilt
// m_log.Debug("[SUN] Total distance travelled = "+TotalDistanceTravelled+", present position = "+OrbitalPosition+".");
// m_log.Debug("[SUN] Total seasonal progress = "+SeasonalOffset+", present tilt = "+Tilt.W+".");
// The sun rotates about the Z axis
Position.X = (float)Math.Cos(-TotalDistanceTravelled);
Position.Y = (float)Math.Sin(-TotalDistanceTravelled);
Position.Z = 0;
// For interest we rotate it slightly about the X access.
// Celestial tilt is a value that ranges .025
Position *= Tilt;
// Finally we shift the axis so that more of the
// circle is above the horizon than below. This
// makes the nights shorter than the days.
Position = Vector3.Normalize(Position);
Position.Z = Position.Z + (float)HorizonShift;
Position = Vector3.Normalize(Position);
// m_log.Debug("[SUN] Position("+Position.X+","+Position.Y+","+Position.Z+")");
Velocity.X = 0;
Velocity.Y = 0;
Velocity.Z = (float)SunSpeed;
// Correct angular velocity to reflect the seasonal rotation
Magnitude = Position.Length();
if (m_SunFixed)
{
Velocity.X = 0;
Velocity.Y = 0;
Velocity.Z = 0;
}
else
{
Velocity = (Velocity * Tilt) * (1.0f / Magnitude);
}
// TODO: Decouple this, so we can get rid of Linden Hour info
// Update Region infor with new Sun Position and Hour
// set estate settings for region access to sun position
if (receivedEstateToolsSunUpdate)
{
m_scene.RegionInfo.RegionSettings.SunVector = Position;
m_scene.RegionInfo.RegionSettings.SunPosition = GetCurrentTimeAsLindenSunHour();
}
}
private float GetCurrentTimeAsLindenSunHour()
{
if (m_SunFixed)
{
return m_SunFixedHour + 6;
}
return GetCurrentSunHour() + 6.0f;
}
#region IRegion Methods
// Called immediately after the module is loaded for a given region
// i.e. Immediately after instance creation.
public void Initialize(Scene scene, IConfigSource config)
{
m_scene = scene;
m_frame = 0;
// This one puts an entry in the main help screen
m_scene.AddCommand(this, String.Empty, "sun", "Usage: sun [param] [value] - Get or Update Sun module paramater", null);
// This one enables the ability to type just "sun" without any parameters
m_scene.AddCommand(this, "sun", String.Empty, String.Empty, HandleSunConsoleCommand);
foreach (KeyValuePair<string, string> kvp in GetParamList())
{
m_scene.AddCommand(this, String.Format("sun {0}", kvp.Key), String.Format("{0} - {1}", kvp.Key, kvp.Value), String.Empty, HandleSunConsoleCommand);
}
// Use a fixed offset from UTC for Pacific time with no DST changes. Must be a specific unchanging offset, could be 0.
TicksUTCOffset = -288000000000; // -8 * 60 * 60 * TICKS_PER_SECOND
// Align ticks with Second Life
TicksToEpoch = new DateTime(1970, 1, 1).Ticks;
// Just in case they don't have the stanzas
try
{
IConfig sunConfig = config.Configs["Sun"];
if (sunConfig == null) {
m_log.Debug("[SUN]: Configuration access missing, using defaults.");
m_RegionMode = d_mode;
m_YearLengthDays = d_year_length;
m_DayLengthHours = d_day_length;
m_HorizonShift = d_day_night;
m_UpdateInterval = d_frame_mod;
m_DayTimeSunHourScale = d_DayTimeSunHourScale;
// m_latitude = d_latitude;
// m_longitude = d_longitude;
} else {
// Mode: determines how the sun is handled
m_RegionMode = config.Configs["Sun"].GetString("mode", d_mode);
// Mode: determines how the sun is handled
// m_latitude = config.Configs["Sun"].GetDouble("latitude", d_latitude);
// Mode: determines how the sun is handled
// m_longitude = config.Configs["Sun"].GetDouble("longitude", d_longitude);
// Year length in days
m_YearLengthDays = config.Configs["Sun"].GetInt("year_length", d_year_length);
// Day length in decimal hours
m_DayLengthHours = config.Configs["Sun"].GetDouble("day_length", d_day_length);
// Horizon shift, this is used to shift the sun's orbit, this affects the day / night ratio
// must hard code to ~.5 to match sun position in LL based viewers
m_HorizonShift = config.Configs["Sun"].GetDouble("day_night_offset", d_day_night);
// Scales the sun hours 0...12 vs 12...24, essentially makes daylight hours longer/shorter vs nighttime hours
m_DayTimeSunHourScale = config.Configs["Sun"].GetDouble("day_time_sun_hour_scale", d_DayTimeSunHourScale);
// Update frequency in frames
m_UpdateInterval = config.Configs["Sun"].GetInt("update_interval", d_frame_mod);
}
}
catch (Exception e)
{
m_log.Debug("[SUN]: Configuration access failed, using defaults. Reason: " + e.Message);
m_RegionMode = d_mode;
m_YearLengthDays = d_year_length;
m_DayLengthHours = d_day_length;
m_HorizonShift = d_day_night;
m_UpdateInterval = d_frame_mod;
m_DayTimeSunHourScale = d_DayTimeSunHourScale;
// m_latitude = d_latitude;
// m_longitude = d_longitude;
}
switch (m_RegionMode)
{
case "T1":
default:
case "SL":
// Time taken to complete a cycle (day and season)
SecondsPerSunCycle = (uint) (m_DayLengthHours * 60 * 60);
SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays);
// Ration of real-to-virtual time
// VWTimeRatio = 24/m_day_length;
// Speed of rotation needed to complete a cycle in the
// designated period (day and season)
SunSpeed = m_SunCycle/SecondsPerSunCycle;
SeasonSpeed = m_SeasonalCycle/SecondsPerYear;
// Horizon translation
HorizonShift = m_HorizonShift; // Z axis translation
// HoursToRadians = (SunCycle/24)*VWTimeRatio;
// Insert our event handling hooks
scene.EventManager.OnFrame += SunUpdate;
scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
scene.EventManager.OnEstateToolsSunUpdate += EstateToolsSunUpdate;
scene.EventManager.OnGetCurrentTimeAsLindenSunHour += GetCurrentTimeAsLindenSunHour;
ready = true;
m_log.Debug("[SUN]: Mode is " + m_RegionMode);
m_log.Debug("[SUN]: Initialization completed. Day is " + SecondsPerSunCycle + " seconds, and year is " + m_YearLengthDays + " days");
m_log.Debug("[SUN]: Axis offset is " + m_HorizonShift);
m_log.Debug("[SUN]: Percentage of time for daylight " + m_DayTimeSunHourScale);
m_log.Debug("[SUN]: Positional data updated every " + m_UpdateInterval + " frames");
break;
}
scene.RegisterModuleInterface<ISunModule>(this);
}
public void PostInitialize()
{
}
public void Close()
{
ready = false;
// Remove our hooks
m_scene.EventManager.OnFrame -= SunUpdate;
m_scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel;
m_scene.EventManager.OnEstateToolsSunUpdate -= EstateToolsSunUpdate;
m_scene.EventManager.OnGetCurrentTimeAsLindenSunHour -= GetCurrentTimeAsLindenSunHour;
}
public string Name
{
get { return "SunModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
#region EventManager Events
public void SunToClient(IClientAPI client)
{
if (m_RegionMode != "T1")
{
if (ready)
{
if (m_SunFixed)
{
// m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString());
client.SendSunPos(Position, Velocity, PosTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
}
else
{
// m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString());
client.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
}
}
}
}
public void SunUpdate()
{
if (((m_frame++ % m_UpdateInterval) != 0) || !ready || m_SunFixed || !receivedEstateToolsSunUpdate)
{
return;
}
GenSunPos(); // Generate shared values once
SunUpdateToAllClients();
}
/// <summary>
/// When an avatar enters the region, it's probably a good idea to send them the current sun info
/// </summary>
/// <param name="avatar"></param>
/// <param name="localLandID"></param>
/// <param name="regionID"></param>
private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
{
SunToClient(avatar.ControllingClient);
}
/// <summary>
///
/// </summary>
/// <param name="regionHandle"></param>
/// <param name="FixedTime">Is the sun's position fixed?</param>
/// <param name="useEstateTime">Use the Region or Estate Sun hour?</param>
/// <param name="FixedSunHour">What hour of the day is the Sun Fixed at?</param>
public void EstateToolsSunUpdate(ulong regionHandle, bool FixedSun, bool useEstateTime, float FixedSunHour)
{
if (m_scene.RegionInfo.RegionHandle == regionHandle)
{
// Must limit the Sun Hour to 0 ... 24
while (FixedSunHour > 24.0f)
FixedSunHour -= 24;
while (FixedSunHour < 0)
FixedSunHour += 24;
m_SunFixedHour = FixedSunHour;
m_SunFixed = FixedSun;
m_log.DebugFormat("[SUN]: Sun Settings Update: Fixed Sun? : {0}", m_SunFixed.ToString());
m_log.DebugFormat("[SUN]: Sun Settings Update: Sun Hour : {0}", m_SunFixedHour.ToString());
receivedEstateToolsSunUpdate = true;
// Generate shared values
GenSunPos();
// When sun settings are updated, we should update all clients with new settings.
SunUpdateToAllClients();
m_log.DebugFormat("[SUN]: PosTime : {0}", PosTime.ToString());
}
}
#endregion
private void SunUpdateToAllClients()
{
List<ScenePresence> avatars = m_scene.GetAvatars();
foreach (ScenePresence avatar in avatars)
{
if (!(avatar.IsChildAgent || avatar.IsDeleted || avatar.IsInTransit))
{
SunToClient(avatar.ControllingClient);
}
}
}
#region ISunModule Members
public double GetSunParameter(string param)
{
switch (param.ToLower())
{
case "year_length":
return m_YearLengthDays;
case "day_length":
return m_DayLengthHours;
case "day_night_offset":
return m_HorizonShift;
case "day_time_sun_hour_scale":
return m_DayTimeSunHourScale;
case "update_interval":
return m_UpdateInterval;
default:
throw new Exception("Unknown sun parameter.");
}
}
public void SetSunParameter(string param, double value)
{
HandleSunConsoleCommand("sun", new string[] {param, value.ToString() });
}
public float GetCurrentSunHour()
{
float ticksleftover = CurrentTime % SecondsPerSunCycle;
return (24.0f * (ticksleftover / SecondsPerSunCycle));
}
#endregion
public void HandleSunConsoleCommand(string module, string[] cmdparams)
{
if (m_scene.ConsoleScene() == null)
{
// FIXME: If console region is root then this will be printed by every module. Currently, there is no
// way to prevent this, short of making the entire module shared (which is complete overkill).
// One possibility is to return a bool to signal whether the module has completely handled the command
m_log.InfoFormat("[Sun]: Please change to a specific region in order to set Sun parameters.");
return;
}
if (m_scene.ConsoleScene() != m_scene)
{
m_log.InfoFormat("[Sun]: Console Scene is not my scene.");
return;
}
m_log.InfoFormat("[Sun]: Processing command.");
foreach (string output in ParseCmdParams(cmdparams))
{
m_log.Info("[SUN] " + output);
}
}
private Dictionary<string, string> GetParamList()
{
Dictionary<string, string> Params = new Dictionary<string, string>();
Params.Add("year_length", "number of days to a year");
Params.Add("day_length", "number of seconds to a day");
Params.Add("day_night_offset", "induces a horizon shift");
Params.Add("update_interval", "how often to update the sun's position in frames");
Params.Add("day_time_sun_hour_scale", "scales day light vs nite hours to change day/night ratio");
return Params;
}
private List<string> ParseCmdParams(string[] args)
{
List<string> Output = new List<string>();
if ((args.Length == 1) || (args[1].ToLower() == "help") || (args[1].ToLower() == "list"))
{
Output.Add("The following parameters can be changed or viewed:");
foreach (KeyValuePair<string, string> kvp in GetParamList())
{
Output.Add(String.Format("{0} - {1}",kvp.Key, kvp.Value));
}
return Output;
}
if (args.Length == 2)
{
try
{
double value = GetSunParameter(args[1]);
Output.Add(String.Format("Parameter {0} is {1}.", args[1], value.ToString()));
}
catch (Exception)
{
Output.Add(String.Format("Unknown parameter {0}.", args[1]));
}
}
else if (args.Length == 3)
{
float value = 0.0f;
if (!float.TryParse(args[2], out value))
{
Output.Add(String.Format("The parameter value {0} is not a valid number.", args[2]));
}
switch (args[1].ToLower())
{
case "year_length":
m_YearLengthDays = (int)value;
break;
case "day_length":
m_DayLengthHours = value;
break;
case "day_night_offset":
m_HorizonShift = value;
break;
case "day_time_sun_hour_scale":
m_DayTimeSunHourScale = value;
break;
case "update_interval":
m_UpdateInterval = (int)value;
break;
default:
Output.Add(String.Format("Unknown parameter {0}.", args[1]));
return Output;
}
Output.Add(String.Format("Parameter {0} set to {1}.", args[1], value.ToString()));
// Generate shared values
GenSunPos();
// When sun settings are updated, we should update all clients with new settings.
SunUpdateToAllClients();
}
return Output;
}
}
}
| |
// 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.Xml;
using System.Globalization;
using System.Collections.Generic;
namespace System.Runtime.Serialization
{
#if USE_REFEMIT || NET_NATIVE
public class XmlReaderDelegator
#else
internal class XmlReaderDelegator
#endif
{
protected XmlReader reader;
protected XmlDictionaryReader dictionaryReader;
protected bool isEndOfEmptyElement = false;
public XmlReaderDelegator(XmlReader reader)
{
XmlObjectSerializer.CheckNull(reader, "reader");
this.reader = reader;
this.dictionaryReader = reader as XmlDictionaryReader;
}
internal XmlReader UnderlyingReader
{
get { return reader; }
}
internal int AttributeCount
{
get { return isEndOfEmptyElement ? 0 : reader.AttributeCount; }
}
internal string GetAttribute(string name)
{
return isEndOfEmptyElement ? null : reader.GetAttribute(name);
}
internal string GetAttribute(string name, string namespaceUri)
{
return isEndOfEmptyElement ? null : reader.GetAttribute(name, namespaceUri);
}
internal string GetAttribute(int i)
{
if (isEndOfEmptyElement)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(i), SR.Format(SR.XmlElementAttributes)));
return reader.GetAttribute(i);
}
internal bool IsEmptyElement
{
get { return false; }
}
internal bool IsNamespaceURI(string ns)
{
if (dictionaryReader == null)
return ns == reader.NamespaceURI;
else
return dictionaryReader.IsNamespaceUri(ns);
}
internal bool IsLocalName(string localName)
{
if (dictionaryReader == null)
return localName == reader.LocalName;
else
return dictionaryReader.IsLocalName(localName);
}
internal bool IsNamespaceUri(XmlDictionaryString ns)
{
if (dictionaryReader == null)
return ns.Value == reader.NamespaceURI;
else
return dictionaryReader.IsNamespaceUri(ns);
}
internal bool IsLocalName(XmlDictionaryString localName)
{
if (dictionaryReader == null)
return localName.Value == reader.LocalName;
else
return dictionaryReader.IsLocalName(localName);
}
internal int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString ns)
{
if (dictionaryReader != null)
return dictionaryReader.IndexOfLocalName(localNames, ns);
if (reader.NamespaceURI == ns.Value)
{
string localName = this.LocalName;
for (int i = 0; i < localNames.Length; i++)
{
if (localName == localNames[i].Value)
{
return i;
}
}
}
return -1;
}
#if USE_REFEMIT
public bool IsStartElement()
#else
internal bool IsStartElement()
#endif
{
return !isEndOfEmptyElement && reader.IsStartElement();
}
internal bool IsStartElement(string localname, string ns)
{
return !isEndOfEmptyElement && reader.IsStartElement(localname, ns);
}
#if USE_REFEMIT
public bool IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns)
#else
internal bool IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns)
#endif
{
if (dictionaryReader == null)
return !isEndOfEmptyElement && reader.IsStartElement(localname.Value, ns.Value);
else
return !isEndOfEmptyElement && dictionaryReader.IsStartElement(localname, ns);
}
internal bool MoveToAttribute(string name)
{
return isEndOfEmptyElement ? false : reader.MoveToAttribute(name);
}
internal bool MoveToAttribute(string name, string ns)
{
return isEndOfEmptyElement ? false : reader.MoveToAttribute(name, ns);
}
internal void MoveToAttribute(int i)
{
if (isEndOfEmptyElement)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(i), SR.Format(SR.XmlElementAttributes)));
reader.MoveToAttribute(i);
}
internal bool MoveToElement()
{
return isEndOfEmptyElement ? false : reader.MoveToElement();
}
internal bool MoveToFirstAttribute()
{
return isEndOfEmptyElement ? false : reader.MoveToFirstAttribute();
}
internal bool MoveToNextAttribute()
{
return isEndOfEmptyElement ? false : reader.MoveToNextAttribute();
}
#if USE_REFEMIT
public XmlNodeType NodeType
#else
internal XmlNodeType NodeType
#endif
{
get { return isEndOfEmptyElement ? XmlNodeType.EndElement : reader.NodeType; }
}
internal bool Read()
{
//reader.MoveToFirstAttribute();
//if (NodeType == XmlNodeType.Attribute)
reader.MoveToElement();
if (!reader.IsEmptyElement)
return reader.Read();
if (isEndOfEmptyElement)
{
isEndOfEmptyElement = false;
return reader.Read();
}
isEndOfEmptyElement = true;
return true;
}
internal XmlNodeType MoveToContent()
{
if (isEndOfEmptyElement)
return XmlNodeType.EndElement;
return reader.MoveToContent();
}
internal bool ReadAttributeValue()
{
return isEndOfEmptyElement ? false : reader.ReadAttributeValue();
}
#if USE_REFEMIT
public void ReadEndElement()
#else
internal void ReadEndElement()
#endif
{
if (isEndOfEmptyElement)
Read();
else
reader.ReadEndElement();
}
private void ThrowConversionException(string value, string type)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, type))));
}
private void ThrowNotAtElement()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement")));
}
#if USE_REFEMIT
public virtual char ReadElementContentAsChar()
#else
internal virtual char ReadElementContentAsChar()
#endif
{
return ToChar(ReadElementContentAsInt());
}
private char ToChar(int value)
{
if (value < char.MinValue || value > char.MaxValue)
{
ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Char");
}
return (char)value;
}
#if USE_REFEMIT
public string ReadElementContentAsString()
#else
internal string ReadElementContentAsString()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsString();
}
internal string ReadContentAsString()
{
return isEndOfEmptyElement ? String.Empty : reader.ReadContentAsString();
}
#if USE_REFEMIT
public bool ReadElementContentAsBoolean()
#else
internal bool ReadElementContentAsBoolean()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsBoolean();
}
internal bool ReadContentAsBoolean()
{
if (isEndOfEmptyElement)
ThrowConversionException(string.Empty, "Boolean");
return reader.ReadContentAsBoolean();
}
#if USE_REFEMIT
public float ReadElementContentAsFloat()
#else
internal float ReadElementContentAsFloat()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsFloat();
}
#if USE_REFEMIT
public double ReadElementContentAsDouble()
#else
internal double ReadElementContentAsDouble()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsDouble();
}
#if USE_REFEMIT
public decimal ReadElementContentAsDecimal()
#else
internal decimal ReadElementContentAsDecimal()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsDecimal();
}
#if USE_REFEMIT
public virtual byte[] ReadElementContentAsBase64()
#else
internal virtual byte[] ReadElementContentAsBase64()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
if (dictionaryReader == null)
{
return ReadContentAsBase64(reader.ReadElementContentAsString());
}
else
{
return dictionaryReader.ReadElementContentAsBase64();
}
}
internal byte[] ReadContentAsBase64(string str)
{
if (str == null)
return null;
str = str.Trim();
if (str.Length == 0)
return Array.Empty<byte>();
try
{
return Convert.FromBase64String(str);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "byte[]", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "byte[]", exception));
}
}
#if USE_REFEMIT
public virtual DateTime ReadElementContentAsDateTime()
#else
internal virtual DateTime ReadElementContentAsDateTime()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return XmlConvert.ToDateTime(reader.ReadElementContentAsString(), XmlDateTimeSerializationMode.RoundtripKind);
}
#if USE_REFEMIT
public int ReadElementContentAsInt()
#else
internal int ReadElementContentAsInt()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsInt();
}
internal int ReadContentAsInt()
{
if (isEndOfEmptyElement)
ThrowConversionException(string.Empty, "Int32");
return reader.ReadContentAsInt();
}
#if USE_REFEMIT
public long ReadElementContentAsLong()
#else
internal long ReadElementContentAsLong()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsLong();
}
#if USE_REFEMIT
public short ReadElementContentAsShort()
#else
internal short ReadElementContentAsShort()
#endif
{
return ToShort(ReadElementContentAsInt());
}
private short ToShort(int value)
{
if (value < short.MinValue || value > short.MaxValue)
{
ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Int16");
}
return (short)value;
}
#if USE_REFEMIT
public byte ReadElementContentAsUnsignedByte()
#else
internal byte ReadElementContentAsUnsignedByte()
#endif
{
return ToByte(ReadElementContentAsInt());
}
private byte ToByte(int value)
{
if (value < byte.MinValue || value > byte.MaxValue)
{
ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Byte");
}
return (byte)value;
}
#if USE_REFEMIT
[CLSCompliant(false)]
public SByte ReadElementContentAsSignedByte()
#else
internal SByte ReadElementContentAsSignedByte()
#endif
{
return ToSByte(ReadElementContentAsInt());
}
private SByte ToSByte(int value)
{
if (value < SByte.MinValue || value > SByte.MaxValue)
{
ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "SByte");
}
return (SByte)value;
}
#if USE_REFEMIT
[CLSCompliant(false)]
public UInt32 ReadElementContentAsUnsignedInt()
#else
internal UInt32 ReadElementContentAsUnsignedInt()
#endif
{
return ToUInt32(ReadElementContentAsLong());
}
private UInt32 ToUInt32(long value)
{
if (value < UInt32.MinValue || value > UInt32.MaxValue)
{
ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "UInt32");
}
return (UInt32)value;
}
#if USE_REFEMIT
[CLSCompliant(false)]
public virtual UInt64 ReadElementContentAsUnsignedLong()
#else
internal virtual UInt64 ReadElementContentAsUnsignedLong()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
string str = reader.ReadElementContentAsString();
if (str == null || str.Length == 0)
ThrowConversionException(string.Empty, "UInt64");
return XmlConverter.ToUInt64(str);
}
#if USE_REFEMIT
[CLSCompliant(false)]
public UInt16 ReadElementContentAsUnsignedShort()
#else
internal UInt16 ReadElementContentAsUnsignedShort()
#endif
{
return ToUInt16(ReadElementContentAsInt());
}
private UInt16 ToUInt16(int value)
{
if (value < UInt16.MinValue || value > UInt16.MaxValue)
{
ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "UInt16");
}
return (UInt16)value;
}
#if USE_REFEMIT
public TimeSpan ReadElementContentAsTimeSpan()
#else
internal TimeSpan ReadElementContentAsTimeSpan()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
string str = reader.ReadElementContentAsString();
return XmlConverter.ToTimeSpan(str);
}
#if USE_REFEMIT
public Guid ReadElementContentAsGuid()
#else
internal Guid ReadElementContentAsGuid()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
string str = reader.ReadElementContentAsString();
try
{
return new Guid(str);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception));
}
}
#if USE_REFEMIT
public Uri ReadElementContentAsUri()
#else
internal Uri ReadElementContentAsUri()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
string str = ReadElementContentAsString();
try
{
return new Uri(str, UriKind.RelativeOrAbsolute);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Uri", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Uri", exception));
}
}
#if USE_REFEMIT
public XmlQualifiedName ReadElementContentAsQName()
#else
internal XmlQualifiedName ReadElementContentAsQName()
#endif
{
Read();
XmlQualifiedName obj = ReadContentAsQName();
ReadEndElement();
return obj;
}
internal virtual XmlQualifiedName ReadContentAsQName()
{
return ParseQualifiedName(ReadContentAsString());
}
private XmlQualifiedName ParseQualifiedName(string str)
{
string name, ns, prefix;
if (str == null || str.Length == 0)
name = ns = String.Empty;
else
XmlObjectSerializerReadContext.ParseQualifiedName(str, this, out name, out ns, out prefix);
return new XmlQualifiedName(name, ns);
}
private void CheckExpectedArrayLength(XmlObjectSerializerReadContext context, int arrayLength)
{
context.IncrementItemCount(arrayLength);
}
protected int GetArrayLengthQuota(XmlObjectSerializerReadContext context)
{
return Math.Min(context.RemainingItemCount, int.MaxValue);
}
private void CheckActualArrayLength(int expectedLength, int actualLength, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
if (expectedLength != actualLength)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSizeAttribute, expectedLength, itemName.Value, itemNamespace.Value)));
}
#if USE_REFEMIT
public bool TryReadBooleanArray(XmlObjectSerializerReadContext context,
#else
internal bool TryReadBooleanArray(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out bool[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new bool[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = BooleanArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
#if USE_REFEMIT
public bool TryReadDateTimeArray(XmlObjectSerializerReadContext context,
#else
internal bool TryReadDateTimeArray(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out DateTime[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new DateTime[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = DateTimeArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
#if USE_REFEMIT
public bool TryReadDecimalArray(XmlObjectSerializerReadContext context,
#else
internal bool TryReadDecimalArray(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out decimal[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new decimal[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = DecimalArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
#if USE_REFEMIT
public bool TryReadInt32Array(XmlObjectSerializerReadContext context,
#else
internal bool TryReadInt32Array(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out int[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new int[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = Int32ArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
#if USE_REFEMIT
public bool TryReadInt64Array(XmlObjectSerializerReadContext context,
#else
internal bool TryReadInt64Array(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out long[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new long[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = Int64ArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
#if USE_REFEMIT
public bool TryReadSingleArray(XmlObjectSerializerReadContext context,
#else
internal bool TryReadSingleArray(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out float[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new float[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = SingleArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
#if USE_REFEMIT
public bool TryReadDoubleArray(XmlObjectSerializerReadContext context,
#else
internal bool TryReadDoubleArray(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out double[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new double[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = DoubleArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
return (reader is IXmlNamespaceResolver) ? ((IXmlNamespaceResolver)reader).GetNamespacesInScope(scope) : null;
}
// IXmlLineInfo members
internal bool HasLineInfo()
{
IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo;
return (iXmlLineInfo == null) ? false : iXmlLineInfo.HasLineInfo();
}
internal int LineNumber
{
get
{
IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo;
return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LineNumber;
}
}
internal int LinePosition
{
get
{
IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo;
return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LinePosition;
}
}
// IXmlTextParser members
// delegating properties and methods
internal string Name { get { return reader.Name; } }
internal string LocalName { get { return reader.LocalName; } }
internal string NamespaceURI { get { return reader.NamespaceURI; } }
internal string Value { get { return reader.Value; } }
internal Type ValueType { get { return reader.ValueType; } }
internal int Depth { get { return reader.Depth; } }
internal string LookupNamespace(string prefix) { return reader.LookupNamespace(prefix); }
internal bool EOF { get { return reader.EOF; } }
internal void Skip()
{
reader.Skip();
isEndOfEmptyElement = false;
}
}
}
| |
//
// 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.Linq;
using System.Net.Http;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.OperationalInsights;
namespace Microsoft.Azure.Management.OperationalInsights
{
/// <summary>
/// .Net client wrapper for the REST API for Azure Operational Insights
/// </summary>
public partial class OperationalInsightsManagementClient : ServiceClient<OperationalInsightsManagementClient>, IOperationalInsightsManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IStorageInsightOperations _storageInsights;
/// <summary>
/// Operations for managing storage insights.
/// </summary>
public virtual IStorageInsightOperations StorageInsights
{
get { return this._storageInsights; }
}
private IWorkspaceOperations _workspaces;
/// <summary>
/// Operations for managing Operational Insights workspaces.
/// </summary>
public virtual IWorkspaceOperations Workspaces
{
get { return this._workspaces; }
}
/// <summary>
/// Initializes a new instance of the
/// OperationalInsightsManagementClient class.
/// </summary>
public OperationalInsightsManagementClient()
: base()
{
this._storageInsights = new StorageInsightOperations(this);
this._workspaces = new WorkspaceOperations(this);
this._apiVersion = "2015-03-20";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(120);
}
/// <summary>
/// Initializes a new instance of the
/// OperationalInsightsManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public OperationalInsightsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the
/// OperationalInsightsManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public OperationalInsightsManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the
/// OperationalInsightsManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public OperationalInsightsManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._storageInsights = new StorageInsightOperations(this);
this._workspaces = new WorkspaceOperations(this);
this._apiVersion = "2015-03-20";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(120);
}
/// <summary>
/// Initializes a new instance of the
/// OperationalInsightsManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public OperationalInsightsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the
/// OperationalInsightsManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public OperationalInsightsManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// OperationalInsightsManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of OperationalInsightsManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<OperationalInsightsManagementClient> client)
{
base.Clone(client);
if (client is OperationalInsightsManagementClient)
{
OperationalInsightsManagementClient clonedClient = ((OperationalInsightsManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
using static MicrosoftCodeQualityAnalyzersResources;
/// <summary>
/// CA2225: Operator overloads have named alternates
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class OperatorOverloadsHaveNamedAlternatesAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA2225";
internal const string DiagnosticKindText = "DiagnosticKind";
internal const string AddAlternateText = "AddAlternate";
internal const string FixVisibilityText = "FixVisibility";
internal const string IsTrueText = "IsTrue";
private const string OpTrueText = "op_True";
private const string OpFalseText = "op_False";
private static readonly LocalizableString s_localizableTitle = CreateLocalizableResourceString(nameof(OperatorOverloadsHaveNamedAlternatesTitle));
private static readonly LocalizableString s_localizableDescription = CreateLocalizableResourceString(nameof(OperatorOverloadsHaveNamedAlternatesDescription));
internal static readonly DiagnosticDescriptor DefaultRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(OperatorOverloadsHaveNamedAlternatesMessageDefault)),
DiagnosticCategory.Usage,
RuleLevel.Disabled,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static readonly DiagnosticDescriptor PropertyRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(OperatorOverloadsHaveNamedAlternatesMessageProperty)),
DiagnosticCategory.Usage,
RuleLevel.Disabled,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static readonly DiagnosticDescriptor MultipleRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(OperatorOverloadsHaveNamedAlternatesMessageMultiple)),
DiagnosticCategory.Usage,
RuleLevel.Disabled,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static readonly DiagnosticDescriptor VisibilityRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(OperatorOverloadsHaveNamedAlternatesMessageVisibility)),
DiagnosticCategory.Usage,
RuleLevel.Disabled,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(DefaultRule, PropertyRule, MultipleRule, VisibilityRule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.Method);
}
private static void AnalyzeSymbol(SymbolAnalysisContext symbolContext)
{
var methodSymbol = (IMethodSymbol)symbolContext.Symbol;
// FxCop compat: only analyze externally visible symbols by default.
// Note all the descriptors/rules for this analyzer have the same ID and category and hence
// will always have identical configured visibility.
if (!symbolContext.Options.MatchesConfiguredVisibility(DefaultRule, methodSymbol, symbolContext.Compilation))
{
return;
}
if (methodSymbol.ContainingSymbol is ITypeSymbol typeSymbol && (methodSymbol.MethodKind == MethodKind.UserDefinedOperator || methodSymbol.MethodKind == MethodKind.Conversion))
{
string operatorName = methodSymbol.Name;
if (IsPropertyExpected(operatorName) && operatorName != OpFalseText)
{
// don't report a diagnostic on the `op_False` method because then the user would see two diagnostics for what is really one error
// special-case looking for `IsTrue` instance property
// named properties can't be overloaded so there will only ever be 0 or 1
IPropertySymbol property = typeSymbol.GetMembers(IsTrueText).OfType<IPropertySymbol>().FirstOrDefault();
if (property == null || property.Type.SpecialType != SpecialType.System_Boolean)
{
symbolContext.ReportDiagnostic(CreateDiagnostic(PropertyRule, GetSymbolLocation(methodSymbol), AddAlternateText, IsTrueText, operatorName));
}
else if (!property.IsPublic())
{
symbolContext.ReportDiagnostic(CreateDiagnostic(VisibilityRule, GetSymbolLocation(property), FixVisibilityText, IsTrueText, operatorName));
}
}
else
{
ExpectedAlternateMethodGroup? expectedGroup = GetExpectedAlternateMethodGroup(operatorName, methodSymbol.ReturnType, methodSymbol.Parameters.FirstOrDefault()?.Type);
if (expectedGroup == null)
{
// no alternate methods required
return;
}
var matchedMethods = new List<IMethodSymbol>();
var unmatchedMethods = new HashSet<string>() { expectedGroup.AlternateMethod1 };
if (expectedGroup.AlternateMethod2 != null)
{
unmatchedMethods.Add(expectedGroup.AlternateMethod2);
}
foreach (IMethodSymbol candidateMethod in typeSymbol.GetMembers().OfType<IMethodSymbol>())
{
if (candidateMethod.Name == expectedGroup.AlternateMethod1 || candidateMethod.Name == expectedGroup.AlternateMethod2)
{
// found an appropriately-named method
matchedMethods.Add(candidateMethod);
unmatchedMethods.Remove(candidateMethod.Name);
}
}
// only one public method match is required
if (matchedMethods.Any(m => m.IsPublic()))
{
// at least one public alternate method was found, do nothing
}
else
{
// either we found at least one method that should be public or we didn't find anything
IMethodSymbol notPublicMethod = matchedMethods.FirstOrDefault(m => !m.IsPublic());
if (notPublicMethod != null)
{
// report error for improper visibility directly on the method itself
symbolContext.ReportDiagnostic(CreateDiagnostic(VisibilityRule, GetSymbolLocation(notPublicMethod), FixVisibilityText, notPublicMethod.Name, operatorName));
}
else
{
// report error for missing methods on the operator overload
if (expectedGroup.AlternateMethod2 == null)
{
// only one alternate expected
symbolContext.ReportDiagnostic(CreateDiagnostic(DefaultRule, GetSymbolLocation(methodSymbol), AddAlternateText, expectedGroup.AlternateMethod1, operatorName));
}
else
{
// one of two alternates expected
symbolContext.ReportDiagnostic(CreateDiagnostic(MultipleRule, GetSymbolLocation(methodSymbol), AddAlternateText, expectedGroup.AlternateMethod1, expectedGroup.AlternateMethod2, operatorName));
}
}
}
}
}
}
private static Location GetSymbolLocation(ISymbol symbol)
{
return symbol.OriginalDefinition.Locations.First();
}
private static Diagnostic CreateDiagnostic(DiagnosticDescriptor descriptor, Location location, string kind, params string[] messageArgs)
{
return Diagnostic.Create(descriptor, location, ImmutableDictionary.Create<string, string>().Add(DiagnosticKindText, kind), messageArgs);
}
internal static bool IsPropertyExpected(string operatorName)
{
return operatorName switch
{
OpTrueText or OpFalseText => true,
_ => false,
};
}
internal static ExpectedAlternateMethodGroup? GetExpectedAlternateMethodGroup(string operatorName, ITypeSymbol returnType, ITypeSymbol? parameterType)
{
// list of operator alternate names: https://docs.microsoft.com/visualstudio/code-quality/ca2225
// the most common case; create a static method with the already specified types
static ExpectedAlternateMethodGroup createSingle(string methodName) => new(methodName);
return operatorName switch
{
"op_Addition"
or "op_AdditonAssignment" => createSingle("Add"),
"op_BitwiseAnd"
or "op_BitwiseAndAssignment" => createSingle("BitwiseAnd"),
"op_BitwiseOr"
or "op_BitwiseOrAssignment" => createSingle("BitwiseOr"),
"op_Decrement" => createSingle("Decrement"),
"op_Division"
or "op_DivisionAssignment" => createSingle("Divide"),
"op_Equality"
or "op_Inequality" => createSingle("Equals"),
"op_ExclusiveOr"
or "op_ExclusiveOrAssignment" => createSingle("Xor"),
"op_GreaterThan"
or "op_GreaterThanOrEqual" or "op_LessThan" or "op_LessThanOrEqual" => new ExpectedAlternateMethodGroup(alternateMethod1: "CompareTo", alternateMethod2: "Compare"),
"op_Increment" => createSingle("Increment"),
"op_LeftShift"
or "op_LeftShiftAssignment" => createSingle("LeftShift"),
"op_LogicalAnd" => createSingle("LogicalAnd"),
"op_LogicalOr" => createSingle("LogicalOr"),
"op_LogicalNot" => createSingle("LogicalNot"),
"op_Modulus"
or "op_ModulusAssignment" => new ExpectedAlternateMethodGroup(alternateMethod1: "Mod", alternateMethod2: "Remainder"),
"op_MultiplicationAssignment"
or "op_Multiply" => createSingle("Multiply"),
"op_OnesComplement" => createSingle("OnesComplement"),
"op_RightShift"
or "op_RightShiftAssignment"
or "op_SignedRightShift"
or "op_UnsignedRightShift"
or "op_UnsignedRightShiftAssignment" => createSingle("RightShift"),
"op_Subtraction"
or "op_SubtractionAssignment" => createSingle("Subtract"),
"op_UnaryNegation" => createSingle("Negate"),
"op_UnaryPlus" => createSingle("Plus"),
"op_Implicit"
or "op_Explicit" => new ExpectedAlternateMethodGroup(alternateMethod1: $"To{GetTypeName(returnType)}", alternateMethod2: parameterType != null ? $"From{GetTypeName(parameterType)}" : null),
_ => null,
};
static string GetTypeName(ITypeSymbol typeSymbol)
{
if (typeSymbol.TypeKind != TypeKind.Array)
{
return typeSymbol.Name;
}
var elementType = typeSymbol;
do
{
elementType = ((IArrayTypeSymbol)elementType).ElementType;
}
while (elementType.TypeKind == TypeKind.Array);
return elementType.Name + "Array";
}
}
internal class ExpectedAlternateMethodGroup
{
public string AlternateMethod1 { get; }
public string? AlternateMethod2 { get; }
public ExpectedAlternateMethodGroup(string alternateMethod1, string? alternateMethod2 = null)
{
AlternateMethod1 = alternateMethod1;
AlternateMethod2 = alternateMethod2;
}
}
}
}
| |
using System;
using System.Text;
namespace Lucene.Net.Search
{
/*
* 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 AttributeSource = Lucene.Net.Util.AttributeSource;
using BytesRef = Lucene.Net.Util.BytesRef;
using Term = Lucene.Net.Index.Term;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
/// <summary>
/// A <see cref="Query"/> that matches documents within an range of terms.
///
/// <para/>This query matches the documents looking for terms that fall into the
/// supplied range according to
/// <see cref="byte.CompareTo(byte)"/>. It is not intended
/// for numerical ranges; use <see cref="NumericRangeQuery"/> instead.
///
/// <para/>This query uses the
/// <see cref="MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT"/>
/// rewrite method.
/// <para/>
/// @since 2.9
/// </summary>
public class TermRangeQuery : MultiTermQuery
{
private BytesRef lowerTerm;
private BytesRef upperTerm;
private bool includeLower;
private bool includeUpper;
/// <summary>
/// Constructs a query selecting all terms greater/equal than <paramref name="lowerTerm"/>
/// but less/equal than <paramref name="upperTerm"/>.
///
/// <para/>
/// If an endpoint is <c>null</c>, it is said
/// to be "open". Either or both endpoints may be open. Open endpoints may not
/// be exclusive (you can't select all but the first or last term without
/// explicitly specifying the term to exclude.)
/// </summary>
/// <param name="field"> The field that holds both lower and upper terms. </param>
/// <param name="lowerTerm">
/// The term text at the lower end of the range. </param>
/// <param name="upperTerm">
/// The term text at the upper end of the range. </param>
/// <param name="includeLower">
/// If true, the <paramref name="lowerTerm"/> is
/// included in the range. </param>
/// <param name="includeUpper">
/// If true, the <paramref name="upperTerm"/> is
/// included in the range. </param>
public TermRangeQuery(string field, BytesRef lowerTerm, BytesRef upperTerm, bool includeLower, bool includeUpper)
: base(field)
{
this.lowerTerm = lowerTerm;
this.upperTerm = upperTerm;
this.includeLower = includeLower;
this.includeUpper = includeUpper;
}
/// <summary>
/// Factory that creates a new <see cref="TermRangeQuery"/> using <see cref="string"/>s for term text.
/// </summary>
public static TermRangeQuery NewStringRange(string field, string lowerTerm, string upperTerm, bool includeLower, bool includeUpper)
{
BytesRef lower = lowerTerm == null ? null : new BytesRef(lowerTerm);
BytesRef upper = upperTerm == null ? null : new BytesRef(upperTerm);
return new TermRangeQuery(field, lower, upper, includeLower, includeUpper);
}
/// <summary>
/// Returns the lower value of this range query </summary>
public virtual BytesRef LowerTerm => lowerTerm;
/// <summary>
/// Returns the upper value of this range query </summary>
public virtual BytesRef UpperTerm => upperTerm;
/// <summary>
/// Returns <c>true</c> if the lower endpoint is inclusive </summary>
public virtual bool IncludesLower => includeLower;
/// <summary>
/// Returns <c>true</c> if the upper endpoint is inclusive </summary>
public virtual bool IncludesUpper => includeUpper;
protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
{
if (lowerTerm != null && upperTerm != null && lowerTerm.CompareTo(upperTerm) > 0)
{
return TermsEnum.EMPTY;
}
TermsEnum tenum = terms.GetEnumerator();
if ((lowerTerm == null || (includeLower && lowerTerm.Length == 0)) && upperTerm == null)
{
return tenum;
}
return new TermRangeTermsEnum(tenum, lowerTerm, upperTerm, includeLower, includeUpper);
}
/// <summary>
/// Prints a user-readable version of this query. </summary>
public override string ToString(string field)
{
StringBuilder buffer = new StringBuilder();
if (!Field.Equals(field, StringComparison.Ordinal))
{
buffer.Append(Field);
buffer.Append(":");
}
buffer.Append(includeLower ? '[' : '{');
// TODO: all these toStrings for queries should just output the bytes, it might not be UTF-8!
buffer.Append(lowerTerm != null ? ("*".Equals(Term.ToString(lowerTerm), StringComparison.Ordinal) ? "\\*" : Term.ToString(lowerTerm)) : "*");
buffer.Append(" TO ");
buffer.Append(upperTerm != null ? ("*".Equals(Term.ToString(upperTerm), StringComparison.Ordinal) ? "\\*" : Term.ToString(upperTerm)) : "*");
buffer.Append(includeUpper ? ']' : '}');
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
public override int GetHashCode()
{
const int prime = 31;
int result = base.GetHashCode();
result = prime * result + (includeLower ? 1231 : 1237);
result = prime * result + (includeUpper ? 1231 : 1237);
result = prime * result + ((lowerTerm == null) ? 0 : lowerTerm.GetHashCode());
result = prime * result + ((upperTerm == null) ? 0 : upperTerm.GetHashCode());
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (!base.Equals(obj))
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
TermRangeQuery other = (TermRangeQuery)obj;
if (includeLower != other.includeLower)
{
return false;
}
if (includeUpper != other.includeUpper)
{
return false;
}
if (lowerTerm == null)
{
if (other.lowerTerm != null)
{
return false;
}
}
else if (!lowerTerm.Equals(other.lowerTerm))
{
return false;
}
if (upperTerm == null)
{
if (other.upperTerm != null)
{
return false;
}
}
else if (!upperTerm.Equals(other.upperTerm))
{
return false;
}
return true;
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.ComponentModel;
using System.Configuration;
using System.Drawing.Design;
using System.Web.Configuration;
using System.Web.UI;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Portal.IdentityModel.Web.Handlers;
using Microsoft.Xrm.Portal.Web.Handlers;
using Microsoft.Xrm.Portal.Web.Security;
using Microsoft.Xrm.Portal.Web.Security.LiveId;
using Microsoft.Security.Application;
namespace Microsoft.Xrm.Portal.Web.UI.WebControls
{
/// <summary>
/// The LiveIdLoginStatus control displays a login link for users who are not authenticated and a logout link for users who are authenticated.
/// When anonymous, the link takes the user to Windows Live or optionally (using LoginNavigateUrl) to a specified landing page that lets the user know they're going to Windows Live.
/// When authenticated, the logout link resets the current user's identity to be an anonymous user.
/// </summary>
/// <remarks>
/// When a LoginNavigateUrl is not specified, the link takes the user directly to Windows Live.
///
/// If a landing page is desired, set the LoginNavigateUrl to be your landing page, and then place this control on your landing page with no LoginNavigateUrl.
///
/// The application ID and secret key from your Live ID site registration must be provided in the connection string the <see cref="LiveIdMembershipProvider"/> uses.
/// See the example below for the connection string syntax.
///
/// If you wish to provide a logout page URL, it must be provided in the connection string the <see cref="LiveIdMembershipProvider"/> uses.
/// See the example below for the connection string syntax.
///
/// When returning from sign-in, if the user is authenticated but has never registered, they can be sent to a specified RegistrationUrl.
/// If no RegistrationUrl is given, the user can be automatically registered if the Auto Register connection string setting is true.
/// If there is no RegistrationUrl, and automatic registration is disabled, the user will be signed out.
///
/// <example>
/// <![CDATA[
/// <connectionStrings>
/// <add name="LiveId" connectionString="Application Id=???; Secret=???; Signed Out Url=???; Auto Register=true"/>
/// </connectionStrings>
/// ]]>
/// The Signed Out Url and Auto Register settings are optional.
/// </example>
///
/// The return URL for your Live ID site registration should be the url to the LiveIdWebAuthenticationHandler that must be specified in the web.config.
/// </remarks>
[ToolboxData("<{0}:LiveIdLoginStatus runat=server></{0}:LiveIdLoginStatus>")]
public sealed class LiveIdLoginStatus : System.Web.UI.WebControls.WebControl
{
private System.Web.UI.WebControls.HyperLink _hyperLink;
private string _loginText;
private string _logoutText;
/// <summary>
/// When returning from sign-in, if the user is authenticated and registered, they will be sent to the specified URL.
/// </summary>
[UrlProperty]
public string LoginDestinationUrl { get; set; }
/// <summary>
/// Gets or sets the URL of the image used for the login link.
/// </summary>
[DefaultValue(""), UrlProperty, Editor("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
public string LoginImageUrl { get; set; }
/// <summary>
/// Gets or sets the text used for the login link.
/// </summary>
[DefaultValue(typeof(string), "Sign In")]
public string LoginText
{
get { return string.IsNullOrEmpty(_loginText) ? "Sign In" : _loginText; }
set { _loginText = value; }
}
/// <summary>
/// Gets or sets the URL of the image used for the logout button.
/// </summary>
[DefaultValue(""), UrlProperty, Editor("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
public string LogoutImageUrl { get; set; }
/// <summary>
/// Gets or sets the text used for the logout link.
/// </summary>
[DefaultValue(typeof(string), "Sign Out")]
public string LogoutText
{
get { return string.IsNullOrEmpty(_logoutText) ? "Sign Out" : _logoutText; }
set { _logoutText = value; }
}
/// <summary>
/// When a LoginNavigateUrl is not specified, the link takes the user directly to Windows Live.
///
/// If a landing page is desired, set the LoginNavigateUrl to be your landing page, and then place this control on your landing page with no LoginNavigateUrl.
/// </summary>
[UrlProperty]
public string LoginNavigateUrl { get; set; }
/// <summary>
/// When returning from sign-in, if the user is authenticated but has never registered, they will be sent to the specified URL.
/// The URL must be one that exists that the server can POST to. It cannot be a custom URL or one that will cause a 404 redirect.
/// </summary>
/// <remarks>If no registration URL is given, the user can be automatically registered if one sets the AutoRegister connection string setting to true.</remarks>
[UrlProperty]
public string RegistrationUrl { get; set; }
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.A; }
}
protected override void CreateChildControls()
{
Controls.Clear();
_hyperLink = new System.Web.UI.WebControls.HyperLink { EnableViewState = false, EnableTheming = false };
Controls.Add(_hyperLink);
}
protected override void Render(HtmlTextWriter writer)
{
RenderContents(writer);
}
protected override void RenderContents(HtmlTextWriter writer)
{
AssertConfiguration();
SetChildProperties();
if (!string.IsNullOrEmpty(ID))
{
writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);
}
base.RenderContents(writer);
}
private void AssertConfiguration()
{
var missingHandlerException = new ConfigurationErrorsException("The LiveIdLoginStatus control requires a '{0}' or '{1}' to be configured.".FormatWith(typeof(LiveIdMembershipProvider), typeof(LiveIdAccountTransferHandler)));
if (LiveIdMembershipProvider.Current == null) throw missingHandlerException;
if (!LiveIdWebAuthenticationHandlerExists()) throw missingHandlerException;
var windowsLive = new WindowsLiveLogin(true);
if (string.IsNullOrEmpty(windowsLive.AppId)) throw new ConfigurationErrorsException("The LiveIdLoginStatus control requires the application ID that you obtained when you registered your site to be specified in the LiveIdMembershipProvider connection string.");
}
private bool LiveIdWebAuthenticationHandlerExists()
{
if (Context.Request.ServerVariables.Get("MANAGED_PIPELINE_MODE") == "Integrated") return true;
var handlersSection = (HttpHandlersSection)WebConfigurationManager.GetSection("system.web/httpHandlers");
foreach (HttpHandlerAction handler in handlersSection.Handlers)
{
if (Type.GetType(handler.Type) == typeof(LiveIdWebAuthenticationHandler)
|| Type.GetType(handler.Type) == typeof(LiveIdAccountTransferHandler))
{
return true;
}
}
return false;
}
private void SetChildProperties()
{
EnsureChildControls();
if (Context.Request.IsAuthenticated)
{
_hyperLink.ImageUrl = LogoutImageUrl;
_hyperLink.Text = LogoutText;
var live = LiveIdMembershipProvider.Current;
_hyperLink.NavigateUrl = "http://login.live.com/logout.srf?appid={0}".FormatWith(Encoder.UrlEncode(live.AppId));
}
else
{
_hyperLink.ImageUrl = LoginImageUrl;
_hyperLink.Text = LoginText;
var loginDestinationUrl = LoginDestinationUrl
?? Context.Request.QueryString["ReturnUrl"]
?? Context.Request.QueryString["URL"]
?? Context.Request.RawUrl;
if (!string.IsNullOrEmpty(LoginNavigateUrl))
{
var url = new UrlBuilder(LoginNavigateUrl);
url.QueryString.Set("ReturnUrl", loginDestinationUrl);
_hyperLink.NavigateUrl = url.PathWithQueryString;
}
else
{
// the user did not supply a LoginNavigateSiteMarker, set the link to go to Windows Live.
_hyperLink.NavigateUrl = "http://login.live.com/wlogin.srf?appid={0}&alg=wsignin1.0&appctx=loginpath{1}$registrationpath{2}".FormatWith(
Encoder.UrlEncode(LiveIdMembershipProvider.Current.AppId),
Encoder.UrlEncode(loginDestinationUrl),
Encoder.UrlEncode(RegistrationUrl));
}
}
_hyperLink.CopyBaseAttributes(this);
_hyperLink.ApplyStyle(ControlStyle);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Framework.Logging;
using osu.Framework.Screens;
using osu.Framework.Threading;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Input.Bindings;
using osu.Game.Overlays;
using osu.Game.Overlays.Mods;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Menu;
using osu.Game.Screens.Select.Options;
using osuTK;
using osuTK.Graphics;
using osuTK.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Audio.Track;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Bindings;
using osu.Game.Collections;
using osu.Game.Graphics.UserInterface;
using System.Diagnostics;
using osu.Game.Screens.Play;
using osu.Game.Database;
namespace osu.Game.Screens.Select
{
public abstract class SongSelect : ScreenWithBeatmapBackground, IKeyBindingHandler<GlobalAction>
{
public static readonly float WEDGE_HEIGHT = 245;
protected const float BACKGROUND_BLUR = 20;
private const float left_area_padding = 20;
public FilterControl FilterControl { get; private set; }
protected virtual bool ShowFooter => true;
protected virtual bool DisplayStableImportPrompt => stableImportManager?.SupportsImportFromStable == true;
public override bool? AllowTrackAdjustments => true;
/// <summary>
/// Can be null if <see cref="ShowFooter"/> is false.
/// </summary>
protected BeatmapOptionsOverlay BeatmapOptions { get; private set; }
/// <summary>
/// Can be null if <see cref="ShowFooter"/> is false.
/// </summary>
protected Footer Footer { get; private set; }
/// <summary>
/// Contains any panel which is triggered by a footer button.
/// Helps keep them located beneath the footer itself.
/// </summary>
protected Container FooterPanels { get; private set; }
/// <summary>
/// Whether entering editor mode should be allowed.
/// </summary>
public virtual bool AllowEditing => true;
[Resolved]
private Bindable<IReadOnlyList<Mod>> selectedMods { get; set; }
protected BeatmapCarousel Carousel { get; private set; }
protected Container LeftArea { get; private set; }
private BeatmapInfoWedge beatmapInfoWedge;
private DialogOverlay dialogOverlay;
[Resolved]
private BeatmapManager beatmaps { get; set; }
[Resolved(CanBeNull = true)]
private StableImportManager stableImportManager { get; set; }
protected ModSelectOverlay ModSelect { get; private set; }
protected Sample SampleConfirm { get; private set; }
private Sample sampleChangeDifficulty;
private Sample sampleChangeBeatmap;
private Container carouselContainer;
protected BeatmapDetailArea BeatmapDetails { get; private set; }
private readonly Bindable<RulesetInfo> decoupledRuleset = new Bindable<RulesetInfo>();
[Resolved]
private MusicController music { get; set; }
[BackgroundDependencyLoader(true)]
private void load(AudioManager audio, DialogOverlay dialog, OsuColour colours, ManageCollectionsDialog manageCollectionsDialog, DifficultyRecommender recommender)
{
// initial value transfer is required for FilterControl (it uses our re-cached bindables in its async load for the initial filter).
transferRulesetValue();
LoadComponentAsync(Carousel = new BeatmapCarousel
{
AllowSelection = false, // delay any selection until our bindables are ready to make a good choice.
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
RelativeSizeAxes = Axes.Both,
BleedTop = FilterControl.HEIGHT,
BleedBottom = Footer.HEIGHT,
SelectionChanged = updateSelectedBeatmap,
BeatmapSetsChanged = carouselBeatmapsLoaded,
GetRecommendedBeatmap = s => recommender?.GetRecommendedBeatmap(s),
}, c => carouselContainer.Child = c);
AddRangeInternal(new Drawable[]
{
new ResetScrollContainer(() => Carousel.ScrollToSelected())
{
RelativeSizeAxes = Axes.Y,
Width = 250,
},
new VerticalMaskingContainer
{
Children = new Drawable[]
{
new GridContainer // used for max width implementation
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Relative, 0.5f, maxSize: 850),
},
Content = new[]
{
new Drawable[]
{
new ParallaxContainer
{
ParallaxAmount = 0.005f,
RelativeSizeAxes = Axes.Both,
Child = new WedgeBackground
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Right = -150 },
},
},
carouselContainer = new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding
{
Top = FilterControl.HEIGHT,
Bottom = Footer.HEIGHT
},
Child = new LoadingSpinner(true) { State = { Value = Visibility.Visible } }
}
},
}
},
FilterControl = new FilterControl
{
RelativeSizeAxes = Axes.X,
Height = FilterControl.HEIGHT,
FilterChanged = ApplyFilterToCarousel,
},
new GridContainer // used for max width implementation
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.Relative, 0.5f, maxSize: 650),
},
Content = new[]
{
new Drawable[]
{
LeftArea = new Container
{
Origin = Anchor.BottomLeft,
Anchor = Anchor.BottomLeft,
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = left_area_padding },
Children = new Drawable[]
{
beatmapInfoWedge = new BeatmapInfoWedge
{
Height = WEDGE_HEIGHT,
RelativeSizeAxes = Axes.X,
Margin = new MarginPadding
{
Right = left_area_padding,
Left = -BeatmapInfoWedge.BORDER_THICKNESS, // Hide the left border
},
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding
{
Bottom = Footer.HEIGHT,
Top = WEDGE_HEIGHT,
Left = left_area_padding,
Right = left_area_padding * 2,
},
Child = BeatmapDetails = CreateBeatmapDetailArea().With(d =>
{
d.RelativeSizeAxes = Axes.Both;
d.Padding = new MarginPadding { Top = 10, Right = 5 };
})
},
}
},
},
}
}
}
},
});
if (ShowFooter)
{
AddRangeInternal(new Drawable[]
{
new GridContainer // used for max height implementation
{
RelativeSizeAxes = Axes.Both,
RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Relative, 1f, maxSize: ModSelectOverlay.HEIGHT + Footer.HEIGHT),
},
Content = new[]
{
null,
new Drawable[]
{
FooterPanels = new Container
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Bottom = Footer.HEIGHT },
Children = new Drawable[]
{
BeatmapOptions = new BeatmapOptionsOverlay(),
ModSelect = CreateModSelectOverlay()
}
}
}
}
},
Footer = new Footer()
});
}
if (Footer != null)
{
foreach (var (button, overlay) in CreateFooterButtons())
Footer.AddButton(button, overlay);
BeatmapOptions.AddButton(@"Manage", @"collections", FontAwesome.Solid.Book, colours.Green, () => manageCollectionsDialog?.Show());
BeatmapOptions.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, colours.Pink, () => delete(Beatmap.Value.BeatmapSetInfo));
BeatmapOptions.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, colours.Purple, null);
BeatmapOptions.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, colours.Purple, () => clearScores(Beatmap.Value.BeatmapInfo));
}
dialogOverlay = dialog;
sampleChangeDifficulty = audio.Samples.Get(@"SongSelect/select-difficulty");
sampleChangeBeatmap = audio.Samples.Get(@"SongSelect/select-expand");
SampleConfirm = audio.Samples.Get(@"SongSelect/confirm-selection");
if (dialogOverlay != null)
{
Schedule(() =>
{
// if we have no beatmaps, let's prompt the user to import from over a stable install if he has one.
if (!beatmaps.GetAllUsableBeatmapSetsEnumerable(IncludedDetails.Minimal).Any() && DisplayStableImportPrompt)
{
dialogOverlay.Push(new ImportFromStablePopup(() =>
{
Task.Run(() => stableImportManager.ImportFromStableAsync(StableContent.All));
}));
}
});
}
}
/// <summary>
/// Creates the buttons to be displayed in the footer.
/// </summary>
/// <returns>A set of <see cref="FooterButton"/> and an optional <see cref="OverlayContainer"/> which the button opens when pressed.</returns>
protected virtual IEnumerable<(FooterButton, OverlayContainer)> CreateFooterButtons() => new (FooterButton, OverlayContainer)[]
{
(new FooterButtonMods { Current = Mods }, ModSelect),
(new FooterButtonRandom
{
NextRandom = () => Carousel.SelectNextRandom(),
PreviousRandom = Carousel.SelectPreviousRandom
}, null),
(new FooterButtonOptions(), BeatmapOptions)
};
protected virtual ModSelectOverlay CreateModSelectOverlay() => new UserModSelectOverlay();
protected virtual void ApplyFilterToCarousel(FilterCriteria criteria)
{
// if not the current screen, we want to get carousel in a good presentation state before displaying (resume or enter).
bool shouldDebounce = this.IsCurrentScreen();
Carousel.Filter(criteria, shouldDebounce);
}
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
dependencies.CacheAs(this);
dependencies.CacheAs(decoupledRuleset);
dependencies.CacheAs<IBindable<RulesetInfo>>(decoupledRuleset);
return dependencies;
}
/// <summary>
/// Creates the beatmap details to be displayed underneath the wedge.
/// </summary>
protected abstract BeatmapDetailArea CreateBeatmapDetailArea();
public void Edit(BeatmapInfo beatmapInfo = null)
{
if (!AllowEditing)
throw new InvalidOperationException($"Attempted to edit when {nameof(AllowEditing)} is disabled");
Beatmap.Value = beatmaps.GetWorkingBeatmap(beatmapInfo ?? beatmapInfoNoDebounce);
this.Push(new EditorLoader());
}
/// <summary>
/// Call to make a selection and perform the default action for this SongSelect.
/// </summary>
/// <param name="beatmapInfo">An optional beatmap to override the current carousel selection.</param>
/// <param name="ruleset">An optional ruleset to override the current carousel selection.</param>
/// <param name="customStartAction">An optional custom action to perform instead of <see cref="OnStart"/>.</param>
public void FinaliseSelection(BeatmapInfo beatmapInfo = null, RulesetInfo ruleset = null, Action customStartAction = null)
{
// This is very important as we have not yet bound to screen-level bindables before the carousel load is completed.
if (!Carousel.BeatmapSetsLoaded)
return;
if (ruleset != null)
Ruleset.Value = ruleset;
transferRulesetValue();
// while transferRulesetValue will flush, it only does so if the ruleset changes.
// the user could have changed a filter, and we want to ensure we are 100% up-to-date and consistent here.
Carousel.FlushPendingFilterOperations();
// avoid attempting to continue before a selection has been obtained.
// this could happen via a user interaction while the carousel is still in a loading state.
if (Carousel.SelectedBeatmapInfo == null) return;
if (beatmapInfo != null)
Carousel.SelectBeatmap(beatmapInfo);
if (selectionChangedDebounce?.Completed == false)
{
selectionChangedDebounce.RunTask();
selectionChangedDebounce?.Cancel(); // cancel the already scheduled task.
selectionChangedDebounce = null;
}
if (customStartAction != null)
{
customStartAction();
Carousel.AllowSelection = false;
}
else if (OnStart())
Carousel.AllowSelection = false;
}
/// <summary>
/// Called when a selection is made.
/// </summary>
/// <returns>If a resultant action occurred that takes the user away from SongSelect.</returns>
protected abstract bool OnStart();
private ScheduledDelegate selectionChangedDebounce;
private void workingBeatmapChanged(ValueChangedEvent<WorkingBeatmap> e)
{
if (e.NewValue is DummyWorkingBeatmap || !this.IsCurrentScreen()) return;
Logger.Log($"Song select working beatmap updated to {e.NewValue}");
if (!Carousel.SelectBeatmap(e.NewValue.BeatmapInfo, false))
{
// A selection may not have been possible with filters applied.
// There was possibly a ruleset mismatch. This is a case we can help things along by updating the game-wide ruleset to match.
if (e.NewValue.BeatmapInfo.Ruleset != null && !e.NewValue.BeatmapInfo.Ruleset.Equals(decoupledRuleset.Value))
{
Ruleset.Value = e.NewValue.BeatmapInfo.Ruleset;
transferRulesetValue();
}
// Even if a ruleset mismatch was not the cause (ie. a text filter is applied),
// we still want to temporarily show the new beatmap, bypassing filters.
// This will be undone the next time the user changes the filter.
var criteria = FilterControl.CreateCriteria();
criteria.SelectedBeatmapSet = e.NewValue.BeatmapInfo.BeatmapSet;
Carousel.Filter(criteria);
Carousel.SelectBeatmap(e.NewValue.BeatmapInfo);
}
}
// We need to keep track of the last selected beatmap ignoring debounce to play the correct selection sounds.
private BeatmapInfo beatmapInfoNoDebounce;
private RulesetInfo rulesetNoDebounce;
private void updateSelectedBeatmap(BeatmapInfo beatmapInfo)
{
if (beatmapInfo == null && beatmapInfoNoDebounce == null)
return;
if (beatmapInfo?.Equals(beatmapInfoNoDebounce) == true)
return;
beatmapInfoNoDebounce = beatmapInfo;
performUpdateSelected();
}
private void updateSelectedRuleset(RulesetInfo ruleset)
{
if (ruleset == null && rulesetNoDebounce == null)
return;
if (ruleset?.Equals(rulesetNoDebounce) == true)
return;
rulesetNoDebounce = ruleset;
performUpdateSelected();
}
/// <summary>
/// Selection has been changed as the result of a user interaction.
/// </summary>
private void performUpdateSelected()
{
var beatmap = beatmapInfoNoDebounce;
var ruleset = rulesetNoDebounce;
selectionChangedDebounce?.Cancel();
if (beatmapInfoNoDebounce == null)
run();
else
selectionChangedDebounce = Scheduler.AddDelayed(run, 200);
void run()
{
// clear pending task immediately to track any potential nested debounce operation.
selectionChangedDebounce = null;
Logger.Log($"updating selection with beatmap:{beatmap?.ID.ToString() ?? "null"} ruleset:{ruleset?.ID.ToString() ?? "null"}");
if (transferRulesetValue())
{
Mods.Value = Array.Empty<Mod>();
// transferRulesetValue() may trigger a re-filter. If the current selection does not match the new ruleset, we want to switch away from it.
// The default logic on WorkingBeatmap change is to switch to a matching ruleset (see workingBeatmapChanged()), but we don't want that here.
// We perform an early selection attempt and clear out the beatmap selection to avoid a second ruleset change (revert).
if (beatmap != null && !Carousel.SelectBeatmap(beatmap, false))
beatmap = null;
}
if (selectionChangedDebounce != null)
{
// a new nested operation was started; switch to it for further selection.
// this avoids having two separate debounces trigger from the same source.
selectionChangedDebounce.RunTask();
return;
}
// We may be arriving here due to another component changing the bindable Beatmap.
// In these cases, the other component has already loaded the beatmap, so we don't need to do so again.
if (!EqualityComparer<BeatmapInfo>.Default.Equals(beatmap, Beatmap.Value.BeatmapInfo))
{
Logger.Log($"beatmap changed from \"{Beatmap.Value.BeatmapInfo}\" to \"{beatmap}\"");
int? lastSetID = Beatmap.Value?.BeatmapInfo.BeatmapSetInfoID;
Beatmap.Value = beatmaps.GetWorkingBeatmap(beatmap);
if (beatmap != null)
{
if (beatmap.BeatmapSetInfoID == lastSetID)
sampleChangeDifficulty.Play();
else
sampleChangeBeatmap.Play();
}
}
if (this.IsCurrentScreen())
ensurePlayingSelected();
updateComponentFromBeatmap(Beatmap.Value);
}
}
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
this.FadeInFromZero(250);
FilterControl.Activate();
ModSelect.SelectedMods.BindTo(selectedMods);
beginLooping();
}
private const double logo_transition = 250;
protected override void LogoArriving(OsuLogo logo, bool resuming)
{
base.LogoArriving(logo, resuming);
Vector2 position = new Vector2(0.95f, 0.96f);
if (logo.Alpha > 0.8f)
{
logo.MoveTo(position, 500, Easing.OutQuint);
}
else
{
logo.Hide();
logo.ScaleTo(0.2f);
logo.MoveTo(position);
}
logo.FadeIn(logo_transition, Easing.OutQuint);
logo.ScaleTo(0.4f, logo_transition, Easing.OutQuint);
logo.Action = () =>
{
FinaliseSelection();
return false;
};
}
protected override void LogoExiting(OsuLogo logo)
{
base.LogoExiting(logo);
logo.ScaleTo(0.2f, logo_transition / 2, Easing.Out);
logo.FadeOut(logo_transition / 2, Easing.Out);
}
public override void OnResuming(IScreen last)
{
base.OnResuming(last);
// required due to https://github.com/ppy/osu-framework/issues/3218
ModSelect.SelectedMods.Disabled = false;
ModSelect.SelectedMods.BindTo(selectedMods);
Carousel.AllowSelection = true;
BeatmapDetails.Refresh();
beginLooping();
music.ResetTrackAdjustments();
if (Beatmap != null && !Beatmap.Value.BeatmapSetInfo.DeletePending)
{
updateComponentFromBeatmap(Beatmap.Value);
// restart playback on returning to song select, regardless.
// not sure this should be a permanent thing (we may want to leave a user pause paused even on returning)
music.Play(requestedByUser: true);
}
this.FadeIn(250);
this.ScaleTo(1, 250, Easing.OutSine);
FilterControl.Activate();
}
public override void OnSuspending(IScreen next)
{
ModSelect.SelectedMods.UnbindFrom(selectedMods);
ModSelect.Hide();
BeatmapOptions.Hide();
endLooping();
this.ScaleTo(1.1f, 250, Easing.InSine);
this.FadeOut(250);
FilterControl.Deactivate();
base.OnSuspending(next);
}
public override bool OnExiting(IScreen next)
{
if (base.OnExiting(next))
return true;
beatmapInfoWedge.Hide();
this.FadeOut(100);
FilterControl.Deactivate();
endLooping();
return false;
}
private bool isHandlingLooping;
private void beginLooping()
{
Debug.Assert(!isHandlingLooping);
isHandlingLooping = true;
ensureTrackLooping(Beatmap.Value, TrackChangeDirection.None);
music.TrackChanged += ensureTrackLooping;
}
private void endLooping()
{
// may be called multiple times during screen exit process.
if (!isHandlingLooping)
return;
music.CurrentTrack.Looping = isHandlingLooping = false;
music.TrackChanged -= ensureTrackLooping;
}
private void ensureTrackLooping(WorkingBeatmap beatmap, TrackChangeDirection changeDirection)
=> beatmap.PrepareTrackForPreviewLooping();
public override bool OnBackButton()
{
if (ModSelect.State.Value == Visibility.Visible)
{
ModSelect.Hide();
return true;
}
return false;
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
decoupledRuleset.UnbindAll();
if (music != null)
music.TrackChanged -= ensureTrackLooping;
}
/// <summary>
/// Allow components in SongSelect to update their loaded beatmap details.
/// This is a debounced call (unlike directly binding to WorkingBeatmap.ValueChanged).
/// </summary>
/// <param name="beatmap">The working beatmap.</param>
private void updateComponentFromBeatmap(WorkingBeatmap beatmap)
{
ApplyToBackground(backgroundModeBeatmap =>
{
backgroundModeBeatmap.Beatmap = beatmap;
backgroundModeBeatmap.BlurAmount.Value = BACKGROUND_BLUR;
backgroundModeBeatmap.FadeColour(Color4.White, 250);
});
beatmapInfoWedge.Beatmap = beatmap;
BeatmapDetails.Beatmap = beatmap;
}
private readonly WeakReference<ITrack> lastTrack = new WeakReference<ITrack>(null);
/// <summary>
/// Ensures some music is playing for the current track.
/// Will resume playback from a manual user pause if the track has changed.
/// </summary>
private void ensurePlayingSelected()
{
ITrack track = music.CurrentTrack;
bool isNewTrack = !lastTrack.TryGetTarget(out var last) || last != track;
if (!track.IsRunning && (music.UserPauseRequested != true || isNewTrack))
music.Play(true);
lastTrack.SetTarget(track);
}
private void carouselBeatmapsLoaded()
{
bindBindables();
Carousel.AllowSelection = true;
// If a selection was already obtained, do not attempt to update the selected beatmap.
if (Carousel.SelectedBeatmapSet != null)
return;
// Attempt to select the current beatmap on the carousel, if it is valid to be selected.
if (!Beatmap.IsDefault && Beatmap.Value.BeatmapSetInfo?.DeletePending == false && Beatmap.Value.BeatmapSetInfo?.Protected == false)
{
if (Carousel.SelectBeatmap(Beatmap.Value.BeatmapInfo, false))
return;
// prefer not changing ruleset at this point, so look for another difficulty in the currently playing beatmap
var found = Beatmap.Value.BeatmapSetInfo.Beatmaps.FirstOrDefault(b => b.Ruleset.Equals(decoupledRuleset.Value));
if (found != null && Carousel.SelectBeatmap(found, false))
return;
}
// If the current active beatmap could not be selected, select a new random beatmap.
if (!Carousel.SelectNextRandom())
{
// in the case random selection failed, we want to trigger selectionChanged
// to show the dummy beatmap (we have nothing else to display).
performUpdateSelected();
}
}
private bool boundLocalBindables;
private void bindBindables()
{
if (boundLocalBindables)
return;
// manual binding to parent ruleset to allow for delayed load in the incoming direction.
transferRulesetValue();
Ruleset.ValueChanged += r => updateSelectedRuleset(r.NewValue);
decoupledRuleset.ValueChanged += r => Ruleset.Value = r.NewValue;
decoupledRuleset.DisabledChanged += r => Ruleset.Disabled = r;
Beatmap.BindValueChanged(workingBeatmapChanged);
boundLocalBindables = true;
}
/// <summary>
/// Transfer the game-wide ruleset to the local decoupled ruleset.
/// Will immediately run filter operations if required.
/// </summary>
/// <returns>Whether a transfer occurred.</returns>
private bool transferRulesetValue()
{
if (decoupledRuleset.Value?.Equals(Ruleset.Value) == true)
return false;
Logger.Log($"decoupled ruleset transferred (\"{decoupledRuleset.Value}\" -> \"{Ruleset.Value}\")");
rulesetNoDebounce = decoupledRuleset.Value = Ruleset.Value;
// if we have a pending filter operation, we want to run it now.
// it could change selection (ie. if the ruleset has been changed).
Carousel?.FlushPendingFilterOperations();
return true;
}
private void delete(BeatmapSetInfo beatmap)
{
if (beatmap == null || beatmap.ID <= 0) return;
dialogOverlay?.Push(new BeatmapDeleteDialog(beatmap));
}
private void clearScores(BeatmapInfo beatmapInfo)
{
if (beatmapInfo == null || beatmapInfo.ID <= 0) return;
dialogOverlay?.Push(new BeatmapClearScoresDialog(beatmapInfo, () =>
// schedule done here rather than inside the dialog as the dialog may fade out and never callback.
Schedule(() => BeatmapDetails.Refresh())));
}
public virtual bool OnPressed(KeyBindingPressEvent<GlobalAction> e)
{
if (!this.IsCurrentScreen()) return false;
switch (e.Action)
{
case GlobalAction.Select:
FinaliseSelection();
return true;
}
return false;
}
public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e)
{
}
protected override bool OnKeyDown(KeyDownEvent e)
{
if (e.Repeat) return false;
switch (e.Key)
{
case Key.Delete:
if (e.ShiftPressed)
{
if (!Beatmap.IsDefault)
delete(Beatmap.Value.BeatmapSetInfo);
return true;
}
break;
}
return base.OnKeyDown(e);
}
private class VerticalMaskingContainer : Container
{
private const float panel_overflow = 1.2f;
protected override Container<Drawable> Content { get; }
public VerticalMaskingContainer()
{
RelativeSizeAxes = Axes.Both;
Masking = true;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
Width = panel_overflow; // avoid horizontal masking so the panels don't clip when screen stack is pushed.
InternalChild = Content = new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Width = 1 / panel_overflow,
};
}
}
private class ResetScrollContainer : Container
{
private readonly Action onHoverAction;
public ResetScrollContainer(Action onHoverAction)
{
this.onHoverAction = onHoverAction;
}
protected override bool OnHover(HoverEvent e)
{
onHoverAction?.Invoke();
return base.OnHover(e);
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
public class GA_SetupWizard : EditorWindow
{
private GUIContent _nextTour = new GUIContent(">", "Continue the GameAnalytics setup and introduction tour.");
private GUIContent _prevTour = new GUIContent("<", "Go back to the previous page.");
private GUIContent _backToStart = new GUIContent("Back to page 1", "Go back to the first page.");
private GUIContent _closeWizard = new GUIContent("Close Wizard", "Closes the GameAnalytics setup and introduction tour.");
private GUIContent _myHomePage = new GUIContent("GA account", "Opens your home page on the GameAnalytics website. If you have not created a GameAnalytics account yet you can do that here.");
private GUIContent _documentationLink = new GUIContent("Documentation", "Opens the GameAnalytics Unity3D package documentation page in your browser. https://beta.gameanalytics.com/docs/unity3d.html");
private GUIContent _copyCode = new GUIContent("Copy Code", "Copy the code to clipboard.");
private GUIContent _openExampleGame = new GUIContent("Example Game", "Opens the GameAnalytics example game scene.");
private GUIContent _publicKeyLabel = new GUIContent("Game Key", "Your GameAnalytics Game Key - copy/paste from the GA website.");
private GUIContent _privateKeyLabel = new GUIContent("Secret Key", "Your GameAnalytics Secret Key - copy/paste from the GA website.");
private GUIContent _apiKeyLabel = new GUIContent("API Key", "Your GameAnalytics API Key - copy/paste from the GA website.");
private GUIContent _stepOne = new GUIContent("Create GA account", "Create your GA account and add a game studio and game.");
private GUIContent _stepTwo = new GUIContent("Setup GA_Settings", "Copy/paste your Game Key and Secret Key from the website.");
private GUIContent _stepThree = new GUIContent("GA_Status overview", "The GA_Status window shows whether or not the settings have been setup correctly, and also shows the number of successful and failed messages sent.");
private GUIContent _stepFour = new GUIContent("System tracking", "Use the GA_SystemTracker for tracking system info, errors, performance, etc.");
private GUIContent _stepFive = new GUIContent("Object tracking", "Use the GA_Tracker to track predefined events for a game object.");
private GUIContent _stepSix = new GUIContent("Custom tracking", "Track your own custom events in the code.");
private GUIContent _stepSeven = new GUIContent("Heatmap visualization", "Visualize 3D heatmaps of your data in the Unity3D editor.");
private GUIContent _stepEight = new GUIContent("Heatmap histogram", "Explains how the histogram for heatmap datasets works.");
private int _tourStep = 0;
private int _lastStep = 9;
void OnGUI ()
{
switch(_tourStep)
{
case 0:
GUILayout.Label("Thank you for downloading the GameAnalytics Unity3D wrapper", EditorStyles.whiteLargeLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("By using GameAnalytics you will be able to find out what type of players play your game, how they play, and lots more!", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("This Setup Wizard will help you set up GameAnalytics, and teach you how to track system events, crashes, custom events, etc. You will also learn how to use heatmaps to visualize your data!", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Jump to Setup:", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button(_stepOne)) { _tourStep = 1; }
if (GUILayout.Button(_stepTwo)) { _tourStep = 2; }
if (GUILayout.Button(_stepThree)) { _tourStep = 3; }
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.LabelField("Jump to Tracking:", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button(_stepFour)) { _tourStep = 4; }
if (GUILayout.Button(_stepFive)) { _tourStep = 5; }
if (GUILayout.Button(_stepSix)) { _tourStep = 6; }
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.LabelField("Jump to Heatmaps:", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button(_stepSeven)) { _tourStep = 7; }
if (GUILayout.Button(_stepEight)) { _tourStep = 8; }
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Visit the online documentation:", EditorStyles.boldLabel);
if (GUILayout.Button(_documentationLink, GUILayout.Width(150)))
{
Application.OpenURL("http://easy.gameanalytics.com/SupportDocu");
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
GUILayout.Space(4);
break;
case 1:
GUILayout.Label("Step 1: Create your GA account and game", EditorStyles.whiteLargeLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("The first thing you should do is create a GameAnalytics account on the GA website. Open the site using the button below, create and verify your GA account, and then you will be able to both create a game studio and add games to it.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Once you have created your first game on the website you will have what you need to continue this tour. If you have already created a GA account and a game you should skip this step.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("GA account creation website:", EditorStyles.boldLabel);
if (GUILayout.Button(_myHomePage, GUILayout.Width(150)))
{
Application.OpenURL("http://easy.gameanalytics.com/CreateGameAnalytics");
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(6);
EditorGUILayout.HelpBox("The GA website lets you view all the data you have collected in a multitude of ways. Along with the Design, Quality, Business, and User views, which give you quick overviews of these aspects of your game, the GA site also features the Explore tool, Funnels and Cohorts.\n\nUsing the Explore tool you can visualize a ton of standard matrices, such as DAU (daily average users) or ARPU (average revenue per user), or custom matrices based on your own custom events.\nFunnels give you an overview of how users progress through a sequence of events you define, and Cohorts help you keep track of player retention.", MessageType.Info, true);
GUILayout.Space(4);
break;
case 2:
GUILayout.Label("Step 2: Setup GA settings", EditorStyles.whiteLargeLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Now it's time to copy/paste your Game Key and Secret Key from the website to the fields below. These keys were generated when you created your game on the website. You can also find the keys under the game's settings from your home page.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Your keys are stored in the GA_Settings object, which also contains other useful settings - you can always find it under Window > GameAnalytics > Select GA_Settings.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("GA account home:", EditorStyles.boldLabel);
if (GUILayout.Button(_myHomePage, GUILayout.Width(150)))
{
Application.OpenURL("http://easy.gameanalytics.com/LoginGA");
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label(_publicKeyLabel, EditorStyles.boldLabel);
GA.SettingsGA.GameKey = EditorGUILayout.TextField("", GA.SettingsGA.GameKey);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label(_privateKeyLabel, EditorStyles.boldLabel);
GA.SettingsGA.SecretKey = EditorGUILayout.TextField("", GA.SettingsGA.SecretKey);
GUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.HelpBox("Your Game Key uniquely identifies your game, so the Unity Package knows where to store your data. Your Secret Key is used for security as message authorization, and makes sure that no-one else gets a hold of your data!", MessageType.Info, true);
GUILayout.Space(31);
break;
case 3:
GUILayout.Label("Step 3: The GA_Status Window", EditorStyles.whiteLargeLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("A quick tip before we start tracking tons of events; the GA_Status window shows whether the GameAnalytics Unity3D Package has been set up correctly. Both the Game Key and Secret Key must be set up to satisfy the GA_Status window. This window is accessible through Window > GameAnalytics > Open GA_Status.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("The GA_Status window also shows the status of messages sent to the server. You get an overview of the total number of messages sent successfully, and the total number of messages that failed. The GA_Status window also shows you the number of successful/failed messages for each message category.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("To make sure the GA Package is tracking the events you set up it might be a good idea to keep an eye on this window while you play your game. Remember that messages are clustered and sent to the server at certain intervals (you can set this interval on the GA_Settings object, under the Advanced tab).", EditorStyles.wordWrappedLabel);
GUILayout.Space(46);
break;
case 4:
GUILayout.Label("Step 4: The GA_SystemTracker Prefab (Optional)", EditorStyles.whiteLargeLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("The rest of this tour is completely optional - if you got this far you are ready to track events. Now you just need to set up some events to track!", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("The GA_SystemTracker is useful for tracking system info, errors, performance, etc. To add it to a scene go to Window > GameAnalytics > Create GA_SystemTracker.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("You can add a GA_SystemTracker to each of the scenes you want to track, or you can add a GA_SystemTracker to your first scene. Enable \"Use For Subsequent Levels\", and it will work for any scene that follows.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.HelpBox("It can be very useful to track how many levels players complete, and their completion times. The GA_SystemTracker will help you do this.\n\nThe GA_SystemTracker is also useful for gathering information on your players' system hardware. When you combine this with tracking game performance (average and Critical FPS events), you can get an overview of which system specifications have trouble running your game.\n\nYou can also use the GA_SystemTracker to track exceptions. This feature can generate a lot of data, but it can also be a great way of discovering bugs.", MessageType.Info, true);
GUILayout.Space(7);
break;
case 5:
GUILayout.Label("Step 5: The GA_Tracker Component (Optional)", EditorStyles.whiteLargeLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("The GA_Tracker component can be added to any game object in a scene from Window > GameAnalytics > Add GA_Tracker to Object. It allows you to easily set up auto-tracking of a bunch of simple, predefined events for that game object.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.HelpBox("The auto-tracked events available through the GA_Tracker component lets you set up some simple tracking for testing, etc. without having to code your own custom events.", MessageType.Info, true);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Using the GA_Tracker you can also enable Track Target for a game object. Some key events used by the GA_SystemTracker will use the location of the game object set up as Track Target - so only one GA_Tracker per scene can have Track Target enabled. Events include Submit Critical FPS, Submit Errors, and GA GUI events.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.HelpBox("You can put a GA_Tracker component on your player or camera object, and enable Track Target. This way you will know the location of the player when a Critical FPS event occurred - there is probably something causing bad performance in that area!", MessageType.Info, true);
GUILayout.Space(18);
break;
case 6:
GUILayout.Label("Step 6: Tracking your own custom events (Optional)", EditorStyles.whiteLargeLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("It is of course possible to track your own custom events, such as when a player kills an enemy, picks up an item, or dies. Here are a few simple copy/paste code examples, but we recommend you check out the online documentation for a complete overview.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Design examples:", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.SelectableLabel("GA.API.Design.NewEvent(\"Kill:Robot\", transform.position);", EditorStyles.textField, new GUILayoutOption[] { GUILayout.Height(19) });
if (GUILayout.Button(_copyCode, GUILayout.MaxWidth(82)))
{
TextEditor te = new TextEditor();
te.content = new GUIContent("GA.API.Design.NewEvent(\"Kill:Robot\", transform.position);");
te.SelectAll();
te.Copy();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("Quality example:", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.SelectableLabel("GA.API.Quality.NewEvent(\"System:os\");", EditorStyles.textField, new GUILayoutOption[] { GUILayout.Height(19) });
if (GUILayout.Button(_copyCode, GUILayout.MaxWidth(82)))
{
TextEditor te = new TextEditor();
te.content = new GUIContent("GA.API.Quality.NewEvent(\"System:os\");");
te.SelectAll();
te.Copy();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("Business example:", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.SelectableLabel("GA.API.Business.NewEvent(\"Buy:PlayerSkin\", \"USD\", 10);", EditorStyles.textField, new GUILayoutOption[] { GUILayout.Height(19) });
if (GUILayout.Button(_copyCode, GUILayout.MaxWidth(82)))
{
TextEditor te = new TextEditor();
te.content = new GUIContent("GA.API.Business.NewEvent(\"Buy:PlayerSkin\", \"USD\", 10);");
te.SelectAll();
te.Copy();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("User example:", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.SelectableLabel("GA.API.User.NewUser(GA_User.Gender.Male, 1976, 7);", EditorStyles.textField, new GUILayoutOption[] { GUILayout.Height(19) });
if (GUILayout.Button(_copyCode, GUILayout.MaxWidth(82)))
{
TextEditor te = new TextEditor();
te.content = new GUIContent("GA.API.User.NewUser(GA_User.Gender.Male, 1976, 7);");
te.SelectAll();
te.Copy();
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(10);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Visit the online documentation:", EditorStyles.boldLabel);
if (GUILayout.Button(_documentationLink, GUILayout.Width(150)))
{
Application.OpenURL("http://easy.gameanalytics.com/SupportDocu");
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(7);
break;
case 7:
GUILayout.Label("Step 7A: 3D Heatmap data visualization (Optional)", EditorStyles.whiteLargeLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("In order to use the heatmap feature you must first copy/paste your API Key from the website to the field below. You can find the key under your game's settings from your home page. Your API key is stored in the GA_Settings object, under the Advanced tab.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("GA account home:", EditorStyles.boldLabel);
if (GUILayout.Button(_myHomePage, GUILayout.Width(150)))
{
Application.OpenURL("http://easy.gameanalytics.com/LoginGA");
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.Label(_apiKeyLabel, EditorStyles.boldLabel);
GA.SettingsGA.ApiKey = EditorGUILayout.TextField("", GA.SettingsGA.ApiKey);
GUILayout.EndHorizontal();
GUILayout.Space(3);
EditorGUILayout.Space();
EditorGUILayout.LabelField("To add a heatmap object to a scene go to Window > GameAnalytics > Create GA_Heatmap. Heatmaps. This allows you to visualize the data you have collected inside Unity3D.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("To use the GA_Heatmap prefab you first have to get your data from the GA servers. To do this click the Update Index button. This will update the available builds, areas, and events. After you select the appropriate values, which correspond to the event you want to visualize, you simply click the Download Heatmap button. If any data is present for the combination of values you have selected, you should now see a heatmap in your scene.", EditorStyles.wordWrappedLabel);
GUILayout.Space(11);
break;
case 8:
GUILayout.Label("Step 7B: 3D Heatmap data histogram (Optional)", EditorStyles.whiteLargeLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("3D heatmaps come with a histogram of the downloaded dataset, which provides an overview of the data, and allows you to filter and focus on a smaller subset using the slider below the histogram.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("All data collected for heatmaps is aggregated into a grid. Each column in the histogram represents a frequency of occurrence for the event in a grid point. The height of the column indicates the number of grid points with this frequency. The column furthest to the left represents the lowest frequency, i.e. the number of grid points where this event only occurred a few times. The column furthest to the right represents the highest frequency.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Histogram scale switches between a linear and logarithmic view of the histogram, making it easier for you to focus on exactly the data you want.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Transparent render model gives a better overview of clustered data, while solid varies the size of each data point depending on the value. The overlay option allows you to view the heatmap through any other scene objects.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Point radius sets the size of each heatmap data point, and Show values will display the values of each data point (this can be bad for performance).", EditorStyles.wordWrappedLabel);
GUILayout.Space(11);
break;
case 9:
EditorGUILayout.LabelField("That's it!", EditorStyles.whiteLargeLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Of course, this tour only covered the basics of the Unity3D Package. For a complete overview, as well as examples, please visit our online documentation.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("You might also want to check out the example game included with the GA Package. You can find the scene in the Examples folder.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Once again, thank you for choosing GameAnalytics, and please do not hesitate to use the Support feature on our website (found on left side of the screen when you are logged in) to submit any feedback, or ask any questions you might have.", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Happy tracking!", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Visit your GA home page:", EditorStyles.boldLabel);
if (GUILayout.Button(_myHomePage, GUILayout.Width(150)))
{
Application.OpenURL("http://easy.gameanalytics.com/LoginGA");
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Visit the online documentation:", EditorStyles.boldLabel);
if (GUILayout.Button(_documentationLink, GUILayout.Width(150)))
{
Application.OpenURL("http://easy.gameanalytics.com/SupportDocu");
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Open GA example game scene:", EditorStyles.boldLabel);
if (GUILayout.Button(_openExampleGame, GUILayout.Width(150)))
{
if (EditorApplication.SaveCurrentSceneIfUserWantsTo())
{
EditorApplication.OpenScene("Assets/GameAnalytics/Plugins/Examples/ga_example.unity");
Close();
}
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(11);
break;
}
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
if (_tourStep > 0 && GUILayout.Button(_backToStart))
{
_tourStep = 0;
}
if (_tourStep > 0 && GUILayout.Button(_prevTour))
{
_tourStep--;
MoveToNewStepAction();
}
if ((_tourStep == 0 || _tourStep == _lastStep) && GUILayout.Button(_closeWizard))
{
Close();
}
if (_tourStep < _lastStep && GUILayout.Button(_nextTour))
{
_tourStep++;
MoveToNewStepAction();
}
EditorGUILayout.EndHorizontal();
}
public void SetTourStep(int step)
{
_tourStep = step;
MoveToNewStepAction();
}
private void MoveToNewStepAction()
{
if (_tourStep == 2)
{
Selection.activeObject = GA.SettingsGA;
GA.SettingsGA.CurrentInspectorState = GA_Settings.InspectorStates.Basic;
}
else if (_tourStep == 7)
{
Selection.activeObject = GA.SettingsGA;
GA.SettingsGA.CurrentInspectorState = GA_Settings.InspectorStates.Pref;
}
}
}
| |
// 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.
#if FEATURE_CODEPAGES_FILE
namespace System.Text
{
using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
// Our input file data structures look like:
//
// Header Structure Looks Like:
// struct NLSPlusHeader
// {
// WORD[16] filename; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // I.e: 3, 2, 0, 0
// WORD count; // 2 bytes = 42 // Number of code page index's that'll follow
// }
//
// Each code page section looks like:
// struct NLSCodePageIndex
// {
// WORD[16] codePageName; // 32 bytes
// WORD codePage; // +2 bytes = 34
// WORD byteCount; // +2 bytes = 36
// DWORD offset; // +4 bytes = 40 // Bytes from beginning of FILE.
// }
//
// Each code page then has its own header
// struct NLSCodePage
// {
// WORD[16] codePageName; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // I.e: 3.2.0.0
// WORD codePage; // 2 bytes = 42
// WORD byteCount; // 2 bytes = 44 // 1 or 2 byte code page (SBCS or DBCS)
// WORD unicodeReplace; // 2 bytes = 46 // default replacement unicode character
// WORD byteReplace; // 2 bytes = 48 // default replacement byte(s)
// BYTE[] data; // data section
// }
[Serializable]
internal abstract class BaseCodePageEncoding : EncodingNLS, ISerializable
{
// Static & Const stuff
internal const String CODE_PAGE_DATA_FILE_NAME = "codepages.nlp";
[NonSerialized]
protected int dataTableCodePage;
// Variables to help us allocate/mark our memory section correctly
[NonSerialized]
protected bool bFlagDataTable = true;
[NonSerialized]
protected int iExtraBytes = 0;
// Our private unicode to bytes best fit array and visa versa.
[NonSerialized]
protected char[] arrayUnicodeBestFit = null;
[NonSerialized]
protected char[] arrayBytesBestFit = null;
// This is used to help ISCII, EUCJP and ISO2022 figure out they're MlangEncodings
[NonSerialized]
protected bool m_bUseMlangTypeForSerialization = false;
[System.Security.SecuritySafeCritical] // static constructors should be safe to call
static BaseCodePageEncoding()
{
}
//
// This is the header for the native data table that we load from CODE_PAGE_DATA_FILE_NAME.
//
// Explicit layout is used here since a syntax like char[16] can not be used in sequential layout.
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct CodePageDataFileHeader
{
[FieldOffset(0)]
internal char TableName; // WORD[16]
[FieldOffset(0x20)]
internal ushort Version; // WORD[4]
[FieldOffset(0x28)]
internal short CodePageCount; // WORD
[FieldOffset(0x2A)]
internal short unused1; // Add a unused WORD so that CodePages is aligned with DWORD boundary.
// Otherwise, 64-bit version will fail.
[FieldOffset(0x2C)]
internal CodePageIndex CodePages; // Start of code page index
}
[StructLayout(LayoutKind.Explicit, Pack=2)]
internal unsafe struct CodePageIndex
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal short CodePage; // WORD
[FieldOffset(0x22)]
internal short ByteCount; // WORD
[FieldOffset(0x24)]
internal int Offset; // DWORD
}
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct CodePageHeader
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal ushort VersionMajor; // WORD
[FieldOffset(0x22)]
internal ushort VersionMinor; // WORD
[FieldOffset(0x24)]
internal ushort VersionRevision;// WORD
[FieldOffset(0x26)]
internal ushort VersionBuild; // WORD
[FieldOffset(0x28)]
internal short CodePage; // WORD
[FieldOffset(0x2a)]
internal short ByteCount; // WORD // 1 or 2 byte code page (SBCS or DBCS)
[FieldOffset(0x2c)]
internal char UnicodeReplace; // WORD // default replacement unicode character
[FieldOffset(0x2e)]
internal ushort ByteReplace; // WORD // default replacement bytes
[FieldOffset(0x30)]
internal short FirstDataWord; // WORD[]
}
// Initialize our global stuff
[SecurityCritical]
unsafe static CodePageDataFileHeader* m_pCodePageFileHeader =
(CodePageDataFileHeader*)GlobalizationAssembly.GetGlobalizationResourceBytePtr(
typeof(CharUnicodeInfo).Assembly, CODE_PAGE_DATA_FILE_NAME);
// Real variables
[NonSerialized]
[SecurityCritical]
unsafe protected CodePageHeader* pCodePage = null;
// Safe handle wrapper around section map view
[System.Security.SecurityCritical] // auto-generated
[NonSerialized]
protected SafeViewOfFileHandle safeMemorySectionHandle = null;
// Safe handle wrapper around mapped file handle
[System.Security.SecurityCritical] // auto-generated
[NonSerialized]
protected SafeFileMappingHandle safeFileMappingHandle = null;
[System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(int codepage) : this(codepage, codepage)
{
}
[System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(int codepage, int dataCodePage) :
base(codepage == 0? Microsoft.Win32.Win32Native.GetACP(): codepage)
{
// Remember number of code page that we'll be using the table for.
dataTableCodePage = dataCodePage;
LoadCodePageTables();
}
// Constructor called by serialization.
[System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
{
// We cannot ever call this, we've proxied ourselved to CodePageEncoding
throw new ArgumentNullException("this");
}
// ISerializable implementation
#if FEATURE_SERIALIZATION
[System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Make sure to get the base stuff too This throws if info is null
SerializeEncoding(info, context);
Contract.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw");
// Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding)
info.AddValue(m_bUseMlangTypeForSerialization ? "m_maxByteSize" : "maxCharSize",
this.IsSingleByte ? 1 : 2);
// Use this class or MLangBaseCodePageEncoding as our deserializer.
info.SetType(m_bUseMlangTypeForSerialization ? typeof(MLangCodePageEncoding) :
typeof(CodePageEncoding));
}
#endif
// We need to load tables for our code page
[System.Security.SecurityCritical] // auto-generated
private unsafe void LoadCodePageTables()
{
CodePageHeader* pCodePage = FindCodePage(dataTableCodePage);
// Make sure we have one
if (pCodePage == null)
{
// Didn't have one
throw new NotSupportedException(
Environment.GetResourceString("NotSupported_NoCodepageData", CodePage));
}
// Remember our code page
this.pCodePage = pCodePage;
// We had it, so load it
LoadManagedCodePage();
}
// Look up the code page pointer
[System.Security.SecurityCritical] // auto-generated
private static unsafe CodePageHeader* FindCodePage(int codePage)
{
// We'll have to loop through all of the m_pCodePageIndex[] items to find our code page, this isn't
// binary or anything so its not monsterously fast.
for (int i = 0; i < m_pCodePageFileHeader->CodePageCount; i++)
{
CodePageIndex* pCodePageIndex = (&(m_pCodePageFileHeader->CodePages)) + i;
if (pCodePageIndex->CodePage == codePage)
{
// Found it!
CodePageHeader* pCodePage =
(CodePageHeader*)((byte*)m_pCodePageFileHeader + pCodePageIndex->Offset);
return pCodePage;
}
}
// Couldn't find it
return null;
}
// Get our code page byte count
[System.Security.SecurityCritical] // auto-generated
internal static unsafe int GetCodePageByteSize(int codePage)
{
// Get our code page info
CodePageHeader* pCodePage = FindCodePage(codePage);
// If null return 0
if (pCodePage == null)
return 0;
Contract.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2,
"[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePage->ByteCount + ") in table");
// Return what it says for byte count
return pCodePage->ByteCount;
}
// We have a managed code page entry, so load our tables
[System.Security.SecurityCritical]
protected abstract unsafe void LoadManagedCodePage();
// Allocate memory to load our code page
[System.Security.SecurityCritical] // auto-generated
protected unsafe byte* GetSharedMemory(int iSize)
{
// Build our name
String strName = GetMemorySectionName();
IntPtr mappedFileHandle;
// This gets shared memory for our map. If its can't, it gives us clean memory.
Byte *pMemorySection = EncodingTable.nativeCreateOpenFileMapping(strName, iSize, out mappedFileHandle);
Contract.Assert(pMemorySection != null,
"[BaseCodePageEncoding.GetSharedMemory] Expected non-null memory section to be opened");
// If that failed, we have to die.
if (pMemorySection == null)
throw new OutOfMemoryException(
Environment.GetResourceString("Arg_OutOfMemoryException"));
// if we have null file handle. this means memory was allocated after
// failing to open the mapped file.
if (mappedFileHandle != IntPtr.Zero)
{
safeMemorySectionHandle = new SafeViewOfFileHandle((IntPtr) pMemorySection, true);
safeFileMappingHandle = new SafeFileMappingHandle(mappedFileHandle, true);
}
return pMemorySection;
}
[System.Security.SecurityCritical] // auto-generated
protected unsafe virtual String GetMemorySectionName()
{
int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage;
String strName = String.Format(CultureInfo.InvariantCulture, "NLS_CodePage_{0}_{1}_{2}_{3}_{4}",
iUseCodePage, this.pCodePage->VersionMajor, this.pCodePage->VersionMinor,
this.pCodePage->VersionRevision, this.pCodePage->VersionBuild);
return strName;
}
[System.Security.SecurityCritical]
protected abstract unsafe void ReadBestFitTable();
[System.Security.SecuritySafeCritical]
internal override char[] GetBestFitUnicodeToBytesData()
{
// Read in our best fit table if necessary
if (arrayUnicodeBestFit == null) ReadBestFitTable();
Contract.Assert(arrayUnicodeBestFit != null,
"[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit");
// Normally we don't have any best fit data.
return arrayUnicodeBestFit;
}
[System.Security.SecuritySafeCritical]
internal override char[] GetBestFitBytesToUnicodeData()
{
// Read in our best fit table if necessary
if (arrayBytesBestFit == null) ReadBestFitTable();
Contract.Assert(arrayBytesBestFit != null,
"[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit");
// Normally we don't have any best fit data.
return arrayBytesBestFit;
}
// During the AppDomain shutdown the Encoding class may already finalized and the memory section
// is invalid. so we detect that by validating the memory section handle then re-initialize the memory
// section by calling LoadManagedCodePage() method and eventually the mapped file handle and
// the memory section pointer will get finalized one more time.
[System.Security.SecurityCritical] // auto-generated
internal unsafe void CheckMemorySection()
{
if (safeMemorySectionHandle != null && safeMemorySectionHandle.DangerousGetHandle() == IntPtr.Zero)
{
LoadManagedCodePage();
}
}
}
}
#endif // FEATURE_CODEPAGES_FILE
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using SampleMetadata;
using Xunit;
namespace System.Reflection.Tests
{
public static partial class FieldTests
{
[Fact]
public unsafe static void TestFields1()
{
TestField1Worker(typeof(ClassWithFields1<>).Project());
TestField1Worker(typeof(ClassWithFields1<int>).Project());
TestField1Worker(typeof(ClassWithFields1<string>).Project());
}
private static void TestField1Worker(Type t)
{
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
FieldInfo[] fields = t.GetFields(bf);
foreach (FieldInfo f in fields)
{
Assert.Equal(t, f.DeclaringType);
Assert.Equal(t, f.ReflectedType);
Assert.Equal(t.Module, f.Module);
}
Type theT = t.GetGenericArguments()[0];
{
FieldInfo f = fields.Single(f1 => f1.Name == "ConstField1");
Assert.Equal(FieldAttributes.Private | FieldAttributes.Static | FieldAttributes.Literal | FieldAttributes.HasDefault, f.Attributes);
Assert.Equal(typeof(int).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "Field1");
Assert.Equal(FieldAttributes.Public, f.Attributes);
Assert.Equal(typeof(int).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "Field2");
Assert.Equal(FieldAttributes.Family, f.Attributes);
Assert.Equal(typeof(GenericClass2<int, string>).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "Field3");
Assert.Equal(FieldAttributes.Private, f.Attributes);
Assert.Equal(typeof(Interface1).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "Field4");
Assert.Equal(FieldAttributes.Assembly, f.Attributes);
Assert.Equal(typeof(int[]).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "Field5");
Assert.Equal(FieldAttributes.FamORAssem, f.Attributes);
Assert.Equal(typeof(int*).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "Field6");
Assert.Equal(FieldAttributes.FamANDAssem, f.Attributes);
Assert.Equal(theT, f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "ReadOnlyField1");
Assert.Equal(FieldAttributes.Private | FieldAttributes.InitOnly, f.Attributes);
Assert.Equal(typeof(IEnumerable<int>).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "SField1");
Assert.Equal(FieldAttributes.Static | FieldAttributes.Public, f.Attributes);
Assert.Equal(typeof(byte).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "SField2");
Assert.Equal(FieldAttributes.Static | FieldAttributes.Family, f.Attributes);
Assert.Equal(typeof(GenericClass2<,>).Project().MakeGenericType(typeof(int).Project(), theT), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "SField3");
Assert.Equal(FieldAttributes.Static | FieldAttributes.Private, f.Attributes);
Assert.Equal(typeof(Interface1).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "SField4");
Assert.Equal(FieldAttributes.Static | FieldAttributes.Assembly, f.Attributes);
Assert.Equal(typeof(int[,]).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "SField5");
Assert.Equal(FieldAttributes.Static | FieldAttributes.FamORAssem, f.Attributes);
Assert.Equal(typeof(int*).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "SField6");
Assert.Equal(FieldAttributes.Static | FieldAttributes.FamANDAssem, f.Attributes);
Assert.Equal(theT, f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "VolatileField1");
Assert.Equal(FieldAttributes.Public, f.Attributes);
Assert.Equal(typeof(int).Project(), f.FieldType);
}
}
[Fact]
public unsafe static void TestLiteralFields1()
{
Type t = typeof(ClassWithLiteralFields).Project();
FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly);
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.NotLiteral));
Assert.Throws<InvalidOperationException>(() => f.GetRawConstantValue());
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.NotLiteralJustReadOnly));
Assert.Throws<InvalidOperationException>(() => f.GetRawConstantValue());
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitBool1));
object o = f.GetRawConstantValue();
Assert.True(o is bool);
Assert.Equal(ClassWithLiteralFields.LitBool1, (bool)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitBool2));
object o = f.GetRawConstantValue();
Assert.True(o is bool);
Assert.Equal(ClassWithLiteralFields.LitBool2, (bool)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitChar1));
object o = f.GetRawConstantValue();
Assert.True(o is char);
Assert.Equal(ClassWithLiteralFields.LitChar1, (char)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitChar2));
object o = f.GetRawConstantValue();
Assert.True(o is char);
Assert.Equal(ClassWithLiteralFields.LitChar2, (char)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitChar3));
object o = f.GetRawConstantValue();
Assert.True(o is char);
Assert.Equal(ClassWithLiteralFields.LitChar3, (char)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitByte1));
object o = f.GetRawConstantValue();
Assert.True(o is byte);
Assert.Equal(ClassWithLiteralFields.LitByte1, (byte)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitByte2));
object o = f.GetRawConstantValue();
Assert.True(o is byte);
Assert.Equal(ClassWithLiteralFields.LitByte2, (byte)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitByte3));
object o = f.GetRawConstantValue();
Assert.True(o is byte);
Assert.Equal(ClassWithLiteralFields.LitByte3, (byte)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitSByte1));
object o = f.GetRawConstantValue();
Assert.True(o is sbyte);
Assert.Equal(ClassWithLiteralFields.LitSByte1, (sbyte)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitSByte2));
object o = f.GetRawConstantValue();
Assert.True(o is sbyte);
Assert.Equal(ClassWithLiteralFields.LitSByte2, (sbyte)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitSByte3));
object o = f.GetRawConstantValue();
Assert.True(o is sbyte);
Assert.Equal(ClassWithLiteralFields.LitSByte3, (sbyte)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitShort1));
object o = f.GetRawConstantValue();
Assert.True(o is short);
Assert.Equal(ClassWithLiteralFields.LitShort1, (short)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitShort2));
object o = f.GetRawConstantValue();
Assert.True(o is short);
Assert.Equal(ClassWithLiteralFields.LitShort2, (short)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitShort3));
object o = f.GetRawConstantValue();
Assert.True(o is short);
Assert.Equal(ClassWithLiteralFields.LitShort3, (short)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitUShort1));
object o = f.GetRawConstantValue();
Assert.True(o is ushort);
Assert.Equal(ClassWithLiteralFields.LitUShort1, (ushort)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitUShort2));
object o = f.GetRawConstantValue();
Assert.True(o is ushort);
Assert.Equal(ClassWithLiteralFields.LitUShort2, (ushort)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitUShort3));
object o = f.GetRawConstantValue();
Assert.True(o is ushort);
Assert.Equal(ClassWithLiteralFields.LitUShort3, (ushort)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitInt1));
object o = f.GetRawConstantValue();
Assert.True(o is int);
Assert.Equal(ClassWithLiteralFields.LitInt1, (int)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitInt2));
object o = f.GetRawConstantValue();
Assert.True(o is int);
Assert.Equal(ClassWithLiteralFields.LitInt2, (int)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitInt3));
object o = f.GetRawConstantValue();
Assert.True(o is int);
Assert.Equal(ClassWithLiteralFields.LitInt3, (int)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitUInt1));
object o = f.GetRawConstantValue();
Assert.True(o is uint);
Assert.Equal(ClassWithLiteralFields.LitUInt1, (uint)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitUInt2));
object o = f.GetRawConstantValue();
Assert.True(o is uint);
Assert.Equal(ClassWithLiteralFields.LitUInt2, (uint)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitUInt3));
object o = f.GetRawConstantValue();
Assert.True(o is uint);
Assert.Equal(ClassWithLiteralFields.LitUInt3, (uint)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitLong1));
object o = f.GetRawConstantValue();
Assert.True(o is long);
Assert.Equal(ClassWithLiteralFields.LitLong1, (long)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitLong2));
object o = f.GetRawConstantValue();
Assert.True(o is long);
Assert.Equal(ClassWithLiteralFields.LitLong2, (long)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitLong3));
object o = f.GetRawConstantValue();
Assert.True(o is long);
Assert.Equal(ClassWithLiteralFields.LitLong3, (long)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitULong1));
object o = f.GetRawConstantValue();
Assert.True(o is ulong);
Assert.Equal(ClassWithLiteralFields.LitULong1, (ulong)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitULong2));
object o = f.GetRawConstantValue();
Assert.True(o is ulong);
Assert.Equal(ClassWithLiteralFields.LitULong2, (ulong)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitULong3));
object o = f.GetRawConstantValue();
Assert.True(o is ulong);
Assert.Equal(ClassWithLiteralFields.LitULong3, (ulong)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitSingle1));
object o = f.GetRawConstantValue();
Assert.True(o is float);
Assert.Equal(ClassWithLiteralFields.LitSingle1, (float)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitSingle2));
object o = f.GetRawConstantValue();
Assert.True(o is float);
Assert.Equal(ClassWithLiteralFields.LitSingle2, (float)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitDouble1));
object o = f.GetRawConstantValue();
Assert.True(o is double);
Assert.Equal(ClassWithLiteralFields.LitDouble1, (double)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitDouble2));
object o = f.GetRawConstantValue();
Assert.True(o is double);
Assert.Equal(ClassWithLiteralFields.LitDouble2, (double)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitString1));
object o = f.GetRawConstantValue();
Assert.True(o is string);
Assert.Equal(ClassWithLiteralFields.LitString1, (string)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitString2));
object o = f.GetRawConstantValue();
Assert.True(o == null);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitObject));
object o = f.GetRawConstantValue();
Assert.True(o == null);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitMyColor1));
object o = f.GetRawConstantValue();
Assert.True(o is int);
Assert.Equal((int)(ClassWithLiteralFields.LitMyColor1), (int)o);
}
}
[Fact]
public unsafe static void TestCustomModifiers1()
{
using (TypeLoader tl = new TypeLoader("mscorlib"))
{
tl.Resolving +=
delegate (TypeLoader sender, AssemblyName name)
{
if (name.Name == "mscorlib")
return tl.LoadFromStream(TestUtils.CreateStreamForCoreAssembly());
return null;
};
Assembly a = tl.LoadFromByteArray(TestData.s_CustomModifiersImage);
Type t = a.GetType("N", throwOnError: true);
Type reqA = a.GetType("ReqA", throwOnError: true);
Type reqB = a.GetType("ReqB", throwOnError: true);
Type reqC = a.GetType("ReqC", throwOnError: true);
Type optA = a.GetType("OptA", throwOnError: true);
Type optB = a.GetType("OptB", throwOnError: true);
Type optC = a.GetType("OptC", throwOnError: true);
FieldInfo f = t.GetField("MyField");
Type[] req = f.GetRequiredCustomModifiers();
Type[] opt = f.GetOptionalCustomModifiers();
Assert.Equal<Type>(new Type[] { reqA, reqB, reqC }, req);
Assert.Equal<Type>(new Type[] { optA, optB, optC }, opt);
TestUtils.AssertNewObjectReturnedEachTime(() => f.GetRequiredCustomModifiers());
TestUtils.AssertNewObjectReturnedEachTime(() => f.GetOptionalCustomModifiers());
}
}
[Fact]
public unsafe static void TestCustomModifiers2()
{
using (TypeLoader tl = new TypeLoader("mscorlib"))
{
tl.Resolving +=
delegate (TypeLoader sender, AssemblyName name)
{
if (name.Name == "mscorlib")
return tl.LoadFromStream(TestUtils.CreateStreamForCoreAssembly());
return null;
};
Assembly a = tl.LoadFromByteArray(TestData.s_CustomModifiersImage);
Type t = a.GetType("N", throwOnError: true);
Type reqA = a.GetType("ReqA", throwOnError: true);
Type reqB = a.GetType("ReqB", throwOnError: true);
Type reqC = a.GetType("ReqC", throwOnError: true);
Type optA = a.GetType("OptA", throwOnError: true);
Type optB = a.GetType("OptB", throwOnError: true);
Type optC = a.GetType("OptC", throwOnError: true);
FieldInfo f = t.GetField("MyArrayField");
Type[] req = f.GetRequiredCustomModifiers();
Type[] opt = f.GetOptionalCustomModifiers();
Assert.Equal<Type>(new Type[] { reqB }, req);
Assert.Equal<Type>(new Type[] { }, opt);
TestUtils.AssertNewObjectReturnedEachTime(() => f.GetRequiredCustomModifiers());
TestUtils.AssertNewObjectReturnedEachTime(() => f.GetOptionalCustomModifiers());
}
}
}
}
| |
// 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.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass001.regclass001;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;
public class MyClass
{
public int Field = 0;
}
public struct MyStruct
{
public int Number;
}
public enum MyEnum
{
First = 1,
Second = 2,
Third = 3
}
public class MemberClass
{
public string Property_string
{
set;
get;
}
public MyClass Property_MyClass
{
get;
set;
}
public MyStruct Property_MyStruct
{
set;
get;
}
public MyEnum Property_MyEnum
{
set;
private get;
}
public short Property_short
{
set;
protected get;
}
public ulong Property_ulong
{
set;
protected internal get;
}
public char Property_char
{
private set;
get;
}
public bool Property_bool
{
protected set;
get;
}
public decimal Property_decimal
{
protected internal set;
get;
}
public MyStruct? Property_MyStructNull
{
set;
get;
}
public MyEnum? Property_MyEnumNull
{
set;
private get;
}
public short? Property_shortNull
{
set;
get;
}
public ulong? Property_ulongNull
{
set;
protected internal get;
}
public char? Property_charNull
{
private set;
get;
}
public bool? Property_boolNull
{
protected set;
get;
}
public decimal? Property_decimalNull
{
protected internal set;
get;
}
public string[] Property_stringArr
{
set;
get;
}
public MyClass[] Property_MyClassArr
{
set;
get;
}
public MyStruct[] Property_MyStructArr
{
get;
set;
}
public MyEnum[] Property_MyEnumArr
{
set;
private get;
}
public short[] Property_shortArr
{
set;
protected get;
}
public ulong[] Property_ulongArr
{
set;
protected internal get;
}
public char[] Property_charArr
{
private set;
get;
}
public bool[] Property_boolArr
{
protected set;
get;
}
public decimal[] Property_decimalArr
{
protected internal set;
get;
}
public MyStruct?[] Property_MyStructNullArr
{
set;
get;
}
public MyEnum?[] Property_MyEnumNullArr
{
set;
private get;
}
public short?[] Property_shortNullArr
{
set;
protected get;
}
public ulong?[] Property_ulongNullArr
{
set;
protected internal get;
}
public char?[] Property_charNullArr
{
private set;
get;
}
public bool?[] Property_boolNullArr
{
protected set;
get;
}
public decimal?[] Property_decimalNullArr
{
protected internal set;
get;
}
public float Property_Float
{
get;
set;
}
public float?[] Property_FloatNullArr
{
get;
set;
}
public dynamic Property_Dynamic
{
get;
set;
}
public static string Property_stringStatic
{
set;
get;
}
// Move declarations to the call site
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass001.regclass001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass001.regclass001;
// <Title> Tests regular class auto property used in generic method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t1 = new Test();
return t1.TestGetMethod<long>(1, new MemberClass()) + t1.TestSetMethod<Test, string>(string.Empty, new MemberClass()) == 0 ? 0 : 1;
}
public int TestGetMethod<T>(T t, MemberClass mc)
{
mc.Property_string = "Test";
dynamic dy = mc;
if ((string)dy.Property_string != "Test")
return 1;
else
return 0;
}
public int TestSetMethod<U, V>(V v, MemberClass mc)
{
dynamic dy = mc;
dy.Property_string = "Test";
mc = dy; //because we might change the property on a boxed version of it if MemberClass is a struct
if (mc.Property_string != "Test")
return 1;
else
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass003.regclass003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass003.regclass003;
// <Title> Tests regular class auto property used in variable initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
string[] bas = new string[]
{
"Test", string.Empty, null
}
;
MemberClass mc = new MemberClass();
mc.Property_stringArr = bas;
dynamic dy = mc;
string[] loc = dy.Property_stringArr;
if (ReferenceEquals(bas, loc) && loc[0] == "Test" && loc[1] == string.Empty && loc[2] == null)
{
return 0;
}
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass004.regclass004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass004.regclass004;
// <Title> Tests regular class auto property used in implicitly-typed array initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc1 = new MemberClass();
MemberClass mc2 = new MemberClass();
mc1.Property_MyStructNull = null;
mc2.Property_MyStructNull = new MyStruct()
{
Number = 1
}
;
dynamic dy1 = mc1;
dynamic dy2 = mc2;
var loc = new MyStruct?[]
{
(MyStruct? )dy1.Property_MyStructNull, (MyStruct? )dy2.Property_MyStructNull
}
;
if (loc.Length == 2 && loc[0] == null && loc[1].Value.Number == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass005.regclass005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass005.regclass005;
// <Title> Tests regular class auto property used in operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc1 = new MemberClass();
MemberClass mc2 = new MemberClass();
mc1.Property_string = "a";
mc2.Property_string = "b";
dynamic dy1 = mc1;
dynamic dy2 = mc2;
string s = (string)dy1.Property_string + (string)dy2.Property_string;
if (s == "ab")
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass006.regclass006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass006.regclass006;
// <Title> Tests regular class auto property used in null coalescing operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.Property_MyStructArr = new MyStruct[]
{
new MyStruct()
{
Number = 0
}
, new MyStruct()
{
Number = 1
}
}
;
dynamic dy = mc;
string s1 = ((string)dy.Property_string) ?? string.Empty;
mc.Property_string = "Test";
dy = mc;
MyStruct[] b1 = ((MyStruct[])dy.Property_MyStructArr) ?? (new MyStruct[1]);
MyStruct[] b2 = ((MyStruct[])dy.Property_MyStructArr) ?? (new MyStruct[1]);
string s2 = ((string)dy.Property_string) ?? string.Empty;
if (b1.Length == 2 && s1 == string.Empty && b2.Length == 2 && s2 == "Test")
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass007.regclass007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass007.regclass007;
// <Title> Tests regular class auto property used in destructor.</Title>
// <Description>
// On IA64 the GC.WaitForPendingFinalizers() does not actually work...
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Runtime.CompilerServices;
public class Test
{
private static string s_field;
public static object locker = new object();
~Test()
{
lock (locker)
{
MemberClass mc = new MemberClass();
mc.Property_string = "Test";
dynamic dy = mc;
s_field = dy.Property_string;
}
}
public void Foo()
{
}
private static int Verify()
{
lock (Test.locker)
{
if (Test.s_field != "Test")
{
return 1;
}
}
return 0;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void RequireLifetimesEnded()
{
Test t = new Test();
Test.s_field = "Field";
t.Foo();
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
RequireLifetimesEnded();
GC.Collect();
GC.WaitForPendingFinalizers();
// If move the code in Verify() to here, the finalizer will only be executed after exited Main
return Verify();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass008.regclass008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass008.regclass008;
// <Title> Tests regular class auto property used in extension method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int a1 = 10;
MyStruct ms1 = a1.TestSetMyStruct();
MyStruct ms2 = a1.TestGetMyStruct();
if (ms1.Number == 10 && ms2.Number == 10)
return 0;
return 1;
}
}
public static class Extension
{
public static MyStruct TestSetMyStruct(this int i)
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
dy.Property_MyStruct = new MyStruct()
{
Number = i
}
;
mc = dy; //because MC might be a struct
return mc.Property_MyStruct;
}
public static MyStruct TestGetMyStruct(this int i)
{
MemberClass mc = new MemberClass();
mc.Property_MyStruct = new MyStruct()
{
Number = i
}
;
dynamic dy = mc;
return (MyStruct)dy.Property_MyStruct;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass009.regclass009
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass009.regclass009;
// <Title> Tests regular class auto property used in variable initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
char value = (char)dy.Property_char;
if (value == default(char))
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass010.regclass010
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass010.regclass010;
// <Title> Tests regular class auto property used in array initializer list.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
bool[] array = new bool[]
{
(bool)dy.Property_bool, true
}
;
if (array.Length == 2 && array[0] == false && array[1] == true)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass014.regclass014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass014.regclass014;
// <Title> Tests regular class auto property used in for loop body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic mc = new MemberClass();
ulong[] array = new ulong[]
{
1L, 2L, 3L, ulong.MinValue, ulong.MaxValue
}
;
for (int i = 0; i < array.Length; i++)
{
mc.Property_ulong = array[i];
}
ulong x = (ulong)mc.Property_ulong;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass015.regclass015
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass015.regclass015;
// <Title> Tests regular class auto property used in foreach expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.Property_MyClassArr = new MyClass[]
{
null, new MyClass()
{
Field = -1
}
}
;
dynamic dy = mc;
List<MyClass> list = new List<MyClass>();
foreach (MyClass myclass in dy.Property_MyClassArr)
{
list.Add(myclass);
}
if (list.Count == 2 && list[0] == null && list[1].Field == -1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass016.regclass016
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass016.regclass016;
// <Title> Tests regular class auto property used in while body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test : MemberClass
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test mc = new Test();
dynamic dy = mc;
short a = 0;
short v = 0;
while (a < 10)
{
v = a;
dy.Property_shortNull = a;
a = (short)((short)dy.Property_shortNull + 1);
if (a != v + 1)
return 1;
}
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass018.regclass018
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass018.regclass018;
// <Title> Tests regular class auto property used in uncheck expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
ulong result = 1;
dy.Property_ulongNull = ulong.MaxValue;
result = unchecked(dy.Property_ulongNull + 1); //0
return (int)result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass019.regclass019
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass019.regclass019;
// <Title> Tests regular class auto property used in static constructor.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static char? s_charValue = 'a';
static Test()
{
dynamic dy = new MemberClass();
s_charValue = dy.Property_charNull;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (Test.s_charValue == null)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass020.regclass020
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass020.regclass020;
// <Title> Tests regular class auto property used in variable named dynamic.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dynamic = new MemberClass();
if (dynamic.Property_boolNull == null)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass022.regclass022
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass022.regclass022;
// <Title> Tests regular class auto property used in field initailizer outside of constructor.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static dynamic s_dy = new MemberClass();
private char[] _result = s_dy.Property_charArr;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
if (t._result == null)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass023.regclass023
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass023.regclass023;
// <Title> Tests regular class auto property used in static generic method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return TestMethod<Test>();
}
private static int TestMethod<T>()
{
dynamic dy = new MemberClass();
dy.Property_MyEnumArr = new MyEnum[0];
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass024.regclass024
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass024.regclass024;
// <Title> Tests regular class auto property used in static generic method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return TestMethod<int>();
}
private static int TestMethod<T>()
{
dynamic dy = new MemberClass();
dy.Property_shortArr = new short[2];
try
{
short[] result = dy.Property_shortArr; // protected
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_shortArr"))
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass025.regclass025
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass025.regclass025;
// <Title> Tests regular class auto property used in inside#if, #else block.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass();
ulong[] array = null;
dy.Property_ulongArr = new ulong[]
{
0, 1
}
;
#if MS
array = new ulong[] { (ulong)dy.Property_ulong };
#else
try
{
array = dy.Property_ulongArr;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_ulongArr"))
return 0;
else
{
System.Console.WriteLine(e);
return 1;
}
}
#endif
// different case actually
if (array.Length == 2 && array[0] == 0 && array[1] == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass026.regclass026
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass026.regclass026;
// <Title> Tests regular class auto property used in regular method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (new Test().TestMethod())
return 0;
return 1;
}
private bool TestMethod()
{
dynamic dy = new MemberClass();
bool[] result = dy.Property_boolArr;
return result == null;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass027.regclass027
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass027.regclass027;
// <Title> Tests regular class auto property used in using block.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.IO;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.Property_decimalArr = new decimal[]
{
1M, 1.1M
}
;
dynamic dy = mc;
using (MemoryStream ms = new MemoryStream())
{
if (((decimal[])dy.Property_decimalArr)[0] != 1M && ((decimal[])dy.Property_decimalArr)[1] != 1.1M)
return 1;
}
using (MemoryStream ms = new MemoryStream())
{
dy.Property_decimalArr = new decimal[]
{
10M
}
;
((decimal[])dy.Property_decimalArr)[0] = 10.01M;
}
if (mc.Property_decimalArr.Length == 1 && mc.Property_decimalArr[0] == 10.01M)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass028.regclass028
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass028.regclass028;
// <Title> Tests regular class auto property used in ternary operator expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
return t.TestGet() + t.TestSet();
}
public int TestGet()
{
MemberClass mc = new MemberClass();
mc.Property_MyStructNullArr = new MyStruct?[]
{
null, new MyStruct()
{
Number = 10
}
}
;
dynamic dy = mc;
return (int)dy.Property_MyStructNullArr.Length == 2 ? 0 : 1;
}
public int TestSet()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
dy.Property_MyStructNullArr = new MyStruct?[]
{
null, new MyStruct()
{
Number = 10
}
}
;
mc = dy;
return (int)dy.Property_MyStructNullArr.Length == 2 ? 0 : 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass029.regclass029
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass029.regclass029;
// <Title> Tests regular class auto property used in null coalescing operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass();
try
{
MyEnum?[] result = dy.Property_MyEnumNullArr ?? new MyEnum?[1]; //private, should have exception
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_MyEnumNullArr"))
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass030.regclass030
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass030.regclass030;
// <Title> Tests regular class auto property used in constructor.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static int Return;
public Test()
{
dynamic dy = new MemberClass();
try
{
// public for struct
short?[] result = dy.Property_shortNullArr; //protected, should have exception
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_shortNullArr"))
Test.Return = 0;
else
Test.Return = 1;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
return Test.Return;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass031.regclass031
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass031.regclass031;
// <Title> Tests regular class auto property used in null coalescing operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
ulong?[] result1 = dy.Property_ulongNullArr ?? new ulong?[1];
if (result1.Length != 1 || dy.Property_ulongNullArr != null)
return 1;
dy.Property_ulongNullArr = dy.Property_ulongNullArr ?? new ulong?[0];
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass032.regclass032
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass032.regclass032;
// <Title> Tests regular class auto property used in static variable.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static dynamic s_dy = new MemberClass();
private static char?[] s_result = s_dy.Property_charNullArr;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (s_result == null)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass034.regclass034
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass034.regclass034;
// <Title> Tests regular class auto property used in switch section statement.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
int result = int.MaxValue;
try
{
dy.Property_decimalNullArr = new decimal?[]
{
int.MinValue
}
;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleSetter, e.Message, "MemberClass.Property_decimalNullArr"))
result = int.MaxValue;
}
switch (result)
{
case int.MaxValue:
try
{
result = (int)((decimal?[])dy.Property_decimalNullArr)[0];
}
catch (System.NullReferenceException)
{
result = int.MinValue;
}
break;
default:
break;
}
if (result == int.MinValue)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass035.regclass035
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass035.regclass035;
// <Title> Tests regular class auto property used in switch default section statement.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
int result = 4;
dy.Property_Float = 4;
switch (result)
{
case 4:
dy.Property_Float = float.NaN;
break;
default:
result = (int)dy.Property_Float;
break;
}
if (result == 4)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass036.regclass036
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass036.regclass036;
// <Title> Tests regular class auto property used in foreach body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
dy.Property_FloatNullArr = new float?[]
{
float.Epsilon, float.MaxValue, float.MinValue, float.NaN, float.NegativeInfinity, float.PositiveInfinity
}
;
if (dy.Property_FloatNullArr.Length == 6 && dy.Property_FloatNullArr[0] == float.Epsilon && dy.Property_FloatNullArr[1] == float.MaxValue && dy.Property_FloatNullArr[2] == float.MinValue && float.IsNaN((float)dy.Property_FloatNullArr[3]) && float.IsNegativeInfinity((float)dy.Property_FloatNullArr[4]) && float.IsPositiveInfinity((float)dy.Property_FloatNullArr[5]))
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass037.regclass037
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass037.regclass037;
// <Title> Tests regular class auto property used in static method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass.Property_stringStatic = "Test";
dynamic dynamic = MemberClass.Property_stringStatic;
if ((string)dynamic == "Test")
return 0;
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.
// This file defines an internal class used to throw exceptions in BCL code.
// The main purpose is to reduce code size.
//
// The old way to throw an exception generates quite a lot IL code and assembly code.
// Following is an example:
// C# source
// throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
// IL code:
// IL_0003: ldstr "key"
// IL_0008: ldstr "ArgumentNull_Key"
// IL_000d: call string System.Environment::GetResourceString(string)
// IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string)
// IL_0017: throw
// which is 21bytes in IL.
//
// So we want to get rid of the ldstr and call to Environment.GetResource in IL.
// In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the
// argument name and resource name in a small integer. The source code will be changed to
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key);
//
// The IL code will be 7 bytes.
// IL_0008: ldc.i4.4
// IL_0009: ldc.i4.4
// IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument)
// IL_000f: ldarg.0
//
// This will also reduce the Jitted code size a lot.
//
// It is very important we do this for generic classes because we can easily generate the same code
// multiple times for different instantiation.
//
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace System
{
[StackTraceHidden]
internal static class ThrowHelper
{
internal static void ThrowArrayTypeMismatchException()
{
throw new ArrayTypeMismatchException();
}
internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeWithPointersNotSupported, targetType));
}
internal static void ThrowIndexOutOfRangeException()
{
throw new IndexOutOfRangeException();
}
internal static void ThrowArgumentOutOfRangeException()
{
throw new ArgumentOutOfRangeException();
}
internal static void ThrowArgumentException_DestinationTooShort()
{
throw new ArgumentException(SR.Argument_DestinationTooShort);
}
internal static void ThrowArgumentException_OverlapAlignmentMismatch()
{
throw new ArgumentException(SR.Argument_OverlapAlignmentMismatch);
}
internal static void ThrowArgumentException_CannotExtractScalar(ExceptionArgument argument)
{
throw GetArgumentException(ExceptionResource.Argument_CannotExtractScalar, argument);
}
internal static void ThrowArgumentOutOfRange_IndexException()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.index,
ExceptionResource.ArgumentOutOfRange_Index);
}
internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.index,
ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
internal static void ThrowValueArgumentOutOfRange_NeedNonNegNumException()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.value,
ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.length,
ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex,
ExceptionResource.ArgumentOutOfRange_Index);
}
internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count()
{
throw GetArgumentOutOfRangeException(ExceptionArgument.count,
ExceptionResource.ArgumentOutOfRange_Count);
}
internal static void ThrowWrongKeyTypeArgumentException<T>(T key, Type targetType)
{
// Generic key to move the boxing to the right hand side of throw
throw GetWrongKeyTypeArgumentException((object)key, targetType);
}
internal static void ThrowWrongValueTypeArgumentException<T>(T value, Type targetType)
{
// Generic key to move the boxing to the right hand side of throw
throw GetWrongValueTypeArgumentException((object)value, targetType);
}
private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key)
{
return new ArgumentException(SR.Format(SR.Argument_AddingDuplicateWithKey, key));
}
internal static void ThrowAddingDuplicateWithKeyArgumentException<T>(T key)
{
// Generic key to move the boxing to the right hand side of throw
throw GetAddingDuplicateWithKeyArgumentException((object)key);
}
internal static void ThrowKeyNotFoundException<T>(T key)
{
// Generic key to move the boxing to the right hand side of throw
throw GetKeyNotFoundException((object)key);
}
internal static void ThrowArgumentException(ExceptionResource resource)
{
throw GetArgumentException(resource);
}
internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument)
{
throw GetArgumentException(resource, argument);
}
private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument)
{
return new ArgumentNullException(GetArgumentName(argument));
}
internal static void ThrowArgumentNullException(ExceptionArgument argument)
{
throw GetArgumentNullException(argument);
}
internal static void ThrowArgumentNullException(ExceptionResource resource)
{
throw new ArgumentNullException(GetResourceString(resource));
}
internal static void ThrowArgumentNullException(ExceptionArgument argument, ExceptionResource resource)
{
throw new ArgumentNullException(GetArgumentName(argument), GetResourceString(resource));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument)
{
throw new ArgumentOutOfRangeException(GetArgumentName(argument));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
{
throw GetArgumentOutOfRangeException(argument, resource);
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource)
{
throw GetArgumentOutOfRangeException(argument, paramNumber, resource);
}
internal static void ThrowInvalidOperationException()
{
throw new InvalidOperationException();
}
internal static void ThrowInvalidOperationException(ExceptionResource resource)
{
throw GetInvalidOperationException(resource);
}
internal static void ThrowInvalidOperationException_OutstandingReferences()
{
throw new InvalidOperationException(SR.Memory_OutstandingReferences);
}
internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e)
{
throw new InvalidOperationException(GetResourceString(resource), e);
}
internal static void ThrowSerializationException(ExceptionResource resource)
{
throw new SerializationException(GetResourceString(resource));
}
internal static void ThrowSecurityException(ExceptionResource resource)
{
throw new System.Security.SecurityException(GetResourceString(resource));
}
internal static void ThrowRankException(ExceptionResource resource)
{
throw new RankException(GetResourceString(resource));
}
internal static void ThrowNotSupportedException(ExceptionResource resource)
{
throw new NotSupportedException(GetResourceString(resource));
}
internal static void ThrowUnauthorizedAccessException(ExceptionResource resource)
{
throw new UnauthorizedAccessException(GetResourceString(resource));
}
internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource)
{
throw new ObjectDisposedException(objectName, GetResourceString(resource));
}
internal static void ThrowObjectDisposedException(ExceptionResource resource)
{
throw new ObjectDisposedException(null, GetResourceString(resource));
}
internal static void ThrowNotSupportedException()
{
throw new NotSupportedException();
}
internal static void ThrowAggregateException(List<Exception> exceptions)
{
throw new AggregateException(exceptions);
}
internal static void ThrowOutOfMemoryException()
{
throw new OutOfMemoryException();
}
internal static void ThrowArgumentException_Argument_InvalidArrayType()
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
internal static void ThrowInvalidOperationException_InvalidOperation_EnumNotStarted()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
}
internal static void ThrowInvalidOperationException_InvalidOperation_EnumEnded()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
}
internal static void ThrowInvalidOperationException_EnumCurrent(int index)
{
throw GetInvalidOperationException_EnumCurrent(index);
}
internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen()
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
internal static void ThrowInvalidOperationException_InvalidOperation_NoValue()
{
throw new InvalidOperationException(SR.InvalidOperation_NoValue);
}
internal static void ThrowInvalidOperationException_ConcurrentOperationsNotSupported()
{
throw new InvalidOperationException(SR.InvalidOperation_ConcurrentOperationsNotSupported);
}
internal static void ThrowInvalidOperationException_HandleIsNotInitialized()
{
throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotInitialized);
}
internal static void ThrowInvalidOperationException_HandleIsNotPinned()
{
throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotPinned);
}
internal static void ThrowArraySegmentCtorValidationFailedExceptions(Array array, int offset, int count)
{
throw GetArraySegmentCtorValidationFailedException(array, offset, count);
}
internal static void ThrowFormatException_BadFormatSpecifier()
{
throw new FormatException(SR.Argument_BadFormatSpecifier);
}
internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge()
{
throw new ArgumentOutOfRangeException("precision", SR.Format(SR.Argument_PrecisionTooLarge, StandardFormat.MaxPrecision));
}
internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit()
{
throw new ArgumentOutOfRangeException("symbol", SR.Argument_BadFormatSpecifier);
}
private static Exception GetArraySegmentCtorValidationFailedException(Array array, int offset, int count)
{
if (array == null)
return new ArgumentNullException(nameof(array));
if (offset < 0)
return new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
return new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
Debug.Assert(array.Length - offset < count);
return new ArgumentException(SR.Argument_InvalidOffLen);
}
private static ArgumentException GetArgumentException(ExceptionResource resource)
{
return new ArgumentException(GetResourceString(resource));
}
private static InvalidOperationException GetInvalidOperationException(ExceptionResource resource)
{
return new InvalidOperationException(GetResourceString(resource));
}
private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType)
{
return new ArgumentException(SR.Format(SR.Arg_WrongType, key, targetType), nameof(key));
}
private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType)
{
return new ArgumentException(SR.Format(SR.Arg_WrongType, value, targetType), nameof(value));
}
private static KeyNotFoundException GetKeyNotFoundException(object key)
{
return new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key));
}
private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
{
return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource));
}
private static ArgumentException GetArgumentException(ExceptionResource resource, ExceptionArgument argument)
{
return new ArgumentException(GetResourceString(resource), GetArgumentName(argument));
}
private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource)
{
return new ArgumentOutOfRangeException(GetArgumentName(argument) + "[" + paramNumber.ToString() + "]", GetResourceString(resource));
}
private static InvalidOperationException GetInvalidOperationException_EnumCurrent(int index)
{
return new InvalidOperationException(
index < 0 ?
SR.InvalidOperation_EnumNotStarted :
SR.InvalidOperation_EnumEnded);
}
// Allow nulls for reference types and Nullable<U>, but not for value types.
// Aggressively inline so the jit evaluates the if in place and either drops the call altogether
// Or just leaves null test and call to the Non-returning ThrowHelper.ThrowArgumentNullException
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName)
{
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
if (!(default(T) == null) && value == null)
ThrowHelper.ThrowArgumentNullException(argName);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void ThrowForUnsupportedVectorBaseType<T>() where T : struct
{
if (typeof(T) != typeof(byte) && typeof(T) != typeof(sbyte) &&
typeof(T) != typeof(short) && typeof(T) != typeof(ushort) &&
typeof(T) != typeof(int) && typeof(T) != typeof(uint) &&
typeof(T) != typeof(long) && typeof(T) != typeof(ulong) &&
typeof(T) != typeof(float) && typeof(T) != typeof(double))
{
ThrowNotSupportedException(ExceptionResource.Arg_TypeNotSupported);
}
}
#if false // Reflection-based implementation does not work for CoreRT/ProjectN
// This function will convert an ExceptionArgument enum value to the argument name string.
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetArgumentName(ExceptionArgument argument)
{
Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
"The enum value is not defined, please check the ExceptionArgument Enum.");
return argument.ToString();
}
#endif
private static string GetArgumentName(ExceptionArgument argument)
{
switch (argument)
{
case ExceptionArgument.obj:
return "obj";
case ExceptionArgument.dictionary:
return "dictionary";
case ExceptionArgument.array:
return "array";
case ExceptionArgument.info:
return "info";
case ExceptionArgument.key:
return "key";
case ExceptionArgument.text:
return "text";
case ExceptionArgument.values:
return "values";
case ExceptionArgument.value:
return "value";
case ExceptionArgument.startIndex:
return "startIndex";
case ExceptionArgument.task:
return "task";
case ExceptionArgument.ch:
return "ch";
case ExceptionArgument.s:
return "s";
case ExceptionArgument.input:
return "input";
case ExceptionArgument.ownedMemory:
return "ownedMemory";
case ExceptionArgument.list:
return "list";
case ExceptionArgument.index:
return "index";
case ExceptionArgument.capacity:
return "capacity";
case ExceptionArgument.collection:
return "collection";
case ExceptionArgument.item:
return "item";
case ExceptionArgument.converter:
return "converter";
case ExceptionArgument.match:
return "match";
case ExceptionArgument.count:
return "count";
case ExceptionArgument.action:
return "action";
case ExceptionArgument.comparison:
return "comparison";
case ExceptionArgument.exceptions:
return "exceptions";
case ExceptionArgument.exception:
return "exception";
case ExceptionArgument.pointer:
return "pointer";
case ExceptionArgument.start:
return "start";
case ExceptionArgument.format:
return "format";
case ExceptionArgument.culture:
return "culture";
case ExceptionArgument.comparer:
return "comparer";
case ExceptionArgument.comparable:
return "comparable";
case ExceptionArgument.source:
return "source";
case ExceptionArgument.state:
return "state";
case ExceptionArgument.length:
return "length";
case ExceptionArgument.comparisonType:
return "comparisonType";
case ExceptionArgument.manager:
return "manager";
case ExceptionArgument.sourceBytesToCopy:
return "sourceBytesToCopy";
case ExceptionArgument.callBack:
return "callBack";
case ExceptionArgument.creationOptions:
return "creationOptions";
case ExceptionArgument.function:
return "function";
case ExceptionArgument.scheduler:
return "scheduler";
case ExceptionArgument.continuationAction:
return "continuationAction";
case ExceptionArgument.continuationFunction:
return "continuationFunction";
case ExceptionArgument.tasks:
return "tasks";
case ExceptionArgument.asyncResult:
return "asyncResult";
case ExceptionArgument.beginMethod:
return "beginMethod";
case ExceptionArgument.endMethod:
return "endMethod";
case ExceptionArgument.endFunction:
return "endFunction";
case ExceptionArgument.cancellationToken:
return "cancellationToken";
case ExceptionArgument.continuationOptions:
return "continuationOptions";
case ExceptionArgument.delay:
return "delay";
case ExceptionArgument.millisecondsDelay:
return "millisecondsDelay";
case ExceptionArgument.millisecondsTimeout:
return "millisecondsTimeout";
case ExceptionArgument.stateMachine:
return "stateMachine";
case ExceptionArgument.timeout:
return "timeout";
case ExceptionArgument.type:
return "type";
case ExceptionArgument.sourceIndex:
return "sourceIndex";
case ExceptionArgument.sourceArray:
return "sourceArray";
case ExceptionArgument.destinationIndex:
return "destinationIndex";
case ExceptionArgument.destinationArray:
return "destinationArray";
case ExceptionArgument.pHandle:
return "pHandle";
case ExceptionArgument.other:
return "other";
case ExceptionArgument.newSize:
return "newSize";
case ExceptionArgument.lowerBounds:
return "lowerBounds";
case ExceptionArgument.lengths:
return "lengths";
case ExceptionArgument.len:
return "len";
case ExceptionArgument.keys:
return "keys";
case ExceptionArgument.indices:
return "indices";
case ExceptionArgument.index1:
return "index1";
case ExceptionArgument.index2:
return "index2";
case ExceptionArgument.index3:
return "index3";
case ExceptionArgument.length1:
return "length1";
case ExceptionArgument.length2:
return "length2";
case ExceptionArgument.length3:
return "length3";
case ExceptionArgument.endIndex:
return "endIndex";
case ExceptionArgument.elementType:
return "elementType";
case ExceptionArgument.arrayIndex:
return "arrayIndex";
default:
Debug.Fail("The enum value is not defined, please check the ExceptionArgument Enum.");
return "";
}
}
#if false // Reflection-based implementation does not work for CoreRT/ProjectN
// This function will convert an ExceptionResource enum value to the resource string.
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetResourceString(ExceptionResource resource)
{
Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
"The enum value is not defined, please check the ExceptionResource Enum.");
return SR.GetResourceString(resource.ToString());
}
#endif
private static string GetResourceString(ExceptionResource resource)
{
switch (resource)
{
case ExceptionResource.ArgumentOutOfRange_Index:
return SR.ArgumentOutOfRange_Index;
case ExceptionResource.ArgumentOutOfRange_Count:
return SR.ArgumentOutOfRange_Count;
case ExceptionResource.Arg_ArrayPlusOffTooSmall:
return SR.Arg_ArrayPlusOffTooSmall;
case ExceptionResource.NotSupported_ReadOnlyCollection:
return SR.NotSupported_ReadOnlyCollection;
case ExceptionResource.Arg_RankMultiDimNotSupported:
return SR.Arg_RankMultiDimNotSupported;
case ExceptionResource.Arg_NonZeroLowerBound:
return SR.Arg_NonZeroLowerBound;
case ExceptionResource.ArgumentOutOfRange_ListInsert:
return SR.ArgumentOutOfRange_ListInsert;
case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum:
return SR.ArgumentOutOfRange_NeedNonNegNum;
case ExceptionResource.ArgumentOutOfRange_SmallCapacity:
return SR.ArgumentOutOfRange_SmallCapacity;
case ExceptionResource.Argument_InvalidOffLen:
return SR.Argument_InvalidOffLen;
case ExceptionResource.Argument_CannotExtractScalar:
return SR.Argument_CannotExtractScalar;
case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection:
return SR.ArgumentOutOfRange_BiggerThanCollection;
case ExceptionResource.Serialization_MissingKeys:
return SR.Serialization_MissingKeys;
case ExceptionResource.Serialization_NullKey:
return SR.Serialization_NullKey;
case ExceptionResource.NotSupported_KeyCollectionSet:
return SR.NotSupported_KeyCollectionSet;
case ExceptionResource.NotSupported_ValueCollectionSet:
return SR.NotSupported_ValueCollectionSet;
case ExceptionResource.InvalidOperation_NullArray:
return SR.InvalidOperation_NullArray;
case ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted:
return SR.TaskT_TransitionToFinal_AlreadyCompleted;
case ExceptionResource.TaskCompletionSourceT_TrySetException_NullException:
return SR.TaskCompletionSourceT_TrySetException_NullException;
case ExceptionResource.TaskCompletionSourceT_TrySetException_NoExceptions:
return SR.TaskCompletionSourceT_TrySetException_NoExceptions;
case ExceptionResource.NotSupported_StringComparison:
return SR.NotSupported_StringComparison;
case ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported:
return SR.ConcurrentCollection_SyncRoot_NotSupported;
case ExceptionResource.Task_MultiTaskContinuation_NullTask:
return SR.Task_MultiTaskContinuation_NullTask;
case ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple:
return SR.InvalidOperation_WrongAsyncResultOrEndCalledMultiple;
case ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList:
return SR.Task_MultiTaskContinuation_EmptyTaskList;
case ExceptionResource.Task_Start_TaskCompleted:
return SR.Task_Start_TaskCompleted;
case ExceptionResource.Task_Start_Promise:
return SR.Task_Start_Promise;
case ExceptionResource.Task_Start_ContinuationTask:
return SR.Task_Start_ContinuationTask;
case ExceptionResource.Task_Start_AlreadyStarted:
return SR.Task_Start_AlreadyStarted;
case ExceptionResource.Task_RunSynchronously_Continuation:
return SR.Task_RunSynchronously_Continuation;
case ExceptionResource.Task_RunSynchronously_Promise:
return SR.Task_RunSynchronously_Promise;
case ExceptionResource.Task_RunSynchronously_TaskCompleted:
return SR.Task_RunSynchronously_TaskCompleted;
case ExceptionResource.Task_RunSynchronously_AlreadyStarted:
return SR.Task_RunSynchronously_AlreadyStarted;
case ExceptionResource.AsyncMethodBuilder_InstanceNotInitialized:
return SR.AsyncMethodBuilder_InstanceNotInitialized;
case ExceptionResource.Task_ContinueWith_ESandLR:
return SR.Task_ContinueWith_ESandLR;
case ExceptionResource.Task_ContinueWith_NotOnAnything:
return SR.Task_ContinueWith_NotOnAnything;
case ExceptionResource.Task_Delay_InvalidDelay:
return SR.Task_Delay_InvalidDelay;
case ExceptionResource.Task_Delay_InvalidMillisecondsDelay:
return SR.Task_Delay_InvalidMillisecondsDelay;
case ExceptionResource.Task_Dispose_NotCompleted:
return SR.Task_Dispose_NotCompleted;
case ExceptionResource.Task_ThrowIfDisposed:
return SR.Task_ThrowIfDisposed;
case ExceptionResource.Task_WaitMulti_NullTask:
return SR.Task_WaitMulti_NullTask;
case ExceptionResource.ArgumentException_OtherNotArrayOfCorrectLength:
return SR.ArgumentException_OtherNotArrayOfCorrectLength;
case ExceptionResource.ArgumentNull_SafeHandle:
return SR.ArgumentNull_SafeHandle;
case ExceptionResource.ArgumentOutOfRange_EndIndexStartIndex:
return SR.ArgumentOutOfRange_EndIndexStartIndex;
case ExceptionResource.ArgumentOutOfRange_Enum:
return SR.ArgumentOutOfRange_Enum;
case ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported:
return SR.ArgumentOutOfRange_HugeArrayNotSupported;
case ExceptionResource.Argument_AddingDuplicate:
return SR.Argument_AddingDuplicate;
case ExceptionResource.Argument_InvalidArgumentForComparison:
return SR.Argument_InvalidArgumentForComparison;
case ExceptionResource.Arg_LowerBoundsMustMatch:
return SR.Arg_LowerBoundsMustMatch;
case ExceptionResource.Arg_MustBeType:
return SR.Arg_MustBeType;
case ExceptionResource.Arg_Need1DArray:
return SR.Arg_Need1DArray;
case ExceptionResource.Arg_Need2DArray:
return SR.Arg_Need2DArray;
case ExceptionResource.Arg_Need3DArray:
return SR.Arg_Need3DArray;
case ExceptionResource.Arg_NeedAtLeast1Rank:
return SR.Arg_NeedAtLeast1Rank;
case ExceptionResource.Arg_RankIndices:
return SR.Arg_RankIndices;
case ExceptionResource.Arg_RanksAndBounds:
return SR.Arg_RanksAndBounds;
case ExceptionResource.InvalidOperation_IComparerFailed:
return SR.InvalidOperation_IComparerFailed;
case ExceptionResource.NotSupported_FixedSizeCollection:
return SR.NotSupported_FixedSizeCollection;
case ExceptionResource.Rank_MultiDimNotSupported:
return SR.Rank_MultiDimNotSupported;
case ExceptionResource.Arg_TypeNotSupported:
return SR.Arg_TypeNotSupported;
default:
Debug.Fail("The enum value is not defined, please check the ExceptionResource Enum.");
return "";
}
}
}
//
// The convention for this enum is using the argument name as the enum name
//
internal enum ExceptionArgument
{
obj,
dictionary,
array,
info,
key,
text,
values,
value,
startIndex,
task,
ch,
s,
input,
ownedMemory,
list,
index,
capacity,
collection,
item,
converter,
match,
count,
action,
comparison,
exceptions,
exception,
pointer,
start,
format,
culture,
comparer,
comparable,
source,
state,
length,
comparisonType,
manager,
sourceBytesToCopy,
callBack,
creationOptions,
function,
scheduler,
continuationAction,
continuationFunction,
tasks,
asyncResult,
beginMethod,
endMethod,
endFunction,
cancellationToken,
continuationOptions,
delay,
millisecondsDelay,
millisecondsTimeout,
stateMachine,
timeout,
type,
sourceIndex,
sourceArray,
destinationIndex,
destinationArray,
pHandle,
other,
newSize,
lowerBounds,
lengths,
len,
keys,
indices,
index1,
index2,
index3,
length1,
length2,
length3,
endIndex,
elementType,
arrayIndex,
}
//
// The convention for this enum is using the resource name as the enum name
//
internal enum ExceptionResource
{
ArgumentOutOfRange_Index,
ArgumentOutOfRange_Count,
Arg_ArrayPlusOffTooSmall,
NotSupported_ReadOnlyCollection,
Arg_RankMultiDimNotSupported,
Arg_NonZeroLowerBound,
ArgumentOutOfRange_ListInsert,
ArgumentOutOfRange_NeedNonNegNum,
ArgumentOutOfRange_SmallCapacity,
Argument_InvalidOffLen,
Argument_CannotExtractScalar,
ArgumentOutOfRange_BiggerThanCollection,
Serialization_MissingKeys,
Serialization_NullKey,
NotSupported_KeyCollectionSet,
NotSupported_ValueCollectionSet,
InvalidOperation_NullArray,
TaskT_TransitionToFinal_AlreadyCompleted,
TaskCompletionSourceT_TrySetException_NullException,
TaskCompletionSourceT_TrySetException_NoExceptions,
NotSupported_StringComparison,
ConcurrentCollection_SyncRoot_NotSupported,
Task_MultiTaskContinuation_NullTask,
InvalidOperation_WrongAsyncResultOrEndCalledMultiple,
Task_MultiTaskContinuation_EmptyTaskList,
Task_Start_TaskCompleted,
Task_Start_Promise,
Task_Start_ContinuationTask,
Task_Start_AlreadyStarted,
Task_RunSynchronously_Continuation,
Task_RunSynchronously_Promise,
Task_RunSynchronously_TaskCompleted,
Task_RunSynchronously_AlreadyStarted,
AsyncMethodBuilder_InstanceNotInitialized,
Task_ContinueWith_ESandLR,
Task_ContinueWith_NotOnAnything,
Task_Delay_InvalidDelay,
Task_Delay_InvalidMillisecondsDelay,
Task_Dispose_NotCompleted,
Task_ThrowIfDisposed,
Task_WaitMulti_NullTask,
ArgumentException_OtherNotArrayOfCorrectLength,
ArgumentNull_SafeHandle,
ArgumentOutOfRange_EndIndexStartIndex,
ArgumentOutOfRange_Enum,
ArgumentOutOfRange_HugeArrayNotSupported,
Argument_AddingDuplicate,
Argument_InvalidArgumentForComparison,
Arg_LowerBoundsMustMatch,
Arg_MustBeType,
Arg_Need1DArray,
Arg_Need2DArray,
Arg_Need3DArray,
Arg_NeedAtLeast1Rank,
Arg_RankIndices,
Arg_RanksAndBounds,
InvalidOperation_IComparerFailed,
NotSupported_FixedSizeCollection,
Rank_MultiDimNotSupported,
Arg_TypeNotSupported,
}
}
| |
/**
* MetroFramework - Modern UI for WinForms
*
* The MIT License (MIT)
* Copyright (c) 2011 Sven Walter, http://github.com/viperneo
*
* 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.
*/
// Based on original work by
// (c) Mick Doherty / Oscar Londono
// http://dotnetrix.co.uk/tabcontrol.htm
// http://www.pcreview.co.uk/forums/adding-custom-tabpages-design-time-t2904262.html
// http://www.codeproject.com/Articles/12185/A-NET-Flat-TabControl-CustomDraw
// http://www.codeproject.com/Articles/278/Fully-owner-drawn-tab-control
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Design;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Windows.Forms;
using MetroFramework.Components;
using MetroFramework.Drawing;
using MetroFramework.Interfaces;
using MetroFramework.Native;
using System.Collections.Generic;
using MetroFramework.Controls;
namespace MetroFramework.Controls
{
#region MetroTabPageCollection
[ToolboxItem(false)]
[Editor("MetroFramework.Design.MetroTabPageCollectionEditor, " + AssemblyRef.MetroFrameworkDesignSN, typeof(UITypeEditor))]
public class MetroTabPageCollection : TabControl.TabPageCollection
{
public MetroTabPageCollection(MetroTabControl owner)
: base(owner)
{ }
}
#endregion
#region HiddenTabClass
public class HiddenTabs
{
public HiddenTabs(int id, string page)
{
_index = id;
_tabpage = page;
}
private int _index;
private string _tabpage;
public int index { get { return _index; } }
public string tabpage { get { return _tabpage; } }
}
#endregion HiddenTabClass
[Designer("MetroFramework.Design.Controls.MetroTabControlDesigner, " + AssemblyRef.MetroFrameworkDesignSN)]
[ToolboxBitmap(typeof(TabControl))]
public class MetroTabControl : TabControl, IMetroControl
{
#region Interface
[Category(MetroDefaults.PropertyCategory.Appearance)]
public event EventHandler<MetroPaintEventArgs> CustomPaintBackground;
protected virtual void OnCustomPaintBackground(MetroPaintEventArgs e)
{
if (GetStyle(ControlStyles.UserPaint) && CustomPaintBackground != null)
{
CustomPaintBackground(this, e);
}
}
[Category(MetroDefaults.PropertyCategory.Appearance)]
public event EventHandler<MetroPaintEventArgs> CustomPaint;
protected virtual void OnCustomPaint(MetroPaintEventArgs e)
{
if (GetStyle(ControlStyles.UserPaint) && CustomPaint != null)
{
CustomPaint(this, e);
}
}
[Category(MetroDefaults.PropertyCategory.Appearance)]
public event EventHandler<MetroPaintEventArgs> CustomPaintForeground;
protected virtual void OnCustomPaintForeground(MetroPaintEventArgs e)
{
if (GetStyle(ControlStyles.UserPaint) && CustomPaintForeground != null)
{
CustomPaintForeground(this, e);
}
}
private MetroColorStyle metroStyle = MetroColorStyle.Default;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(MetroColorStyle.Default)]
public MetroColorStyle Style
{
get
{
if (DesignMode || metroStyle != MetroColorStyle.Default)
{
return metroStyle;
}
if (StyleManager != null && metroStyle == MetroColorStyle.Default)
{
return StyleManager.Style;
}
if (StyleManager == null && metroStyle == MetroColorStyle.Default)
{
return MetroDefaults.Style;
}
return metroStyle;
}
set { metroStyle = value; }
}
private MetroThemeStyle metroTheme = MetroThemeStyle.Default;
[Category(MetroDefaults.PropertyCategory.Appearance)]
[DefaultValue(MetroThemeStyle.Default)]
public MetroThemeStyle Theme
{
get
{
if (DesignMode || metroTheme != MetroThemeStyle.Default)
{
return metroTheme;
}
if (StyleManager != null && metroTheme == MetroThemeStyle.Default)
{
return StyleManager.Theme;
}
if (StyleManager == null && metroTheme == MetroThemeStyle.Default)
{
return MetroDefaults.Theme;
}
return metroTheme;
}
set { metroTheme = value; }
}
private MetroStyleManager metroStyleManager = null;
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public MetroStyleManager StyleManager
{
get { return metroStyleManager; }
set { metroStyleManager = value; }
}
private bool useCustomBackColor = false;
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool UseCustomBackColor
{
get { return useCustomBackColor; }
set { useCustomBackColor = value; }
}
private bool useCustomForeColor = false;
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool UseCustomForeColor
{
get { return useCustomForeColor; }
set { useCustomForeColor = value; }
}
private bool useStyleColors = false;
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public bool UseStyleColors
{
get { return useStyleColors; }
set { useStyleColors = value; }
}
[Browsable(false)]
[Category(MetroDefaults.PropertyCategory.Behaviour)]
[DefaultValue(false)]
public bool UseSelectable
{
get { return GetStyle(ControlStyles.Selectable); }
set { SetStyle(ControlStyles.Selectable, value); }
}
#endregion
#region Fields
//Additional variables to be used by HideTab and ShowTab
private List<string> tabDisable = new List<string>();
private List<string> tabOrder = new List<string>();
private List<HiddenTabs> hidTabs = new List<HiddenTabs>();
private SubClass scUpDown = null;
private bool bUpDown = false;
private const int TabBottomBorderHeight = 3;
private MetroTabControlSize metroLabelSize = MetroTabControlSize.Medium;
[DefaultValue(MetroTabControlSize.Medium)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public MetroTabControlSize FontSize
{
get { return metroLabelSize; }
set { metroLabelSize = value; }
}
private MetroTabControlWeight metroLabelWeight = MetroTabControlWeight.Light;
[DefaultValue(MetroTabControlWeight.Light)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public MetroTabControlWeight FontWeight
{
get { return metroLabelWeight; }
set { metroLabelWeight = value; }
}
private ContentAlignment textAlign = ContentAlignment.MiddleLeft;
[DefaultValue(ContentAlignment.MiddleLeft)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public ContentAlignment TextAlign
{
get
{
return textAlign;
}
set
{
textAlign = value;
}
}
[Editor("MetroFramework.Design.MetroTabPageCollectionEditor, " + AssemblyRef.MetroFrameworkDesignSN, typeof(UITypeEditor))]
public new TabPageCollection TabPages
{
get
{
return base.TabPages;
}
}
private bool isMirrored;
[DefaultValue(false)]
[Category(MetroDefaults.PropertyCategory.Appearance)]
public new bool IsMirrored
{
get
{
return isMirrored;
}
set
{
if (isMirrored == value)
{
return;
}
isMirrored = value;
UpdateStyles();
}
}
#endregion
#region Constructor
public MetroTabControl()
{
SetStyle(ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.SupportsTransparentBackColor, true);
Padding = new Point(6, 8);
this.Selecting += MetroTabControl_Selecting;
}
#endregion
#region Paint Methods
protected override void OnPaintBackground(PaintEventArgs e)
{
try
{
Color backColor = BackColor;
if (!useCustomBackColor)
{
backColor = MetroPaint.BackColor.Form(Theme);
}
if (backColor.A == 255 && BackgroundImage == null)
{
e.Graphics.Clear(backColor);
return;
}
base.OnPaintBackground(e);
OnCustomPaintBackground(new MetroPaintEventArgs(backColor, Color.Empty, e.Graphics));
}
catch
{
Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
try
{
if (GetStyle(ControlStyles.AllPaintingInWmPaint))
{
OnPaintBackground(e);
}
OnCustomPaint(new MetroPaintEventArgs(Color.Empty, Color.Empty, e.Graphics));
OnPaintForeground(e);
}
catch
{
Invalidate();
}
}
protected virtual void OnPaintForeground(PaintEventArgs e)
{
for (var index = 0; index < TabPages.Count; index++)
{
if (index != SelectedIndex)
{
DrawTab(index, e.Graphics);
}
}
if (SelectedIndex <= -1)
{
return;
}
DrawTabBottomBorder(SelectedIndex, e.Graphics);
DrawTab(SelectedIndex, e.Graphics);
DrawTabSelected(SelectedIndex, e.Graphics);
OnCustomPaintForeground(new MetroPaintEventArgs(Color.Empty, Color.Empty, e.Graphics));
}
private void DrawTabBottomBorder(int index, Graphics graphics)
{
using (Brush bgBrush = new SolidBrush(MetroPaint.BorderColor.TabControl.Normal(Theme)))
{
Rectangle borderRectangle = new Rectangle(DisplayRectangle.X, GetTabRect(index).Bottom + 2 - TabBottomBorderHeight, DisplayRectangle.Width, TabBottomBorderHeight);
graphics.FillRectangle(bgBrush, borderRectangle);
}
}
private void DrawTabSelected(int index, Graphics graphics)
{
using (Brush selectionBrush = new SolidBrush(MetroPaint.GetStyleColor(Style)))
{
Rectangle selectedTabRect = GetTabRect(index);
Rectangle borderRectangle = new Rectangle(selectedTabRect.X + ((index == 0) ? 2 : 0), GetTabRect(index).Bottom + 2 - TabBottomBorderHeight, selectedTabRect.Width + ((index == 0) ? 0 : 2), TabBottomBorderHeight);
graphics.FillRectangle(selectionBrush, borderRectangle);
}
}
private Size MeasureText(string text)
{
Size preferredSize;
using (Graphics g = CreateGraphics())
{
Size proposedSize = new Size(int.MaxValue, int.MaxValue);
preferredSize = TextRenderer.MeasureText(g, text, MetroFonts.TabControl(metroLabelSize, metroLabelWeight),
proposedSize,
MetroPaint.GetTextFormatFlags(TextAlign) |
TextFormatFlags.NoPadding);
}
return preferredSize;
}
private void DrawTab(int index, Graphics graphics)
{
Color foreColor;
Color backColor = BackColor;
if (!useCustomBackColor)
{
backColor = MetroPaint.BackColor.Form(Theme);
}
TabPage tabPage = TabPages[index];
Rectangle tabRect = GetTabRect(index);
if (!Enabled || tabDisable.Contains(tabPage.Name))
{
foreColor = MetroPaint.ForeColor.Label.Disabled(Theme);
}
else
{
if (useCustomForeColor)
{
foreColor = DefaultForeColor;
}
else
{
foreColor = !useStyleColors ? MetroPaint.ForeColor.TabControl.Normal(Theme) : MetroPaint.GetStyleColor(Style);
}
}
if (index == 0)
{
tabRect.X = DisplayRectangle.X;
}
Rectangle bgRect = tabRect;
tabRect.Width += 20;
using (Brush bgBrush = new SolidBrush(backColor))
{
graphics.FillRectangle(bgBrush, bgRect);
}
TextRenderer.DrawText(graphics, tabPage.Text, MetroFonts.TabControl(metroLabelSize, metroLabelWeight),
tabRect, foreColor, backColor, MetroPaint.GetTextFormatFlags(TextAlign));
}
[SecuritySafeCritical]
private void DrawUpDown(Graphics graphics)
{
Color backColor = Parent != null ? Parent.BackColor : MetroPaint.BackColor.Form(Theme);
Rectangle borderRect = new Rectangle();
WinApi.GetClientRect(scUpDown.Handle, ref borderRect);
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.Clear(backColor);
using (Brush b = new SolidBrush(MetroPaint.BorderColor.TabControl.Normal(Theme)))
{
GraphicsPath gp = new GraphicsPath(FillMode.Winding);
PointF[] pts = { new PointF(6, 6), new PointF(16, 0), new PointF(16, 12) };
gp.AddLines(pts);
graphics.FillPath(b, gp);
gp.Reset();
PointF[] pts2 = { new PointF(borderRect.Width - 15, 0), new PointF(borderRect.Width - 5, 6), new PointF(borderRect.Width - 15, 12) };
gp.AddLines(pts2);
graphics.FillPath(b, gp);
gp.Dispose();
}
}
#endregion
#region Overridden Methods
protected override void OnEnabledChanged(EventArgs e)
{
base.OnEnabledChanged(e);
Invalidate();
}
protected override void OnParentBackColorChanged(EventArgs e)
{
base.OnParentBackColorChanged(e);
Invalidate();
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Invalidate();
}
[SecuritySafeCritical]
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (!DesignMode)
{
WinApi.ShowScrollBar(Handle, (int)WinApi.ScrollBar.SB_BOTH, 0);
}
}
protected override CreateParams CreateParams
{
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
const int WS_EX_LAYOUTRTL = 0x400000;
const int WS_EX_NOINHERITLAYOUT = 0x100000;
var cp = base.CreateParams;
if (isMirrored)
{
cp.ExStyle = cp.ExStyle | WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT;
}
return cp;
}
}
private new Rectangle GetTabRect(int index)
{
if (index < 0)
return new Rectangle();
Rectangle baseRect = base.GetTabRect(index);
return baseRect;
}
protected override void OnMouseWheel(MouseEventArgs e)
{
if (SelectedIndex != -1)
{
if (!TabPages[SelectedIndex].Focused)
{
bool subControlFocused = false;
foreach (Control ctrl in TabPages[SelectedIndex].Controls)
{
if (ctrl.Focused)
{
subControlFocused = true;
return;
}
}
if (!subControlFocused)
{
TabPages[SelectedIndex].Select();
TabPages[SelectedIndex].Focus();
}
}
}
base.OnMouseWheel(e);
}
protected override void OnCreateControl()
{
base.OnCreateControl();
this.OnFontChanged(EventArgs.Empty);
FindUpDown();
}
protected override void OnControlAdded(ControlEventArgs e)
{
base.OnControlAdded(e);
FindUpDown();
UpdateUpDown();
}
protected override void OnControlRemoved(ControlEventArgs e)
{
base.OnControlRemoved(e);
FindUpDown();
UpdateUpDown();
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
base.OnSelectedIndexChanged(e);
UpdateUpDown();
Invalidate();
}
//send font change to properly resize tab page header rects
//http://www.codeproject.com/Articles/13305/Painting-Your-Own-Tabs?msg=2707590#xx2707590xx
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
private const int WM_SETFONT = 0x30;
private const int WM_FONTCHANGE = 0x1d;
[SecuritySafeCritical]
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
IntPtr hFont = MetroFonts.TabControl(metroLabelSize, metroLabelWeight).ToHfont();
SendMessage(this.Handle, WM_SETFONT, hFont, (IntPtr)(-1));
SendMessage(this.Handle, WM_FONTCHANGE, IntPtr.Zero, IntPtr.Zero);
this.UpdateStyles();
}
void MetroTabControl_Selecting(object sender, TabControlCancelEventArgs e)
{
if (tabDisable.Count > 0 && tabDisable.Contains(e.TabPage.Name))
{
e.Cancel = true;
}
}
#endregion
#region Helper Methods
[SecuritySafeCritical]
private void FindUpDown()
{
if (!DesignMode)
{
bool bFound = false;
IntPtr pWnd = WinApi.GetWindow(Handle, WinApi.GW_CHILD);
while (pWnd != IntPtr.Zero)
{
char[] className = new char[33];
int length = WinApi.GetClassName(pWnd, className, 32);
string s = new string(className, 0, length);
if (s == "msctls_updown32")
{
bFound = true;
if (!bUpDown)
{
this.scUpDown = new SubClass(pWnd, true);
this.scUpDown.SubClassedWndProc += new SubClass.SubClassWndProcEventHandler(scUpDown_SubClassedWndProc);
bUpDown = true;
}
break;
}
pWnd = WinApi.GetWindow(pWnd, WinApi.GW_HWNDNEXT);
}
if ((!bFound) && (bUpDown))
bUpDown = false;
}
}
[SecuritySafeCritical]
private void UpdateUpDown()
{
if (bUpDown && !DesignMode)
{
if (WinApi.IsWindowVisible(scUpDown.Handle))
{
Rectangle rect = new Rectangle();
WinApi.GetClientRect(scUpDown.Handle, ref rect);
WinApi.InvalidateRect(scUpDown.Handle, ref rect, true);
}
}
}
[SecuritySafeCritical]
private int scUpDown_SubClassedWndProc(ref Message m)
{
switch (m.Msg)
{
case (int)WinApi.Messages.WM_PAINT:
IntPtr hDC = WinApi.GetWindowDC(scUpDown.Handle);
Graphics g = Graphics.FromHdc(hDC);
DrawUpDown(g);
g.Dispose();
WinApi.ReleaseDC(scUpDown.Handle, hDC);
m.Result = IntPtr.Zero;
Rectangle rect = new Rectangle();
WinApi.GetClientRect(scUpDown.Handle, ref rect);
WinApi.ValidateRect(scUpDown.Handle, ref rect);
return 1;
}
return 0;
}
#endregion
#region Additional functions by DenRic Denise
/// <summary>
/// This will hide MetroTabPage from MetroTabControl
/// Hidden MetroTabPage can be displayed by calling ShowTab functions
/// </summary>
/// <param name="tabpage"></param>
public void HideTab(MetroTabPage tabpage)
{
if (this.TabPages.Contains(tabpage))
{
int _tabid = this.TabPages.IndexOf(tabpage);
hidTabs.Add(new HiddenTabs(_tabid, tabpage.Name));
this.TabPages.Remove(tabpage);
}
}
/// <summary>
/// This will show hiddent MetroTabPage from MetroTabControl
/// </summary>
/// <param name="tabpage"></param>
public void ShowTab(MetroTabPage tabpage)
{
HiddenTabs result = hidTabs.Find(
delegate(HiddenTabs bk)
{
return bk.tabpage == tabpage.Name;
}
);
if (result != null)
{
this.TabPages.Insert(result.index,tabpage);
hidTabs.Remove(result);
}
}
/// <summary>
/// This will disable a MetroTabPage from MetroTabControl
/// </summary>
/// <param name="tabpage"></param>
public void DisableTab(MetroTabPage tabpage)
{
if (!tabDisable.Contains(tabpage.Name))
{
if (this.SelectedTab == tabpage && this.TabCount == 1) return;
if (this.SelectedTab == tabpage)
{
if (SelectedIndex == this.TabCount - 1)
{ SelectedIndex = 0; }
else { SelectedIndex++; }
}
int _tabid = this.TabPages.IndexOf(tabpage);
tabDisable.Add(tabpage.Name);
Graphics e = this.CreateGraphics();
DrawTab(_tabid, e);
DrawTabBottomBorder(SelectedIndex, e);
DrawTabSelected(SelectedIndex, e);
}
}
/// <summary>
/// This will enable a MetroTabPage from MetroTabControl
/// </summary>
/// <param name="tabpage"></param>
public void EnableTab(MetroTabPage tabpage)
{
if (tabDisable.Contains(tabpage.Name))
{
tabDisable.Remove(tabpage.Name);
int _tabid = this.TabPages.IndexOf(tabpage);
Graphics e = this.CreateGraphics();
DrawTab(_tabid, e);
DrawTabBottomBorder(SelectedIndex, e);
DrawTabSelected(SelectedIndex, e);
}
}
/// <summary>
/// This will check if MetroTabPage is enable or not
/// true if enable otherwise false
/// </summary>
/// <param name="tabpage"></param>
/// <returns></returns>
public bool IsTabEnable(MetroTabPage tabpage)
{
return tabDisable.Contains(tabpage.Name);
}
/// <summary>
/// This will check if MetroTabPage is hidden or not
/// true if hidden otherwise false
/// </summary>
public bool IsTabHidden(MetroTabPage tabpage)
{
HiddenTabs result = hidTabs.Find(
delegate(HiddenTabs bk)
{
return bk.tabpage == tabpage.Name;
}
);
return (result != null);
}
#endregion
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Bot.Connector
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
public static partial class ConversationsExtensions
{
/// <summary>
/// CreateConversation
/// </summary>
/// Create a new Conversation.
///
/// POST to this method with a
/// * Bot being the bot creating the conversation
/// * IsGroup set to true if this is not a direct message (default is false)
/// * Members array contining the members you want to have be in the
/// conversation.
///
/// The return value is a ResourceResponse which contains a conversation id
/// which is suitable for use
/// in the message payload and REST API uris.
///
/// Most channels only support the semantics of bots initiating a direct
/// message conversation. An example of how to do that would be:
///
/// ```
/// var resource = await connector.conversations.CreateConversation(new
/// ConversationParameters(){ Bot = bot, members = new ChannelAccount[] { new
/// ChannelAccount("user1") } );
/// await connect.Conversations.SendToConversationAsync(resource.Id, new
/// Activity() ... ) ;
///
/// ```
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='parameters'>
/// Parameters to create the conversation from
/// </param>
public static ResourceResponse CreateConversation(this IConversations operations, ConversationParameters parameters)
{
return Task.Factory.StartNew(s => ((IConversations)s).CreateConversationAsync(parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// CreateConversation
/// </summary>
/// Create a new Conversation.
///
/// POST to this method with a
/// * Bot being the bot creating the conversation
/// * IsGroup set to true if this is not a direct message (default is false)
/// * Members array contining the members you want to have be in the
/// conversation.
///
/// The return value is a ResourceResponse which contains a conversation id
/// which is suitable for use
/// in the message payload and REST API uris.
///
/// Most channels only support the semantics of bots initiating a direct
/// message conversation. An example of how to do that would be:
///
/// ```
/// var resource = await connector.conversations.CreateConversation(new
/// ConversationParameters(){ Bot = bot, members = new ChannelAccount[] { new
/// ChannelAccount("user1") } );
/// await connect.Conversations.SendToConversationAsync(resource.Id, new
/// Activity() ... ) ;
///
/// ```
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='parameters'>
/// Parameters to create the conversation from
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceResponse> CreateConversationAsync(this IConversations operations, ConversationParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.CreateConversationWithHttpMessagesAsync(parameters, null, cancellationToken).ConfigureAwait(false);
return _result.HandleError<ResourceResponse>();
}
/// <summary>
/// SendToConversation
/// </summary>
/// This method allows you to send an activity to a conversation regardless of
/// previous posts to a conversation.
///
/// This is slightly different then ReplyToConversation().
/// * SendToConverstion(conversationId) - will simply append a message to the
/// end of the conversation according to the timestamp or semantics of the
/// channel
/// * ReplyToConversation(conversationId,ActivityId) - models the semantics of
/// threaded conversations, meaning it has the information necessary for the
/// channel to reply to the actual message being responded to.
///
/// SendToConversation is appropriate for the first message which initiates a
/// conversation, or if you don't have a particular activity you are
/// responding to.
///
/// ReplyToConversation is preferable to SendToConversation() because it
/// maintains threaded conversations.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='activity'>
/// Activity to send
/// </param>
/// <param name='conversationId'>
/// Conversation ID
/// </param>
public static APIResponse SendToConversation(this IConversations operations, Activity activity, string conversationId)
{
return Task.Factory.StartNew(s => ((IConversations)s).SendToConversationAsync(activity, conversationId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// SendToConversation
/// </summary>
/// This method allows you to send an activity to a conversation regardless of
/// previous posts to a conversation.
///
/// This is slightly different then ReplyToConversation().
/// * SendToConverstion(conversationId) - will simply append a message to the
/// end of the conversation according to the timestamp or semantics of the
/// channel
/// * ReplyToConversation(conversationId,ActivityId) - models the semantics of
/// threaded conversations, meaning it has the information necessary for the
/// channel to reply to the actual message being responded to.
///
/// SendToConversation is appropriate for the first message which initiates a
/// conversation, or if you don't have a particular activity you are
/// responding to.
///
/// ReplyToConversation is preferable to SendToConversation() because it
/// maintains threaded conversations.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='activity'>
/// Activity to send
/// </param>
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<APIResponse> SendToConversationAsync(this IConversations operations, Activity activity, string conversationId, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.SendToConversationWithHttpMessagesAsync(activity, conversationId, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// ReplyToActivity
/// </summary>
/// This method allows you to reply to an activity.
///
/// This is slightly different then SendToConversation().
/// * SendToConverstion(conversationId) - will simply append a message to the
/// end of the conversation according to the timestamp or semantics of the
/// channel
/// * ReplyToConversation(conversationId,ActivityId) - models the semantics of
/// threaded conversations, meaning it has the information necessary for the
/// channel to reply to the actual message being responded to.
///
/// ReplyToConversation is almost always preferable to SendToConversation()
/// because it maintains threaded conversations.
///
/// SendToConversation is appropriate for the first message which initiates a
/// conversation, or if you don't have a particular activity you are
/// responding to.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='activityId'>
/// activityId the reply is to (OPTIONAL)
/// </param>
/// <param name='activity'>
/// Activity to send
/// </param>
public static APIResponse ReplyToActivity(this IConversations operations, string conversationId, string activityId, Activity activity)
{
return Task.Factory.StartNew(s => ((IConversations)s).ReplyToActivityAsync(conversationId, activityId, activity), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// ReplyToActivity
/// </summary>
/// This method allows you to reply to an activity.
///
/// This is slightly different then SendToConversation().
/// * SendToConverstion(conversationId) - will simply append a message to the
/// end of the conversation according to the timestamp or semantics of the
/// channel
/// * ReplyToConversation(conversationId,ActivityId) - models the semantics of
/// threaded conversations, meaning it has the information necessary for the
/// channel to reply to the actual message being responded to.
///
/// ReplyToConversation is almost always preferable to SendToConversation()
/// because it maintains threaded conversations.
///
/// SendToConversation is appropriate for the first message which initiates a
/// conversation, or if you don't have a particular activity you are
/// responding to.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='activityId'>
/// activityId the reply is to (OPTIONAL)
/// </param>
/// <param name='activity'>
/// Activity to send
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<APIResponse> ReplyToActivityAsync(this IConversations operations, string conversationId, string activityId, Activity activity, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ReplyToActivityWithHttpMessagesAsync(conversationId, activityId, activity, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// GetConversationMembers
/// </summary>
/// Call this method to enumerate the members of a converstion.
///
/// This REST API takes a ConversationId and returns an array of
/// ChannelAccount[] objects
/// which are the members of the conversation.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='conversationId'>
/// Conversation ID
/// </param>
public static ChannelAccount[] GetConversationMembers(this IConversations operations, string conversationId)
{
return Task.Factory.StartNew(s => ((IConversations)s).GetConversationMembersAsync(conversationId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// GetConversationMembers
/// </summary>
/// Call this method to enumerate the members of a converstion.
///
/// This REST API takes a ConversationId and returns an array of
/// ChannelAccount[] objects
/// which are the members of the conversation.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ChannelAccount[]> GetConversationMembersAsync(this IConversations operations, string conversationId, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.GetConversationMembersWithHttpMessagesAsync(conversationId, null, cancellationToken).ConfigureAwait(false);
return _result.HandleError<ChannelAccount[]>();
}
/// <summary>
/// GetActivityMembers
/// </summary>
/// Call this method to enumerate the members of an activity.
///
/// This REST API takes a ConversationId and a ActivityId, returning an array
/// of ChannelAccount[] objects
/// which are the members of the particular activity in the conversation.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='activityId'>
/// Activity ID
/// </param>
public static ChannelAccount[] GetActivityMembers(this IConversations operations, string conversationId, string activityId)
{
return Task.Factory.StartNew(s => ((IConversations)s).GetActivityMembersAsync(conversationId, activityId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// GetActivityMembers
/// </summary>
/// Call this method to enumerate the members of an activity.
///
/// This REST API takes a ConversationId and a ActivityId, returning an array
/// of ChannelAccount[] objects
/// which are the members of the particular activity in the conversation.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='activityId'>
/// Activity ID
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ChannelAccount[]> GetActivityMembersAsync(this IConversations operations, string conversationId, string activityId, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.GetActivityMembersWithHttpMessagesAsync(conversationId, activityId, null, cancellationToken).ConfigureAwait(false);
return _result.HandleError<ChannelAccount[]>();
}
/// <summary>
/// UploadAttachment
/// </summary>
/// This method allows you to upload an attachment directly into a channels
/// blob storage.
///
/// This is useful because it allows you to store data in a compliant store
/// when dealing with enterprises.
///
/// The response is a ResourceResponse which contains an AttachmentId which is
/// suitable for using with the attachments api.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='attachmentUpload'>
/// </param>
public static ResourceResponse UploadAttachment(this IConversations operations, string conversationId, AttachmentData attachmentUpload)
{
return Task.Factory.StartNew(s => ((IConversations)s).UploadAttachmentAsync(conversationId, attachmentUpload), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// UploadAttachment
/// </summary>
/// This method allows you to upload an attachment directly into a channels
/// blob storage.
///
/// This is useful because it allows you to store data in a compliant store
/// when dealing with enterprises.
///
/// The response is a ResourceResponse which contains an AttachmentId which is
/// suitable for using with the attachments api.
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='attachmentUpload'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceResponse> UploadAttachmentAsync(this IConversations operations, string conversationId, AttachmentData attachmentUpload, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.UploadAttachmentWithHttpMessagesAsync(conversationId, attachmentUpload, null, cancellationToken).ConfigureAwait(false);
return _result.HandleError<ResourceResponse>();
}
}
}
| |
// ==========================================================
// FreeImage 3 .NET wrapper
// Original FreeImage 3 functions and .NET compatible derived functions
//
// Design and implementation by
// - Jean-Philippe Goerke (jpgoerke@users.sourceforge.net)
// - Carsten Klein (cklein05@users.sourceforge.net)
//
// Contributors:
// - David Boland (davidboland@vodafone.ie)
//
// Main reference : MSDN Knowlede Base
//
// This file is part of FreeImage 3
//
// COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
// THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
// OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
// CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
// THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
// SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
// PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// Use at your own risk!
// ==========================================================
// ==========================================================
// CVS
// $Revision: 1.5 $
// $Date: 2009/02/27 16:36:23 $
// $Id: FIRational.cs,v 1.5 2009/02/27 16:36:23 cklein05 Exp $
// ==========================================================
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace FreeImageAPI
{
/// <summary>
/// The <b>FIRational</b> structure represents a fraction via two <see cref="Int32"/>
/// instances which are interpreted as numerator and denominator.
/// </summary>
/// <remarks>
/// The structure tries to approximate the value of <see cref="FreeImageAPI.FIRational(decimal)"/>
/// when creating a new instance by using a better algorithm than FreeImage does.
/// <para/>
/// The structure implements the following operators:
/// +, -, ++, --, ==, != , >, >==, <, <== and ~ (which switches nominator and denomiator).
/// <para/>
/// The structure can be converted into all .NET standard types either implicit or
/// explicit.
/// </remarks>
[Serializable, StructLayout(LayoutKind.Sequential), ComVisible(true)]
public struct FIRational : IConvertible, IComparable, IFormattable, IComparable<FIRational>, IEquatable<FIRational>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int numerator;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int denominator;
/// <summary>
/// Represents the largest possible value of <see cref="FIRational"/>. This field is constant.
/// </summary>
public static readonly FIRational MaxValue = new FIRational(Int32.MaxValue, 1);
/// <summary>
/// Represents the smallest possible value of <see cref="FIRational"/>. This field is constant.
/// </summary>
public static readonly FIRational MinValue = new FIRational(Int32.MinValue, 1);
/// <summary>
/// Represents the smallest positive <see cref="FIRational"/> value greater than zero. This field is constant.
/// </summary>
public static readonly FIRational Epsilon = new FIRational(1, Int32.MaxValue);
/// <summary>
/// Initializes a new instance based on the specified parameters.
/// </summary>
/// <param name="n">The numerator.</param>
/// <param name="d">The denominator.</param>
public FIRational(int n, int d)
{
numerator = n;
denominator = d;
Normalize();
}
/// <summary>
/// Initializes a new instance based on the specified parameters.
/// </summary>
/// <param name="tag">The tag to read the data from.</param>
public unsafe FIRational(FITAG tag)
{
switch (FreeImage.GetTagType(tag))
{
case FREE_IMAGE_MDTYPE.FIDT_SRATIONAL:
int* value = (int*)FreeImage.GetTagValue(tag);
numerator = (int)value[0];
denominator = (int)value[1];
Normalize();
return;
default:
throw new ArgumentException("tag");
}
}
/// <summary>
/// Initializes a new instance based on the specified parameters.
/// </summary>
/// <param name="value">The value to convert into a fraction.</param>
/// <exception cref="OverflowException">
/// <paramref name="value"/> cannot be converted into a fraction
/// represented by two integer values.</exception>
public FIRational(decimal value)
{
try
{
int sign = value < 0 ? -1 : 1;
value = Math.Abs(value);
try
{
int[] contFract = CreateContinuedFraction(value);
CreateFraction(contFract, out numerator, out denominator);
Normalize();
}
catch
{
numerator = 0;
denominator = 1;
}
if (Math.Abs(((decimal)numerator / (decimal)denominator) - value) > 0.0001m)
{
int maxDen = (Int32.MaxValue / (int)value) - 2;
maxDen = maxDen < 10000 ? maxDen : 10000;
ApproximateFraction(value, maxDen, out numerator, out denominator);
Normalize();
if (Math.Abs(((decimal)numerator / (decimal)denominator) - value) > 0.0001m)
{
throw new OverflowException("Unable to convert value into a fraction");
}
}
numerator *= sign;
Normalize();
}
catch (Exception ex)
{
throw new OverflowException("Unable to calculate fraction.", ex);
}
}
/// <summary>
/// The numerator of the fraction.
/// </summary>
public int Numerator
{
get { return numerator; }
}
/// <summary>
/// The denominator of the fraction.
/// </summary>
public int Denominator
{
get { return denominator; }
}
/// <summary>
/// Returns the truncated value of the fraction.
/// </summary>
/// <returns></returns>
public int Truncate()
{
return denominator > 0 ? (int)(numerator / denominator) : 0;
}
/// <summary>
/// Returns whether the fraction is representing an integer value.
/// </summary>
public bool IsInteger
{
get
{
return (denominator == 1 ||
(denominator != 0 && (numerator % denominator == 0)) ||
(denominator == 0 && numerator == 0));
}
}
/// <summary>
/// Calculated the greatest common divisor of 'a' and 'b'.
/// </summary>
private static long Gcd(long a, long b)
{
a = Math.Abs(a);
b = Math.Abs(b);
long r;
while (b > 0)
{
r = a % b;
a = b;
b = r;
}
return a;
}
/// <summary>
/// Calculated the smallest common multiple of 'a' and 'b'.
/// </summary>
private static long Scm(int n, int m)
{
return Math.Abs((long)n * (long)m) / Gcd(n, m);
}
/// <summary>
/// Normalizes the fraction.
/// </summary>
private void Normalize()
{
if (denominator == 0)
{
numerator = 0;
denominator = 1;
return;
}
if (numerator != 1 && denominator != 1)
{
int common = (int)Gcd(numerator, denominator);
if (common != 1 && common != 0)
{
numerator /= common;
denominator /= common;
}
}
if (denominator < 0)
{
numerator *= -1;
denominator *= -1;
}
}
/// <summary>
/// Normalizes a fraction.
/// </summary>
private static void Normalize(ref long numerator, ref long denominator)
{
if (denominator == 0)
{
numerator = 0;
denominator = 1;
}
else if (numerator != 1 && denominator != 1)
{
long common = Gcd(numerator, denominator);
if (common != 1)
{
numerator /= common;
denominator /= common;
}
}
if (denominator < 0)
{
numerator *= -1;
denominator *= -1;
}
}
/// <summary>
/// Returns the digits after the point.
/// </summary>
private static int GetDigits(decimal value)
{
int result = 0;
value -= decimal.Truncate(value);
while (value != 0)
{
value *= 10;
value -= decimal.Truncate(value);
result++;
}
return result;
}
/// <summary>
/// Creates a continued fraction of a decimal value.
/// </summary>
private static int[] CreateContinuedFraction(decimal value)
{
int precision = GetDigits(value);
decimal epsilon = 0.0000001m;
List<int> list = new List<int>();
value = Math.Abs(value);
byte b = 0;
list.Add((int)value);
value -= ((int)value);
while (value != 0m)
{
if (++b == byte.MaxValue || value < epsilon)
{
break;
}
value = 1m / value;
if (Math.Abs((Math.Round(value, precision - 1) - value)) < epsilon)
{
value = Math.Round(value, precision - 1);
}
list.Add((int)value);
value -= ((int)value);
}
return list.ToArray();
}
/// <summary>
/// Creates a fraction from a continued fraction.
/// </summary>
private static void CreateFraction(int[] continuedFraction, out int numerator, out int denominator)
{
numerator = 1;
denominator = 0;
int temp;
for (int i = continuedFraction.Length - 1; i > -1; i--)
{
temp = numerator;
numerator = continuedFraction[i] * numerator + denominator;
denominator = temp;
}
}
/// <summary>
/// Tries 'brute force' to approximate <paramref name="value"/> with a fraction.
/// </summary>
private static void ApproximateFraction(decimal value, int maxDen, out int num, out int den)
{
num = 0;
den = 0;
decimal bestDifference = 1m;
decimal currentDifference = -1m;
int digits = GetDigits(value);
if (digits <= 9)
{
int mul = 1;
for (int i = 1; i <= digits; i++)
{
mul *= 10;
}
if (mul <= maxDen)
{
num = (int)(value * mul);
den = mul;
return;
}
}
for (int i = 1; i <= maxDen; i++)
{
int numerator = (int)Math.Floor(value * (decimal)i + 0.5m);
currentDifference = Math.Abs(value - (decimal)numerator / (decimal)i);
if (currentDifference < bestDifference)
{
num = numerator;
den = i;
bestDifference = currentDifference;
}
}
}
/// <summary>
/// Converts the numeric value of the <see cref="FIRational"/> object
/// to its equivalent string representation.
/// </summary>
/// <returns>The string representation of the value of this instance.</returns>
public override string ToString()
{
return ((IConvertible)this).ToDouble(null).ToString();
}
/// <summary>
/// Tests whether the specified object is a <see cref="FIRational"/> structure
/// and is equivalent to this <see cref="FIRational"/> structure.
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><b>true</b> if <paramref name="obj"/> is a <see cref="FIRational"/> structure
/// equivalent to this <see cref="FIRational"/> structure; otherwise, <b>false</b>.</returns>
public override bool Equals(object obj)
{
return ((obj is FIRational) && (this == ((FIRational)obj)));
}
/// <summary>
/// Returns a hash code for this <see cref="FIRational"/> structure.
/// </summary>
/// <returns>An integer value that specifies the hash code for this <see cref="FIRational"/>.</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
#region Operators
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static FIRational operator +(FIRational r1)
{
return r1;
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static FIRational operator -(FIRational r1)
{
r1.numerator *= -1;
return r1;
}
/// <summary>
/// Returns the reciprocal value of this instance.
/// </summary>
public static FIRational operator ~(FIRational r1)
{
int temp = r1.denominator;
r1.denominator = r1.numerator;
r1.numerator = temp;
r1.Normalize();
return r1;
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static FIRational operator ++(FIRational r1)
{
checked
{
r1.numerator += r1.denominator;
}
return r1;
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static FIRational operator --(FIRational r1)
{
checked
{
r1.numerator -= r1.denominator;
}
return r1;
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static FIRational operator +(FIRational r1, FIRational r2)
{
long numerator = 0;
long denominator = Scm(r1.denominator, r2.denominator);
numerator = (r1.numerator * (denominator / r1.denominator)) + (r2.numerator * (denominator / r2.denominator));
Normalize(ref numerator, ref denominator);
checked
{
return new FIRational((int)numerator, (int)denominator);
}
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static FIRational operator -(FIRational r1, FIRational r2)
{
return r1 + (-r2);
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static FIRational operator *(FIRational r1, FIRational r2)
{
long numerator = r1.numerator * r2.numerator;
long denominator = r1.denominator * r2.denominator;
Normalize(ref numerator, ref denominator);
checked
{
return new FIRational((int)numerator, (int)denominator);
}
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static FIRational operator /(FIRational r1, FIRational r2)
{
int temp = r2.denominator;
r2.denominator = r2.numerator;
r2.numerator = temp;
return r1 * r2;
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static FIRational operator %(FIRational r1, FIRational r2)
{
r2.Normalize();
if (Math.Abs(r2.numerator) < r2.denominator)
return new FIRational(0, 0);
int div = (int)(r1 / r2);
return r1 - (r2 * div);
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static bool operator ==(FIRational r1, FIRational r2)
{
r1.Normalize();
r2.Normalize();
return (r1.numerator == r2.numerator) && (r1.denominator == r2.denominator);
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static bool operator !=(FIRational r1, FIRational r2)
{
return !(r1 == r2);
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static bool operator >(FIRational r1, FIRational r2)
{
long denominator = Scm(r1.denominator, r2.denominator);
return (r1.numerator * (denominator / r1.denominator)) > (r2.numerator * (denominator / r2.denominator));
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static bool operator <(FIRational r1, FIRational r2)
{
long denominator = Scm(r1.denominator, r2.denominator);
return (r1.numerator * (denominator / r1.denominator)) < (r2.numerator * (denominator / r2.denominator));
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static bool operator >=(FIRational r1, FIRational r2)
{
long denominator = Scm(r1.denominator, r2.denominator);
return (r1.numerator * (denominator / r1.denominator)) >= (r2.numerator * (denominator / r2.denominator));
}
/// <summary>
/// Standard implementation of the operator.
/// </summary>
public static bool operator <=(FIRational r1, FIRational r2)
{
long denominator = Scm(r1.denominator, r2.denominator);
return (r1.numerator * (denominator / r1.denominator)) <= (r2.numerator * (denominator / r2.denominator));
}
#endregion
#region Conversions
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to a <see cref="Boolean"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="Boolean"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator bool(FIRational value)
{
return (value.numerator != 0);
}
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to a <see cref="Byte"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="Byte"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator byte(FIRational value)
{
return (byte)(double)value;
}
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to a <see cref="Char"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="Char"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator char(FIRational value)
{
return (char)(double)value;
}
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to a <see cref="Decimal"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="Decimal"/> initialized to <paramref name="value"/>.</returns>
public static implicit operator decimal(FIRational value)
{
return value.denominator == 0 ? 0m : (decimal)value.numerator / (decimal)value.denominator;
}
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to a <see cref="Double"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="Double"/> initialized to <paramref name="value"/>.</returns>
public static implicit operator double(FIRational value)
{
return value.denominator == 0 ? 0d : (double)value.numerator / (double)value.denominator;
}
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to an <see cref="Int16"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="Int16"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator short(FIRational value)
{
return (short)(double)value;
}
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to an <see cref="Int32"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="Int32"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator int(FIRational value)
{
return (int)(double)value;
}
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to an <see cref="Int64"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="Int64"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator long(FIRational value)
{
return (byte)(double)value;
}
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to a <see cref="Single"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="Single"/> initialized to <paramref name="value"/>.</returns>
public static implicit operator float(FIRational value)
{
return value.denominator == 0 ? 0f : (float)value.numerator / (float)value.denominator;
}
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to a <see cref="SByte"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="SByte"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator sbyte(FIRational value)
{
return (sbyte)(double)value;
}
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to an <see cref="UInt16"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="UInt16"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator ushort(FIRational value)
{
return (ushort)(double)value;
}
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to an <see cref="UInt32"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="UInt32"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator uint(FIRational value)
{
return (uint)(double)value;
}
/// <summary>
/// Converts the value of a <see cref="FIRational"/> structure to an <see cref="UInt64"/> structure.
/// </summary>
/// <param name="value">A <see cref="FIRational"/> structure.</param>
/// <returns>A new instance of <see cref="UInt64"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator ulong(FIRational value)
{
return (ulong)(double)value;
}
//
/// <summary>
/// Converts the value of a <see cref="Boolean"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">A <see cref="Boolean"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator FIRational(bool value)
{
return new FIRational(value ? 1 : 0, 1);
}
/// <summary>
/// Converts the value of a <see cref="Byte"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">A <see cref="Byte"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static implicit operator FIRational(byte value)
{
return new FIRational(value, 1);
}
/// <summary>
/// Converts the value of a <see cref="Char"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">A <see cref="Char"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static implicit operator FIRational(char value)
{
return new FIRational(value, 1);
}
/// <summary>
/// Converts the value of a <see cref="Decimal"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">A <see cref="Decimal"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator FIRational(decimal value)
{
return new FIRational(value);
}
/// <summary>
/// Converts the value of a <see cref="Double"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">A <see cref="Double"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator FIRational(double value)
{
return new FIRational((decimal)value);
}
/// <summary>
/// Converts the value of an <see cref="Int16"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">An <see cref="Int16"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static implicit operator FIRational(short value)
{
return new FIRational(value, 1);
}
/// <summary>
/// Converts the value of an <see cref="Int32"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">An <see cref="Int32"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static implicit operator FIRational(int value)
{
return new FIRational(value, 1);
}
/// <summary>
/// Converts the value of an <see cref="Int64"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">An <see cref="Int64"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator FIRational(long value)
{
return new FIRational((int)value, 1);
}
/// <summary>
/// Converts the value of a <see cref="SByte"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">A <see cref="SByte"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static implicit operator FIRational(sbyte value)
{
return new FIRational(value, 1);
}
/// <summary>
/// Converts the value of a <see cref="Single"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">A <see cref="Single"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator FIRational(float value)
{
return new FIRational((decimal)value);
}
/// <summary>
/// Converts the value of an <see cref="UInt16"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">An <see cref="UInt16"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static implicit operator FIRational(ushort value)
{
return new FIRational(value, 1);
}
/// <summary>
/// Converts the value of an <see cref="UInt32"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">An <see cref="UInt32"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator FIRational(uint value)
{
return new FIRational((int)value, 1);
}
/// <summary>
/// Converts the value of an <see cref="UInt64"/> structure to a <see cref="FIRational"/> structure.
/// </summary>
/// <param name="value">An <see cref="UInt64"/> structure.</param>
/// <returns>A new instance of <see cref="FIRational"/> initialized to <paramref name="value"/>.</returns>
public static explicit operator FIRational(ulong value)
{
return new FIRational((int)value, 1);
}
#endregion
#region IConvertible Member
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.Double;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return (bool)this;
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return (byte)this;
}
char IConvertible.ToChar(IFormatProvider provider)
{
return (char)this;
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return Convert.ToDateTime(((IConvertible)this).ToDouble(provider));
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return this;
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return this;
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return (short)this;
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return (int)this;
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return (long)this;
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return (sbyte)this;
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return this;
}
string IConvertible.ToString(IFormatProvider provider)
{
return ToString(((double)this).ToString(), provider);
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return Convert.ChangeType(((IConvertible)this).ToDouble(provider), conversionType, provider);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return (ushort)this;
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return (uint)this;
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return (ulong)this;
}
#endregion
#region IComparable Member
/// <summary>
/// Compares this instance with a specified <see cref="Object"/>.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>A 32-bit signed integer indicating the lexical relationship between the two comparands.</returns>
/// <exception cref="ArgumentException"><paramref name="obj"/> is not a <see cref="FIRational"/>.</exception>
public int CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
if (!(obj is FIRational))
{
throw new ArgumentException();
}
return CompareTo((FIRational)obj);
}
#endregion
#region IFormattable Member
/// <summary>
/// Formats the value of the current instance using the specified format.
/// </summary>
/// <param name="format">The String specifying the format to use.</param>
/// <param name="formatProvider">The IFormatProvider to use to format the value.</param>
/// <returns>A String containing the value of the current instance in the specified format.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
if (format == null)
{
format = "";
}
return String.Format(formatProvider, format, ((IConvertible)this).ToDouble(formatProvider));
}
#endregion
#region IEquatable<FIRational> Member
/// <summary>
/// Tests whether the specified <see cref="FIRational"/> structure is equivalent to this <see cref="FIRational"/> structure.
/// </summary>
/// <param name="other">A <see cref="FIRational"/> structure to compare to this instance.</param>
/// <returns><b>true</b> if <paramref name="obj"/> is a <see cref="FIRational"/> structure
/// equivalent to this <see cref="FIRational"/> structure; otherwise, <b>false</b>.</returns>
public bool Equals(FIRational other)
{
return (this == other);
}
#endregion
#region IComparable<FIRational> Member
/// <summary>
/// Compares this instance with a specified <see cref="FIRational"/> object.
/// </summary>
/// <param name="other">A <see cref="FIRational"/> to compare.</param>
/// <returns>A signed number indicating the relative values of this instance
/// and <paramref name="other"/>.</returns>
public int CompareTo(FIRational other)
{
FIRational difference = this - other;
difference.Normalize();
if (difference.numerator > 0) return 1;
if (difference.numerator < 0) return -1;
else return 0;
}
#endregion
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using Microsoft.SPOT.Platform.Test;
namespace Microsoft.SPOT.Platform.Tests
{
public class SystemTypeTests : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// Add your functionality here.
Log.Comment("These tests examine the System.Type methods and properties");
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
//SystemType Test methods
interface iEmpty{ }
class TestObject1{ }
class TestObject2 : iEmpty
{
public TestObject2(Int32 i)
{
m_data = (int)i;
}
public int m_data;
class m_subTestObject
{
}
public void Method1()
{
}
public Int32 Method2(Int32 I)
{
return I;
}
}
[TestMethod]
public MFTestResults Number_ToString_Test()
{
bool bRet = true;
// if the negative number can not be truncated to the range specified it
// will display its full hex value
bRet &= "FE" == ((sbyte ) -2).ToString("x02");
bRet &= "36" == ((byte ) 0x36).ToString("x02");
bRet &= "FF" == ((byte ) 255).ToString("X2");
bRet &= "FFFD" == ((short ) -3).ToString("x04");
bRet &= "3049" == ((ushort) 0x3049).ToString("x4");
bRet &= "FC00" == ((short ) -1024).ToString("x02");
bRet &= "FFFFFFFC" == ((int ) -4).ToString("x8");
bRet &= "00004494" == ((uint ) 0x4494).ToString("x8");
bRet &= "FFFFFFFC" == ((int ) -4).ToString("x04");
bRet &= "FFFFFFFFFFFFFFFB" == ((long ) -5).ToString("x016");
bRet &= "1234567890123456" == ((ulong )0x1234567890123456).ToString("x16");
// you should not be able to truncate the value only leading zeros
bRet &= "1234567890123456" == ((ulong )0x1234567890123456).ToString("x06");
bRet &= "34567890123456" == ((ulong )0x0034567890123456).ToString("x14");
string tst = 3210.ToString("D");
bRet &= "3210" == tst;
tst = (-3210).ToString("d");
bRet &= "-3210" == tst;
tst = 3210.ToString("d06");
bRet &= "003210" == tst;
tst = (-3210).ToString("d06");
bRet &= "-003210" == tst;
tst = 3210.ToString("d1");
bRet &= "3210" == tst;
tst = (-3210).ToString("d1");
bRet &= "-3210" == tst;
tst = 3210.ToString("g");
bRet &= "3210" == tst;
tst = (-3210).ToString("g");
bRet &= "-3210" == tst;
bRet &= "NaN" == ((float)0f / 0f).ToString();
bRet &= "Infinity" == ((float)1f / 0f).ToString();
bRet &= "-Infinity" == ((float)-1f / 0f).ToString();
bRet &= "NaN" == ((double)0f / 0f).ToString();
bRet &= "Infinity" == ((double)1f / 0f).ToString();
bRet &= "-Infinity" == ((double)-1f / 0f).ToString();
if (bRet)
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults SystemType1_GetType_Test()
{
/// <summary>
/// 1. Tests the GetType(String) method
/// 2. Tests the GetType() method
/// </summary>
///
bool testResult = true;
try
{
Int32 testInt32 = 0;
Assembly Int32Assm = Assembly.Load("mscorlib");
Log.Comment("This tests the Assembly.GetType(String) by passing \"Namespace.Class\"");
Type myType0 = Int32Assm.GetType("System.Int32");
Log.Comment("The full name is " + myType0.FullName);
testResult &= (myType0 == testInt32.GetType());
Log.Comment("This tests the Type.GetType(String) by passing \"Namespace.Class\"");
Type myType1 = Type.GetType("System.Int32");
Log.Comment("The full name is " + myType1.FullName);
testResult &= (myType1 == testInt32.GetType());
Log.Comment("This tests the Type.GetType(String) by passing \"Namespace.Class, assembly\"");
Type myType2 = Type.GetType("System.Int32, mscorlib");
Log.Comment("The full name is " + myType2.FullName);
testResult &= (myType2 == testInt32.GetType());
Log.Comment("This tests the Type.GetType(String) by passing \"Namespace.Class, assembly, Version=\"a.b.c.d\"\"");
string typeName3 = "System.Int32, mscorlib, Version=" + Int32Assm.GetName().Version.ToString();
Type myType3 = Type.GetType(typeName3);
Log.Comment("The full name is " + myType3.FullName);
testResult &= (myType3 == testInt32.GetType());
Log.Comment("This tests the Type.GetType() method for nested classes");
TestObject1 testTestObject1 = new TestObject1();
Type myType4 = testTestObject1.GetType();
Log.Comment("The full name is " + myType4.FullName);
testResult &= (myType4 == Type.GetType("Microsoft.SPOT.Platform.Tests.SystemTypeTests+TestObject1"));
Log.Comment("Since NoneSuch does not exist in this assembly, ");
Log.Comment("GetType throws a TypeLoadException.");
Type myType5 = Type.GetType("NoneSuch");
Log.Comment("The full name is " + myType5.FullName);
}
catch (Exception e)
{
Log.Comment("Typeless " + e.Message);
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemType1_Type_Names_Test()
{
/// <summary>
/// 1. Tests the Name(String) method
/// 2. Tests the AssemblyQualifiedName() method
/// </summary>
///
bool testResult = false;
try
{
Assembly Int32Assm = Assembly.Load("mscorlib");
// types must be the same whereexver they come from
Type myType0 = Int32Assm.GetType("System.Int32");
Type myType1 = Type.GetType("System.Int32");
if (myType0 == myType1)
{
// names must be compatible and composable
if (myType0.Name == myType1.Name)
{
// names must be compatible and composable
if (myType0.FullName == myType1.FullName)
{
// assembly must be the same
if (myType0.Assembly == myType1.Assembly)
{
// type must come from assembly it is supposed to come from
if (Int32Assm == myType0.Assembly)
{
// verify that the long name is corrent
string fullAssmName = Int32Assm.FullName;
if (myType0.AssemblyQualifiedName == (myType0.FullName + ", " + fullAssmName))
{
testResult = true;
}
}
}
}
}
}
}
catch (Exception e)
{
Log.Comment("Exception caught " + e.Message);
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemType2_Assembly_Test()
{
/// <summary>
/// 1. Tests the Assembly property for system and user defined types
/// Fails if exception thrown
/// </summary>
///
bool testResult = true;
try
{
Log.Comment("This tests the Assembly property");
//Assigned and manipulated to avoid compiler warning
Int32 testInt32 = -1;
testInt32++;
Type myType1 = Type.GetType("System.Int32");
Log.Comment("The full name is " + myType1.Assembly.FullName);
testResult &= (myType1.Assembly.FullName == "mscorlib, Version=" + myType1.Assembly.GetName().Version.ToString());
TestObject1 testTestObject1 = new TestObject1();
Type myType2 = testTestObject1.GetType();
Log.Comment("The full name is " + myType2.Assembly.FullName);
testResult &= (myType2.Assembly.FullName == "Microsoft.SPOT.Platform.Tests.Systemlib2, Version=" + myType2.Assembly.GetName().Version.ToString());
}
catch (Exception e)
{
Log.Comment("Typeless " + e.Message);
testResult = false;
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemType3_BaseType_Test()
{
/// <summary>
/// 1. Tests the BaseType property for system and user defined types
/// </summary>
///
bool testResult = true;
try
{
Log.Comment("This tests the BaseType() method");
//Assigned and manipulated to avoid compiler warning
Int32 testInt32 = -1;
testInt32++;
Type myType1 = Type.GetType("System.Int32");
Log.Comment("The full name is " + myType1.FullName);
testResult &= (myType1.BaseType == Type.GetType("System.ValueType"));
TestObject1 testTestObject1 = new TestObject1();
Type myType2 = testTestObject1.GetType();
Log.Comment("The full name is " + myType2.FullName);
testResult &= (myType2.BaseType == Type.GetType("System.Object"));
}
catch (Exception e)
{
Log.Comment("Typeless " + e.Message);
testResult = false;
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemType4_DeclaringType_Test()
{
/// <summary>
/// 1. Tests the BaseType DeclaringType for system and user defined types
/// </summary>
///
bool testResult = true;
try
{
Log.Comment("This tests the DeclaringType property");
//Assigned and manipulated to avoid compiler warning
Int32 testInt32 = -1;
testInt32++;
Type myType1 = Type.GetType("System.Int32");
Log.Comment("The full name is " + myType1.FullName);
testResult &= (myType1.DeclaringType == null);
TestObject1 testTestObject1 = new TestObject1();
Type myType2 = testTestObject1.GetType();
Log.Comment("The full name is " + myType2.FullName);
Type myType3 = this.GetType();
testResult &= (myType2.DeclaringType == myType3);
}
catch (Exception e)
{
Log.Comment("Typeless " + e.Message);
testResult = false;
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemType5_GetConstructor_Test()
{
/// <summary>
/// 1. Tests the GetConstructor(Type[]) method for a user defined type
/// </summary>
///
bool testResult = true;
try
{
Log.Comment("This tests the GetConstructor(Type[]) method");
TestObject2 testTestObject2 = new TestObject2(5);
Type myType2 = testTestObject2.GetType();
Log.Comment("The full name is " + myType2.FullName);
Type[] typeOfInt32Arr = new Type[] { Type.GetType("System.Int32") };
object[] value5Arr = new object[] { 5 };
TestObject2 testTestObject3 =
(TestObject2)myType2.GetConstructor(typeOfInt32Arr).Invoke(value5Arr);
testResult &= (testTestObject2.m_data == testTestObject3.m_data);
}
catch (Exception e)
{
Log.Comment("Typeless " + e.Message);
testResult = false;
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemType6_GetElementType_Test()
{
/// <summary>
/// 1. Tests the GetElementType() method for a user defined type
/// </summary>
///
bool testResult = true;
try
{
Log.Comment("This tests the GetElementType() method");
//Assigned and manipulated to avoid compiler warning
Int32 testInt32 = -1;
testInt32++;
Type myType1 = Type.GetType("System.Int32");
Log.Comment("The full name is " + myType1.FullName);
Int32[] int32Arr = new Int32[] { };
Type int32ArrType = int32Arr.GetType();
testResult &= (myType1 == int32ArrType.GetElementType());
testResult &= (myType1.GetElementType() == null);
}
catch (Exception e)
{
Log.Comment("Typeless " + e.Message);
testResult = false;
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemType7_GetField_Test()
{
/// <summary>
/// 1. Test the GetField(String) method
/// 2. Test the GetField(String,BindingFlags) method
/// TODO: Expand test #2 once bug 17246 is resolved
/// </summary>
///
bool testResult = true;
try
{
Log.Comment("This tests the GetField(String) ");
Log.Comment("and the GetField(String,BindingFlags) methods)");
Log.Comment("Currently this test fails, see 17246 for more details.");
Type myType1 = Type.GetType("System.Int32");
Log.Comment("The full name is " + myType1.FullName);
testResult &= (myType1.GetField("m_data") == null);
Log.Comment(" TestObject2 type has one data member \"m_data\" of type Int32.");
TestObject2 testTestObject2 = new TestObject2(5);
Type myType2 = testTestObject2.GetType();
Log.Comment("The full name is " + myType2.FullName);
Log.Comment(" Check that type of m_data is Int32");
testResult &= (myType2.GetField("m_data", BindingFlags.GetField |
BindingFlags.Public | BindingFlags.Instance).FieldType == myType1);
Log.Comment(" Check that value in m_data is 5 ( becuase we called new TestObject2(5))");
testResult &= ((int)myType2.GetField("m_data", BindingFlags.IgnoreCase |
BindingFlags.GetField | BindingFlags.Public |
BindingFlags.Instance).GetValue(testTestObject2) == 5);
if ( !testResult ) { Log.Exception( " Last test failed " ); }
Log.Comment(" Check that m_data is a field");
testResult &= (myType2.GetField("m_data").MemberType == MemberTypes.Field);
if (!testResult) { Log.Exception(" Last test failed "); }
Log.Comment(" Check that field m_data has Name \"m_data\"");
testResult &= (myType2.GetField("m_data").Name == "m_data");
if (!testResult) { Log.Exception(" Last test failed "); }
Log.Comment(" Check that misspelling of m_data return NULL.");
testResult &= null == myType2.GetField("data");
if (!testResult) { Log.Exception(" Last test failed "); }
Log.Comment(" Checks that case misspelling of m_data return NULL if flag BindingFlags.IgnoreCase not specified.");
testResult &= null == myType2.GetField("m_Data");
if (!testResult) { Log.Exception(" Last test failed "); }
Log.Comment("Check retrieval with BindingFlags.IgnoreCase. If flag BindingFlags.IgnoreCase is ised, then the case should be ignored. We should get the same type information.");
FieldInfo fInfo_m_Data = myType2.GetField("m_Data", BindingFlags.IgnoreCase | BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance);
FieldInfo fInfo_m_data = myType2.GetField("m_data");
testResult &= fInfo_m_Data != null && fInfo_m_data != null;
testResult &= fInfo_m_Data.Name.Equals( fInfo_m_data.Name );
if (!testResult) { Log.Exception(" Last test failed "); }
Log.Comment(" Indirectly set m_data in testTestObject2 to 6 and then check it.");
myType2.GetField("m_data").SetValue(testTestObject2, 6);
testResult &= ((int)myType2.GetField("m_data").GetValue(testTestObject2) == 6);
testResult &= testTestObject2.m_data == 6;
if (!testResult) { Log.Exception(" Last test failed "); }
}
// In case of exceptions we log it and set testResult = false;
catch (NullReferenceException e)
{
Log.Comment("NullRef " + e.Message);
testResult = false;
}
catch (Exception e)
{
Log.Comment("Typeless " + e.Message);
testResult = false;
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemType8_GetFields_Test()
{
/// <summary>
/// 1. Test the GetFields(String) method
/// 2. Test the GetFields(String,BindingFlags) method
/// This test is currently a stub
/// TODO: Write test #2 once bug 17246 is resolved
/// </summary>
///
bool testResult = true;
try
{
Log.Comment("This tests the GetFields(String) method");
Log.Comment("This test must be re-written once BindingFlags is working, ");
Log.Comment("see 17246 for more details.");
Type myType1 = Type.GetType("System.Int32");
Log.Comment("The full name is " + myType1.FullName);
testResult &= (myType1.GetField("m_data") == null);
TestObject2 testTestObject2 = new TestObject2(5);
Type myType2 = testTestObject2.GetType();
Log.Comment("The full name is " + myType2.FullName);
testResult &= (myType2.GetField("m_data").FieldType == myType1);
testResult &= ((int)myType2.GetField("m_data").GetValue(testTestObject2) == 5);
testResult &= (myType2.GetField("m_data").MemberType == MemberTypes.Field);
testResult &= (myType2.GetField("m_data").Name == "m_data");
myType2.GetField("m_data").SetValue(testTestObject2, 6);
testResult &= ((int)myType2.GetField("m_data").GetValue(testTestObject2) == 6);
}
catch (Exception e)
{
Log.Comment("Typeless " + e.Message); testResult = false;
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemType9_GetInterfaces_Test()
{
/// <summary>
/// 1. Test the GetInterfaces(String) method
/// 2. Test the GetInterfaces(String,BindingFlags) method
/// This test is currently a stub
/// TODO: Write test #2 once bug 17246 is resolved
/// </summary>
///
bool testResult = true;
try
{
Log.Comment("This tests the GetInterfaces() method");
Log.Comment("This test must be re-written once BindingFlags is working, ");
Log.Comment("see 17246 for more details.");
Type myType1 = Type.GetType("System.Int32");
Log.Comment("The full name is " + myType1.FullName);
testResult &= (myType1.GetInterfaces().Length == 0);
TestObject2 testTestObject2 = new TestObject2(5);
Type myType2 = testTestObject2.GetType();
Log.Comment("The full name is " + myType2.FullName);
Type myType3 =
Type.GetType("Microsoft.SPOT.Platform.Tests.SystemTypeTests+iEmpty");
testResult &= (myType2.GetInterfaces()[0] == myType3);
}
catch (Exception e)
{
Log.Comment("Typeless " + e.Message); testResult = false;
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemType10_GetMethod_Test()
{
/// <summary>
/// 1. Test the GetMethod(String) method
/// 2. Test the GetMethod(String,BindingFlags) method
/// This test is currently a stub
/// TODO: Write test #2 once bug 17246 is resolved
/// </summary>
///
bool testResult = true;
try
{
Log.Comment("This tests the GetMethod(String) method");
Log.Comment("This test must be re-written once BindingFlags is working, ");
Log.Comment("see 17246 for more details.");
Int32 I = 0;
I++;
TestObject2 testTestObject2 = new TestObject2(5);
Type myType2 = testTestObject2.GetType();
Log.Comment("The full name is " + myType2.FullName);
MethodInfo methodInfo1 = myType2.GetMethod("Method2");
testResult &= (methodInfo1.IsAbstract == false);
testResult &= (methodInfo1.IsFinal == false);
testResult &= (methodInfo1.IsPublic == true);
testResult &= (methodInfo1.IsStatic == false);
testResult &= (methodInfo1.IsVirtual == false);
testResult &= (methodInfo1.MemberType == MemberTypes.Method);
testResult &= (methodInfo1.Name == "Method2");
testResult &= (methodInfo1.ReturnType == I.GetType());
testResult &= (methodInfo1.DeclaringType == myType2);
testResult &=
((int)(methodInfo1.Invoke(testTestObject2, new object[] { 1 })) == 1);
}
catch (Exception e)
{
Log.Comment("Typeless " + e.Message); testResult = false;
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemType11_GetMethods_Test()
{
/// <summary>
/// 1. Test the GetMethods(String) method
/// 2. Test the GetMethods(String,BindingFlags) method
/// This test is currently a stub
/// TODO: Write test #2 once bug 17246 is resolved
/// </summary>
///
bool testResult = true;
try
{
Log.Comment("This tests the GetMethods() method");
Log.Comment("This test must be re-written once BindingFlags is working, ");
Log.Comment("see 17246 for more details.");
//Assigned and manipulated to avoid compiler warning
Int32 I = 0;
I++;
TestObject2 testTestObject2 = new TestObject2(5);
Type myType2 = testTestObject2.GetType();
Log.Comment("The full name is " + myType2.FullName);
MethodInfo[] methodInfoArr1 = myType2.GetMethods();
MethodInfo methodInfo1 = null;
if (methodInfoArr1[0].Name == "Method2")
{
methodInfo1 = methodInfoArr1[0];
Log.Comment("Method2 found in position 0");
}
else if (methodInfoArr1[1].Name == "Method2")
{
methodInfo1 = methodInfoArr1[1];
Log.Comment("Method2 found in position 1");
}
testResult &= (methodInfo1.IsAbstract == false);
testResult &= (methodInfo1.IsFinal == false);
testResult &= (methodInfo1.IsPublic == true);
testResult &= (methodInfo1.IsStatic == false);
testResult &= (methodInfo1.IsVirtual == false);
testResult &= (methodInfo1.MemberType == MemberTypes.Method);
testResult &= (methodInfo1.Name == "Method2");
testResult &= (methodInfo1.ReturnType == I.GetType());
testResult &= (methodInfo1.DeclaringType == myType2);
testResult &=
((int)(methodInfo1.Invoke(testTestObject2, new object[] { 1 })) == 1);
}
catch (Exception e)
{
Log.Comment("Typeless " + e.Message); testResult = false;
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
[TestMethod]
public MFTestResults SystemType12_InvokeMember_Test()
{
/// <summary>
/// 1. Test the InvokeMember(String,BindingFlags) method
/// This test is currently a stub
/// TODO: expand test #1 once bug 17246 is resolved
/// </summary>
///
bool testResult = true;
try
{
Log.Comment("This tests the InvokeMember(String,BindingFlags) method");
Log.Comment("This test must be re-written once BindingFlags is working, ");
Log.Comment("see 17246 for more details.");
//Assigned and manipulated to avoid compiler warning
Int32 I = 0;
I++;
TestObject2 testTestObject2 = new TestObject2(5);
Type myType2 = testTestObject2.GetType();
Log.Comment("The full name is " + myType2.FullName);
testResult &= ((int)myType2.InvokeMember("Method2", BindingFlags.Default
| BindingFlags.InvokeMethod, null, testTestObject2,
new object[] { -6 }) == -6);
}
catch (NotImplementedException)
{
return MFTestResults.KnownFailure;
}
catch (Exception e)
{
Log.Comment("Typeless " + e.Message); testResult = false;
}
return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Newtonsoft.Json.ObservableSupport;
using Newtonsoft.Json.Utilities;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Specialized;
using AddingNewEventArgs = Newtonsoft.Json.ObservableSupport.AddingNewEventArgs;
using AddingNewEventHandler = Newtonsoft.Json.ObservableSupport.AddingNewEventHandler;
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a token that can contain other tokens.
/// </summary>
public abstract class JContainer : JToken, IList<JToken>
#if !(UNITY_ANDROID || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
, ITypedList, IBindingList
#else
, IList
#endif
{
#if !(UNITY_ANDROID || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
/// <summary>
/// Occurs when the list changes or an item in the list changes.
/// </summary>
public event ListChangedEventHandler ListChanged;
/// <summary>
/// Occurs before an item is added to the collection.
/// </summary>
public event AddingNewEventHandler AddingNew;
#endif
/// <summary>
/// Gets the container's children tokens.
/// </summary>
/// <value>The container's children tokens.</value>
protected abstract IList<JToken> ChildrenTokens { get; }
private object _syncRoot;
#pragma warning disable 649
private bool _busy;
#pragma warning restore 649
internal JContainer()
{
}
internal JContainer(JContainer other)
{
ValidationUtils.ArgumentNotNull(other, "c");
foreach (JToken child in other)
{
Add(child);
}
}
internal void CheckReentrancy()
{
if (_busy)
throw new InvalidOperationException("Cannot change {0} during a collection change event.".FormatWith(CultureInfo.InvariantCulture, GetType()));
}
#if !(UNITY_ANDROID || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
/// <summary>
/// Raises the <see cref="AddingNew"/> event.
/// </summary>
/// <param name="e">The <see cref="System.ComponentModel.AddingNewEventArgs"/> instance containing the event data.</param>
protected virtual void OnAddingNew(AddingNewEventArgs e)
{
AddingNewEventHandler handler = AddingNew;
if (handler != null)
handler(this, e);
}
/// <summary>
/// Raises the <see cref="ListChanged"/> event.
/// </summary>
/// <param name="e">The <see cref="ListChangedEventArgs"/> instance containing the event data.</param>
protected virtual void OnListChanged(ListChangedEventArgs e)
{
ListChangedEventHandler handler = ListChanged;
if (handler != null)
{
_busy = true;
try
{
handler(this, e);
}
finally
{
_busy = false;
}
}
}
#endif
/// <summary>
/// Gets a value indicating whether this token has childen tokens.
/// </summary>
/// <value>
/// <c>true</c> if this token has child values; otherwise, <c>false</c>.
/// </value>
public override bool HasValues
{
get { return ChildrenTokens.Count > 0; }
}
internal bool ContentsEqual(JContainer container)
{
JToken t1 = First;
JToken t2 = container.First;
if (t1 == t2)
return true;
do
{
if (t1 == null && t2 == null)
return true;
if (t1 != null && t2 != null && t1.DeepEquals(t2))
{
t1 = (t1 != Last) ? t1.Next : null;
t2 = (t2 != container.Last) ? t2.Next : null;
}
else
{
return false;
}
}
while (true);
}
/// <summary>
/// Get the first child token of this token.
/// </summary>
/// <value>
/// A <see cref="JToken"/> containing the first child token of the <see cref="JToken"/>.
/// </value>
public override JToken First
{
get { return ChildrenTokens.FirstOrDefault(); }
}
/// <summary>
/// Get the last child token of this token.
/// </summary>
/// <value>
/// A <see cref="JToken"/> containing the last child token of the <see cref="JToken"/>.
/// </value>
public override JToken Last
{
get { return ChildrenTokens.LastOrDefault(); }
}
/// <summary>
/// Returns a collection of the child tokens of this token, in document order.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> containing the child tokens of this <see cref="JToken"/>, in document order.
/// </returns>
public override JEnumerable<JToken> Children()
{
return new JEnumerable<JToken>(ChildrenTokens);
}
/// <summary>
/// Returns a collection of the child values of this token, in document order.
/// </summary>
/// <typeparam name="T">The type to convert the values to.</typeparam>
/// <returns>
/// A <see cref="IEnumerable{T}"/> containing the child values of this <see cref="JToken"/>, in document order.
/// </returns>
public override IEnumerable<T> Values<T>()
{
return ChildrenTokens.Convert<JToken, T>();
}
/// <summary>
/// Returns a collection of the descendant tokens for this token in document order.
/// </summary>
/// <returns>An <see cref="IEnumerable{JToken}"/> containing the descendant tokens of the <see cref="JToken"/>.</returns>
public IEnumerable<JToken> Descendants()
{
foreach (JToken o in ChildrenTokens)
{
yield return o;
JContainer c = o as JContainer;
if (c != null)
{
foreach (JToken d in c.Descendants())
{
yield return d;
}
}
}
}
internal bool IsMultiContent(object content)
{
return (content is IEnumerable && !(content is string) && !(content is JToken) && !(content is byte[]));
}
internal JToken EnsureParentToken(JToken item)
{
if (item == null)
return new JValue((object) null);
if (item.Parent != null)
{
item = item.CloneToken();
}
else
{
// check whether attempting to add a token to itself
JContainer parent = this;
while (parent.Parent != null)
{
parent = parent.Parent;
}
if (item == parent)
{
item = item.CloneToken();
}
}
return item;
}
private class JTokenReferenceEqualityComparer : IEqualityComparer<JToken>
{
public static readonly JTokenReferenceEqualityComparer Instance = new JTokenReferenceEqualityComparer();
public bool Equals(JToken x, JToken y)
{
return ReferenceEquals(x, y);
}
public int GetHashCode(JToken obj)
{
if (obj == null)
return 0;
return obj.GetHashCode();
}
}
internal int IndexOfItem(JToken item)
{
return ChildrenTokens.IndexOf(item, JTokenReferenceEqualityComparer.Instance);
}
internal virtual void InsertItem(int index, JToken item)
{
if (index > ChildrenTokens.Count)
throw new ArgumentOutOfRangeException("index", "Index must be within the bounds of the List.");
CheckReentrancy();
item = EnsureParentToken(item);
JToken previous = (index == 0) ? null : ChildrenTokens[index - 1];
// haven't inserted new token yet so next token is still at the inserting index
JToken next = (index == ChildrenTokens.Count) ? null : ChildrenTokens[index];
ValidateToken(item, null);
item.Parent = this;
item.Previous = previous;
if (previous != null)
previous.Next = item;
item.Next = next;
if (next != null)
next.Previous = item;
ChildrenTokens.Insert(index, item);
#if !(UNITY_ANDROID || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
if (ListChanged != null)
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, index));
#endif
}
internal virtual void RemoveItemAt(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException("index", "Index is less than 0.");
if (index >= ChildrenTokens.Count)
throw new ArgumentOutOfRangeException("index", "Index is equal to or greater than Count.");
CheckReentrancy();
JToken item = ChildrenTokens[index];
JToken previous = (index == 0) ? null : ChildrenTokens[index - 1];
JToken next = (index == ChildrenTokens.Count - 1) ? null : ChildrenTokens[index + 1];
if (previous != null)
previous.Next = next;
if (next != null)
next.Previous = previous;
item.Parent = null;
item.Previous = null;
item.Next = null;
//IList implementation is broken on Web Player (Unity Bug) and RemoveAt will not remove the item
#if !UNITY_WEBPLAYER
ChildrenTokens.RemoveAt(index);
#else
if(ChildrenTokens is JObject.JPropertKeyedCollection)
{
(ChildrenTokens as JObject.JPropertKeyedCollection).RemoveItemAt(index);
}
#endif
#if !(UNITY_ANDROID || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index));
#endif
}
internal virtual bool RemoveItem(JToken item)
{
int index = IndexOfItem(item);
if (index >= 0)
{
RemoveItemAt(index);
return true;
}
return false;
}
internal virtual JToken GetItem(int index)
{
return ChildrenTokens[index];
}
internal virtual void SetItem(int index, JToken item)
{
if (index < 0)
throw new ArgumentOutOfRangeException("index", "Index is less than 0.");
if (index >= ChildrenTokens.Count)
throw new ArgumentOutOfRangeException("index", "Index is equal to or greater than Count.");
JToken existing = ChildrenTokens[index];
if (IsTokenUnchanged(existing, item))
return;
CheckReentrancy();
item = EnsureParentToken(item);
ValidateToken(item, existing);
JToken previous = (index == 0) ? null : ChildrenTokens[index - 1];
JToken next = (index == ChildrenTokens.Count - 1) ? null : ChildrenTokens[index + 1];
item.Parent = this;
item.Previous = previous;
if (previous != null)
previous.Next = item;
item.Next = next;
if (next != null)
next.Previous = item;
ChildrenTokens[index] = item;
existing.Parent = null;
existing.Previous = null;
existing.Next = null;
#if !(UNITY_ANDROID || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index));
#endif
}
internal virtual void ClearItems()
{
CheckReentrancy();
foreach (JToken item in ChildrenTokens)
{
item.Parent = null;
item.Previous = null;
item.Next = null;
}
ChildrenTokens.Clear();
#if !(UNITY_ANDROID || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
#endif
}
internal virtual void ReplaceItem(JToken existing, JToken replacement)
{
if (existing == null || existing.Parent != this)
return;
int index = IndexOfItem(existing);
SetItem(index, replacement);
}
internal virtual bool ContainsItem(JToken item)
{
return (IndexOfItem(item) != -1);
}
internal virtual void CopyItemsTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0.");
if (arrayIndex >= array.Length)
throw new ArgumentException("arrayIndex is equal to or greater than the length of array.");
if (Count > array.Length - arrayIndex)
throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.");
int index = 0;
foreach (JToken token in ChildrenTokens)
{
array.SetValue(token, arrayIndex + index);
index++;
}
}
internal static bool IsTokenUnchanged(JToken currentValue, JToken newValue)
{
JValue v1 = currentValue as JValue;
if (v1 != null)
{
// null will get turned into a JValue of type null
if (v1.Type == JTokenType.Null && newValue == null)
return true;
return v1.Equals(newValue);
}
return false;
}
internal virtual void ValidateToken(JToken o, JToken existing)
{
ValidationUtils.ArgumentNotNull(o, "o");
if (o.Type == JTokenType.Property)
throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType()));
}
/// <summary>
/// Adds the specified content as children of this <see cref="JToken"/>.
/// </summary>
/// <param name="content">The content to be added.</param>
public virtual void Add(object content)
{
AddInternal(ChildrenTokens.Count, content);
}
/// <summary>
/// Adds the specified content as the first children of this <see cref="JToken"/>.
/// </summary>
/// <param name="content">The content to be added.</param>
public void AddFirst(object content)
{
AddInternal(0, content);
}
internal void AddInternal(int index, object content)
{
if (IsMultiContent(content))
{
IEnumerable enumerable = (IEnumerable)content;
int multiIndex = index;
foreach (object c in enumerable)
{
AddInternal(multiIndex, c);
multiIndex++;
}
}
else
{
JToken item = CreateFromContent(content);
InsertItem(index, item);
}
}
internal JToken CreateFromContent(object content)
{
if (content is JToken)
return (JToken)content;
return new JValue(content);
}
/// <summary>
/// Creates an <see cref="JsonWriter"/> that can be used to add tokens to the <see cref="JToken"/>.
/// </summary>
/// <returns>An <see cref="JsonWriter"/> that is ready to have content written to it.</returns>
public JsonWriter CreateWriter()
{
return new JTokenWriter(this);
}
/// <summary>
/// Replaces the children nodes of this token with the specified content.
/// </summary>
/// <param name="content">The content.</param>
public void ReplaceAll(object content)
{
ClearItems();
Add(content);
}
/// <summary>
/// Removes the child nodes from this token.
/// </summary>
public void RemoveAll()
{
ClearItems();
}
internal void ReadTokenFrom(JsonReader r)
{
int startDepth = r.Depth;
if (!r.Read())
throw new Exception("Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name));
ReadContentFrom(r);
int endDepth = r.Depth;
if (endDepth > startDepth)
throw new Exception("Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name));
}
internal void ReadContentFrom(JsonReader r)
{
ValidationUtils.ArgumentNotNull(r, "r");
IJsonLineInfo lineInfo = r as IJsonLineInfo;
JContainer parent = this;
do
{
if (parent is JProperty && ((JProperty)parent).Value != null)
{
if (parent == this)
return;
parent = parent.Parent;
}
switch (r.TokenType)
{
case JsonToken.None:
// new reader. move to actual content
break;
case JsonToken.StartArray:
JArray a = new JArray();
a.SetLineInfo(lineInfo);
parent.Add(a);
parent = a;
break;
case JsonToken.EndArray:
if (parent == this)
return;
parent = parent.Parent;
break;
case JsonToken.StartObject:
JObject o = new JObject();
o.SetLineInfo(lineInfo);
parent.Add(o);
parent = o;
break;
case JsonToken.EndObject:
if (parent == this)
return;
parent = parent.Parent;
break;
case JsonToken.StartConstructor:
JConstructor constructor = new JConstructor(r.Value.ToString());
constructor.SetLineInfo(constructor);
parent.Add(constructor);
parent = constructor;
break;
case JsonToken.EndConstructor:
if (parent == this)
return;
parent = parent.Parent;
break;
case JsonToken.String:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Date:
case JsonToken.Boolean:
case JsonToken.Bytes:
JValue v = new JValue(r.Value);
v.SetLineInfo(lineInfo);
parent.Add(v);
break;
case JsonToken.Comment:
v = JValue.CreateComment(r.Value.ToString());
v.SetLineInfo(lineInfo);
parent.Add(v);
break;
case JsonToken.Null:
v = new JValue(null, JTokenType.Null);
v.SetLineInfo(lineInfo);
parent.Add(v);
break;
case JsonToken.Undefined:
v = new JValue(null, JTokenType.Undefined);
v.SetLineInfo(lineInfo);
parent.Add(v);
break;
case JsonToken.PropertyName:
string propertyName = r.Value.ToString();
JProperty property = new JProperty(propertyName);
property.SetLineInfo(lineInfo);
JObject parentObject = (JObject) parent;
// handle multiple properties with the same name in JSON
JProperty existingPropertyWithName = parentObject.Property(propertyName);
if (existingPropertyWithName == null)
parent.Add(property);
else
existingPropertyWithName.Replace(property);
parent = property;
break;
default:
throw new InvalidOperationException("The JsonReader should not be on a token of type {0}.".FormatWith(CultureInfo.InvariantCulture, r.TokenType));
}
}
while (r.Read());
}
internal int ContentsHashCode()
{
int hashCode = 0;
foreach (JToken item in ChildrenTokens)
{
hashCode ^= item.GetDeepHashCode();
}
return hashCode;
}
#if !(UNITY_ANDROID || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1))
string ITypedList.GetListName(PropertyDescriptor[] listAccessors)
{
return string.Empty;
}
PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors)
{
ICustomTypeDescriptor d = First as ICustomTypeDescriptor;
if (d != null)
return d.GetProperties();
return null;
}
#endif
#region IList<JToken> Members
int IList<JToken>.IndexOf(JToken item)
{
return IndexOfItem(item);
}
void IList<JToken>.Insert(int index, JToken item)
{
InsertItem(index, item);
}
void IList<JToken>.RemoveAt(int index)
{
RemoveItemAt(index);
}
JToken IList<JToken>.this[int index]
{
get { return GetItem(index); }
set { SetItem(index, value); }
}
#endregion
#region ICollection<JToken> Members
void ICollection<JToken>.Add(JToken item)
{
Add(item);
}
void ICollection<JToken>.Clear()
{
ClearItems();
}
bool ICollection<JToken>.Contains(JToken item)
{
return ContainsItem(item);
}
void ICollection<JToken>.CopyTo(JToken[] array, int arrayIndex)
{
CopyItemsTo(array, arrayIndex);
}
bool ICollection<JToken>.IsReadOnly
{
get { return false; }
}
bool ICollection<JToken>.Remove(JToken item)
{
return RemoveItem(item);
}
#endregion
private JToken EnsureValue(object value)
{
if (value == null)
return null;
if (value is JToken)
return (JToken) value;
throw new ArgumentException("Argument is not a JToken.");
}
#region IList Members
int IList.Add(object value)
{
Add(EnsureValue(value));
return Count - 1;
}
void IList.Clear()
{
ClearItems();
}
bool IList.Contains(object value)
{
return ContainsItem(EnsureValue(value));
}
int IList.IndexOf(object value)
{
return IndexOfItem(EnsureValue(value));
}
void IList.Insert(int index, object value)
{
InsertItem(index, EnsureValue(value));
}
bool IList.IsFixedSize
{
get { return false; }
}
bool IList.IsReadOnly
{
get { return false; }
}
void IList.Remove(object value)
{
RemoveItem(EnsureValue(value));
}
void IList.RemoveAt(int index)
{
RemoveItemAt(index);
}
object IList.this[int index]
{
get { return GetItem(index); }
set { SetItem(index, EnsureValue(value)); }
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
CopyItemsTo(array, index);
}
/// <summary>
/// Gets the count of child JSON tokens.
/// </summary>
/// <value>The count of child JSON tokens</value>
public int Count
{
get { return ChildrenTokens.Count; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
Interlocked.CompareExchange(ref _syncRoot, new object(), null);
return _syncRoot;
}
}
#endregion
#region IBindingList Members
#if !(UNITY_ANDROID || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1))
void IBindingList.AddIndex(PropertyDescriptor property)
{
}
object IBindingList.AddNew()
{
AddingNewEventArgs args = new AddingNewEventArgs();
OnAddingNew(args);
if (args.NewObject == null)
throw new Exception("Could not determine new value to add to '{0}'.".FormatWith(CultureInfo.InvariantCulture, GetType()));
if (!(args.NewObject is JToken))
throw new Exception("New item to be added to collection must be compatible with {0}.".FormatWith(CultureInfo.InvariantCulture, typeof (JToken)));
JToken newItem = (JToken)args.NewObject;
Add(newItem);
return newItem;
}
bool IBindingList.AllowEdit
{
get { return true; }
}
bool IBindingList.AllowNew
{
get { return true; }
}
bool IBindingList.AllowRemove
{
get { return true; }
}
void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction)
{
throw new NotSupportedException();
}
int IBindingList.Find(PropertyDescriptor property, object key)
{
throw new NotSupportedException();
}
bool IBindingList.IsSorted
{
get { return false; }
}
void IBindingList.RemoveIndex(PropertyDescriptor property)
{
}
void IBindingList.RemoveSort()
{
throw new NotSupportedException();
}
ListSortDirection IBindingList.SortDirection
{
get { return ListSortDirection.Ascending; }
}
PropertyDescriptor IBindingList.SortProperty
{
get { return null; }
}
bool IBindingList.SupportsChangeNotification
{
get { return true; }
}
bool IBindingList.SupportsSearching
{
get { return false; }
}
bool IBindingList.SupportsSorting
{
get { return false; }
}
#endif
#endregion
}
}
#endif
| |
// <copyright file="Range.cs" company="SoftChains">
// Copyright 2016 Dan Gershony
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// </copyright>
#pragma warning disable 1591
namespace Blockchain.Protocol.Bitcoin.Extension
{
#region Using Directives
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
/// <summary>
/// The range.
/// </summary>
public static class Range
{
/// <summary>
/// The s byte.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<sbyte> SByte(sbyte from, sbyte to, int step)
{
return Int32(@from, to, step).Select(i => (sbyte)i);
}
/// <summary>
/// The byte.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<byte> Byte(byte from, byte to, int step)
{
return Int32(@from, to, step).Select(i => (byte)i);
}
/// <summary>
/// The char.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<char> Char(char from, char to, int step)
{
return Int32(@from, to, step).Select(i => (char)i);
}
/// <summary>
/// The int 16.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<short> Int16(short from, short to, int step)
{
return Int32(@from, to, step).Select(i => (short)i);
}
/// <summary>
/// The u int 16.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<ushort> UInt16(ushort from, ushort to, int step)
{
return Int32(@from, to, step).Select(i => (ushort)i);
}
/// <summary>
/// The int 32.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<int> Int32(int from, int to, int step)
{
if (step <= 0) step = (step == 0) ? 1 : -step;
if (@from <= to)
{
for (int i = @from; i <= to; i += step) yield return i;
}
else
{
for (int i = @from; i >= to; i -= step) yield return i;
}
}
/// <summary>
/// The u int 32.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<uint> UInt32(uint from, uint to, uint step)
{
if (step == 0U) step = 1U;
if (@from <= to)
{
for (uint ui = @from; ui <= to; ui += step) yield return ui;
}
else
{
for (uint ui = @from; ui >= to; ui -= step) yield return ui;
}
}
/// <summary>
/// The int 64.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<long> Int64(long from, long to, long step)
{
if (step <= 0L) step = (step == 0L) ? 1L : -step;
if (@from <= to)
{
for (long l = @from; l <= to; l += step) yield return l;
}
else
{
for (long l = @from; l >= to; l -= step) yield return l;
}
}
/// <summary>
/// The u int 64.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<ulong> UInt64(ulong from, ulong to, ulong step)
{
if (step == 0UL) step = 1UL;
if (@from <= to)
{
for (ulong ul = @from; ul <= to; ul += step) yield return ul;
}
else
{
for (ulong ul = @from; ul >= to; ul -= step) yield return ul;
}
}
/// <summary>
/// The single.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<float> Single(float from, float to, float step)
{
if (step <= 0.0f) step = (step == 0.0f) ? 1.0f : -step;
if (@from <= to)
{
for (float f = @from; f <= to; f += step) yield return f;
}
else
{
for (float f = @from; f >= to; f -= step) yield return f;
}
}
/// <summary>
/// The double.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<double> Double(double from, double to, double step)
{
if (step <= 0.0) step = (step == 0.0) ? 1.0 : -step;
if (@from <= to)
{
for (double d = @from; d <= to; d += step) yield return d;
}
else
{
for (double d = @from; d >= to; d -= step) yield return d;
}
}
/// <summary>
/// The decimal.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<decimal> Decimal(decimal from, decimal to, decimal step)
{
if (step <= 0.0m) step = (step == 0.0m) ? 1.0m : -step;
if (@from <= to)
{
for (decimal m = @from; m <= to; m += step) yield return m;
}
else
{
for (decimal m = @from; m >= to; m -= step) yield return m;
}
}
/// <summary>
/// The date time.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <param name="step">
/// The step.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<DateTime> DateTime(DateTime from, DateTime to, double step)
{
if (step <= 0.0) step = (step == 0.0) ? 1.0 : -step;
if (@from <= to)
{
for (DateTime dt = @from; dt <= to; dt = dt.AddDays(step)) yield return dt;
}
else
{
for (DateTime dt = @from; dt >= to; dt = dt.AddDays(-step)) yield return dt;
}
}
/// <summary>
/// The s byte.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<sbyte> SByte(sbyte from, sbyte to)
{
return SByte(@from, to, 1);
}
/// <summary>
/// The byte.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<byte> Byte(byte from, byte to)
{
return Byte(@from, to, 1);
}
/// <summary>
/// The char.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<char> Char(char from, char to)
{
return Char(@from, to, 1);
}
/// <summary>
/// The int 16.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<short> Int16(short from, short to)
{
return Int16(@from, to, 1);
}
/// <summary>
/// The u int 16.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<ushort> UInt16(ushort from, ushort to)
{
return UInt16(@from, to, 1);
}
/// <summary>
/// The int 32.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<int> Int32(int from, int to)
{
return Int32(@from, to, 1);
}
/// <summary>
/// The u int 32.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<uint> UInt32(uint from, uint to)
{
return UInt32(@from, to, 1U);
}
/// <summary>
/// The int 64.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<long> Int64(long from, long to)
{
return Int64(@from, to, 1L);
}
/// <summary>
/// The u int 64.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<ulong> UInt64(ulong from, ulong to)
{
return UInt64(@from, to, 1UL);
}
/// <summary>
/// The single.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<float> Single(float from, float to)
{
return Single(@from, to, 1.0f);
}
/// <summary>
/// The double.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<double> Double(double from, double to)
{
return Double(@from, to, 1.0);
}
/// <summary>
/// The decimal.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<decimal> Decimal(decimal from, decimal to)
{
return Decimal(@from, to, 1.0m);
}
/// <summary>
/// The date time.
/// </summary>
/// <param name="from">
/// The from.
/// </param>
/// <param name="to">
/// The to.
/// </param>
/// <returns>
/// The IEnumerable.
/// </returns>
public static IEnumerable<DateTime> DateTime(DateTime from, DateTime to)
{
return DateTime(@from, to, 1.0);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal partial class AbstractSymbolDisplayService
{
protected abstract partial class AbstractSymbolDescriptionBuilder
{
private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance |
SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions: SymbolDisplayParameterOptions.None,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
propertyStyle:
SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeOptionalBrackets,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_descriptionStyle =
new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword);
private static readonly SymbolDisplayFormat s_globalNamespaceStyle =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included);
private readonly ISymbolDisplayService _displayService;
private readonly SemanticModel _semanticModel;
private readonly int _position;
private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService;
private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap =
new Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>>();
protected readonly Workspace Workspace;
protected readonly CancellationToken CancellationToken;
protected AbstractSymbolDescriptionBuilder(
ISymbolDisplayService displayService,
SemanticModel semanticModel,
int position,
Workspace workspace,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
CancellationToken cancellationToken)
{
_displayService = displayService;
_anonymousTypeDisplayService = anonymousTypeDisplayService;
this.Workspace = workspace;
this.CancellationToken = cancellationToken;
_semanticModel = semanticModel;
_position = position;
}
protected abstract void AddExtensionPrefix();
protected abstract void AddAwaitablePrefix();
protected abstract void AddAwaitableExtensionPrefix();
protected abstract void AddDeprecatedPrefix();
protected abstract Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol);
protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; }
protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; }
protected void AddPrefixTextForAwaitKeyword()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
PlainText(FeaturesResources.PrefixTextForAwaitKeyword),
Space());
}
protected void AddTextForSystemVoid()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
PlainText(FeaturesResources.TextForSystemVoid));
}
protected SemanticModel GetSemanticModel(SyntaxTree tree)
{
if (_semanticModel.SyntaxTree == tree)
{
return _semanticModel;
}
var model = _semanticModel.GetOriginalSemanticModel();
if (model.Compilation.ContainsSyntaxTree(tree))
{
return model.Compilation.GetSemanticModel(tree);
}
// it is from one of its p2p references
foreach (var referencedCompilation in model.Compilation.GetReferencedCompilations())
{
// find the reference that contains the given tree
if (referencedCompilation.ContainsSyntaxTree(tree))
{
return referencedCompilation.GetSemanticModel(tree);
}
}
// the tree, a source symbol is defined in, doesn't exist in universe
// how this can happen?
Contract.Requires(false, "How?");
return null;
}
private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols)
{
await AddDescriptionPartAsync(symbols[0]).ConfigureAwait(false);
AddOverloadCountPart(symbols);
FixAllAnonymousTypes(symbols[0]);
AddExceptions(symbols[0]);
}
private void AddExceptions(ISymbol symbol)
{
var exceptionTypes = symbol.GetDocumentationComment().ExceptionTypes;
if (exceptionTypes.Any())
{
var parts = new List<SymbolDisplayPart>();
parts.Add(new SymbolDisplayPart(kind: SymbolDisplayPartKind.Text, symbol: null, text: $"\r\n{WorkspacesResources.Exceptions}"));
foreach (var exceptionString in exceptionTypes)
{
parts.AddRange(LineBreak());
parts.AddRange(Space(count: 2));
parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel));
}
AddToGroup(SymbolDescriptionGroups.Exceptions, parts);
}
}
public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync(
ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return this.BuildDescription(groups);
}
public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return this.BuildDescriptionSections();
}
private async Task AddDescriptionPartAsync(ISymbol symbol)
{
if (symbol.GetAttributes().Any(x => x.AttributeClass.MetadataName == "ObsoleteAttribute"))
{
AddDeprecatedPrefix();
}
if (symbol is IDynamicTypeSymbol)
{
AddDescriptionForDynamicType();
}
else if (symbol is IFieldSymbol)
{
await AddDescriptionForFieldAsync((IFieldSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is ILocalSymbol)
{
await AddDescriptionForLocalAsync((ILocalSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is IMethodSymbol)
{
AddDescriptionForMethod((IMethodSymbol)symbol);
}
else if (symbol is ILabelSymbol)
{
AddDescriptionForLabel((ILabelSymbol)symbol);
}
else if (symbol is INamedTypeSymbol)
{
await AddDescriptionForNamedTypeAsync((INamedTypeSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is INamespaceSymbol)
{
AddDescriptionForNamespace((INamespaceSymbol)symbol);
}
else if (symbol is IParameterSymbol)
{
await AddDescriptionForParameterAsync((IParameterSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is IPropertySymbol)
{
AddDescriptionForProperty((IPropertySymbol)symbol);
}
else if (symbol is IRangeVariableSymbol)
{
AddDescriptionForRangeVariable((IRangeVariableSymbol)symbol);
}
else if (symbol is ITypeParameterSymbol)
{
AddDescriptionForTypeParameter((ITypeParameterSymbol)symbol);
}
else if (symbol is IAliasSymbol)
{
await AddDescriptionPartAsync(((IAliasSymbol)symbol).Target).ConfigureAwait(false);
}
else
{
AddDescriptionForArbitrarySymbol(symbol);
}
}
private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups)
{
var finalParts = new List<SymbolDisplayPart>();
var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2);
foreach (var group in orderedGroups)
{
if ((groups & group) == 0)
{
continue;
}
if (!finalParts.IsEmpty())
{
var newLines = GetPrecedingNewLineCount(group);
finalParts.AddRange(LineBreak(newLines));
}
var parts = _groupMap[group];
finalParts.AddRange(parts);
}
return finalParts.AsImmutable();
}
private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group)
{
switch (group)
{
case SymbolDescriptionGroups.MainDescription:
// these parts are continuations of whatever text came before them
return 0;
case SymbolDescriptionGroups.Documentation:
return 1;
case SymbolDescriptionGroups.AnonymousTypes:
return 0;
case SymbolDescriptionGroups.Exceptions:
case SymbolDescriptionGroups.TypeParameterMap:
// Everything else is in a group on its own
return 2;
default:
return Contract.FailWithReturn<int>("unknown part kind");
}
}
private IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>> BuildDescriptionSections()
{
return _groupMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.AsImmutableOrEmpty());
}
private void AddDescriptionForDynamicType()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Keyword("dynamic"));
AddToGroup(SymbolDescriptionGroups.Documentation,
PlainText(FeaturesResources.RepresentsAnObjectWhoseOperations));
}
private async Task AddDescriptionForNamedTypeAsync(INamedTypeSymbol symbol)
{
if (symbol.IsAwaitableNonDynamic(_semanticModel, _position))
{
AddAwaitablePrefix();
}
var token = await _semanticModel.SyntaxTree.GetTouchingTokenAsync(_position, this.CancellationToken).ConfigureAwait(false);
if (token != default(SyntaxToken))
{
var syntaxFactsService = this.Workspace.Services.GetLanguageServices(token.Language).GetService<ISyntaxFactsService>();
if (syntaxFactsService.IsAwaitKeyword(token))
{
AddPrefixTextForAwaitKeyword();
if (symbol.SpecialType == SpecialType.System_Void)
{
AddTextForSystemVoid();
return;
}
}
}
if (symbol.TypeKind == TypeKind.Delegate)
{
var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol.OriginalDefinition, style));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol.OriginalDefinition, s_descriptionStyle));
}
if (!symbol.IsUnboundGenericType && !TypeArgumentsAndParametersAreSame(symbol))
{
var allTypeParameters = symbol.GetAllTypeParameters().ToList();
var allTypeArguments = symbol.GetAllTypeArguments().ToList();
AddTypeParameterMapPart(allTypeParameters, allTypeArguments);
}
}
private bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol)
{
var typeArguments = symbol.GetAllTypeArguments().ToList();
var typeParameters = symbol.GetAllTypeParameters().ToList();
for (int i = 0; i < typeArguments.Count; i++)
{
var typeArgument = typeArguments[i];
var typeParameter = typeParameters[i];
if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name)
{
continue;
}
return false;
}
return true;
}
private void AddDescriptionForNamespace(INamespaceSymbol symbol)
{
if (symbol.IsGlobalNamespace)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol, s_globalNamespaceStyle));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol, s_descriptionStyle));
}
}
private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol)
{
var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false);
// Don't bother showing disambiguating text for enum members. The icon displayed
// on Quick Info should be enough.
if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum)
{
AddToGroup(SymbolDescriptionGroups.MainDescription, parts);
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.Constant)
: Description(FeaturesResources.Field),
parts);
}
}
private async Task<IEnumerable<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts;
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol)
{
var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false);
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.LocalConstant)
: Description(FeaturesResources.LocalVariable),
parts);
}
private async Task<IEnumerable<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts;
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private void AddDescriptionForLabel(ILabelSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.Label),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.RangeVariable),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForMethod(IMethodSymbol method)
{
// TODO : show duplicated member case
var awaitable = method.IsAwaitableNonDynamic(_semanticModel, _position);
var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension;
if (awaitable && extension)
{
AddAwaitableExtensionPrefix();
}
else if (awaitable)
{
AddAwaitablePrefix();
}
else if (extension)
{
AddExtensionPrefix();
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat));
if (awaitable)
{
AddAwaitableUsageText(method, _semanticModel, _position);
}
}
protected abstract void AddAwaitableUsageText(IMethodSymbol method, SemanticModel semanticModel, int position);
private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol)
{
IEnumerable<SymbolDisplayPart> initializerParts;
if (symbol.IsOptional)
{
initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.Parameter), parts);
return;
}
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.Parameter),
ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants));
}
protected virtual void AddDescriptionForProperty(IPropertySymbol symbol)
{
if (symbol.IsIndexer)
{
// TODO : show duplicated member case
// TODO : a way to check whether it is a member call off dynamic type?
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat));
return;
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat));
}
private void AddDescriptionForArbitrarySymbol(ISymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol)
{
Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol),
Space(),
PlainText(FeaturesResources.In),
Space(),
ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat));
}
private void AddOverloadCountPart(
ImmutableArray<ISymbol> symbolGroup)
{
var count = GetOverloadCount(symbolGroup);
if (count >= 1)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Space(),
Punctuation("("),
Punctuation("+"),
Space(),
PlainText(count.ToString()),
Space(),
count == 1 ? PlainText(FeaturesResources.Overload) : PlainText(FeaturesResources.Overloads),
Punctuation(")"));
}
}
private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup)
{
return symbolGroup.Select(s => s.OriginalDefinition)
.Where(s => !s.Equals(symbolGroup.First().OriginalDefinition))
.Where(s => s is IMethodSymbol || s.IsIndexer())
.Count();
}
protected void AddTypeParameterMapPart(
List<ITypeParameterSymbol> typeParameters,
List<ITypeSymbol> typeArguments)
{
var parts = new List<SymbolDisplayPart>();
var count = typeParameters.Count;
for (int i = 0; i < count; i++)
{
parts.AddRange(TypeParameterName(typeParameters[i].Name));
parts.AddRange(Space());
parts.AddRange(PlainText(FeaturesResources.Is));
parts.AddRange(Space());
parts.AddRange(ToMinimalDisplayParts(typeArguments[i]));
if (i < count - 1)
{
parts.AddRange(LineBreak());
}
}
AddToGroup(SymbolDescriptionGroups.TypeParameterMap,
parts);
}
protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray)
{
AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray);
}
protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray)
{
var partsList = partsArray.Flatten().ToList();
if (partsList.Count > 0)
{
IList<SymbolDisplayPart> existingParts;
if (!_groupMap.TryGetValue(group, out existingParts))
{
existingParts = new List<SymbolDisplayPart>();
_groupMap.Add(group, existingParts);
}
existingParts.AddRange(partsList);
}
}
private IEnumerable<SymbolDisplayPart> Description(string description)
{
return Punctuation("(")
.Concat(PlainText(description))
.Concat(Punctuation(")"))
.Concat(Space());
}
protected IEnumerable<SymbolDisplayPart> Keyword(string text)
{
return Part(SymbolDisplayPartKind.Keyword, text);
}
protected IEnumerable<SymbolDisplayPart> LineBreak(int count = 1)
{
for (int i = 0; i < count; i++)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n");
}
}
protected IEnumerable<SymbolDisplayPart> PlainText(string text)
{
return Part(SymbolDisplayPartKind.Text, text);
}
protected IEnumerable<SymbolDisplayPart> Punctuation(string text)
{
return Part(SymbolDisplayPartKind.Punctuation, text);
}
protected IEnumerable<SymbolDisplayPart> Space(int count = 1)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count));
}
protected IEnumerable<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
format = format ?? MinimallyQualifiedFormat;
return _displayService.ToMinimalDisplayParts(_semanticModel, _position, symbol, format);
}
protected IEnumerable<SymbolDisplayPart> ToDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
return _displayService.ToDisplayParts(symbol, format);
}
private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text)
{
yield return new SymbolDisplayPart(kind, symbol, text);
}
private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text)
{
return Part(kind, null, text);
}
private IEnumerable<SymbolDisplayPart> TypeParameterName(string text)
{
return Part(SymbolDisplayPartKind.TypeParameterName, text);
}
protected IEnumerable<SymbolDisplayPart> ConvertClassifications(SourceText text, IEnumerable<ClassifiedSpan> classifications)
{
var parts = new List<SymbolDisplayPart>();
ClassifiedSpan? lastSpan = null;
foreach (var span in classifications)
{
// If there is space between this span and the last one, then add a space.
if (lastSpan != null && lastSpan.Value.TextSpan.End != span.TextSpan.Start)
{
parts.AddRange(Space());
}
var kind = GetClassificationKind(span.ClassificationType);
if (kind != null)
{
parts.Add(new SymbolDisplayPart(kind.Value, null, text.ToString(span.TextSpan)));
lastSpan = span;
}
}
return parts;
}
private SymbolDisplayPartKind? GetClassificationKind(string type)
{
switch (type)
{
default:
return null;
case ClassificationTypeNames.Identifier:
return SymbolDisplayPartKind.Text;
case ClassificationTypeNames.Keyword:
return SymbolDisplayPartKind.Keyword;
case ClassificationTypeNames.NumericLiteral:
return SymbolDisplayPartKind.NumericLiteral;
case ClassificationTypeNames.StringLiteral:
return SymbolDisplayPartKind.StringLiteral;
case ClassificationTypeNames.WhiteSpace:
return SymbolDisplayPartKind.Space;
case ClassificationTypeNames.Operator:
return SymbolDisplayPartKind.Operator;
case ClassificationTypeNames.Punctuation:
return SymbolDisplayPartKind.Punctuation;
case ClassificationTypeNames.ClassName:
return SymbolDisplayPartKind.ClassName;
case ClassificationTypeNames.StructName:
return SymbolDisplayPartKind.StructName;
case ClassificationTypeNames.InterfaceName:
return SymbolDisplayPartKind.InterfaceName;
case ClassificationTypeNames.DelegateName:
return SymbolDisplayPartKind.DelegateName;
case ClassificationTypeNames.EnumName:
return SymbolDisplayPartKind.EnumName;
case ClassificationTypeNames.TypeParameterName:
return SymbolDisplayPartKind.TypeParameterName;
case ClassificationTypeNames.ModuleName:
return SymbolDisplayPartKind.ModuleName;
case ClassificationTypeNames.VerbatimStringLiteral:
return SymbolDisplayPartKind.StringLiteral;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.IO
{
/// <devdoc>
/// Listens to the system directory change notifications and
/// raises events when a directory or file within a directory changes.
/// </devdoc>
public partial class FileSystemWatcher : IDisposable
{
/// <devdoc>
/// Private instance variables
/// </devdoc>
// Directory being monitored
private string _directory;
// Filter for name matching
private string _filter;
// The watch filter for the API call.
private const NotifyFilters c_defaultNotifyFilters = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
private NotifyFilters _notifyFilters = c_defaultNotifyFilters;
// Flag to watch subtree of this directory
private bool _includeSubdirectories = false;
// Flag to note whether we are attached to the thread pool and responding to changes
private bool _enabled = false;
// Buffer size
private int _internalBufferSize = 8192;
// Used for synchronization
private bool _disposed;
// Event handlers
private FileSystemEventHandler _onChangedHandler = null;
private FileSystemEventHandler _onCreatedHandler = null;
private FileSystemEventHandler _onDeletedHandler = null;
private RenamedEventHandler _onRenamedHandler = null;
private ErrorEventHandler _onErrorHandler = null;
// To validate the input for "path"
private static readonly char[] s_wildcards = new char[] { '?', '*' };
private const int c_notifyFiltersValidMask = (int)(NotifyFilters.Attributes |
NotifyFilters.CreationTime |
NotifyFilters.DirectoryName |
NotifyFilters.FileName |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Security |
NotifyFilters.Size);
#if DEBUG
static FileSystemWatcher()
{
int s_notifyFiltersValidMask = 0;
foreach (int enumValue in Enum.GetValues(typeof(NotifyFilters)))
s_notifyFiltersValidMask |= enumValue;
Debug.Assert(c_notifyFiltersValidMask == s_notifyFiltersValidMask, "The NotifyFilters enum has changed. The c_notifyFiltersValidMask must be updated to reflect the values of the NotifyFilters enum.");
}
#endif
~FileSystemWatcher()
{
this.Dispose(false);
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class.
/// </devdoc>
public FileSystemWatcher()
{
_directory = string.Empty;
_filter = "*.*";
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class,
/// given the specified directory to monitor.
/// </devdoc>
public FileSystemWatcher(string path) : this(path, "*.*")
{
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class,
/// given the specified directory and type of files to monitor.
/// </devdoc>
public FileSystemWatcher(string path, string filter)
{
if (path == null)
throw new ArgumentNullException("path");
if (filter == null)
throw new ArgumentNullException("filter");
// Early check for directory parameter so that an exception can be thrown as early as possible.
if (path.Length == 0 || !Directory.Exists(path))
throw new ArgumentException(SR.Format(SR.InvalidDirName, path), "path");
_directory = path;
_filter = filter;
}
/// <devdoc>
/// Gets or sets the type of changes to watch for.
/// </devdoc>
public NotifyFilters NotifyFilter
{
get
{
return _notifyFilters;
}
set
{
if (((int)value & ~c_notifyFiltersValidMask) != 0)
throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, "value", (int)value, typeof(NotifyFilters).Name));
if (_notifyFilters != value)
{
_notifyFilters = value;
Restart();
}
}
}
/// <devdoc>
/// Gets or sets a value indicating whether the component is enabled.
/// </devdoc>
public bool EnableRaisingEvents
{
get
{
return _enabled;
}
set
{
if (_enabled == value)
{
return;
}
if (value)
{
StartRaisingEventsIfNotDisposed(); // will set _enabled to true once successfully started
}
else
{
StopRaisingEvents(); // will set _enabled to false
}
}
}
/// <devdoc>
/// Gets or sets the filter string, used to determine what files are monitored in a directory.
/// </devdoc>
public string Filter
{
get
{
return _filter;
}
set
{
if (string.IsNullOrEmpty(value))
{
// Skip the string compare for "*.*" since it has no case-insensitive representation that differs from
// the case-sensitive representation.
_filter = "*.*";
}
else if (!string.Equals(_filter, value, PathInternal.StringComparison))
{
_filter = value;
}
}
}
/// <devdoc>
/// Gets or sets a value indicating whether subdirectories within the specified path should be monitored.
/// </devdoc>
public bool IncludeSubdirectories
{
get
{
return _includeSubdirectories;
}
set
{
if (_includeSubdirectories != value)
{
_includeSubdirectories = value;
Restart();
}
}
}
/// <devdoc>
/// Gets or sets the size of the internal buffer.
/// </devdoc>
public int InternalBufferSize
{
get
{
return _internalBufferSize;
}
set
{
if (_internalBufferSize != value)
{
if (value < 4096)
{
_internalBufferSize = 4096;
}
else
{
_internalBufferSize = value;
}
Restart();
}
}
}
/// <summary>Allocates a buffer of the requested internal buffer size.</summary>
/// <returns>The allocated buffer.</returns>
private byte[] AllocateBuffer()
{
try
{
return new byte[_internalBufferSize];
}
catch (OutOfMemoryException)
{
throw new OutOfMemoryException(SR.Format(SR.BufferSizeTooLarge, _internalBufferSize));
}
}
/// <devdoc>
/// Gets or sets the path of the directory to watch.
/// </devdoc>
public string Path
{
get
{
return _directory;
}
set
{
value = (value == null) ? string.Empty : value;
if (!string.Equals(_directory, value, PathInternal.StringComparison))
{
if (!Directory.Exists(value))
{
throw new ArgumentException(SR.Format(SR.InvalidDirName, value));
}
_directory = value;
Restart();
}
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is changed.
/// </devdoc>
public event FileSystemEventHandler Changed
{
add
{
_onChangedHandler += value;
}
remove
{
_onChangedHandler -= value;
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is created.
/// </devdoc>
public event FileSystemEventHandler Created
{
add
{
_onCreatedHandler += value;
}
remove
{
_onCreatedHandler -= value;
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is deleted.
/// </devdoc>
public event FileSystemEventHandler Deleted
{
add
{
_onDeletedHandler += value;
}
remove
{
_onDeletedHandler -= value;
}
}
/// <devdoc>
/// Occurs when the internal buffer overflows.
/// </devdoc>
public event ErrorEventHandler Error
{
add
{
_onErrorHandler += value;
}
remove
{
_onErrorHandler -= value;
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/>
/// is renamed.
/// </devdoc>
public event RenamedEventHandler Renamed
{
add
{
_onRenamedHandler += value;
}
remove
{
_onRenamedHandler -= value;
}
}
/// <devdoc>
/// Disposes of the <see cref='System.IO.FileSystemWatcher'/>.
/// </devdoc>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <devdoc>
/// </devdoc>
protected virtual void Dispose(bool disposing)
{
try
{
if (disposing)
{
//Stop raising events cleans up managed and
//unmanaged resources.
StopRaisingEvents();
// Clean up managed resources
_onChangedHandler = null;
_onCreatedHandler = null;
_onDeletedHandler = null;
_onRenamedHandler = null;
_onErrorHandler = null;
}
else
{
FinalizeDispose();
}
}
finally
{
_disposed = true;
}
}
/// <devdoc>
/// Sees if the name given matches the name filter we have.
/// </devdoc>
/// <internalonly/>
private bool MatchPattern(string relativePath)
{
string name = System.IO.Path.GetFileName(relativePath);
return name != null ?
PatternMatcher.StrictMatchPattern(_filter, name) :
false;
}
/// <devdoc>
/// Raises the event to each handler in the list.
/// </devdoc>
/// <internalonly/>
private void NotifyInternalBufferOverflowEvent()
{
ErrorEventHandler handler = _onErrorHandler;
if (handler != null)
{
handler(this, new ErrorEventArgs(
new InternalBufferOverflowException(SR.Format(SR.FSW_BufferOverflow, _directory))));
}
}
/// <devdoc>
/// Raises the event to each handler in the list.
/// </devdoc>
/// <internalonly/>
private void NotifyRenameEventArgs(WatcherChangeTypes action, string name, string oldName)
{
// filter if there's no handler or neither new name or old name match a specified pattern
RenamedEventHandler handler = _onRenamedHandler;
if (handler != null &&
(MatchPattern(name) || MatchPattern(oldName)))
{
handler(this, new RenamedEventArgs(action, _directory, name, oldName));
}
}
/// <devdoc>
/// Raises the event to each handler in the list.
/// </devdoc>
/// <internalonly/>
private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, string name)
{
FileSystemEventHandler handler = null;
switch (changeType)
{
case WatcherChangeTypes.Created:
handler = _onCreatedHandler;
break;
case WatcherChangeTypes.Deleted:
handler = _onDeletedHandler;
break;
case WatcherChangeTypes.Changed:
handler = _onChangedHandler;
break;
default:
Debug.Fail("Unknown FileSystemEvent change type! Value: " + changeType);
break;
}
if (handler != null && MatchPattern(string.IsNullOrEmpty(name) ? _directory : name))
{
handler(this, new FileSystemEventArgs(changeType, _directory, name));
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Changed'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnChanged(FileSystemEventArgs e)
{
FileSystemEventHandler changedHandler = _onChangedHandler;
if (changedHandler != null)
{
changedHandler(this, e);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Created'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnCreated(FileSystemEventArgs e)
{
FileSystemEventHandler createdHandler = _onCreatedHandler;
if (createdHandler != null)
{
createdHandler(this, e);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Deleted'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnDeleted(FileSystemEventArgs e)
{
FileSystemEventHandler deletedHandler = _onDeletedHandler;
if (deletedHandler != null)
{
deletedHandler(this, e);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Error'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnError(ErrorEventArgs e)
{
ErrorEventHandler errorHandler = _onErrorHandler;
if (errorHandler != null)
{
errorHandler(this, e);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Renamed'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnRenamed(RenamedEventArgs e)
{
RenamedEventHandler renamedHandler = _onRenamedHandler;
if (renamedHandler != null)
{
renamedHandler(this, e);
}
}
/// <devdoc>
/// Stops and starts this object.
/// </devdoc>
/// <internalonly/>
private void Restart()
{
if (_enabled)
{
StopRaisingEvents();
StartRaisingEventsIfNotDisposed();
}
}
private void StartRaisingEventsIfNotDisposed()
{
//Cannot allocate the directoryHandle and the readBuffer if the object has been disposed; finalization has been suppressed.
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
StartRaisingEvents();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.Cci.Extensions.CSharp;
namespace Microsoft.Cci.Writers.CSharp
{
public partial class CSDeclarationWriter
{
private void WriteFieldDefinition(IFieldDefinition field)
{
if (field.IsSpecialName)
return;
WriteAttributes(field.Attributes);
if (!field.IsStatic && field.ContainingTypeDefinition.Layout == LayoutKind.Explicit && !(field is DummyPrivateField))
{
WriteFakeAttribute("System.Runtime.InteropServices.FieldOffsetAttribute", field.Offset.ToString());
}
if (field.IsNotSerialized)
{
WriteFakeAttribute("System.NonSerializedAttribute");
}
if (!field.ContainingTypeDefinition.IsEnum)
{
WriteVisibility(field.Visibility);
WriteCustomModifiers(field.CustomModifiers);
if (field.Type.IsUnsafeType())
WriteKeyword("unsafe");
if (field.IsCompileTimeConstant)
{
if (field.GetHiddenBaseField(_filter) != Dummy.Field)
WriteKeyword("new");
WriteKeyword("const");
}
else
{
if (field.IsStatic)
WriteKeyword("static");
if (field.IsReadOnly)
WriteKeyword("readonly");
}
if (!field.IsCompileTimeConstant && field.GetHiddenBaseField(_filter) != Dummy.Field)
WriteKeyword("new");
WriteTypeName(field.Type);
string name = field.Name.Value;
if (name.Contains("<") || name.Contains(">"))
{
name = name.Replace("<", "_").Replace(">", "_");
}
WriteIdentifier(name, true);
if (field.Constant != null && field.IsCompileTimeConstant)
{
WriteSpace();
WriteSymbol("=", true);
if (field.Type.IsEnum)
{
WriteFieldDefinitionValue(field);
}
else
{
WriteMetadataConstant(field.Constant);
}
}
WriteSymbol(";");
}
else
{
WriteIdentifier(field.Name);
if (field.Constant != null && field.Constant.Value != null)
{
WriteSpace();
WriteSymbol("=", true);
WriteMetadataConstant(field.Constant);
}
WriteSymbol(",");
}
}
private void WriteFieldDefinitionValue(IFieldDefinition field)
{
var resolvedType = field.Type.ResolvedType;
if (resolvedType != null)
{
foreach (var enumField in resolvedType.Fields)
{
var enumFieldValue = enumField?.Constant?.Value;
if (enumFieldValue != null && enumFieldValue.Equals(field.Constant.Value))
{
WriteTypeName(field.Type, noSpace: true);
WriteSymbol(".");
WriteIdentifier(enumField.Name);
return;
}
}
}
// couldn't find a symbol for enum, just cast it
WriteSymbol("(");
WriteTypeName(field.Type, noSpace: true);
WriteSymbol(")");
WriteMetadataConstant(field.Constant);
}
}
public class DummyPrivateField : IFieldDefinition
{
private ITypeDefinition _parentType;
private ITypeReference _type;
private IName _name;
public DummyPrivateField(ITypeDefinition parentType, ITypeReference type, string name)
{
_parentType = parentType;
_type = type;
_name = new NameTable().GetNameFor(name);
}
public uint BitLength => 0;
public IMetadataConstant CompileTimeValue => null;
public ISectionBlock FieldMapping => null;
public bool IsBitField => false;
public bool IsCompileTimeConstant => false;
public bool IsMapped { get { throw new System.NotImplementedException(); } }
public bool IsMarshalledExplicitly { get { throw new System.NotImplementedException(); } }
public bool IsNotSerialized => false;
public bool IsReadOnly => _parentType.Attributes.HasIsReadOnlyAttribute();
public bool IsRuntimeSpecial => false;
public bool IsSpecialName => false;
public IMarshallingInformation MarshallingInformation { get { throw new System.NotImplementedException(); } }
public uint Offset => 0;
public int SequenceNumber { get { throw new System.NotImplementedException(); } }
public ITypeDefinition ContainingTypeDefinition => _parentType;
public TypeMemberVisibility Visibility => TypeMemberVisibility.Private;
public ITypeDefinition Container { get { throw new System.NotImplementedException(); } }
public IName Name => _name;
public IScope<ITypeDefinitionMember> ContainingScope { get { throw new System.NotImplementedException(); } }
public IEnumerable<ICustomModifier> CustomModifiers => System.Linq.Enumerable.Empty<ICustomModifier>();
public uint InternedKey { get { throw new System.NotImplementedException(); } }
public bool IsModified { get { throw new System.NotImplementedException(); } }
public bool IsStatic => false;
public ITypeReference Type => _type;
public IFieldDefinition ResolvedField { get { throw new System.NotImplementedException(); } }
public ITypeReference ContainingType => _parentType;
public ITypeDefinitionMember ResolvedTypeDefinitionMember { get { throw new System.NotImplementedException(); } }
public IEnumerable<ICustomAttribute> Attributes => System.Linq.Enumerable.Empty<ICustomAttribute>();
public IEnumerable<ILocation> Locations { get { throw new System.NotImplementedException(); } }
public IMetadataConstant Constant => null;
public void Dispatch(IMetadataVisitor visitor)
{
throw new System.NotImplementedException();
}
public void DispatchAsReference(IMetadataVisitor visitor)
{
throw new System.NotImplementedException();
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.IO.Stores;
using osu.Framework.Platform;
using osu.Framework.Testing;
using osu.Game.Database;
using osu.Game.IO.Archives;
using osu.Game.Models;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Overlays.Notifications;
using osu.Game.Rulesets;
using osu.Game.Skinning;
using osu.Game.Stores;
using osu.Game.Utils;
#nullable enable
namespace osu.Game.Beatmaps
{
/// <summary>
/// Handles general operations related to global beatmap management.
/// </summary>
[ExcludeFromDynamicCompile]
public class BeatmapManager : IModelManager<BeatmapSetInfo>, IModelFileManager<BeatmapSetInfo, RealmNamedFileUsage>, IModelImporter<BeatmapSetInfo>, IWorkingBeatmapCache, IDisposable
{
public ITrackStore BeatmapTrackStore { get; }
private readonly BeatmapModelManager beatmapModelManager;
private readonly WorkingBeatmapCache workingBeatmapCache;
private readonly BeatmapOnlineLookupQueue? onlineBeatmapLookupQueue;
private readonly RealmAccess realm;
public BeatmapManager(Storage storage, RealmAccess realm, RulesetStore rulesets, IAPIProvider? api, AudioManager audioManager, IResourceStore<byte[]> gameResources, GameHost? host = null, WorkingBeatmap? defaultBeatmap = null, bool performOnlineLookups = false)
{
this.realm = realm;
if (performOnlineLookups)
{
if (api == null)
throw new ArgumentNullException(nameof(api), "API must be provided if online lookups are required.");
onlineBeatmapLookupQueue = new BeatmapOnlineLookupQueue(api, storage);
}
var userResources = new RealmFileStore(realm, storage).Store;
BeatmapTrackStore = audioManager.GetTrackStore(userResources);
beatmapModelManager = CreateBeatmapModelManager(storage, realm, rulesets, onlineBeatmapLookupQueue);
workingBeatmapCache = CreateWorkingBeatmapCache(audioManager, gameResources, userResources, defaultBeatmap, host);
beatmapModelManager.WorkingBeatmapCache = workingBeatmapCache;
}
protected virtual WorkingBeatmapCache CreateWorkingBeatmapCache(AudioManager audioManager, IResourceStore<byte[]> resources, IResourceStore<byte[]> storage, WorkingBeatmap? defaultBeatmap, GameHost? host)
{
return new WorkingBeatmapCache(BeatmapTrackStore, audioManager, resources, storage, defaultBeatmap, host);
}
protected virtual BeatmapModelManager CreateBeatmapModelManager(Storage storage, RealmAccess realm, RulesetStore rulesets, BeatmapOnlineLookupQueue? onlineLookupQueue) =>
new BeatmapModelManager(realm, storage, onlineLookupQueue);
/// <summary>
/// Create a new beatmap set, backed by a <see cref="BeatmapSetInfo"/> model,
/// with a single difficulty which is backed by a <see cref="BeatmapInfo"/> model
/// and represented by the returned usable <see cref="WorkingBeatmap"/>.
/// </summary>
public WorkingBeatmap CreateNew(RulesetInfo ruleset, APIUser user)
{
var metadata = new BeatmapMetadata
{
Author = new RealmUser
{
OnlineID = user.OnlineID,
Username = user.Username,
}
};
var beatmapSet = new BeatmapSetInfo
{
Beatmaps =
{
new BeatmapInfo(ruleset, new BeatmapDifficulty(), metadata)
}
};
foreach (BeatmapInfo b in beatmapSet.Beatmaps)
b.BeatmapSet = beatmapSet;
var imported = beatmapModelManager.Import(beatmapSet);
if (imported == null)
throw new InvalidOperationException("Failed to import new beatmap");
return imported.PerformRead(s => GetWorkingBeatmap(s.Beatmaps.First()));
}
/// <summary>
/// Add a new difficulty to the provided <paramref name="targetBeatmapSet"/> based on the provided <paramref name="referenceWorkingBeatmap"/>.
/// The new difficulty will be backed by a <see cref="BeatmapInfo"/> model
/// and represented by the returned <see cref="WorkingBeatmap"/>.
/// </summary>
/// <remarks>
/// Contrary to <see cref="CopyExistingDifficulty"/>, this method does not preserve hitobjects and beatmap-level settings from <paramref name="referenceWorkingBeatmap"/>.
/// The created beatmap will have zero hitobjects and will have default settings (including difficulty settings), but will preserve metadata and existing timing points.
/// </remarks>
/// <param name="targetBeatmapSet">The <see cref="BeatmapSetInfo"/> to add the new difficulty to.</param>
/// <param name="referenceWorkingBeatmap">The <see cref="WorkingBeatmap"/> to use as a baseline reference when creating the new difficulty.</param>
/// <param name="rulesetInfo">The ruleset with which the new difficulty should be created.</param>
public virtual WorkingBeatmap CreateNewDifficulty(BeatmapSetInfo targetBeatmapSet, WorkingBeatmap referenceWorkingBeatmap, RulesetInfo rulesetInfo)
{
var playableBeatmap = referenceWorkingBeatmap.GetPlayableBeatmap(rulesetInfo);
var newBeatmapInfo = new BeatmapInfo(rulesetInfo, new BeatmapDifficulty(), playableBeatmap.Metadata.DeepClone())
{
DifficultyName = NamingUtils.GetNextBestName(targetBeatmapSet.Beatmaps.Select(b => b.DifficultyName), "New Difficulty")
};
var newBeatmap = new Beatmap { BeatmapInfo = newBeatmapInfo };
foreach (var timingPoint in playableBeatmap.ControlPointInfo.TimingPoints)
newBeatmap.ControlPointInfo.Add(timingPoint.Time, timingPoint.DeepClone());
return addDifficultyToSet(targetBeatmapSet, newBeatmap, referenceWorkingBeatmap.Skin);
}
/// <summary>
/// Add a copy of the provided <paramref name="referenceWorkingBeatmap"/> to the provided <paramref name="targetBeatmapSet"/>.
/// The new difficulty will be backed by a <see cref="BeatmapInfo"/> model
/// and represented by the returned <see cref="WorkingBeatmap"/>.
/// </summary>
/// <remarks>
/// Contrary to <see cref="CreateNewDifficulty"/>, this method creates a nearly-exact copy of <paramref name="referenceWorkingBeatmap"/>
/// (with the exception of a few key properties that cannot be copied under any circumstance, like difficulty name, beatmap hash, or online status).
/// </remarks>
/// <param name="targetBeatmapSet">The <see cref="BeatmapSetInfo"/> to add the copy to.</param>
/// <param name="referenceWorkingBeatmap">The <see cref="WorkingBeatmap"/> to be copied.</param>
public virtual WorkingBeatmap CopyExistingDifficulty(BeatmapSetInfo targetBeatmapSet, WorkingBeatmap referenceWorkingBeatmap)
{
var newBeatmap = referenceWorkingBeatmap.GetPlayableBeatmap(referenceWorkingBeatmap.BeatmapInfo.Ruleset).Clone();
BeatmapInfo newBeatmapInfo;
newBeatmap.BeatmapInfo = newBeatmapInfo = referenceWorkingBeatmap.BeatmapInfo.Clone();
// assign a new ID to the clone.
newBeatmapInfo.ID = Guid.NewGuid();
// add "(copy)" suffix to difficulty name, and additionally ensure that it doesn't conflict with any other potentially pre-existing copies.
newBeatmapInfo.DifficultyName = NamingUtils.GetNextBestName(
targetBeatmapSet.Beatmaps.Select(b => b.DifficultyName),
$"{newBeatmapInfo.DifficultyName} (copy)");
// clear the hash, as that's what is used to match .osu files with their corresponding realm beatmaps.
newBeatmapInfo.Hash = string.Empty;
// clear online properties.
newBeatmapInfo.OnlineID = -1;
newBeatmapInfo.Status = BeatmapOnlineStatus.None;
return addDifficultyToSet(targetBeatmapSet, newBeatmap, referenceWorkingBeatmap.Skin);
}
private WorkingBeatmap addDifficultyToSet(BeatmapSetInfo targetBeatmapSet, IBeatmap newBeatmap, ISkin beatmapSkin)
{
// populate circular beatmap set info <-> beatmap info references manually.
// several places like `BeatmapModelManager.Save()` or `GetWorkingBeatmap()`
// rely on them being freely traversable in both directions for correct operation.
targetBeatmapSet.Beatmaps.Add(newBeatmap.BeatmapInfo);
newBeatmap.BeatmapInfo.BeatmapSet = targetBeatmapSet;
beatmapModelManager.Save(newBeatmap.BeatmapInfo, newBeatmap, beatmapSkin);
workingBeatmapCache.Invalidate(targetBeatmapSet);
return GetWorkingBeatmap(newBeatmap.BeatmapInfo);
}
/// <summary>
/// Delete a beatmap difficulty.
/// </summary>
/// <param name="beatmapInfo">The beatmap difficulty to hide.</param>
public void Hide(BeatmapInfo beatmapInfo)
{
realm.Run(r =>
{
using (var transaction = r.BeginWrite())
{
if (!beatmapInfo.IsManaged)
beatmapInfo = r.Find<BeatmapInfo>(beatmapInfo.ID);
beatmapInfo.Hidden = true;
transaction.Commit();
}
});
}
/// <summary>
/// Restore a beatmap difficulty.
/// </summary>
/// <param name="beatmapInfo">The beatmap difficulty to restore.</param>
public void Restore(BeatmapInfo beatmapInfo)
{
realm.Run(r =>
{
using (var transaction = r.BeginWrite())
{
if (!beatmapInfo.IsManaged)
beatmapInfo = r.Find<BeatmapInfo>(beatmapInfo.ID);
beatmapInfo.Hidden = false;
transaction.Commit();
}
});
}
public void RestoreAll()
{
realm.Run(r =>
{
using (var transaction = r.BeginWrite())
{
foreach (var beatmap in r.All<BeatmapInfo>().Where(b => b.Hidden))
beatmap.Hidden = false;
transaction.Commit();
}
});
}
/// <summary>
/// Returns a list of all usable <see cref="BeatmapSetInfo"/>s.
/// </summary>
/// <returns>A list of available <see cref="BeatmapSetInfo"/>.</returns>
public List<BeatmapSetInfo> GetAllUsableBeatmapSets()
{
return realm.Run(r =>
{
r.Refresh();
return r.All<BeatmapSetInfo>().Where(b => !b.DeletePending).Detach();
});
}
/// <summary>
/// Perform a lookup query on available <see cref="BeatmapSetInfo"/>s.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>The first result for the provided query, or null if no results were found.</returns>
public Live<BeatmapSetInfo>? QueryBeatmapSet(Expression<Func<BeatmapSetInfo, bool>> query)
{
return realm.Run(r => r.All<BeatmapSetInfo>().FirstOrDefault(query)?.ToLive(realm));
}
#region Delegation to BeatmapModelManager (methods which previously existed locally).
/// <summary>
/// Perform a lookup query on available <see cref="BeatmapInfo"/>s.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>The first result for the provided query, or null if no results were found.</returns>
public BeatmapInfo? QueryBeatmap(Expression<Func<BeatmapInfo, bool>> query) => beatmapModelManager.QueryBeatmap(query)?.Detach();
/// <summary>
/// Saves an <see cref="IBeatmap"/> file against a given <see cref="BeatmapInfo"/>.
/// </summary>
/// <param name="info">The <see cref="BeatmapInfo"/> to save the content against. The file referenced by <see cref="BeatmapInfo.Path"/> will be replaced.</param>
/// <param name="beatmapContent">The <see cref="IBeatmap"/> content to write.</param>
/// <param name="beatmapSkin">The beatmap <see cref="ISkin"/> content to write, null if to be omitted.</param>
public virtual void Save(BeatmapInfo info, IBeatmap beatmapContent, ISkin? beatmapSkin = null) =>
beatmapModelManager.Save(info, beatmapContent, beatmapSkin);
/// <summary>
/// A default representation of a WorkingBeatmap to use when no beatmap is available.
/// </summary>
public IWorkingBeatmap DefaultBeatmap => workingBeatmapCache.DefaultBeatmap;
/// <summary>
/// Fired when a notification should be presented to the user.
/// </summary>
public Action<Notification> PostNotification
{
set => beatmapModelManager.PostNotification = value;
}
#endregion
#region Implementation of IModelManager<BeatmapSetInfo>
public bool IsAvailableLocally(BeatmapSetInfo model)
{
return beatmapModelManager.IsAvailableLocally(model);
}
public bool Delete(BeatmapSetInfo item)
{
return beatmapModelManager.Delete(item);
}
public void Delete(List<BeatmapSetInfo> items, bool silent = false)
{
beatmapModelManager.Delete(items, silent);
}
public void Delete(Expression<Func<BeatmapSetInfo, bool>>? filter = null, bool silent = false)
{
realm.Run(r =>
{
var items = r.All<BeatmapSetInfo>().Where(s => !s.DeletePending && !s.Protected);
if (filter != null)
items = items.Where(filter);
beatmapModelManager.Delete(items.ToList(), silent);
});
}
public void UndeleteAll()
{
realm.Run(r => beatmapModelManager.Undelete(r.All<BeatmapSetInfo>().Where(s => s.DeletePending).ToList()));
}
public void Undelete(List<BeatmapSetInfo> items, bool silent = false)
{
beatmapModelManager.Undelete(items, silent);
}
public void Undelete(BeatmapSetInfo item)
{
beatmapModelManager.Undelete(item);
}
#endregion
#region Implementation of ICanAcceptFiles
public Task Import(params string[] paths)
{
return beatmapModelManager.Import(paths);
}
public Task Import(params ImportTask[] tasks)
{
return beatmapModelManager.Import(tasks);
}
public Task<IEnumerable<Live<BeatmapSetInfo>>> Import(ProgressNotification notification, params ImportTask[] tasks)
{
return beatmapModelManager.Import(notification, tasks);
}
public Task<Live<BeatmapSetInfo>?> Import(ImportTask task, bool lowPriority = false, CancellationToken cancellationToken = default)
{
return beatmapModelManager.Import(task, lowPriority, cancellationToken);
}
public Task<Live<BeatmapSetInfo>?> Import(ArchiveReader archive, bool lowPriority = false, CancellationToken cancellationToken = default)
{
return beatmapModelManager.Import(archive, lowPriority, cancellationToken);
}
public Live<BeatmapSetInfo>? Import(BeatmapSetInfo item, ArchiveReader? archive = null, bool lowPriority = false, CancellationToken cancellationToken = default)
{
return beatmapModelManager.Import(item, archive, lowPriority, cancellationToken);
}
public IEnumerable<string> HandledExtensions => beatmapModelManager.HandledExtensions;
#endregion
#region Implementation of IWorkingBeatmapCache
public WorkingBeatmap GetWorkingBeatmap(BeatmapInfo? importedBeatmap)
{
// Detached sets don't come with files.
// If we seem to be missing files, now is a good time to re-fetch.
if (importedBeatmap?.BeatmapSet?.Files.Count == 0)
{
realm.Run(r =>
{
var refetch = r.Find<BeatmapInfo>(importedBeatmap.ID)?.Detach();
if (refetch != null)
importedBeatmap = refetch;
});
}
return workingBeatmapCache.GetWorkingBeatmap(importedBeatmap);
}
public WorkingBeatmap GetWorkingBeatmap(Live<BeatmapInfo>? importedBeatmap)
{
WorkingBeatmap working = workingBeatmapCache.GetWorkingBeatmap(null);
importedBeatmap?.PerformRead(b => working = workingBeatmapCache.GetWorkingBeatmap(b));
return working;
}
void IWorkingBeatmapCache.Invalidate(BeatmapSetInfo beatmapSetInfo) => workingBeatmapCache.Invalidate(beatmapSetInfo);
void IWorkingBeatmapCache.Invalidate(BeatmapInfo beatmapInfo) => workingBeatmapCache.Invalidate(beatmapInfo);
#endregion
#region Implementation of IModelFileManager<in BeatmapSetInfo,in BeatmapSetFileInfo>
public void ReplaceFile(BeatmapSetInfo model, RealmNamedFileUsage file, Stream contents)
{
beatmapModelManager.ReplaceFile(model, file, contents);
}
public void DeleteFile(BeatmapSetInfo model, RealmNamedFileUsage file)
{
beatmapModelManager.DeleteFile(model, file);
}
public void AddFile(BeatmapSetInfo model, Stream contents, string filename)
{
beatmapModelManager.AddFile(model, contents, filename);
}
#endregion
#region Implementation of IDisposable
public void Dispose()
{
onlineBeatmapLookupQueue?.Dispose();
}
#endregion
#region Implementation of IPostImports<out BeatmapSetInfo>
public Action<IEnumerable<Live<BeatmapSetInfo>>>? PostImport
{
set => beatmapModelManager.PostImport = value;
}
#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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Text.RegularExpressions
{
public partial class Capture
{
internal Capture() { }
public int Index { get { throw null; } }
public int Length { get { throw null; } }
public string Value { get { throw null; } }
public override string ToString() { throw null; }
}
public partial class CaptureCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal CaptureCollection() { }
public int Count { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public System.Text.RegularExpressions.Capture this[int i] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(System.Array array, int arrayIndex) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
}
public partial class Group : System.Text.RegularExpressions.Capture
{
internal Group() { }
public System.Text.RegularExpressions.CaptureCollection Captures { get { throw null; } }
public string Name { get { throw null; } }
public bool Success { get { throw null; } }
public static System.Text.RegularExpressions.Group Synchronized(System.Text.RegularExpressions.Group inner) { throw null; }
}
public partial class GroupCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal GroupCollection() { }
public int Count { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public System.Text.RegularExpressions.Group this[int groupnum] { get { throw null; } }
public System.Text.RegularExpressions.Group this[string groupname] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(System.Array array, int arrayIndex) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
}
public partial class Match : System.Text.RegularExpressions.Group
{
internal Match() { }
public static System.Text.RegularExpressions.Match Empty { get { throw null; } }
public virtual System.Text.RegularExpressions.GroupCollection Groups { get { throw null; } }
public System.Text.RegularExpressions.Match NextMatch() { throw null; }
public virtual string Result(string replacement) { throw null; }
public static System.Text.RegularExpressions.Match Synchronized(System.Text.RegularExpressions.Match inner) { throw null; }
}
public partial class MatchCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
internal MatchCollection() { }
public int Count { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public virtual System.Text.RegularExpressions.Match this[int i] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(System.Array array, int arrayIndex) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
}
public delegate string MatchEvaluator(System.Text.RegularExpressions.Match match);
public partial class Regex : System.Runtime.Serialization.ISerializable
{
protected internal System.Collections.Hashtable caps;
protected internal System.Collections.Hashtable capnames;
protected internal int capsize;
protected internal string[] capslist;
protected internal System.Text.RegularExpressions.RegexRunnerFactory factory;
public static readonly System.TimeSpan InfiniteMatchTimeout;
protected internal System.TimeSpan internalMatchTimeout;
[System.CLSCompliant(false)]
protected System.Collections.IDictionary Caps { get { throw null; } set { } }
[System.CLSCompliant(false)]
protected System.Collections.IDictionary CapNames { get { throw null; } set { } }
protected internal string pattern;
protected internal System.Text.RegularExpressions.RegexOptions roptions;
protected Regex() { }
protected Regex(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public Regex(string pattern) { }
public Regex(string pattern, System.Text.RegularExpressions.RegexOptions options) { }
public Regex(string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { }
public static int CacheSize { get { throw null; } set { } }
public System.TimeSpan MatchTimeout { get { throw null; } }
public System.Text.RegularExpressions.RegexOptions Options { get { throw null; } }
public bool RightToLeft { get { throw null; } }
public static string Escape(string str) { throw null; }
public string[] GetGroupNames() { throw null; }
public int[] GetGroupNumbers() { throw null; }
public string GroupNameFromNumber(int i) { throw null; }
public int GroupNumberFromName(string name) { throw null; }
protected void InitializeReferences() { }
public bool IsMatch(string input) { throw null; }
public bool IsMatch(string input, int startat) { throw null; }
public static bool IsMatch(string input, string pattern) { throw null; }
public static bool IsMatch(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; }
public static bool IsMatch(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; }
public System.Text.RegularExpressions.Match Match(string input) { throw null; }
public System.Text.RegularExpressions.Match Match(string input, int startat) { throw null; }
public System.Text.RegularExpressions.Match Match(string input, int beginning, int length) { throw null; }
public static System.Text.RegularExpressions.Match Match(string input, string pattern) { throw null; }
public static System.Text.RegularExpressions.Match Match(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; }
public static System.Text.RegularExpressions.Match Match(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; }
public System.Text.RegularExpressions.MatchCollection Matches(string input) { throw null; }
public System.Text.RegularExpressions.MatchCollection Matches(string input, int startat) { throw null; }
public static System.Text.RegularExpressions.MatchCollection Matches(string input, string pattern) { throw null; }
public static System.Text.RegularExpressions.MatchCollection Matches(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; }
public static System.Text.RegularExpressions.MatchCollection Matches(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; }
public string Replace(string input, string replacement) { throw null; }
public string Replace(string input, string replacement, int count) { throw null; }
public string Replace(string input, string replacement, int count, int startat) { throw null; }
public static string Replace(string input, string pattern, string replacement) { throw null; }
public static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options) { throw null; }
public static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; }
public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator) { throw null; }
public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options) { throw null; }
public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; }
public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator) { throw null; }
public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count) { throw null; }
public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count, int startat) { throw null; }
public string[] Split(string input) { throw null; }
public string[] Split(string input, int count) { throw null; }
public string[] Split(string input, int count, int startat) { throw null; }
public static string[] Split(string input, string pattern) { throw null; }
public static string[] Split(string input, string pattern, System.Text.RegularExpressions.RegexOptions options) { throw null; }
public static string[] Split(string input, string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { throw null; }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { }
public override string ToString() { throw null; }
public static string Unescape(string str) { throw null; }
protected bool UseOptionC() { throw null; }
protected bool UseOptionR() { throw null; }
protected internal static void ValidateMatchTimeout(System.TimeSpan matchTimeout) { }
}
public partial class RegexMatchTimeoutException : System.TimeoutException, System.Runtime.Serialization.ISerializable
{
public RegexMatchTimeoutException() { }
protected RegexMatchTimeoutException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public RegexMatchTimeoutException(string message) { }
public RegexMatchTimeoutException(string message, System.Exception inner) { }
public RegexMatchTimeoutException(string regexInput, string regexPattern, System.TimeSpan matchTimeout) { }
public string Input { get { throw null; } }
public System.TimeSpan MatchTimeout { get { throw null; } }
public string Pattern { get { throw null; } }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { }
}
[System.FlagsAttribute]
public enum RegexOptions
{
Compiled = 8,
CultureInvariant = 512,
ECMAScript = 256,
ExplicitCapture = 4,
IgnoreCase = 1,
IgnorePatternWhitespace = 32,
Multiline = 2,
None = 0,
RightToLeft = 64,
Singleline = 16,
}
public abstract partial class RegexRunner
{
protected internal int[] runcrawl;
protected internal int runcrawlpos;
protected internal System.Text.RegularExpressions.Match runmatch;
protected internal System.Text.RegularExpressions.Regex runregex;
protected internal int[] runstack;
protected internal int runstackpos;
protected internal string runtext;
protected internal int runtextbeg;
protected internal int runtextend;
protected internal int runtextpos;
protected internal int runtextstart;
protected internal int[] runtrack;
protected internal int runtrackcount;
protected internal int runtrackpos;
protected internal RegexRunner() { }
protected void Capture(int capnum, int start, int end) { }
protected static bool CharInClass(char ch, string charClass) { throw null; }
protected static bool CharInSet(char ch, string @set, string category) { throw null; }
protected void CheckTimeout() { }
protected void Crawl(int i) { }
protected int Crawlpos() { throw null; }
protected void DoubleCrawl() { }
protected void DoubleStack() { }
protected void DoubleTrack() { }
protected void EnsureStorage() { }
protected abstract bool FindFirstChar();
protected abstract void Go();
protected abstract void InitTrackCount();
protected bool IsBoundary(int index, int startpos, int endpos) { throw null; }
protected bool IsECMABoundary(int index, int startpos, int endpos) { throw null; }
protected bool IsMatched(int cap) { throw null; }
protected int MatchIndex(int cap) { throw null; }
protected int MatchLength(int cap) { throw null; }
protected int Popcrawl() { throw null; }
protected internal System.Text.RegularExpressions.Match Scan(System.Text.RegularExpressions.Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick) { throw null; }
protected internal System.Text.RegularExpressions.Match Scan(System.Text.RegularExpressions.Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick, System.TimeSpan timeout) { throw null; }
protected void TransferCapture(int capnum, int uncapnum, int start, int end) { }
protected void Uncapture() { }
}
public abstract partial class RegexRunnerFactory
{
protected RegexRunnerFactory() { }
protected internal abstract System.Text.RegularExpressions.RegexRunner CreateInstance();
}
}
| |
//
// AssemblyBuilderTest.cs - NUnit Test Cases for the AssemblyBuilder class
//
// Zoltan Varga (vargaz@freemail.hu)
//
// (C) Ximian, Inc. http://www.ximian.com
//
//
using System;
using System.Globalization;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
using System.IO;
using System.Configuration.Assemblies;
using NUnit.Framework;
namespace MonoTests.System.Reflection.Emit
{
[TestFixture]
public class AssemblyBuilderTest
{
[AttributeUsage (AttributeTargets.Assembly)]
public sealed class FooAttribute : Attribute
{
public FooAttribute (string arg)
{
}
public FooAttribute ()
{
}
}
static int nameIndex = 0;
static AppDomain domain;
static AssemblyBuilder ab;
static ModuleBuilder mb;
string tempDir = Path.Combine (Path.GetTempPath (), "MonoTests.System.Reflection.Emit.AssemblyBuilderTest");
[SetUp]
protected void SetUp () {
if (Directory.Exists (tempDir))
Directory.Delete (tempDir, true);
Directory.CreateDirectory (tempDir);
for (int i = 1; i < 3; ++i) {
string resFile = Path.Combine (tempDir, "res" + i + ".txt");
using (StreamWriter sw = new StreamWriter (resFile)) {
sw.WriteLine ("FOO");
}
}
domain = Thread.GetDomain ();
ab = genAssembly ();
mb = ab.DefineDynamicModule ("def_module");
}
[TearDown]
protected void TearDown () {
if (Directory.Exists (tempDir))
Directory.Delete (tempDir, true);
}
private AssemblyName genAssemblyName () {
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "MonoTests.System.Reflection.Emit.AssemblyBuilderTest" + (nameIndex ++);
return assemblyName;
}
private AssemblyBuilder genAssembly () {
return domain.DefineDynamicAssembly (genAssemblyName (),
AssemblyBuilderAccess.RunAndSave,
tempDir);
}
private MethodInfo genEntryFunction (AssemblyBuilder assembly) {
ModuleBuilder module = assembly.DefineDynamicModule("module1");
TypeBuilder tb = module.DefineType ("A");
MethodBuilder mb = tb.DefineMethod ("A",
MethodAttributes.Static, typeof (void), new Type [0]);
mb.GetILGenerator ().Emit (OpCodes.Ret);
return mb;
}
[ExpectedException (typeof (NotSupportedException))]
public void TestCodeBase () {
string codebase = ab.CodeBase;
}
[ExpectedException (typeof (NotSupportedException))]
public void TestLocation () {
string location = ab.Location;
}
public void TestEntryPoint () {
Assert.AreEqual (null, ab.EntryPoint, "EntryPoint defaults to null");
MethodInfo mi = genEntryFunction (ab);
ab.SetEntryPoint (mi);
Assert.AreEqual (mi, ab.EntryPoint, "EntryPoint works");
}
public void TestSetEntryPoint () {
// Check invalid arguments
try {
ab.SetEntryPoint (null);
Assert.Fail ();
}
catch (ArgumentNullException) {
}
// Check method from other assembly
try {
ab.SetEntryPoint (typeof (AssemblyBuilderTest).GetMethod ("TestSetEntryPoint"));
Assert.Fail ();
}
catch (InvalidOperationException) {
}
}
public void TestIsDefined () {
CustomAttributeBuilder cab = new CustomAttributeBuilder (typeof (FooAttribute).GetConstructor (new Type [1] {typeof (string)}), new object [1] { "A" });
ab.SetCustomAttribute (cab);
Assert.IsTrue (ab.IsDefined (typeof (FooAttribute), false),
"IsDefined works");
Assert.IsFalse (ab.IsDefined (typeof (AssemblyVersionAttribute), false),
"IsDefined works");
}
[ExpectedException (typeof (NotSupportedException))]
public void TestGetManifestResourceNames () {
ab.GetManifestResourceNames ();
}
[ExpectedException (typeof (NotSupportedException))]
public void TestGetManifestResourceInfo () {
ab.GetManifestResourceInfo ("foo");
}
[ExpectedException (typeof (NotSupportedException))]
public void TestGetManifestResourceStream1 () {
ab.GetManifestResourceStream ("foo");
}
[ExpectedException (typeof (NotSupportedException))]
public void TestGetManifestResourceStream2 () {
ab.GetManifestResourceStream (typeof (int), "foo");
}
[ExpectedException (typeof (NotSupportedException))]
public void TestGetFiles1 () {
ab.GetFiles ();
}
[ExpectedException (typeof (NotSupportedException))]
public void TestGetFiles2 () {
ab.GetFiles (true);
}
[ExpectedException (typeof (NotSupportedException))]
public void TestGetFile () {
ab.GetFile ("foo");
}
[ExpectedException (typeof (NotSupportedException))]
public void TestGetExportedTypes () {
ab.GetExportedTypes ();
}
[ExpectedException (typeof (ArgumentNullException))]
public void TestGetDynamicModule1 () {
ab.GetDynamicModule (null);
}
[ExpectedException (typeof (ArgumentException))]
public void TestGetDynamicModule2 () {
ab.GetDynamicModule ("");
}
public void TestGetDynamicModule3 () {
Assert.IsNull (ab.GetDynamicModule ("FOO2"));
ModuleBuilder mb = ab.DefineDynamicModule ("FOO");
Assert.AreEqual (mb, ab.GetDynamicModule ("FOO"));
Assert.IsNull (ab.GetDynamicModule ("FOO4"));
}
#if NET_1_1
public void TestImageRuntimeVersion () {
string version = ab.ImageRuntimeVersion;
Assert.IsTrue (version.Length > 0);
}
#endif
[ExpectedException (typeof (ArgumentNullException))]
public void TestAddResourceFileNullName () {
ab.AddResourceFile (null, "foo.txt");
}
[ExpectedException (typeof (ArgumentNullException))]
public void TestAddResourceFileNullFilename () {
ab.AddResourceFile ("foo", null);
}
[ExpectedException (typeof (ArgumentException))]
public void TestAddResourceFileEmptyName () {
ab.AddResourceFile ("", "foo.txt");
}
[ExpectedException (typeof (ArgumentException))]
public void TestAddResourceFileEmptyFilename () {
ab.AddResourceFile ("foo", "");
}
[ExpectedException (typeof (FileNotFoundException))]
public void TestAddResourceFileNonexistentFile () {
ab.AddResourceFile ("foo", "not-existent.txt");
}
[ExpectedException (typeof (ArgumentException))]
public void TestAddResourceFileDuplicateFileName () {
ab.AddResourceFile ("foo", "res1.txt");
ab.AddResourceFile ("foo2", "res1.txt");
}
[ExpectedException (typeof (ArgumentException))]
public void TestAddResourceFileDuplicateName () {
ab.AddResourceFile ("foo", "res1.txt");
ab.AddResourceFile ("foo", "res2.txt");
}
[ExpectedException (typeof (ArgumentException))]
public void TestAddResourceFileFilenameIncludesPath () {
ab.AddResourceFile ("foo", "/tmp/res1.txt");
}
public void TestAddResourceFile () {
ab.AddResourceFile ("foo", "res2.txt", ResourceAttributes.Public);
ab.Save ("TestAddResourceFile.dll");
// TODO: Test reading back
}
public void TestDefineResource () {
ab.DefineResource ("foo", "FOO", "foo.txt", ResourceAttributes.Public);
ab.DefineResource ("foo2", "FOO", "foo2.txt");
ab.Save ("TestDefineResource.dll");
}
[ExpectedException (typeof (ArgumentNullException))]
public void TestDefineDynamicModuleNullName () {
ab.DefineDynamicModule (null, "foo.txt");
}
[ExpectedException (typeof (ArgumentNullException))]
public void TestDefineDynamicModuleNullFilename () {
ab.DefineDynamicModule ("foo", null);
}
[ExpectedException (typeof (ArgumentException))]
public void TestDefineDynamicModuleEmptyName () {
ab.DefineDynamicModule ("", "foo.txt");
}
[ExpectedException (typeof (ArgumentException))]
public void TestDefineDynamicModuleEmptyFilename () {
ab.DefineDynamicModule ("foo", "");
}
[ExpectedException (typeof (ArgumentException))]
public void TestDefineDynamicModuleDuplicateFileName () {
ab.DefineDynamicModule ("foo", "res1.txt");
ab.DefineDynamicModule ("foo2", "res1.txt");
}
[ExpectedException (typeof (ArgumentException))]
public void TestDefineDynamicModuleDuplicateName () {
ab.DefineDynamicModule ("foo", "res1.txt");
ab.DefineDynamicModule ("foo", "res2.txt");
}
[ExpectedException (typeof (ArgumentException))]
public void TestDefineDynamicModuleFilenameIncludesPath () {
ab.DefineDynamicModule ("foo", "/tmp/res1.txt");
}
[ExpectedException (typeof (ArgumentException))]
public void TestDefineDynamicModule5 () {
// Filename without extension
ab.DefineDynamicModule ("foo", "foo");
}
/*
[ExpectedException (typeof (ArgumentException))]
public void TestDefineDynamicModule6 () {
// Name too long
string name = "";
for (int i = 0; i < 259; ++i)
name = name + "A";
try {
ab.DefineDynamicModule (name);
}
catch (Exception) {
Assert.Fail ();
}
name = name + "A";
// LAMESPEC: According to MSDN, this should throw an ArgumentException
ab.DefineDynamicModule (name);
}
*/
[ExpectedException (typeof (InvalidOperationException))]
public void TestDefineDynamicModule7 () {
// Called when assembly was already saved
ab.Save ("TestDefineDynamicModule7.dll");
ab.DefineDynamicModule ("foo", "foo.dll");
}
[ExpectedException (typeof (NotSupportedException))]
public void TestDefineDynamicModule8 () {
// Called on an assembly defined with the Run attribute
AssemblyBuilder ab =
domain.DefineDynamicAssembly (genAssemblyName (),
AssemblyBuilderAccess.Run,
tempDir);
ab.DefineDynamicModule ("foo", "foo.dll");
}
public void TestDefineDynamicModule () {
ab.DefineDynamicModule ("foo", "foo.dll");
ab.DefineDynamicModule ("foo2", true);
ab.DefineDynamicModule ("foo3", "foo3.dll");
ab.DefineDynamicModule ("foo4", "foo4.dll", true);
}
[ExpectedException (typeof (ArgumentNullException))]
public void TestDefineUnmanagedResource1 () {
// Null argument
ab.DefineUnmanagedResource ((byte[])null);
}
[ExpectedException (typeof (ArgumentNullException))]
public void TestDefineUnmanagedResource2 () {
// Null argument
ab.DefineUnmanagedResource ((string)null);
}
[ExpectedException (typeof (ArgumentException))]
public void TestDefineUnmanagedResource3 () {
// Empty filename
ab.DefineUnmanagedResource ("");
}
[ExpectedException (typeof (FileNotFoundException))]
public void TestDefineUnmanagedResource4 () {
// Nonexistent file
ab.DefineUnmanagedResource ("not-exists.txt");
}
[ExpectedException (typeof (ArgumentNullException))]
public void TestSetCustomAttribute1 () {
// Null argument
ab.SetCustomAttribute (null);
}
[ExpectedException (typeof (ArgumentNullException))]
public void TestSetCustomAttribute2 () {
// Null constructor
ab.SetCustomAttribute (null, new byte [0]);
}
[ExpectedException (typeof (ArgumentNullException))]
public void TestSetCustomAttribute3 () {
// Null blob
ab.SetCustomAttribute (typeof(AssemblyCompanyAttribute).GetConstructor (new Type [] { typeof (String) }), null);
}
public void TestSetCustomAttribute () {
// Test common custom attributes
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyVersionAttribute).GetConstructor (new Type [] { typeof (string) }), new object [] { "1.2.3.4"}));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyCultureAttribute).GetConstructor (new Type [] { typeof (string) }), new object [] { "bar"}));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyAlgorithmIdAttribute).GetConstructor (new Type [] { typeof (AssemblyHashAlgorithm) }), new object [] { AssemblyHashAlgorithm.MD5 }));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyFlagsAttribute).GetConstructor (new Type [] { typeof (uint) }), new object [] { (uint)0x0100 }));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyDelaySignAttribute).GetConstructor (new Type [] { typeof (bool) }), new object [] { true }));
ab.SetCustomAttribute (typeof (FooAttribute).GetConstructor (new Type [] {}), new byte [0]);
ab.Save ("TestSetCustomAttribute.dll");
/* We should read back the assembly and check the attributes ... */
}
// strongname generated using "sn -k unit.snk"
static byte[] strongName = {
0x07, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32,
0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x7F, 0x7C, 0xEA, 0x4A,
0x28, 0x33, 0xD8, 0x3C, 0x86, 0x90, 0x86, 0x91, 0x11, 0xBB, 0x30, 0x0D,
0x3D, 0x69, 0x04, 0x4C, 0x48, 0xF5, 0x4F, 0xE7, 0x64, 0xA5, 0x82, 0x72,
0x5A, 0x92, 0xC4, 0x3D, 0xC5, 0x90, 0x93, 0x41, 0xC9, 0x1D, 0x34, 0x16,
0x72, 0x2B, 0x85, 0xC1, 0xF3, 0x99, 0x62, 0x07, 0x32, 0x98, 0xB7, 0xE4,
0xFA, 0x75, 0x81, 0x8D, 0x08, 0xB9, 0xFD, 0xDB, 0x00, 0x25, 0x30, 0xC4,
0x89, 0x13, 0xB6, 0x43, 0xE8, 0xCC, 0xBE, 0x03, 0x2E, 0x1A, 0x6A, 0x4D,
0x36, 0xB1, 0xEB, 0x49, 0x26, 0x6C, 0xAB, 0xC4, 0x29, 0xD7, 0x8F, 0x25,
0x11, 0xA4, 0x7C, 0x81, 0x61, 0x97, 0xCB, 0x44, 0x2D, 0x80, 0x49, 0x93,
0x48, 0xA7, 0xC9, 0xAB, 0xDB, 0xCF, 0xA3, 0x34, 0xCB, 0x6B, 0x86, 0xE0,
0x4D, 0x27, 0xFC, 0xA7, 0x4F, 0x36, 0xCA, 0x13, 0x42, 0xD3, 0x83, 0xC4,
0x06, 0x6E, 0x12, 0xE0, 0xA1, 0x3D, 0x9F, 0xA9, 0xEC, 0xD1, 0xC6, 0x08,
0x1B, 0x3D, 0xF5, 0xDB, 0x4C, 0xD4, 0xF0, 0x2C, 0xAA, 0xFC, 0xBA, 0x18,
0x6F, 0x48, 0x7E, 0xB9, 0x47, 0x68, 0x2E, 0xF6, 0x1E, 0x67, 0x1C, 0x7E,
0x0A, 0xCE, 0x10, 0x07, 0xC0, 0x0C, 0xAD, 0x5E, 0xC1, 0x53, 0x70, 0xD5,
0xE7, 0x25, 0xCA, 0x37, 0x5E, 0x49, 0x59, 0xD0, 0x67, 0x2A, 0xBE, 0x92,
0x36, 0x86, 0x8A, 0xBF, 0x3E, 0x17, 0x04, 0xFB, 0x1F, 0x46, 0xC8, 0x10,
0x5C, 0x93, 0x02, 0x43, 0x14, 0x96, 0x6A, 0xD9, 0x87, 0x17, 0x62, 0x7D,
0x3A, 0x45, 0xBE, 0x35, 0xDE, 0x75, 0x0B, 0x2A, 0xCE, 0x7D, 0xF3, 0x19,
0x85, 0x4B, 0x0D, 0x6F, 0x8D, 0x15, 0xA3, 0x60, 0x61, 0x28, 0x55, 0x46,
0xCE, 0x78, 0x31, 0x04, 0x18, 0x3C, 0x56, 0x4A, 0x3F, 0xA4, 0xC9, 0xB1,
0x41, 0xED, 0x22, 0x80, 0xA1, 0xB3, 0xE2, 0xC7, 0x1B, 0x62, 0x85, 0xE4,
0x81, 0x39, 0xCB, 0x1F, 0x95, 0xCC, 0x61, 0x61, 0xDF, 0xDE, 0xF3, 0x05,
0x68, 0xB9, 0x7D, 0x4F, 0xFF, 0xF3, 0xC0, 0x0A, 0x25, 0x62, 0xD9, 0x8A,
0x8A, 0x9E, 0x99, 0x0B, 0xFB, 0x85, 0x27, 0x8D, 0xF6, 0xD4, 0xE1, 0xB9,
0xDE, 0xB4, 0x16, 0xBD, 0xDF, 0x6A, 0x25, 0x9C, 0xAC, 0xCD, 0x91, 0xF7,
0xCB, 0xC1, 0x81, 0x22, 0x0D, 0xF4, 0x7E, 0xEC, 0x0C, 0x84, 0x13, 0x5A,
0x74, 0x59, 0x3F, 0x3E, 0x61, 0x00, 0xD6, 0xB5, 0x4A, 0xA1, 0x04, 0xB5,
0xA7, 0x1C, 0x29, 0xD0, 0xE1, 0x11, 0x19, 0xD7, 0x80, 0x5C, 0xEE, 0x08,
0x15, 0xEB, 0xC9, 0xA8, 0x98, 0xF5, 0xA0, 0xF0, 0x92, 0x2A, 0xB0, 0xD3,
0xC7, 0x8C, 0x8D, 0xBB, 0x88, 0x96, 0x4F, 0x18, 0xF0, 0x8A, 0xF9, 0x31,
0x9E, 0x44, 0x94, 0x75, 0x6F, 0x78, 0x04, 0x10, 0xEC, 0xF3, 0xB0, 0xCE,
0xA0, 0xBE, 0x7B, 0x25, 0xE1, 0xF7, 0x8A, 0xA8, 0xD4, 0x63, 0xC2, 0x65,
0x47, 0xCC, 0x5C, 0xED, 0x7D, 0x8B, 0x07, 0x4D, 0x76, 0x29, 0x53, 0xAC,
0x27, 0x8F, 0x5D, 0x78, 0x56, 0xFA, 0x99, 0x45, 0xA2, 0xCC, 0x65, 0xC4,
0x54, 0x13, 0x9F, 0x38, 0x41, 0x7A, 0x61, 0x0E, 0x0D, 0x34, 0xBC, 0x11,
0xAF, 0xE2, 0xF1, 0x8B, 0xFA, 0x2B, 0x54, 0x6C, 0xA3, 0x6C, 0x09, 0x1F,
0x0B, 0x43, 0x9B, 0x07, 0x95, 0x83, 0x3F, 0x97, 0x99, 0x89, 0xF5, 0x51,
0x41, 0xF6, 0x8E, 0x5D, 0xEF, 0x6D, 0x24, 0x71, 0x41, 0x7A, 0xAF, 0xBE,
0x81, 0x71, 0xAB, 0x76, 0x2F, 0x1A, 0x5A, 0xBA, 0xF3, 0xA6, 0x65, 0x7A,
0x80, 0x50, 0xCE, 0x23, 0xC3, 0xC7, 0x53, 0xB0, 0x7C, 0x97, 0x77, 0x27,
0x70, 0x98, 0xAE, 0xB5, 0x24, 0x66, 0xE1, 0x60, 0x39, 0x41, 0xDA, 0x54,
0x01, 0x64, 0xFB, 0x10, 0x33, 0xCE, 0x8B, 0xBE, 0x27, 0xD4, 0x21, 0x57,
0xCC, 0x0F, 0x1A, 0xC1, 0x3D, 0xF3, 0xCC, 0x39, 0xF0, 0x2F, 0xAE, 0xF1,
0xC0, 0xCD, 0x3B, 0x23, 0x87, 0x49, 0x7E, 0x40, 0x32, 0x6A, 0xD3, 0x96,
0x4A, 0xE5, 0x5E, 0x6E, 0x26, 0xFD, 0x8A, 0xCF, 0x7E, 0xFC, 0x37, 0xDE,
0x39, 0x0C, 0x53, 0x81, 0x75, 0x08, 0xAF, 0x6B, 0x39, 0x6C, 0xFB, 0xC9,
0x79, 0xC0, 0x9B, 0x5F, 0x34, 0x86, 0xB2, 0xDE, 0xC4, 0x19, 0x84, 0x5F,
0x0E, 0xED, 0x9B, 0xB8, 0xD3, 0x17, 0xDA, 0x78 };
[Test]
public void StrongName_MissingKeyFile_NoDelay ()
{
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyKeyFileAttribute).GetConstructor (new Type [] { typeof (string) }), new object [] { "missing.snk" }));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyDelaySignAttribute).GetConstructor (new Type [] { typeof (bool) }), new object [] { false }));
ab.Save ("StrongName_MissingKeyFile_NoDelay.dll");
string filename = Path.Combine (tempDir, "StrongName_MissingKeyFile_NoDelay.dll");
AssemblyName check = AssemblyName.GetAssemblyName (filename);
// no exception is thrown (file not found)
// because it's not AssemblyBuilder.Save job to do the signing :-/
Assert.IsNull (check.GetPublicKeyToken (), "Token");
}
[Test]
public void StrongName_KeyFile_Delay ()
{
string strongfile = Path.Combine (tempDir, "strongname.snk");
using (FileStream fs = File.OpenWrite (strongfile)) {
fs.Write (strongName, 0, strongName.Length);
fs.Close ();
}
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyKeyFileAttribute).GetConstructor (new Type [] { typeof (string) }), new object [] { strongfile }));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyDelaySignAttribute).GetConstructor (new Type [] { typeof (bool) }), new object [] { true }));
ab.Save ("StrongName_KeyFile_Delay.dll");
string filename = Path.Combine (tempDir, "StrongName_KeyFile_Delay.dll");
AssemblyName check = AssemblyName.GetAssemblyName (filename);
// no public key is inserted into the assembly
// because it's not AssemblyBuilder.Save job to do the signing :-/
Assert.IsNull (check.GetPublicKeyToken (), "Token");
}
[Test]
public void StrongName_WithoutAttributes ()
{
// this demonstrate that AssemblyKeyFileAttribute (or AssemblyKeyNameAttribute)
// aren't required to sign an assembly.
AssemblyName an = genAssemblyName ();
an.KeyPair = new StrongNameKeyPair (strongName);
AssemblyBuilder ab = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.RunAndSave, tempDir);
ab.Save ("StrongName_WithoutAttributes.dll");
string filename = Path.Combine (tempDir, "StrongName_WithoutAttributes.dll");
AssemblyName check = AssemblyName.GetAssemblyName (filename);
Assert.AreEqual ("0E-EA-7C-E6-5F-35-F2-D8", BitConverter.ToString (check.GetPublicKeyToken ()), "Token");
}
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void SaveUnfinishedTypes ()
{
TypeBuilder typeBuilder = mb.DefineType ("TestType", TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(object));
ab.Save ("def_module");
}
[Test]
public void GetModules ()
{
Module[] m;
m = ab.GetModules ();
Assert.IsTrue (m.Length >= 2);
// Test with no modules
AssemblyBuilder ab2 = genAssembly ();
m = ab2.GetModules ();
}
[Test]
[Category ("NotWorking")]
public void AssemblyName_Culture ()
{
AssemblyName assemblyName = new AssemblyName ();
assemblyName.Name = "AssemblyNameTest";
assemblyName.Version = new Version ("1.0.0.0");
assemblyName.CultureInfo = new CultureInfo ("en-US");
const string fullName = "AssemblyNameTest, Version=1.0.0.0, Culture=en-US, PublicKeyToken=null";
const string abName = "AssemblyNameTest, Version=1.0.0.0, Culture=en-US";
AssertAssemblyName (tempDir, assemblyName, abName, fullName);
}
[Test]
[Category ("NotWorking")] // bug #75246
public void AssemblyName_PublicKey ()
{
AssemblyName assemblyName = new AssemblyName ();
assemblyName.Name = "AssemblyNameTest";
assemblyName.Version = new Version ("1.2.3.4");
assemblyName.KeyPair = new StrongNameKeyPair (strongName);
Assert.IsNull (assemblyName.CultureInfo, "#1");
Assert.AreEqual ("AssemblyNameTest, Version=1.2.3.4", assemblyName.FullName, "#2");
const string fullName = "AssemblyNameTest, Version=1.2.3.4, Culture=neutral, PublicKeyToken=0eea7ce65f35f2d8";
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
assemblyName, AssemblyBuilderAccess.Save, tempDir);
AssemblyName abName = ab.GetName ();
Assert.IsNotNull (abName.GetPublicKeyToken (), "#3");
Assert.IsTrue (abName.GetPublicKeyToken ().Length > 0, "#4");
Assert.IsNotNull (abName.GetPublicKey () != null, "#5");
Assert.IsTrue (abName.GetPublicKey ().Length > 0, "#6");
Assert.IsNotNull (abName.CultureInfo != null, "#7");
#if NET_2_0
Assert.IsTrue (abName.CultureInfo != CultureInfo.InvariantCulture, "#8");
Assert.AreEqual (CultureInfo.InvariantCulture.LCID, abName.CultureInfo.LCID, "#9");
Assert.AreEqual (fullName, abName.FullName, "#10");
#else
Assert.AreEqual (CultureInfo.InvariantCulture, abName.CultureInfo, "#11");
Assert.AreEqual ("AssemblyNameTest, Version=1.2.3.4, PublicKeyToken=0eea7ce65f35f2d8", abName.FullName, "#12");
#endif
ab.Save ("AssemblyNameTest.dll");
AssemblyName bakedName = AssemblyName.GetAssemblyName (Path.Combine(
tempDir, "AssemblyNameTest.dll"));
Assert.IsNotNull (bakedName.GetPublicKeyToken (), "#13");
Assert.IsNotNull (bakedName.GetPublicKey (), "#14");
Assert.IsNotNull (bakedName.CultureInfo, "#15");
#if NET_2_0
Assert.IsTrue (abName.CultureInfo != CultureInfo.InvariantCulture, "#16");
Assert.AreEqual (CultureInfo.InvariantCulture.LCID, abName.CultureInfo.LCID, "#17");
#else
Assert.AreEqual (CultureInfo.InvariantCulture, bakedName.CultureInfo, "#18");
#endif
Assert.AreEqual (fullName, bakedName.FullName, "#19");
}
[Test]
[Category ("NotWorking")]
public void AssemblyName_NoVersion ()
{
AssemblyName assemblyName = new AssemblyName ();
assemblyName.Name = "AssemblyNameTest";
const string fullName = "AssemblyNameTest, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
const string abName = "AssemblyNameTest, Version=0.0.0.0";
AssertAssemblyName (tempDir, assemblyName, abName, fullName);
}
[Test]
[Category ("NotWorking")]
public void AssemblyName_Version ()
{
AssemblyName assemblyName = new AssemblyName ();
assemblyName.Name = "AssemblyNameTest";
assemblyName.Version = new Version (1, 2, 3, 4);
const string fullName = "AssemblyNameTest, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null";
const string abName = "AssemblyNameTest, Version=1.2.3.4";
AssertAssemblyName (tempDir, assemblyName, abName, fullName);
}
private static void AssertAssemblyName (string tempDir, AssemblyName assemblyName, string abName, string fullName)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
AppDomain newDomain = null;
try {
AssemblyBuilder ab = currentDomain.DefineDynamicAssembly (
assemblyName, AssemblyBuilderAccess.Save, tempDir);
ab.Save (assemblyName.Name + ".dll");
#if NET_2_0
// on .NET 2.0, the full name of the AssemblyBuilder matches the
// fully qualified assembly name
Assert.AreEqual (fullName, ab.FullName);
#else
Assert.AreEqual (abName, ab.FullName);
#endif
// load assembly in separate domain, so we can clean-up after the
// test
newDomain = AppDomain.CreateDomain ("test2", currentDomain.Evidence,
currentDomain.SetupInformation);
Helper helper = new Helper (Path.Combine (tempDir, assemblyName.Name + ".dll"),
fullName);
newDomain.DoCallBack (new CrossAppDomainDelegate (helper.Test));
} finally {
if (newDomain != null) {
AppDomain.Unload (newDomain);
}
}
}
[Serializable ()]
private class Helper
{
private readonly string _assemblyPath;
private readonly string _assemblyName;
public Helper (string assemblyPath, string assemblyName)
{
_assemblyPath = assemblyPath;
_assemblyName = assemblyName;
}
public void Test ()
{
AssemblyName assemblyName = AssemblyName.GetAssemblyName (_assemblyPath);
Assert.AreEqual (_assemblyName, assemblyName.ToString ());
}
}
}
}
| |
namespace Edi.Dialogs.FindReplace.ViewModel
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Input;
using Core.ViewModels.Base;
using Core.ViewModels.Command;
using Edi.Settings.Interfaces;
using MsgBox;
public class FindReplaceViewModel : DialogViewModelBase
{
#region fields
/// <summary>
/// Maximum of find/replace history list
/// </summary>
private const int MaxCountFindReplaceHistory = 10;
private RelayCommand<object> _mFindCommand;
private RelayCommand<object> _mReplaceCommand;
private RelayCommand<object> _mReplaceAllCommand;
private string _mTextToFind = string.Empty;
private string _mReplacementText = string.Empty;
private bool _mSearchUp = false;
private bool _mUseWildcards = false;
private bool _mCaseSensitive = false;
private bool _mUseRegEx = false;
private bool _mWholeWord = false;
private bool _mAcceptsReturn = false;
private bool _mAllowReplace = true;
private bool _mShowAsFind = true;
private bool _mIsTextToFindFocused = true;
private bool _mIsTextToFindInReplaceFocused = true;
private SearchScope _mSearchIn = SearchScope.CurrentDocument;
private bool _mShowSearchIn = true;
private readonly IMessageBoxService _MsgBox;
#endregion fields
#region constructor
/// <summary>
/// Class constructor from <seealso cref="ISettingsManager"/> manager instance to reade & write
/// strings that were searched and replaced during user session.
/// </summary>
/// <param name="settingsManager"></param>
public FindReplaceViewModel(ISettingsManager settingsManager,
IMessageBoxService msgBox)
: this()
{
_MsgBox = msgBox;
// load the find/replace history from user profile
FindHistory = settingsManager.SessionData.FindHistoryList;
ReplaceHistory = settingsManager.SessionData.ReplaceHistoryList;
}
/// <summary>
/// Hidden standard class constructor.
/// </summary>
protected FindReplaceViewModel()
{
CurrentEditor = null;
// load the find/replace history from user profile
FindHistory = null;
ReplaceHistory = null;
}
#endregion constructor
#region properties
/// <summary>
/// Get the title string of the view - to be displayed in the associated view
/// (e.g. as dialog title)
/// </summary>
public string WindowTitle { get { return Util.Local.Strings.STR_FIND_REPLACE_CAPTION; } }
/// <summary>
/// Get/set text to find via find/replace
/// </summary>
public string TextToFind
{
get { return _mTextToFind; }
set
{
if (_mTextToFind != value)
{
_mTextToFind = value;
RaisePropertyChanged(() => TextToFind);
}
}
}
/// <summary>
/// Get/set text to replace via find/replace
/// </summary>
public string ReplacementText
{
get { return _mReplacementText; }
set
{
if (_mReplacementText != value)
{
_mReplacementText = value;
RaisePropertyChanged(() => ReplacementText);
}
}
}
/// <summary>
/// Get/set whether the search is upward in text or downwards.
/// </summary>
public bool SearchUp
{
get { return _mSearchUp; }
set
{
if (_mSearchUp != value)
{
_mSearchUp = value;
RaisePropertyChanged(() => SearchUp);
}
}
}
/// <summary>
/// Get/set whether to do a wildcard based search or not.
/// </summary>
public bool UseWildcards
{
get { return _mUseWildcards; }
set
{
if (_mUseWildcards != value)
{
_mUseWildcards = value;
RaisePropertyChanged(() => UseWildcards);
}
}
}
/// <summary>
/// Get/set whether to search case sensitive or not.
/// </summary>
public bool CaseSensitive
{
get { return _mCaseSensitive; }
set
{
if (_mCaseSensitive != value)
{
_mCaseSensitive = value;
RaisePropertyChanged(() => CaseSensitive);
}
}
}
/// <summary>
/// Get/set whether to search text with regular expressions or not.
/// </summary>
public bool UseRegEx
{
get { return _mUseRegEx; }
set
{
if (_mUseRegEx != value)
{
_mUseRegEx = value;
RaisePropertyChanged(() => UseRegEx);
}
}
}
/// <summary>
/// Get/set whether to search for a whole word occurrance or not.
/// </summary>
public bool WholeWord
{
get { return _mWholeWord; }
set
{
if (_mWholeWord != value)
{
_mWholeWord = value;
RaisePropertyChanged(() => WholeWord);
}
}
}
/// <summary>
/// Get/set whether Find and Replace textbox in view
/// support multiline input or not.
/// </summary>
public bool AcceptsReturn
{
get { return _mAcceptsReturn; }
set
{
if (_mAcceptsReturn != value)
{
_mAcceptsReturn = value;
RaisePropertyChanged(() => AcceptsReturn);
}
}
}
/// <summary>
/// Get/set whether replace is to be displayed and used in view or not.
/// </summary>
public bool AllowReplace
{
get { return _mAllowReplace; }
set
{
if (_mAllowReplace != value)
{
_mAllowReplace = value;
RaisePropertyChanged(() => AllowReplace);
}
}
}
/// <summary>
/// Get/set property to determine whether dialog should show Find UI (true)
/// or whether it should show Find/Replace UI elements (false).
/// </summary>
public bool ShowAsFind
{
get { return _mShowAsFind; }
set
{
if (_mShowAsFind != value)
{
_mShowAsFind = value;
if (value == true) // Focus textbox on find tab or find/replace tab
{
IsTextToFindFocused = true;
IsTextToFindInReplaceFocused = false;
}
else
{
IsTextToFindFocused = false;
IsTextToFindInReplaceFocused = true;
}
RaisePropertyChanged(() => ShowAsFind);
}
}
}
/// <summary>
/// </summary>
public bool IsTextToFindFocused
{
get { return _mIsTextToFindFocused; }
set
{
if (_mIsTextToFindFocused != value)
{
_mIsTextToFindFocused = value;
RaisePropertyChanged(() => IsTextToFindFocused);
}
}
}
/// <summary>
/// </summary>
public bool IsTextToFindInReplaceFocused
{
get { return _mIsTextToFindInReplaceFocused; }
set
{
if (_mIsTextToFindInReplaceFocused != value)
{
_mIsTextToFindInReplaceFocused = value;
RaisePropertyChanged(() => IsTextToFindInReplaceFocused);
}
}
}
/// <summary>
/// Get/set whether to search in current document, all open documents etc.
/// </summary>
public SearchScope SearchIn
{
get { return _mSearchIn; }
set
{
if (_mSearchIn != value)
{
_mSearchIn = value;
RaisePropertyChanged(() => SearchIn);
}
}
}
/// <summary>
/// Determines whether to display the Search in choice or not.
///
/// The user can use this choice to select whether results are search/replaced:
/// 1> Only in the current document
/// 2> In all open documents
/// </summary>
public bool ShowSearchIn
{
get { return _mShowSearchIn; }
private set
{
if (_mShowSearchIn != value)
{
_mShowSearchIn = value;
RaisePropertyChanged(() => ShowSearchIn);
}
}
}
public IEditor CurrentEditor { get; set; }
public Func<FindReplaceViewModel, bool, bool> FindNext { get; set; }
public ICommand FindCommand
{
get
{
return _mFindCommand ?? (_mFindCommand = new RelayCommand<object>((p) =>
{
if (FindNext != null)
{
// remember the searched text into search history
if (TextToFind.Length > 0)
{
FindHistory.Remove(TextToFind);
FindHistory.Insert(0, TextToFind);
if (FindHistory.Count > MaxCountFindReplaceHistory)
{
FindHistory.RemoveRange(MaxCountFindReplaceHistory, FindHistory.Count - MaxCountFindReplaceHistory);
}
}
FindNext(this, _mSearchUp);
}
}));
}
}
public ICommand ReplaceCommand
{
get
{
return _mReplaceCommand ?? (_mReplaceCommand = new RelayCommand<object>((p) =>
{
AddReplaceHistory();
Replace();
}));
}
}
public ICommand ReplaceAllCommand
{
get
{
return _mReplaceAllCommand ?? (_mReplaceAllCommand = new RelayCommand<object>((p) =>
{
AddReplaceHistory();
ReplaceAll();
}));
}
}
public List<string> FindHistory { get; }
public List<string> ReplaceHistory { get; }
/// <summary>
/// Helper function to add replace history
/// </summary>
private void AddReplaceHistory()
{
// remember the replacement text into replace history
if (ReplacementText.Length > 0)
{
ReplaceHistory.Remove(ReplacementText);
ReplaceHistory.Insert(0, ReplacementText);
if (ReplaceHistory.Count > MaxCountFindReplaceHistory)
{
ReplaceHistory.RemoveRange(MaxCountFindReplaceHistory, ReplaceHistory.Count - MaxCountFindReplaceHistory);
}
}
}
#endregion properties
#region methods
/// <summary>
/// Constructs a regular expression according to the currently selected search parameters.
/// </summary>
/// <param name="forceLeftToRight"></param>
/// <returns>The regular expression.</returns>
public Regex GetRegEx(bool forceLeftToRight = false)
{
// Multiline option is required to support matching start and end of line in regex
// http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regexoptions.aspx
// http://stackoverflow.com/questions/6596060/how-to-match-begin-or-end-of-line-using-c-regex
Regex r;
RegexOptions o = RegexOptions.Multiline;
if (SearchUp && !forceLeftToRight)
o = o | RegexOptions.RightToLeft;
if (!CaseSensitive)
o = o | RegexOptions.IgnoreCase;
if (UseRegEx)
r = new Regex(TextToFind, o);
else
{
string s = Regex.Escape(TextToFind);
if (UseWildcards)
s = s.Replace("\\*", ".*").Replace("\\?", ".");
if (WholeWord)
s = "\\W" + s + "\\W";
r = new Regex(s, o);
}
return r;
}
public void FindPrevious()
{
FindNext?.Invoke(this, true);
}
public void Replace()
{
IEditor ce = GetCurrentEditor();
if (ce == null) return;
// if currently selected text matches -> replace; anyways, find the next match
Regex r = GetRegEx();
string s = ce.Text.Substring(ce.SelectionStart, ce.SelectionLength); // CE.SelectedText;
Match m = r.Match(s);
if (m.Success && m.Index == 0 && m.Length == s.Length)
{
ce.Replace(ce.SelectionStart, ce.SelectionLength, ReplacementText);
//CE.SelectedText = ReplacementText;
}
FindNext?.Invoke(this, false);
}
public void ReplaceAll(bool askBefore = true)
{
IEditor ce = GetCurrentEditor();
if (ce == null) return;
if (!askBefore || _MsgBox.Show(string.Format(Util.Local.Strings.STR_FINDREPLACE_ASK_REALLY_REPLACEEVERYTHING, TextToFind, ReplacementText),
Util.Local.Strings.STR_FINDREPLACE_ReplaceAll_Caption,
MsgBoxButtons.YesNoCancel, MsgBoxImage.Alert) == MsgBoxResult.Yes)
{
object initialEditor = CurrentEditor;
// loop through all editors, until we are back at the starting editor
do
{
Regex r = GetRegEx(true); // force left to right, otherwise indices are screwed up
int offset = 0;
ce.BeginChange();
foreach (Match m in r.Matches(ce.Text))
{
ce.Replace(offset + m.Index, m.Length, ReplacementText);
offset += ReplacementText.Length - m.Length;
}
ce.EndChange();
// XXX TODO CE = GetNextEditor();
} while (CurrentEditor != initialEditor);
}
}
public IEditor GetCurrentEditor()
{
if (CurrentEditor == null)
return null;
return CurrentEditor as IEditor;
//// if (InterfaceConverter == null)
//// return null;
////
//// return InterfaceConverter.Convert(CurrentEditor, typeof(IEditor), null, CultureInfo.CurrentCulture) as IEditor;
}
#endregion methods
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
public class NcSpriteFactory : NcEffectBehaviour
{
[Serializable]
public class NcFrameInfo
{
public int m_nFrameIndex;
public int m_nTexWidth;
public int m_nTexHeight;
public Rect m_TextureUvOffset;
public Rect m_FrameUvOffset;
public Vector2 m_FrameScale;
public Vector2 m_scaleFactor;
}
[SerializeField]
[Serializable]
public class NcSpriteNode
{
public bool m_bIncludedAtlas = true;
public string m_TextureGUID = string.Empty;
public string m_TextureName = string.Empty;
public float m_fMaxTextureAlpha = 1f;
public string m_SpriteName = string.Empty;
public NcSpriteFactory.NcFrameInfo[] m_FrameInfos;
public int m_nTilingX = 1;
public int m_nTilingY = 1;
public int m_nStartFrame;
public int m_nFrameCount = 1;
public bool m_bLoop;
public float m_fFps = 20f;
public float m_fTime;
public int m_nNextSpriteIndex = -1;
public int m_nTestMode;
public float m_fTestSpeed = 1f;
public GameObject m_EffectPrefab;
public int m_nEffectFrame;
public bool m_bEffectOnlyFirst = true;
public bool m_bEffectDetach = true;
public float m_fEffectSpeed = 1f;
public float m_fEffectScale = 1f;
public Vector3 m_EffectPos = Vector3.zero;
public Vector3 m_EffectRot = Vector3.zero;
public AudioClip m_AudioClip;
public int m_nSoundFrame;
public bool m_bSoundOnlyFirst = true;
public bool m_bSoundLoop;
public float m_fSoundVolume = 1f;
public float m_fSoundPitch = 1f;
public NcSpriteFactory.NcSpriteNode GetClone()
{
return null;
}
public int GetStartFrame()
{
if (this.m_FrameInfos == null || this.m_FrameInfos.Length == 0)
{
return 0;
}
return this.m_FrameInfos[0].m_nFrameIndex;
}
}
[SerializeField]
public enum MESH_TYPE
{
BuiltIn_Plane,
BuiltIn_TwosidePlane
}
public enum ALIGN_TYPE
{
TOP,
CENTER,
BOTTOM
}
public enum SPRITE_TYPE
{
NcSpriteTexture,
NcSpriteAnimation
}
public enum SHOW_TYPE
{
NONE,
ALL,
SPRITE,
ANIMATION,
EFFECT
}
public NcSpriteFactory.SPRITE_TYPE m_SpriteType;
public List<NcSpriteFactory.NcSpriteNode> m_SpriteList;
public int m_nCurrentIndex;
public int m_nMaxAtlasTextureSize = 2048;
public bool m_bNeedRebuild = true;
public bool m_bTrimBlack = true;
public bool m_bTrimAlpha = true;
public float m_fUvScale = 1f;
public float m_fTextureRatio = 1f;
public GameObject m_CurrentEffect;
public NcAttachSound m_CurrentSound;
protected bool m_bEndSprite = true;
public NcSpriteFactory.SHOW_TYPE m_ShowType = NcSpriteFactory.SHOW_TYPE.SPRITE;
public bool m_bShowEffect = true;
public bool m_bTestMode = true;
public bool m_bSequenceMode;
protected bool m_bbInstance;
public NcSpriteFactory.NcSpriteNode GetSpriteNode(int nIndex)
{
if (this.m_SpriteList == null || nIndex < 0 || this.m_SpriteList.Count <= nIndex)
{
return null;
}
return this.m_SpriteList[nIndex];
}
public NcSpriteFactory.NcSpriteNode GetSpriteNode(string spriteName)
{
if (this.m_SpriteList == null)
{
return null;
}
foreach (NcSpriteFactory.NcSpriteNode current in this.m_SpriteList)
{
if (current.m_SpriteName == spriteName)
{
return current;
}
}
return null;
}
public NcSpriteFactory.NcSpriteNode SetSpriteNode(int nIndex, NcSpriteFactory.NcSpriteNode newInfo)
{
if (this.m_SpriteList == null || nIndex < 0 || this.m_SpriteList.Count <= nIndex)
{
return null;
}
NcSpriteFactory.NcSpriteNode result = this.m_SpriteList[nIndex];
this.m_SpriteList[nIndex] = newInfo;
return result;
}
public int AddSpriteNode()
{
NcSpriteFactory.NcSpriteNode item = new NcSpriteFactory.NcSpriteNode();
if (this.m_SpriteList == null)
{
this.m_SpriteList = new List<NcSpriteFactory.NcSpriteNode>();
}
this.m_SpriteList.Add(item);
this.m_bNeedRebuild = true;
return this.m_SpriteList.Count - 1;
}
public int AddSpriteNode(NcSpriteFactory.NcSpriteNode addSpriteNode)
{
if (this.m_SpriteList == null)
{
this.m_SpriteList = new List<NcSpriteFactory.NcSpriteNode>();
}
this.m_SpriteList.Add(addSpriteNode.GetClone());
this.m_bNeedRebuild = true;
return this.m_SpriteList.Count - 1;
}
public void DeleteSpriteNode(int nIndex)
{
if (this.m_SpriteList == null || nIndex < 0 || this.m_SpriteList.Count <= nIndex)
{
return;
}
this.m_bNeedRebuild = true;
this.m_SpriteList.Remove(this.m_SpriteList[nIndex]);
}
public void ClearAllSpriteNode()
{
if (this.m_SpriteList == null)
{
return;
}
this.m_bNeedRebuild = true;
this.m_SpriteList.Clear();
}
public int GetSpriteNodeCount()
{
if (this.m_SpriteList == null)
{
return 0;
}
return this.m_SpriteList.Count;
}
public NcSpriteFactory.NcSpriteNode GetCurrentSpriteNode()
{
if (this.m_SpriteList == null || this.m_SpriteList.Count <= this.m_nCurrentIndex)
{
return null;
}
return this.m_SpriteList[this.m_nCurrentIndex];
}
public Rect GetSpriteUvRect(int nStriteIndex, int nFrameIndex)
{
if (this.m_SpriteList.Count <= nStriteIndex || this.m_SpriteList[nStriteIndex].m_FrameInfos == null || this.m_SpriteList[nStriteIndex].m_FrameInfos.Length <= nFrameIndex)
{
return new Rect(0f, 0f, 0f, 0f);
}
return this.m_SpriteList[nStriteIndex].m_FrameInfos[nFrameIndex].m_TextureUvOffset;
}
public bool IsValidFactory()
{
return !this.m_bNeedRebuild;
}
private void Awake()
{
this.m_bbInstance = true;
}
public NcEffectBehaviour SetSprite(int nNodeIndex)
{
return this.SetSprite(nNodeIndex, true);
}
public NcEffectBehaviour SetSprite(int nNodeIndex, bool bRunImmediate)
{
if (this.m_SpriteList == null || nNodeIndex < 0 || this.m_SpriteList.Count <= nNodeIndex)
{
return null;
}
if (bRunImmediate)
{
this.OnChangingSprite(this.m_nCurrentIndex, nNodeIndex);
}
this.m_nCurrentIndex = nNodeIndex;
NcSpriteAnimation component = base.GetComponent<NcSpriteAnimation>();
if (component != null)
{
component.SetSpriteFactoryIndex(nNodeIndex, false);
if (bRunImmediate)
{
component.ResetAnimation();
}
}
NcSpriteTexture component2 = base.GetComponent<NcSpriteTexture>();
if (component2 != null)
{
component2.SetSpriteFactoryIndex(nNodeIndex, -1, false);
if (bRunImmediate)
{
this.CreateEffectObject();
}
}
if (component != null)
{
return component;
}
if (component != null)
{
return component2;
}
return null;
}
public int GetCurrentSpriteIndex()
{
return this.m_nCurrentIndex;
}
public bool IsEndSprite()
{
return this.m_bEndSprite;
}
private void CreateEffectObject()
{
if (!this.m_bbInstance)
{
return;
}
if (!this.m_bShowEffect)
{
return;
}
this.DestroyEffectObject();
if (base.transform.parent != null)
{
base.transform.parent.SendMessage("OnSpriteListEffectFrame", this.m_SpriteList[this.m_nCurrentIndex], SendMessageOptions.DontRequireReceiver);
}
this.m_CurrentEffect = this.CreateSpriteEffect(this.m_nCurrentIndex, base.transform);
if (base.transform.parent != null)
{
base.transform.parent.SendMessage("OnSpriteListEffectInstance", this.m_CurrentEffect, SendMessageOptions.DontRequireReceiver);
}
}
public GameObject CreateSpriteEffect(int nSrcSpriteIndex, Transform parentTrans)
{
GameObject gameObject = null;
if (this.m_SpriteList[nSrcSpriteIndex].m_EffectPrefab != null)
{
gameObject = base.CreateGameObject("Effect_" + this.m_SpriteList[nSrcSpriteIndex].m_EffectPrefab.name);
if (gameObject == null)
{
return null;
}
base.ChangeParent(parentTrans, gameObject.transform, true, null);
NcAttachPrefab ncAttachPrefab = gameObject.AddComponent<NcAttachPrefab>();
ncAttachPrefab.m_AttachPrefab = this.m_SpriteList[nSrcSpriteIndex].m_EffectPrefab;
ncAttachPrefab.m_fPrefabSpeed = this.m_SpriteList[nSrcSpriteIndex].m_fEffectSpeed;
ncAttachPrefab.m_bDetachParent = this.m_SpriteList[nSrcSpriteIndex].m_bEffectDetach;
ncAttachPrefab.CreateAttachPrefabImmediately();
gameObject.transform.localScale *= this.m_SpriteList[nSrcSpriteIndex].m_fEffectScale;
gameObject.transform.localPosition += this.m_SpriteList[nSrcSpriteIndex].m_EffectPos;
gameObject.transform.localRotation *= Quaternion.Euler(this.m_SpriteList[nSrcSpriteIndex].m_EffectRot);
}
return gameObject;
}
private void DestroyEffectObject()
{
if (this.m_CurrentEffect != null)
{
UnityEngine.Object.Destroy(this.m_CurrentEffect);
}
this.m_CurrentEffect = null;
}
private void OnDestroy()
{
if (this.m_CurrentEffect != null)
{
UnityEngine.Object.Destroy(this.m_CurrentEffect);
}
this.m_CurrentEffect = null;
}
private void CreateSoundObject(NcSpriteFactory.NcSpriteNode ncSpriteNode)
{
if (!this.m_bShowEffect)
{
return;
}
if (ncSpriteNode.m_AudioClip != null)
{
if (this.m_CurrentSound == null)
{
this.m_CurrentSound = base.gameObject.AddComponent<NcAttachSound>();
}
this.m_CurrentSound.m_AudioClip = ncSpriteNode.m_AudioClip;
this.m_CurrentSound.m_bLoop = ncSpriteNode.m_bSoundLoop;
this.m_CurrentSound.m_fVolume = ncSpriteNode.m_fSoundVolume;
this.m_CurrentSound.m_fPitch = ncSpriteNode.m_fSoundPitch;
this.m_CurrentSound.enabled = true;
this.m_CurrentSound.Replay();
}
}
public void OnChangingSprite(int nOldNodeIndex, int nNewNodeIndex)
{
this.m_bEndSprite = false;
this.DestroyEffectObject();
}
public void OnAnimationStartFrame(NcSpriteAnimation spriteCom)
{
}
public void OnAnimationChangingFrame(NcSpriteAnimation spriteCom, int nOldIndex, int nNewIndex, int nLoopCount)
{
if (this.m_SpriteList.Count <= this.m_nCurrentIndex)
{
return;
}
if (this.m_SpriteList[this.m_nCurrentIndex].m_EffectPrefab != null && (nOldIndex < this.m_SpriteList[this.m_nCurrentIndex].m_nEffectFrame || nNewIndex <= nOldIndex) && this.m_SpriteList[this.m_nCurrentIndex].m_nEffectFrame <= nNewIndex && (nLoopCount == 0 || !this.m_SpriteList[this.m_nCurrentIndex].m_bEffectOnlyFirst))
{
this.CreateEffectObject();
}
if (this.m_SpriteList[this.m_nCurrentIndex].m_AudioClip != null && (nOldIndex < this.m_SpriteList[this.m_nCurrentIndex].m_nSoundFrame || nNewIndex <= nOldIndex) && this.m_SpriteList[this.m_nCurrentIndex].m_nSoundFrame <= nNewIndex && (nLoopCount == 0 || !this.m_SpriteList[this.m_nCurrentIndex].m_bSoundOnlyFirst))
{
this.CreateSoundObject(this.m_SpriteList[this.m_nCurrentIndex]);
}
}
public bool OnAnimationLastFrame(NcSpriteAnimation spriteCom, int nLoopCount)
{
if (this.m_SpriteList.Count <= this.m_nCurrentIndex)
{
return false;
}
this.m_bEndSprite = true;
if (this.m_bSequenceMode)
{
if (this.m_nCurrentIndex < this.GetSpriteNodeCount() - 1)
{
if (((!this.m_SpriteList[this.m_nCurrentIndex].m_bLoop) ? 1 : 3) == nLoopCount)
{
this.SetSprite(this.m_nCurrentIndex + 1);
return true;
}
}
else
{
this.SetSprite(0);
}
}
else
{
NcSpriteAnimation ncSpriteAnimation = this.SetSprite(this.m_SpriteList[this.m_nCurrentIndex].m_nNextSpriteIndex) as NcSpriteAnimation;
if (ncSpriteAnimation != null)
{
ncSpriteAnimation.ResetAnimation();
return true;
}
}
return false;
}
public override void OnUpdateEffectSpeed(float fSpeedRate, bool bRuntime)
{
}
public static void CreatePlane(MeshFilter meshFilter, float fUvScale, NcSpriteFactory.NcFrameInfo ncSpriteFrameInfo, NcSpriteFactory.ALIGN_TYPE alignType, NcSpriteFactory.MESH_TYPE m_MeshType)
{
Vector2 vector = new Vector2(fUvScale * ncSpriteFrameInfo.m_FrameScale.x, fUvScale * ncSpriteFrameInfo.m_FrameScale.y);
float num = (alignType != NcSpriteFactory.ALIGN_TYPE.BOTTOM) ? ((alignType != NcSpriteFactory.ALIGN_TYPE.TOP) ? 0f : (-1f * vector.y)) : (1f * vector.y);
Vector3[] vertices = new Vector3[]
{
new Vector3(ncSpriteFrameInfo.m_FrameUvOffset.xMax * vector.x, ncSpriteFrameInfo.m_FrameUvOffset.yMax * vector.y + num),
new Vector3(ncSpriteFrameInfo.m_FrameUvOffset.xMax * vector.x, ncSpriteFrameInfo.m_FrameUvOffset.yMin * vector.y + num),
new Vector3(ncSpriteFrameInfo.m_FrameUvOffset.xMin * vector.x, ncSpriteFrameInfo.m_FrameUvOffset.yMin * vector.y + num),
new Vector3(ncSpriteFrameInfo.m_FrameUvOffset.xMin * vector.x, ncSpriteFrameInfo.m_FrameUvOffset.yMax * vector.y + num)
};
Color[] colors = new Color[]
{
Color.white,
Color.white,
Color.white,
Color.white
};
Vector3[] normals = new Vector3[]
{
new Vector3(0f, 0f, -1f),
new Vector3(0f, 0f, -1f),
new Vector3(0f, 0f, -1f),
new Vector3(0f, 0f, -1f)
};
Vector4[] tangents = new Vector4[]
{
new Vector4(1f, 0f, 0f, -1f),
new Vector4(1f, 0f, 0f, -1f),
new Vector4(1f, 0f, 0f, -1f),
new Vector4(1f, 0f, 0f, -1f)
};
int[] triangles;
if (m_MeshType == NcSpriteFactory.MESH_TYPE.BuiltIn_Plane)
{
triangles = new int[]
{
1,
2,
0,
0,
2,
3
};
}
else
{
triangles = new int[]
{
1,
2,
0,
0,
2,
3,
1,
0,
3,
3,
2,
1
};
}
Vector2[] uv = new Vector2[]
{
new Vector2(1f, 1f),
new Vector2(1f, 0f),
new Vector2(0f, 0f),
new Vector2(0f, 1f)
};
meshFilter.mesh.Clear();
meshFilter.mesh.vertices = vertices;
meshFilter.mesh.colors = colors;
meshFilter.mesh.normals = normals;
meshFilter.mesh.tangents = tangents;
meshFilter.mesh.triangles = triangles;
meshFilter.mesh.uv = uv;
meshFilter.mesh.RecalculateBounds();
}
public static void UpdatePlane(MeshFilter meshFilter, float fUvScale, NcSpriteFactory.NcFrameInfo ncSpriteFrameInfo, NcSpriteFactory.ALIGN_TYPE alignType)
{
Vector2 vector = new Vector2(fUvScale * ncSpriteFrameInfo.m_FrameScale.x, fUvScale * ncSpriteFrameInfo.m_FrameScale.y);
float num = (alignType != NcSpriteFactory.ALIGN_TYPE.BOTTOM) ? ((alignType != NcSpriteFactory.ALIGN_TYPE.TOP) ? 0f : (-1f * vector.y)) : (1f * vector.y);
Vector3[] vertices = new Vector3[]
{
new Vector3(ncSpriteFrameInfo.m_FrameUvOffset.xMax * vector.x, ncSpriteFrameInfo.m_FrameUvOffset.yMax * vector.y + num),
new Vector3(ncSpriteFrameInfo.m_FrameUvOffset.xMax * vector.x, ncSpriteFrameInfo.m_FrameUvOffset.yMin * vector.y + num),
new Vector3(ncSpriteFrameInfo.m_FrameUvOffset.xMin * vector.x, ncSpriteFrameInfo.m_FrameUvOffset.yMin * vector.y + num),
new Vector3(ncSpriteFrameInfo.m_FrameUvOffset.xMin * vector.x, ncSpriteFrameInfo.m_FrameUvOffset.yMax * vector.y + num)
};
meshFilter.mesh.vertices = vertices;
meshFilter.mesh.RecalculateBounds();
}
public static void UpdateMeshUVs(MeshFilter meshFilter, Rect uv)
{
Vector2[] uv2 = new Vector2[]
{
new Vector2(uv.x + uv.width, uv.y + uv.height),
new Vector2(uv.x + uv.width, uv.y),
new Vector2(uv.x, uv.y),
new Vector2(uv.x, uv.y + uv.height)
};
meshFilter.mesh.uv = uv2;
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Xml;
using System.Text;
using OpenSource.UPnP;
using System.Reflection;
using System.Collections;
using OpenSource.Utilities;
using System.Runtime.Serialization;
namespace OpenSource.UPnP.AV.CdsMetadata
{
/// <summary>
/// Class can represent any ContentDirectory approved
/// upnp or dublin-core metadata elements that are
/// simple uint values without any attributes.
/// </summary>
[Serializable()]
public sealed class PropertyUInt : ICdsElement, IToXmlData, IDeserializationCallback
{
/// <summary>
/// Returns same value as StringValue
/// </summary>
/// <returns></returns>
public override string ToString() { return this.StringValue; }
/// <summary>
/// Returns an empty list.
/// </summary>
/// <returns></returns>
public static IList GetPossibleAttributes()
{
return new object[0];
}
/// <summary>
/// Returns an empty list.
/// </summary>
/// <returns></returns>
public IList PossibleAttributes
{
get
{
return GetPossibleAttributes();
}
}
/// <summary>
/// Returns an empty list.
/// </summary>
/// <returns></returns>
public IList ValidAttributes
{
get
{
return GetPossibleAttributes();
}
}
/// <summary>
/// No attributes, so always returns null
/// </summary>
/// <param name="attribute"></param>
/// <returns></returns>
public IComparable ExtractAttribute(string attribute) { return null; }
/// <summary>
/// Returns the underlying uint value.
/// </summary>
public IComparable ComparableValue { get { return m_value; } }
/// <summary>
/// Returns the underlying uint value.
/// </summary>
public object Value { get { return m_value; } }
/// <summary>
/// Returns the string representation of the uint value.
/// </summary>
public string StringValue { get { return m_value.ToString(); } }
/// <summary>
/// Prints the XML representation of the metadata element.
/// <para>
/// Implementation calls the <see cref="ToXmlData.ToXml"/>
/// method for its implementation.
/// </para>
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
/// <exception cref="InvalidCastException">
/// Thrown if the "data" argument is not a <see cref="ToXmlData"/> object.
/// </exception>
public void ToXml (ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
ToXmlData.ToXml(this, formatter, (ToXmlData) data, xmlWriter);
}
/// <summary>
/// Instructs the "xmlWriter" argument to start the metadata element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void StartElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
xmlWriter.WriteStartElement(this.ns_tag);
}
/// <summary>
/// Instructs the "xmlWriter" argument to write the value of
/// the metadata element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void WriteValue(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
xmlWriter.WriteString(this.StringValue);
}
/// <summary>
/// Instructs the "xmlWriter" argument to close the metadata element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void EndElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
xmlWriter.WriteEndElement();
}
/// <summary>
/// Empty - this element has no child xml elements.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void WriteInnerXml(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
}
/// <summary>
/// Attempts to case compareToThis as an uint
/// to do the comparison. If the cast
/// fails, then it compares the current
/// value against uint.MinValue.
/// </summary>
/// <param name="compareToThis"></param>
/// <returns></returns>
public int CompareTo (object compareToThis)
{
System.Type type = compareToThis.GetType();
uint compareTo = uint.MinValue;
try
{
if (type == typeof(PropertyUInt))
{
compareTo = ((PropertyUInt)compareToThis).m_value;
}
else if (type == typeof(string))
{
compareTo = uint.Parse(compareToThis.ToString());
}
else
{
compareTo = (uint) compareToThis;
}
}
catch
{
compareTo = uint.MinValue;
}
return this.m_value.CompareTo(compareTo);
}
/// <summary>
/// Extracts the Name of the element and uses
/// the InnerText as the value.
/// </summary>
/// <param name="element"></param>
public PropertyUInt(XmlElement element)
{
this.m_value = uint.Parse(element.InnerText);
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(element.Name);
}
/// <summary>
/// Instantiates a new property that can represent an xml element with
/// an uint as its value.
/// </summary>
/// <param name="namespace_tag">property obtained from Tags[CommonPropertyNames.value]</param>
/// <param name="val"></param>
public PropertyUInt (string namespace_tag, uint val)
{
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(namespace_tag);
this.m_value = val;
}
/// <summary>
/// Assume the name has been read.
/// </summary>
/// <param name="reader"></param>
public PropertyUInt(XmlReader reader)
{
this.m_value = XmlConvert.ToUInt32(reader.Value);
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(reader.Name);
}
/// <summary>
/// Underlying uint value.
/// </summary>
public uint _Value { get { return this.m_value; } }
internal uint m_value;
/// <summary>
/// the namespace and element name to represent
/// </summary>
private string ns_tag;
public void OnDeserialization(object sender)
{
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(this.ns_tag);
}
}
}
| |
// GZipStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-August-08 18:14:39>
//
// ------------------------------------------------------------------
//
// This module defines the GZipStream class, which can be used as a replacement for
// the System.IO.Compression.GZipStream class in the .NET BCL. NB: The design is not
// completely OO clean: there is some intelligence in the ZlibBaseStream that reads the
// GZip header.
//
// ------------------------------------------------------------------
using System;
using System.IO;
namespace Dune.Compression.Zlib
{
/// <summary>
/// A class for compressing and decompressing GZIP streams.
/// </summary>
/// <remarks>
///
/// <para>
/// The <c>GZipStream</c> is a <see
/// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a
/// <see cref="Stream"/>. It adds GZIP compression or decompression to any
/// stream.
/// </para>
///
/// <para>
/// Like the <c>System.IO.Compression.GZipStream</c> in the .NET Base Class Library, the
/// <c>Ionic.Zlib.GZipStream</c> can compress while writing, or decompress while
/// reading, but not vice versa. The compression method used is GZIP, which is
/// documented in <see href="http://www.ietf.org/rfc/rfc1952.txt">IETF RFC
/// 1952</see>, "GZIP file format specification version 4.3".</para>
///
/// <para>
/// A <c>GZipStream</c> can be used to decompress data (through <c>Read()</c>) or
/// to compress data (through <c>Write()</c>), but not both.
/// </para>
///
/// <para>
/// If you wish to use the <c>GZipStream</c> to compress data, you must wrap it
/// around a write-able stream. As you call <c>Write()</c> on the <c>GZipStream</c>, the
/// data will be compressed into the GZIP format. If you want to decompress data,
/// you must wrap the <c>GZipStream</c> around a readable stream that contains an
/// IETF RFC 1952-compliant stream. The data will be decompressed as you call
/// <c>Read()</c> on the <c>GZipStream</c>.
/// </para>
///
/// <para>
/// Though the GZIP format allows data from multiple files to be concatenated
/// together, this stream handles only a single segment of GZIP format, typically
/// representing a single file.
/// </para>
///
/// <para>
/// This class is similar to <see cref="ZlibStream"/> and <see cref="DeflateStream"/>.
/// <c>ZlibStream</c> handles RFC1950-compliant streams. <see cref="DeflateStream"/>
/// handles RFC1951-compliant streams. This class handles RFC1952-compliant streams.
/// </para>
///
/// </remarks>
///
/// <seealso cref="DeflateStream" />
/// <seealso cref="ZlibStream" />
public class GZipStream : System.IO.Stream
{
// GZip format
// source: http://tools.ietf.org/html/rfc1952
//
// header id: 2 bytes 1F 8B
// compress method 1 byte 8= DEFLATE (none other supported)
// flag 1 byte bitfield (See below)
// mtime 4 bytes time_t (seconds since jan 1, 1970 UTC of the file.
// xflg 1 byte 2 = max compress used , 4 = max speed (can be ignored)
// OS 1 byte OS for originating archive. set to 0xFF in compression.
// extra field length 2 bytes optional - only if FEXTRA is set.
// extra field varies
// filename varies optional - if FNAME is set. zero terminated. ISO-8859-1.
// file comment varies optional - if FCOMMENT is set. zero terminated. ISO-8859-1.
// crc16 1 byte optional - present only if FHCRC bit is set
// compressed data varies
// CRC32 4 bytes
// isize 4 bytes data size modulo 2^32
//
// FLG (FLaGs)
// bit 0 FTEXT - indicates file is ASCII text (can be safely ignored)
// bit 1 FHCRC - there is a CRC16 for the header immediately following the header
// bit 2 FEXTRA - extra fields are present
// bit 3 FNAME - the zero-terminated filename is present. encoding; ISO-8859-1.
// bit 4 FCOMMENT - a zero-terminated file comment is present. encoding: ISO-8859-1
// bit 5 reserved
// bit 6 reserved
// bit 7 reserved
//
// On consumption:
// Extra field is a bunch of nonsense and can be safely ignored.
// Header CRC and OS, likewise.
//
// on generation:
// all optional fields get 0, except for the OS, which gets 255.
//
/// <summary>
/// The comment on the GZIP stream.
/// </summary>
///
/// <remarks>
/// <para>
/// The GZIP format allows for each file to optionally have an associated
/// comment stored with the file. The comment is encoded with the ISO-8859-1
/// code page. To include a comment in a GZIP stream you create, set this
/// property before calling <c>Write()</c> for the first time on the
/// <c>GZipStream</c>.
/// </para>
///
/// <para>
/// When using <c>GZipStream</c> to decompress, you can retrieve this property
/// after the first call to <c>Read()</c>. If no comment has been set in the
/// GZIP bytestream, the Comment property will return <c>null</c>
/// (<c>Nothing</c> in VB).
/// </para>
/// </remarks>
public String Comment
{
get
{
return _Comment;
}
set
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
_Comment = value;
}
}
/// <summary>
/// The FileName for the GZIP stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// The GZIP format optionally allows each file to have an associated
/// filename. When compressing data (through <c>Write()</c>), set this
/// FileName before calling <c>Write()</c> the first time on the <c>GZipStream</c>.
/// The actual filename is encoded into the GZIP bytestream with the
/// ISO-8859-1 code page, according to RFC 1952. It is the application's
/// responsibility to insure that the FileName can be encoded and decoded
/// correctly with this code page.
/// </para>
///
/// <para>
/// When decompressing (through <c>Read()</c>), you can retrieve this value
/// any time after the first <c>Read()</c>. In the case where there was no filename
/// encoded into the GZIP bytestream, the property will return <c>null</c> (<c>Nothing</c>
/// in VB).
/// </para>
/// </remarks>
public String FileName
{
get { return _FileName; }
set
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
_FileName = value;
if (_FileName == null) return;
if (_FileName.IndexOf("/") != -1)
{
_FileName = _FileName.Replace("/", "\\");
}
if (_FileName.EndsWith("\\"))
throw new Exception("Illegal filename");
if (_FileName.IndexOf("\\") != -1)
{
// trim any leading path
_FileName = Path.GetFileName(_FileName);
}
}
}
/// <summary>
/// The last modified time for the GZIP stream.
/// </summary>
///
/// <remarks>
/// GZIP allows the storage of a last modified time with each GZIP entry.
/// When compressing data, you can set this before the first call to
/// <c>Write()</c>. When decompressing, you can retrieve this value any time
/// after the first call to <c>Read()</c>.
/// </remarks>
public DateTime? LastModified;
/// <summary>
/// The CRC on the GZIP stream.
/// </summary>
/// <remarks>
/// This is used for internal error checking. You probably don't need to look at this property.
/// </remarks>
public int Crc32 { get { return _Crc32; } }
private int _headerByteCount;
internal ZlibBaseStream _baseStream;
bool _disposed;
bool _firstReadDone;
string _FileName;
string _Comment;
int _Crc32;
/// <summary>
/// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c>.
/// </summary>
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Compress</c>, the <c>GZipStream</c> will use the
/// default compression level.
/// </para>
///
/// <para>
/// As noted in the class documentation, the <c>CompressionMode</c> (Compress
/// or Decompress) also establishes the "direction" of the stream. A
/// <c>GZipStream</c> with <c>CompressionMode.Compress</c> works only through
/// <c>Write()</c>. A <c>GZipStream</c> with
/// <c>CompressionMode.Decompress</c> works only through <c>Read()</c>.
/// </para>
///
/// </remarks>
///
/// <example>
/// This example shows how to use a GZipStream to compress data.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(outputFile))
/// {
/// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Dim outputFile As String = (fileToCompress & ".compressed")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(outputFile)
/// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
///
/// <example>
/// This example shows how to use a GZipStream to uncompress a file.
/// <code>
/// private void GunZipFile(string filename)
/// {
/// if (!filename.EndsWith(".gz))
/// throw new ArgumentException("filename");
/// var DecompressedFile = filename.Substring(0,filename.Length-3);
/// byte[] working = new byte[WORKING_BUFFER_SIZE];
/// int n= 1;
/// using (System.IO.Stream input = System.IO.File.OpenRead(filename))
/// {
/// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
/// {
/// using (var output = System.IO.File.Create(DecompressedFile))
/// {
/// while (n !=0)
/// {
/// n= decompressor.Read(working, 0, working.Length);
/// if (n > 0)
/// {
/// output.Write(working, 0, n);
/// }
/// }
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Private Sub GunZipFile(ByVal filename as String)
/// If Not (filename.EndsWith(".gz)) Then
/// Throw New ArgumentException("filename")
/// End If
/// Dim DecompressedFile as String = filename.Substring(0,filename.Length-3)
/// Dim working(WORKING_BUFFER_SIZE) as Byte
/// Dim n As Integer = 1
/// Using input As Stream = File.OpenRead(filename)
/// Using decompressor As Stream = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, True)
/// Using output As Stream = File.Create(UncompressedFile)
/// Do
/// n= decompressor.Read(working, 0, working.Length)
/// If n > 0 Then
/// output.Write(working, 0, n)
/// End IF
/// Loop While (n > 0)
/// End Using
/// End Using
/// End Using
/// End Sub
/// </code>
/// </example>
///
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param>
public GZipStream(Stream stream, CompressionMode mode)
: this(stream, mode, CompressionLevel.Default, false)
{
}
/// <summary>
/// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c> and
/// the specified <c>CompressionLevel</c>.
/// </summary>
/// <remarks>
///
/// <para>
/// The <c>CompressionMode</c> (Compress or Decompress) also establishes the
/// "direction" of the stream. A <c>GZipStream</c> with
/// <c>CompressionMode.Compress</c> works only through <c>Write()</c>. A
/// <c>GZipStream</c> with <c>CompressionMode.Decompress</c> works only
/// through <c>Read()</c>.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example shows how to use a <c>GZipStream</c> to compress a file into a .gz file.
///
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".gz"))
/// {
/// using (Stream compressor = new GZipStream(raw,
/// CompressionMode.Compress,
/// CompressionLevel.BestCompression))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".gz")
/// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream to be read or written while deflating or inflating.</param>
/// <param name="mode">Indicates whether the <c>GZipStream</c> will compress or decompress.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level)
: this(stream, mode, level, false)
{
}
/// <summary>
/// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c>, and
/// explicitly specify whether the stream should be left open after Deflation
/// or Inflation.
/// </summary>
///
/// <remarks>
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// memory stream that will be re-read after compressed data has been written
/// to it. Specify true for the <paramref name="leaveOpen"/> parameter to leave
/// the stream open.
/// </para>
///
/// <para>
/// The <see cref="CompressionMode"/> (Compress or Decompress) also
/// establishes the "direction" of the stream. A <c>GZipStream</c> with
/// <c>CompressionMode.Compress</c> works only through <c>Write()</c>. A <c>GZipStream</c>
/// with <c>CompressionMode.Decompress</c> works only through <c>Read()</c>.
/// </para>
///
/// <para>
/// The <c>GZipStream</c> will use the default compression level. If you want
/// to specify the compression level, see <see cref="GZipStream(Stream,
/// CompressionMode, CompressionLevel, bool)"/>.
/// </para>
///
/// <para>
/// See the other overloads of this constructor for example code.
/// </para>
///
/// </remarks>
///
/// <param name="stream">
/// The stream which will be read or written. This is called the "captive"
/// stream in other places in this documentation.
/// </param>
///
/// <param name="mode">Indicates whether the GZipStream will compress or decompress.
/// </param>
///
/// <param name="leaveOpen">
/// true if the application would like the base stream to remain open after
/// inflation/deflation.
/// </param>
public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen)
: this(stream, mode, CompressionLevel.Default, leaveOpen)
{
}
/// <summary>
/// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c> and the
/// specified <c>CompressionLevel</c>, and explicitly specify whether the
/// stream should be left open after Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// memory stream that will be re-read after compressed data has been written
/// to it. Specify true for the <paramref name="leaveOpen"/> parameter to
/// leave the stream open.
/// </para>
///
/// <para>
/// As noted in the class documentation, the <c>CompressionMode</c> (Compress
/// or Decompress) also establishes the "direction" of the stream. A
/// <c>GZipStream</c> with <c>CompressionMode.Compress</c> works only through
/// <c>Write()</c>. A <c>GZipStream</c> with <c>CompressionMode.Decompress</c> works only
/// through <c>Read()</c>.
/// </para>
///
/// </remarks>
///
/// <example>
/// This example shows how to use a <c>GZipStream</c> to compress data.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(outputFile))
/// {
/// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Dim outputFile As String = (fileToCompress & ".compressed")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(outputFile)
/// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, True)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param>
/// <param name="leaveOpen">true if the application would like the stream to remain open after inflation/deflation.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen)
{
_baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.GZIP, leaveOpen);
}
#region Zlib properties
/// <summary>
/// This property sets the flush behavior on the stream.
/// </summary>
virtual public FlushType FlushMode
{
get { return (this._baseStream._flushMode); }
set {
if (_disposed) throw new ObjectDisposedException("GZipStream");
this._baseStream._flushMode = value;
}
}
/// <summary>
/// The size of the working buffer for the compression codec.
/// </summary>
///
/// <remarks>
/// <para>
/// The working buffer is used for all stream operations. The default size is
/// 1024 bytes. The minimum size is 128 bytes. You may get better performance
/// with a larger buffer. Then again, you might not. You would have to test
/// it.
/// </para>
///
/// <para>
/// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the
/// stream. If you try to set it afterwards, it will throw.
/// </para>
/// </remarks>
public int BufferSize
{
get
{
return this._baseStream._bufferSize;
}
set
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
if (this._baseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < ZlibConstants.WorkingBufferSizeMin)
throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin));
this._baseStream._bufferSize = value;
}
}
/// <summary> Returns the total number of bytes input so far.</summary>
virtual public long TotalIn
{
get
{
return this._baseStream._z.TotalBytesIn;
}
}
/// <summary> Returns the total number of bytes output so far.</summary>
virtual public long TotalOut
{
get
{
return this._baseStream._z.TotalBytesOut;
}
}
#endregion
#region Stream methods
/// <summary>
/// Dispose the stream.
/// </summary>
/// <remarks>
/// <para>
/// This may or may not result in a <c>Close()</c> call on the captive
/// stream. See the constructors that have a <c>leaveOpen</c> parameter
/// for more information.
/// </para>
/// <para>
/// This method may be invoked in two distinct scenarios. If disposing
/// == true, the method has been called directly or indirectly by a
/// user's code, for example via the public Dispose() method. In this
/// case, both managed and unmanaged resources can be referenced and
/// disposed. If disposing == false, the method has been called by the
/// runtime from inside the object finalizer and this method should not
/// reference other objects; in that case only unmanaged resources must
/// be referenced or disposed.
/// </para>
/// </remarks>
/// <param name="disposing">
/// indicates whether the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing && (this._baseStream != null))
{
this._baseStream.Close();
this._Crc32 = _baseStream.Crc32;
}
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
return _baseStream._stream.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
return _baseStream._stream.CanWrite;
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
_baseStream.Flush();
}
/// <summary>
/// Reading this property always throws a <see cref="NotImplementedException"/>.
/// </summary>
public override long Length
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotImplementedException"/>. Reading will return the total bytes
/// written out, if used in writing, or the total bytes read in, if used in
/// reading. The count may refer to compressed bytes or uncompressed bytes,
/// depending on how you've used the stream.
/// </remarks>
public override long Position
{
get
{
if (this._baseStream._streamMode == ZlibBaseStream.StreamMode.Writer)
return this._baseStream._z.TotalBytesOut + _headerByteCount;
if (this._baseStream._streamMode == ZlibBaseStream.StreamMode.Reader)
return this._baseStream._z.TotalBytesIn + this._baseStream._gzipHeaderByteCount;
return 0;
}
set { throw new NotImplementedException(); }
}
/// <summary>
/// Read and decompress data from the source stream.
/// </summary>
///
/// <remarks>
/// With a <c>GZipStream</c>, decompression is done through reading.
/// </remarks>
///
/// <example>
/// <code>
/// byte[] working = new byte[WORKING_BUFFER_SIZE];
/// using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile))
/// {
/// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
/// {
/// using (var output = System.IO.File.Create(_DecompressedFile))
/// {
/// int n;
/// while ((n= decompressor.Read(working, 0, working.Length)) !=0)
/// {
/// output.Write(working, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
/// <param name="buffer">The buffer into which the decompressed data should be placed.</param>
/// <param name="offset">the offset within that data array to put the first byte read.</param>
/// <param name="count">the number of bytes to read.</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
int n = _baseStream.Read(buffer, offset, count);
// Console.WriteLine("GZipStream::Read(buffer, off({0}), c({1}) = {2}", offset, count, n);
// Console.WriteLine( Util.FormatByteArray(buffer, offset, n) );
if (!_firstReadDone)
{
_firstReadDone = true;
FileName = _baseStream._GzipFileName;
Comment = _baseStream._GzipComment;
}
return n;
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">irrelevant; it will always throw!</param>
/// <param name="origin">irrelevant; it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="value">irrelevant; this method will always throw!</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
/// <summary>
/// Write data to the stream.
/// </summary>
///
/// <remarks>
/// <para>
/// If you wish to use the <c>GZipStream</c> to compress data while writing,
/// you can create a <c>GZipStream</c> with <c>CompressionMode.Compress</c>, and a
/// writable output stream. Then call <c>Write()</c> on that <c>GZipStream</c>,
/// providing uncompressed data as input. The data sent to the output stream
/// will be the compressed form of the data written.
/// </para>
///
/// <para>
/// A <c>GZipStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not
/// both. Writing implies compression. Reading implies decompression.
/// </para>
///
/// </remarks>
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("GZipStream");
if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Undefined)
{
//Console.WriteLine("GZipStream: First write");
if (_baseStream._wantCompress)
{
// first write in compression, therefore, emit the GZIP header
_headerByteCount = EmitHeader();
}
else
{
throw new InvalidOperationException();
}
}
_baseStream.Write(buffer, offset, count);
}
#endregion
internal static readonly System.DateTime _unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
#if SILVERLIGHT || NETCF
internal static readonly System.Text.Encoding iso8859dash1 = new Ionic.Encoding.Iso8859Dash1Encoding();
#else
internal static readonly System.Text.Encoding iso8859dash1 = System.Text.Encoding.GetEncoding("iso-8859-1");
#endif
private int EmitHeader()
{
byte[] commentBytes = (Comment == null) ? null : iso8859dash1.GetBytes(Comment);
byte[] filenameBytes = (FileName == null) ? null : iso8859dash1.GetBytes(FileName);
int cbLength = (Comment == null) ? 0 : commentBytes.Length + 1;
int fnLength = (FileName == null) ? 0 : filenameBytes.Length + 1;
int bufferLength = 10 + cbLength + fnLength;
byte[] header = new byte[bufferLength];
int i = 0;
// ID
header[i++] = 0x1F;
header[i++] = 0x8B;
// compression method
header[i++] = 8;
byte flag = 0;
if (Comment != null)
flag ^= 0x10;
if (FileName != null)
flag ^= 0x8;
// flag
header[i++] = flag;
// mtime
if (!LastModified.HasValue) LastModified = DateTime.Now;
System.TimeSpan delta = LastModified.Value - _unixEpoch;
Int32 timet = (Int32)delta.TotalSeconds;
Array.Copy(BitConverter.GetBytes(timet), 0, header, i, 4);
i += 4;
// xflg
header[i++] = 0; // this field is totally useless
// OS
header[i++] = 0xFF; // 0xFF == unspecified
// extra field length - only if FEXTRA is set, which it is not.
//header[i++]= 0;
//header[i++]= 0;
// filename
if (fnLength != 0)
{
Array.Copy(filenameBytes, 0, header, i, fnLength - 1);
i += fnLength - 1;
header[i++] = 0; // terminate
}
// comment
if (cbLength != 0)
{
Array.Copy(commentBytes, 0, header, i, cbLength - 1);
i += cbLength - 1;
header[i++] = 0; // terminate
}
_baseStream._stream.Write(header, 0, header.Length);
return header.Length; // bytes written
}
/// <summary>
/// Compress a string into a byte array using GZip.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="GZipStream.UncompressString(byte[])"/>.
/// </remarks>
///
/// <seealso cref="GZipStream.UncompressString(byte[])"/>
/// <seealso cref="GZipStream.CompressBuffer(byte[])"/>
///
/// <param name="s">
/// A string to compress. The string will first be encoded
/// using UTF8, then compressed.
/// </param>
///
/// <returns>The string in compressed form</returns>
public static byte[] CompressString(String s)
{
using (var ms = new MemoryStream())
{
System.IO.Stream compressor =
new GZipStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);
ZlibBaseStream.CompressString(s, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Compress a byte array into a new byte array using GZip.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="GZipStream.UncompressBuffer(byte[])"/>.
/// </remarks>
///
/// <seealso cref="GZipStream.CompressString(string)"/>
/// <seealso cref="GZipStream.UncompressBuffer(byte[])"/>
///
/// <param name="b">
/// A buffer to compress.
/// </param>
///
/// <returns>The data in compressed form</returns>
public static byte[] CompressBuffer(byte[] b)
{
using (var ms = new MemoryStream())
{
System.IO.Stream compressor =
new GZipStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression );
ZlibBaseStream.CompressBuffer(b, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Uncompress a GZip'ed byte array into a single string.
/// </summary>
///
/// <seealso cref="GZipStream.CompressString(String)"/>
/// <seealso cref="GZipStream.UncompressBuffer(byte[])"/>
///
/// <param name="compressed">
/// A buffer containing GZIP-compressed data.
/// </param>
///
/// <returns>The uncompressed string</returns>
public static String UncompressString(byte[] compressed)
{
using (var input = new MemoryStream(compressed))
{
Stream decompressor = new GZipStream(input, CompressionMode.Decompress);
return ZlibBaseStream.UncompressString(compressed, decompressor);
}
}
/// <summary>
/// Uncompress a GZip'ed byte array into a byte array.
/// </summary>
///
/// <seealso cref="GZipStream.CompressBuffer(byte[])"/>
/// <seealso cref="GZipStream.UncompressString(byte[])"/>
///
/// <param name="compressed">
/// A buffer containing data that has been compressed with GZip.
/// </param>
///
/// <returns>The data in uncompressed form</returns>
public static byte[] UncompressBuffer(byte[] compressed)
{
using (var input = new System.IO.MemoryStream(compressed))
{
System.IO.Stream decompressor =
new GZipStream( input, CompressionMode.Decompress );
return ZlibBaseStream.UncompressBuffer(compressed, decompressor);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Xml.Schema
{
// SUMMARY
// =======
// For each Xml type, there is a set of Clr types that can represent it. Some of these mappings involve
// loss of fidelity. For example, xsd:dateTime can be represented as System.DateTime, but only at the expense
// of normalizing the time zone. And xs:duration can be represented as System.TimeSpan, but only at the expense
// of discarding variations such as "P50H", "P1D26H", "P2D2H", all of which are normalized as "P2D2H".
//
// Implementations of this class convert between the various Clr representations of Xml types. Note that
// in *no* case is the Xml type ever modified. Only the Clr type is changed. This means that in cases where
// the Xml type is part of the representation (such as XmlAtomicValue), the destination value is guaranteed
// to have the same Xml type.
//
// For all converters, converting to typeof(object) is identical to converting to XmlSchemaType.Datatype.ValueType.
//
//
// ATOMIC MAPPINGS
// ===============
//
// -----------------------------------------------------------------------------------------------------------
// Source/Destination System.String Other Clr Type
// -----------------------------------------------------------------------------------------------------------
// System.String No-op conversion. Use Xsd rules to convert from the string
// to primitive, full-fidelity Clr type (use
// XmlConvert where possible). Use Clr rules
// to convert to destination type.
// -----------------------------------------------------------------------------------------------------------
// Other Clr Type Use Clr rules to convert from Use Clr rules to convert from source to
// source type to primitive, full- destination type.
// fidelity Clr type. Use Xsd rules
// to convert to a string (use
// XmlConvert where possible).
// -----------------------------------------------------------------------------------------------------------
//
//
// LIST MAPPINGS
// =============
// The following Clr types can be used to represent Xsd list types: IList, ICollection, IEnumerable, Type[],
// String.
//
// -----------------------------------------------------------------------------------------------------------
// Source/Destination System.String Clr List Type
// -----------------------------------------------------------------------------------------------------------
// System.String No-op conversion Tokenize the string by whitespace, create a
// String[] from tokens, and follow List => List
// rules.
// -----------------------------------------------------------------------------------------------------------
// Clr List Type Follow List => String[] rules, Create destination list having the same length
// then concatenate strings from array, as the source list. For each item in the
// separating adjacent strings with a source list, call the atomic converter to
// single space character. convert to the destination type. The destination
// item type for IList, ICollection, IEnumerable
// is typeof(object). The destination item type
// for Type[] is Type.
// -----------------------------------------------------------------------------------------------------------
//
//
// UNION MAPPINGS
// ==============
// Union types may only be represented using System.Xml.Schema.XmlAtomicValue or System.String. Either the
// source type or the destination type must therefore always be either System.String or
// System.Xml.Schema.XmlAtomicValue.
//
// -----------------------------------------------------------------------------------------------------------
// Source/Destination System.String XmlAtomicValue Other Clr Type
// -----------------------------------------------------------------------------------------------------------
// System.String No-op conversion Follow System.String=> Call ParseValue in order to determine
// Other Clr Type rules. the member type. Call ChangeType on
// the member type's converter to convert
// to desired Clr type.
// -----------------------------------------------------------------------------------------------------------
// XmlAtomicValue Follow XmlAtomicValue No-op conversion. Call ReadValueAs, where destinationType
// => Other Clr Type is the desired Clr type.
// rules.
// -----------------------------------------------------------------------------------------------------------
// Other Clr Type InvalidCastException InvalidCastException InvalidCastException
// -----------------------------------------------------------------------------------------------------------
//
//
// EXAMPLES
// ========
//
// -----------------------------------------------------------------------------------------------------------
// Source Destination
// Xml Type Value Type Conversion Steps Explanation
// -----------------------------------------------------------------------------------------------------------
// xs:int "10" Byte "10" => 10M => (byte) 10 Primitive, full-fidelity for xs:int
// is a truncated decimal
// -----------------------------------------------------------------------------------------------------------
// xs:int "10.10" Byte FormatException xs:integer parsing rules do not
// allow fractional parts
// -----------------------------------------------------------------------------------------------------------
// xs:int 10.10M Byte 10.10M => (byte) 10 Default Clr rules truncate when
// converting from Decimal to Byte
// -----------------------------------------------------------------------------------------------------------
// xs:int 10.10M Decimal 10.10M => 10.10M Decimal => Decimal is no-op
// -----------------------------------------------------------------------------------------------------------
// xs:int 10.10M String 10.10M => 10M => "10"
// -----------------------------------------------------------------------------------------------------------
// xs:int "hello" String "hello" => "hello" String => String is no-op
// -----------------------------------------------------------------------------------------------------------
// xs:byte "300" Int32 "300" => 300M => (int) 300
// -----------------------------------------------------------------------------------------------------------
// xs:byte 300 Byte 300 => 300M => OverflowException Clr overflows when converting from
// Decimal to Byte
// -----------------------------------------------------------------------------------------------------------
// xs:byte 300 XmlAtomicValue new XmlAtomicValue(xs:byte, 300) Invalid atomic value created
// -----------------------------------------------------------------------------------------------------------
// xs:double 1.234f String 1.234f => 1.2339999675750732d => Converting a Single value to a Double
// "1.2339999675750732" value zero-extends it in base-2, so
// "garbage" digits appear when it's
// converted to base-10.
// -----------------------------------------------------------------------------------------------------------
// xs:int* {1, "2", String {1, "2", 3.1M} => Delegate to xs:int converter to
// 3.1M} {"1", "2", "3"} => "1 2 3" convert each item to a string.
// -----------------------------------------------------------------------------------------------------------
// xs:int* "1 2 3" Int32[] "1 2 3" => {"1", "2", "3"} =>
// {1, 2, 3}
// -----------------------------------------------------------------------------------------------------------
// xs:int* {1, "2", Object[] {1, "2", 3.1M} => xs:int converter uses Int32 by default,
// 3.1M} {(object)1, (object)2, (object)3} so returns boxed Int32 values.
// -----------------------------------------------------------------------------------------------------------
// (xs:int | "1 2001" XmlAtomicValue[] "1 2001" => {(xs:int) 1,
// xs:gYear)* (xs:gYear) 2001}
// -----------------------------------------------------------------------------------------------------------
// (xs:int* | "1 2001" String "1 2001" No-op conversion even though
// xs:gYear*) ParseValue would fail if it were called.
// -----------------------------------------------------------------------------------------------------------
// (xs:int* | "1 2001" Int[] XmlSchemaException ParseValue fails.
// xs:gYear*)
// -----------------------------------------------------------------------------------------------------------
//
internal static class XmlUntypedConverter
{
public static bool ToBoolean(string value)
{
if (value == null) throw new ArgumentNullException("value");
return XmlConvert.ToBoolean((string)value);
}
private static DateTime UntypedAtomicToDateTime(string value)
{
return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd));
}
public static DateTime ToDateTime(string value)
{
if (value == null) throw new ArgumentNullException("value");
return UntypedAtomicToDateTime((string)value);
}
public static double ToDouble(string value)
{
if (value == null) throw new ArgumentNullException("value");
return XmlConvert.ToDouble((string)value);
}
public static int ToInt32(string value)
{
if (value == null) throw new ArgumentNullException("value");
return XmlConvert.ToInt32((string)value);
}
public static long ToInt64(string value)
{
if (value == null) throw new ArgumentNullException("value");
return XmlConvert.ToInt64((string)value);
}
private static readonly Type s_DecimalType = typeof(decimal);
private static readonly Type s_Int32Type = typeof(int);
private static readonly Type s_Int64Type = typeof(long);
private static readonly Type s_StringType = typeof(string);
private static readonly Type s_ByteType = typeof(byte);
private static readonly Type s_Int16Type = typeof(short);
private static readonly Type s_SByteType = typeof(sbyte);
private static readonly Type s_UInt16Type = typeof(ushort);
private static readonly Type s_UInt32Type = typeof(uint);
private static readonly Type s_UInt64Type = typeof(ulong);
private static readonly Type s_DoubleType = typeof(double);
private static readonly Type s_SingleType = typeof(float);
private static readonly Type s_DateTimeType = typeof(DateTime);
private static readonly Type s_DateTimeOffsetType = typeof(DateTimeOffset);
private static readonly Type s_BooleanType = typeof(bool);
private static readonly Type s_ByteArrayType = typeof(Byte[]);
private static readonly Type s_XmlQualifiedNameType = typeof(XmlQualifiedName);
private static readonly Type s_UriType = typeof(Uri);
private static readonly Type s_TimeSpanType = typeof(TimeSpan);
private static string Base64BinaryToString(byte[] value)
{
return Convert.ToBase64String(value);
}
private static string DateTimeToString(DateTime value)
{
return (new XsdDateTime(value, XsdDateTimeFlags.DateTime)).ToString();
}
private static string DateTimeOffsetToString(DateTimeOffset value)
{
return (new XsdDateTime(value, XsdDateTimeFlags.DateTime)).ToString();
}
private static string QNameToString(XmlQualifiedName qname, IXmlNamespaceResolver nsResolver)
{
string prefix;
if (nsResolver == null)
return string.Concat("{", qname.Namespace, "}", qname.Name);
prefix = nsResolver.LookupPrefix(qname.Namespace);
if (prefix == null)
throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoPrefix, qname.ToString(), qname.Namespace));
return (prefix.Length != 0) ? string.Concat(prefix, ":", qname.Name) : qname.Name;
}
private static string AnyUriToString(Uri value)
{
return value.OriginalString;
}
public static string ToString(object value, IXmlNamespaceResolver nsResolver)
{
if (value == null) throw new ArgumentNullException("value");
Type sourceType = value.GetType();
if (sourceType == s_BooleanType) return XmlConvert.ToString((bool)value);
if (sourceType == s_ByteType) return XmlConvert.ToString((byte)value);
if (sourceType == s_ByteArrayType) return Base64BinaryToString((byte[])value);
if (sourceType == s_DateTimeType) return DateTimeToString((DateTime)value);
if (sourceType == s_DateTimeOffsetType) return DateTimeOffsetToString((DateTimeOffset)value);
if (sourceType == s_DecimalType) return XmlConvert.ToString((decimal)value);
if (sourceType == s_DoubleType) return XmlConvert.ToString((double)value);
if (sourceType == s_Int16Type) return XmlConvert.ToString((short)value);
if (sourceType == s_Int32Type) return XmlConvert.ToString((int)value);
if (sourceType == s_Int64Type) return XmlConvert.ToString((long)value);
if (sourceType == s_SByteType) return XmlConvert.ToString((sbyte)value);
if (sourceType == s_SingleType) return XmlConvert.ToString((float)value);
if (sourceType == s_StringType) return ((string)value);
if (sourceType == s_TimeSpanType) return XmlConvert.ToString((TimeSpan)value);
if (sourceType == s_UInt16Type) return XmlConvert.ToString((ushort)value);
if (sourceType == s_UInt32Type) return XmlConvert.ToString((uint)value);
if (sourceType == s_UInt64Type) return XmlConvert.ToString((ulong)value);
Uri valueAsUri = value as Uri;
if (valueAsUri != null) return AnyUriToString(valueAsUri);
XmlQualifiedName valueAsXmlQualifiedName = value as XmlQualifiedName;
if (valueAsXmlQualifiedName != null) return QNameToString(valueAsXmlQualifiedName, nsResolver);
throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeToString, sourceType.Name));
}
private static byte[] StringToBase64Binary(string value)
{
return Convert.FromBase64String(XmlConvertEx.TrimString(value));
}
private static short Int32ToInt16(int value)
{
if (value < (int)Int16.MinValue || value > (int)Int16.MaxValue)
throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Int16" }));
return (short)value;
}
private static byte Int32ToByte(int value)
{
if (value < (int)Byte.MinValue || value > (int)Byte.MaxValue)
throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Byte" }));
return (byte)value;
}
private static ulong DecimalToUInt64(decimal value)
{
if (value < (decimal)UInt64.MinValue || value > (decimal)UInt64.MaxValue)
throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt64" }));
return (ulong)value;
}
private static sbyte Int32ToSByte(int value)
{
if (value < (int)SByte.MinValue || value > (int)SByte.MaxValue)
throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "SByte" }));
return (sbyte)value;
}
private static DateTimeOffset UntypedAtomicToDateTimeOffset(string value)
{
return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd));
}
private static XmlQualifiedName StringToQName(string value, IXmlNamespaceResolver nsResolver)
{
string prefix, localName, ns;
value = value.Trim();
// Parse prefix:localName
try
{
ValidateNames.ParseQNameThrow(value, out prefix, out localName);
}
catch (XmlException e)
{
throw new FormatException(e.Message);
}
// Throw error if no namespaces are in scope
if (nsResolver == null)
throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix));
// Lookup namespace
ns = nsResolver.LookupNamespace(prefix);
if (ns == null)
throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix));
// Create XmlQualfiedName
return new XmlQualifiedName(localName, ns);
}
private static ushort Int32ToUInt16(int value)
{
if (value < (int)UInt16.MinValue || value > (int)UInt16.MaxValue)
throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt16" }));
return (ushort)value;
}
private static uint Int64ToUInt32(long value)
{
if (value < (long)UInt32.MinValue || value > (long)UInt32.MaxValue)
throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt32" }));
return (uint)value;
}
public static object ChangeType(string value, Type destinationType, IXmlNamespaceResolver nsResolver)
{
if (value == null) throw new ArgumentNullException("value");
if (destinationType == null) throw new ArgumentNullException("destinationType");
if (destinationType == s_BooleanType) return XmlConvert.ToBoolean((string)value);
if (destinationType == s_ByteType) return Int32ToByte(XmlConvert.ToInt32((string)value));
if (destinationType == s_ByteArrayType) return StringToBase64Binary((string)value);
if (destinationType == s_DateTimeType) return UntypedAtomicToDateTime((string)value);
if (destinationType == s_DateTimeOffsetType) return XmlConvert.ToDateTimeOffset((string)value);
if (destinationType == s_DecimalType) return XmlConvert.ToDecimal((string)value);
if (destinationType == s_DoubleType) return XmlConvert.ToDouble((string)value);
if (destinationType == s_Int16Type) return Int32ToInt16(XmlConvert.ToInt32((string)value));
if (destinationType == s_Int32Type) return XmlConvert.ToInt32((string)value);
if (destinationType == s_Int64Type) return XmlConvert.ToInt64((string)value);
if (destinationType == s_SByteType) return Int32ToSByte(XmlConvert.ToInt32((string)value));
if (destinationType == s_SingleType) return XmlConvert.ToSingle((string)value);
if (destinationType == s_TimeSpanType) return XmlConvert.ToTimeSpan((string)value);
if (destinationType == s_UInt16Type) return Int32ToUInt16(XmlConvert.ToInt32((string)value));
if (destinationType == s_UInt32Type) return Int64ToUInt32(XmlConvert.ToInt64((string)value));
if (destinationType == s_UInt64Type) return DecimalToUInt64(XmlConvert.ToDecimal((string)value));
if (destinationType == s_UriType) return XmlConvertEx.ToUri((string)value);
if (destinationType == s_XmlQualifiedNameType) return StringToQName((string)value, nsResolver);
if (destinationType == s_StringType) return ((string)value);
throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeFromString, destinationType.Name));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Dynamic
{
/// <summary>
/// Represents the dynamic binding and a binding logic of an object participating in the dynamic binding.
/// </summary>
public class DynamicMetaObject
{
/// <summary>
/// Represents an empty array of type <see cref="DynamicMetaObject"/>. This field is read-only.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
public static readonly DynamicMetaObject[] EmptyMetaObjects = Array.Empty<DynamicMetaObject>();
/// <summary>
/// Initializes a new instance of the <see cref="DynamicMetaObject"/> class.
/// </summary>
/// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param>
/// <param name="restrictions">The set of binding restrictions under which the binding is valid.</param>
public DynamicMetaObject(Expression expression, BindingRestrictions restrictions)
{
ContractUtils.RequiresNotNull(expression, nameof(expression));
ContractUtils.RequiresNotNull(restrictions, nameof(restrictions));
Expression = expression;
Restrictions = restrictions;
}
/// <summary>
/// Initializes a new instance of the <see cref="DynamicMetaObject"/> class.
/// </summary>
/// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param>
/// <param name="restrictions">The set of binding restrictions under which the binding is valid.</param>
/// <param name="value">The runtime value represented by the <see cref="DynamicMetaObject"/>.</param>
public DynamicMetaObject(Expression expression, BindingRestrictions restrictions, object value)
: this(expression, restrictions)
{
Value = value;
HasValue = true;
}
/// <summary>
/// The expression representing the <see cref="DynamicMetaObject"/> during the dynamic binding process.
/// </summary>
public Expression Expression { get; }
/// <summary>
/// The set of binding restrictions under which the binding is valid.
/// </summary>
public BindingRestrictions Restrictions { get; }
/// <summary>
/// The runtime value represented by this <see cref="DynamicMetaObject"/>.
/// </summary>
public object Value { get; }
/// <summary>
/// Gets a value indicating whether the <see cref="DynamicMetaObject"/> has the runtime value.
/// </summary>
public bool HasValue { get; }
/// <summary>
/// Gets the <see cref="Type"/> of the runtime value or null if the <see cref="DynamicMetaObject"/> has no value associated with it.
/// </summary>
public Type RuntimeType
{
get
{
if (HasValue)
{
Type ct = Expression.Type;
// valuetype at compile time, type cannot change.
if (ct.IsValueType)
{
return ct;
}
return Value?.GetType();
}
else
{
return null;
}
}
}
/// <summary>
/// Gets the limit type of the <see cref="DynamicMetaObject"/>.
/// </summary>
/// <remarks>Represents the most specific type known about the object represented by the <see cref="DynamicMetaObject"/>. <see cref="RuntimeType"/> if runtime value is available, a type of the <see cref="Expression"/> otherwise.</remarks>
public Type LimitType => RuntimeType ?? Expression.Type;
/// <summary>
/// Performs the binding of the dynamic conversion operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="ConvertBinder"/> that represents the details of the dynamic operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindConvert(ConvertBinder binder)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackConvert(this);
}
/// <summary>
/// Performs the binding of the dynamic get member operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="GetMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackGetMember(this);
}
/// <summary>
/// Performs the binding of the dynamic set member operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="SetMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set member operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackSetMember(this, value);
}
/// <summary>
/// Performs the binding of the dynamic delete member operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="DeleteMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackDeleteMember(this);
}
/// <summary>
/// Performs the binding of the dynamic get index operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="GetIndexBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the get index operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackGetIndex(this, indexes);
}
/// <summary>
/// Performs the binding of the dynamic set index operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="SetIndexBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the set index operation.</param>
/// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set index operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackSetIndex(this, indexes, value);
}
/// <summary>
/// Performs the binding of the dynamic delete index operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="DeleteIndexBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the delete index operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackDeleteIndex(this, indexes);
}
/// <summary>
/// Performs the binding of the dynamic invoke member operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="InvokeMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke member operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackInvokeMember(this, args);
}
/// <summary>
/// Performs the binding of the dynamic invoke operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="InvokeBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackInvoke(this, args);
}
/// <summary>
/// Performs the binding of the dynamic create instance operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="CreateInstanceBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the create instance operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackCreateInstance(this, args);
}
/// <summary>
/// Performs the binding of the dynamic unary operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="UnaryOperationBinder"/> that represents the details of the dynamic operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackUnaryOperation(this);
}
/// <summary>
/// Performs the binding of the dynamic binary operation.
/// </summary>
/// <param name="binder">An instance of the <see cref="BinaryOperationBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="arg">An instance of the <see cref="DynamicMetaObject"/> representing the right hand side of the binary operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public virtual DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg)
{
ContractUtils.RequiresNotNull(binder, nameof(binder));
return binder.FallbackBinaryOperation(this, arg);
}
/// <summary>
/// Returns the enumeration of all dynamic member names.
/// </summary>
/// <returns>The list of dynamic member names.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public virtual IEnumerable<string> GetDynamicMemberNames() => Array.Empty<string>();
/// <summary>
/// Returns the list of expressions represented by the <see cref="DynamicMetaObject"/> instances.
/// </summary>
/// <param name="objects">An array of <see cref="DynamicMetaObject"/> instances to extract expressions from.</param>
/// <returns>The array of expressions.</returns>
internal static Expression[] GetExpressions(DynamicMetaObject[] objects)
{
ContractUtils.RequiresNotNull(objects, nameof(objects));
Expression[] res = new Expression[objects.Length];
for (int i = 0; i < objects.Length; i++)
{
DynamicMetaObject mo = objects[i];
ContractUtils.RequiresNotNull(mo, nameof(objects));
Expression expr = mo.Expression;
Debug.Assert(expr != null, "Unexpected null expression; ctor should have caught this.");
res[i] = expr;
}
return res;
}
/// <summary>
/// Creates a meta-object for the specified object.
/// </summary>
/// <param name="value">The object to get a meta-object for.</param>
/// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param>
/// <returns>
/// If the given object implements <see cref="IDynamicMetaObjectProvider"/> and is not a remote object from outside the current AppDomain,
/// returns the object's specific meta-object returned by <see cref="IDynamicMetaObjectProvider.GetMetaObject"/>. Otherwise a plain new meta-object
/// with no restrictions is created and returned.
/// </returns>
public static DynamicMetaObject Create(object value, Expression expression)
{
ContractUtils.RequiresNotNull(expression, nameof(expression));
IDynamicMetaObjectProvider ido = value as IDynamicMetaObjectProvider;
if (ido != null)
{
var idoMetaObject = ido.GetMetaObject(expression);
if (idoMetaObject == null ||
!idoMetaObject.HasValue ||
idoMetaObject.Value == null ||
(object)idoMetaObject.Expression != (object)expression)
{
throw System.Linq.Expressions.Error.InvalidMetaObjectCreated(ido.GetType());
}
return idoMetaObject;
}
else
{
return new DynamicMetaObject(expression, BindingRestrictions.Empty, value);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace YAF.Lucene.Net.Util
{
/*
* 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.
*/
/// <summary>
/// <see cref="Sorter"/> implementation based on the
/// <a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">TimSort</a>
/// algorithm.
/// <para/>This implementation is especially good at sorting partially-sorted
/// arrays and sorts small arrays with binary sort.
/// <para/><b>NOTE</b>:There are a few differences with the original implementation:
/// <list type="bullet">
/// <item><description><a name="maxTempSlots"/>The extra amount of memory to perform merges is
/// configurable. This allows small merges to be very fast while large merges
/// will be performed in-place (slightly slower). You can make sure that the
/// fast merge routine will always be used by having <c>maxTempSlots</c>
/// equal to half of the length of the slice of data to sort.</description></item>
/// <item><description>Only the fast merge routine can gallop (the one that doesn't run
/// in-place) and it only gallops on the longest slice.</description></item>
/// </list>
/// <para/>
/// @lucene.internal
/// </summary>
public abstract class TimSorter : Sorter
{
internal const int MINRUN = 32;
internal new const int THRESHOLD = 64;
internal const int STACKSIZE = 40; // depends on MINRUN
internal const int MIN_GALLOP = 7;
internal readonly int maxTempSlots;
internal int minRun;
internal int to;
internal int stackSize;
internal int[] runEnds;
/// <summary>
/// Create a new <see cref="TimSorter"/>. </summary>
/// <param name="maxTempSlots"> The <a href="#maxTempSlots">maximum amount of extra memory to run merges</a> </param>
protected TimSorter(int maxTempSlots)
: base()
{
runEnds = new int[1 + STACKSIZE];
this.maxTempSlots = maxTempSlots;
}
/// <summary>
/// Minimum run length for an array of length <paramref name="length"/>. </summary>
internal static int MinRun(int length)
{
Debug.Assert(length >= MINRUN);
int n = length;
int r = 0;
while (n >= 64)
{
r |= n & 1;
n = (int)((uint)n >> 1);
}
int minRun = n + r;
Debug.Assert(minRun >= MINRUN && minRun <= THRESHOLD);
return minRun;
}
internal virtual int RunLen(int i)
{
int off = stackSize - i;
return runEnds[off] - runEnds[off - 1];
}
internal virtual int RunBase(int i)
{
return runEnds[stackSize - i - 1];
}
internal virtual int RunEnd(int i)
{
return runEnds[stackSize - i];
}
internal virtual void SetRunEnd(int i, int runEnd)
{
runEnds[stackSize - i] = runEnd;
}
internal virtual void PushRunLen(int len)
{
runEnds[stackSize + 1] = runEnds[stackSize] + len;
++stackSize;
}
/// <summary>
/// Compute the length of the next run, make the run sorted and return its
/// length.
/// </summary>
internal virtual int NextRun()
{
int runBase = RunEnd(0);
Debug.Assert(runBase < to);
if (runBase == to - 1)
{
return 1;
}
int o = runBase + 2;
if (Compare(runBase, runBase + 1) > 0)
{
// run must be strictly descending
while (o < to && Compare(o - 1, o) > 0)
{
++o;
}
Reverse(runBase, o);
}
else
{
// run must be non-descending
while (o < to && Compare(o - 1, o) <= 0)
{
++o;
}
}
int runHi = Math.Max(o, Math.Min(to, runBase + minRun));
BinarySort(runBase, runHi, o);
return runHi - runBase;
}
internal virtual void EnsureInvariants()
{
while (stackSize > 1)
{
int runLen0 = RunLen(0);
int runLen1 = RunLen(1);
if (stackSize > 2)
{
int runLen2 = RunLen(2);
if (runLen2 <= runLen1 + runLen0)
{
// merge the smaller of 0 and 2 with 1
if (runLen2 < runLen0)
{
MergeAt(1);
}
else
{
MergeAt(0);
}
continue;
}
}
if (runLen1 <= runLen0)
{
MergeAt(0);
continue;
}
break;
}
}
internal virtual void ExhaustStack()
{
while (stackSize > 1)
{
MergeAt(0);
}
}
internal virtual void Reset(int from, int to)
{
stackSize = 0;
Array.Clear(runEnds, 0, runEnds.Length);
runEnds[0] = from;
this.to = to;
int length = to - from;
this.minRun = length <= THRESHOLD ? length : MinRun(length);
}
internal virtual void MergeAt(int n)
{
Debug.Assert(stackSize >= 2);
Merge(RunBase(n + 1), RunBase(n), RunEnd(n));
for (int j = n + 1; j > 0; --j)
{
SetRunEnd(j, RunEnd(j - 1));
}
--stackSize;
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal virtual void Merge(int lo, int mid, int hi)
{
if (Compare(mid - 1, mid) <= 0)
{
return;
}
lo = Upper2(lo, mid, mid);
hi = Lower2(mid, hi, mid - 1);
if (hi - mid <= mid - lo && hi - mid <= maxTempSlots)
{
MergeHi(lo, mid, hi);
}
else if (mid - lo <= maxTempSlots)
{
MergeLo(lo, mid, hi);
}
else
{
MergeInPlace(lo, mid, hi);
}
}
/// <summary>
/// Sort the slice which starts at <paramref name="from"/> (inclusive) and ends at
/// <paramref name="to"/> (exclusive).
/// </summary>
public override void Sort(int from, int to)
{
CheckRange(from, to);
if (to - from <= 1)
{
return;
}
Reset(from, to);
do
{
EnsureInvariants();
PushRunLen(NextRun());
} while (RunEnd(0) < to);
ExhaustStack();
Debug.Assert(RunEnd(0) == to);
}
internal override void DoRotate(int lo, int mid, int hi)
{
int len1 = mid - lo;
int len2 = hi - mid;
if (len1 == len2)
{
while (mid < hi)
{
Swap(lo++, mid++);
}
}
else if (len2 < len1 && len2 <= maxTempSlots)
{
Save(mid, len2);
for (int i = lo + len1 - 1, j = hi - 1; i >= lo; --i, --j)
{
Copy(i, j);
}
for (int i = 0, j = lo; i < len2; ++i, ++j)
{
Restore(i, j);
}
}
else if (len1 <= maxTempSlots)
{
Save(lo, len1);
for (int i = mid, j = lo; i < hi; ++i, ++j)
{
Copy(i, j);
}
for (int i = 0, j = lo + len2; j < hi; ++i, ++j)
{
Restore(i, j);
}
}
else
{
Reverse(lo, mid);
Reverse(mid, hi);
Reverse(lo, hi);
}
}
internal virtual void MergeLo(int lo, int mid, int hi)
{
Debug.Assert(Compare(lo, mid) > 0);
int len1 = mid - lo;
Save(lo, len1);
Copy(mid, lo);
int i = 0, j = mid + 1, dest = lo + 1;
for (; ; )
{
for (int count = 0; count < MIN_GALLOP; )
{
if (i >= len1 || j >= hi)
{
goto outerBreak;
}
else if (CompareSaved(i, j) <= 0)
{
Restore(i++, dest++);
count = 0;
}
else
{
Copy(j++, dest++);
++count;
}
}
// galloping...
int next = LowerSaved3(j, hi, i);
for (; j < next; ++dest)
{
Copy(j++, dest);
}
Restore(i++, dest++);
//outerContinue: ; // LUCENENET NOTE: Not referenced
}
outerBreak:
for (; i < len1; ++dest)
{
Restore(i++, dest);
}
Debug.Assert(j == dest);
}
internal virtual void MergeHi(int lo, int mid, int hi)
{
Debug.Assert(Compare(mid - 1, hi - 1) > 0);
int len2 = hi - mid;
Save(mid, len2);
Copy(mid - 1, hi - 1);
int i = mid - 2, j = len2 - 1, dest = hi - 2;
for (; ; )
{
for (int count = 0; count < MIN_GALLOP; )
{
if (i < lo || j < 0)
{
goto outerBreak;
}
else if (CompareSaved(j, i) >= 0)
{
Restore(j--, dest--);
count = 0;
}
else
{
Copy(i--, dest--);
++count;
}
}
// galloping
int next = UpperSaved3(lo, i + 1, j);
while (i >= next)
{
Copy(i--, dest--);
}
Restore(j--, dest--);
//outerContinue: ; // LUCENENET NOTE: Not referenced
}
outerBreak:
for (; j >= 0; --dest)
{
Restore(j--, dest);
}
Debug.Assert(i == dest);
}
internal virtual int LowerSaved(int from, int to, int val)
{
int len = to - from;
while (len > 0)
{
int half = (int)((uint)len >> 1);
int mid = from + half;
if (CompareSaved(val, mid) > 0)
{
from = mid + 1;
len = len - half - 1;
}
else
{
len = half;
}
}
return from;
}
internal virtual int UpperSaved(int from, int to, int val)
{
int len = to - from;
while (len > 0)
{
int half = (int)((uint)len >> 1);
int mid = from + half;
if (CompareSaved(val, mid) < 0)
{
len = half;
}
else
{
from = mid + 1;
len = len - half - 1;
}
}
return from;
}
// faster than lowerSaved when val is at the beginning of [from:to[
internal virtual int LowerSaved3(int from, int to, int val)
{
int f = from, t = f + 1;
while (t < to)
{
if (CompareSaved(val, t) <= 0)
{
return LowerSaved(f, t, val);
}
int delta = t - f;
f = t;
t += delta << 1;
}
return LowerSaved(f, to, val);
}
//faster than upperSaved when val is at the end of [from:to[
internal virtual int UpperSaved3(int from, int to, int val)
{
int f = to - 1, t = to;
while (f > from)
{
if (CompareSaved(val, f) >= 0)
{
return UpperSaved(f, t, val);
}
int delta = t - f;
t = f;
f -= delta << 1;
}
return UpperSaved(from, t, val);
}
/// <summary>
/// Copy data from slot <paramref name="src"/> to slot <paramref name="dest"/>>. </summary>
protected abstract void Copy(int src, int dest);
/// <summary>
/// Save all elements between slots <paramref name="i"/> and <paramref name="i"/>+<paramref name="len"/>
/// into the temporary storage.
/// </summary>
protected abstract void Save(int i, int len);
/// <summary>
/// Restore element <paramref name="j"/> from the temporary storage into slot <paramref name="i"/>. </summary>
protected abstract void Restore(int i, int j);
/// <summary>
/// Compare element <paramref name="i"/> from the temporary storage with element
/// <paramref name="j"/> from the slice to sort, similarly to
/// <see cref="Sorter.Compare(int, int)"/>.
/// </summary>
protected abstract int CompareSaved(int i, int j);
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting.Server;
using System.Management.Automation.Tracing;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using Dbg = System.Diagnostics.Debug;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// Shared named pipe utilities.
/// </summary>
internal static class NamedPipeUtils
{
#region Strings
internal const string NamedPipeNamePrefix = "PSHost.";
#if UNIX
internal const string DefaultAppDomainName = "None";
// This `CoreFxPipe` prefix is defined by CoreFx
internal const string NamedPipeNamePrefixSearch = "CoreFxPipe_PSHost*";
#else
internal const string DefaultAppDomainName = "DefaultAppDomain";
internal const string NamedPipeNamePrefixSearch = "PSHost*";
#endif
// On non-Windows, .NET named pipes are limited to up to 104 characters
internal const int MaxNamedPipeNameSize = 104;
#endregion
#region Static Methods
/// <summary>
/// Create a pipe name based on process information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="procId">Process Id.</param>
/// <returns>Pipe name.</returns>
internal static string CreateProcessPipeName(
int procId)
{
return CreateProcessPipeName(
System.Diagnostics.Process.GetProcessById(procId));
}
/// <summary>
/// Create a pipe name based on process information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="proc">Process object.</param>
/// <returns>Pipe name.</returns>
internal static string CreateProcessPipeName(
System.Diagnostics.Process proc)
{
return CreateProcessPipeName(proc, DefaultAppDomainName);
}
/// <summary>
/// Create a pipe name based on process Id and appdomain name information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="procId">Process Id.</param>
/// <param name="appDomainName">Name of process app domain to connect to.</param>
/// <returns>Pipe name.</returns>
internal static string CreateProcessPipeName(
int procId,
string appDomainName)
{
return CreateProcessPipeName(System.Diagnostics.Process.GetProcessById(procId), appDomainName);
}
/// <summary>
/// Create a pipe name based on process and appdomain name information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="proc">Process object.</param>
/// <param name="appDomainName">Name of process app domain to connect to.</param>
/// <returns>Pipe name.</returns>
internal static string CreateProcessPipeName(
System.Diagnostics.Process proc,
string appDomainName)
{
if (proc == null)
{
throw new PSArgumentNullException(nameof(proc));
}
if (string.IsNullOrEmpty(appDomainName))
{
appDomainName = DefaultAppDomainName;
}
System.Text.StringBuilder pipeNameBuilder = new System.Text.StringBuilder(MaxNamedPipeNameSize);
pipeNameBuilder.Append(NamedPipeNamePrefix)
// The starttime is there to prevent another process easily guessing the pipe name
// and squatting on it.
// There is a limit of 104 characters in total including the temp path to the named pipe file
// on non-Windows systems, so we'll convert the starttime to hex and just take the first 8 characters.
#if UNIX
.Append(proc.StartTime.ToFileTime().ToString("X8").AsSpan(1, 8))
#else
.Append(proc.StartTime.ToFileTime().ToString(CultureInfo.InvariantCulture))
#endif
.Append('.')
.Append(proc.Id.ToString(CultureInfo.InvariantCulture))
.Append('.')
.Append(CleanAppDomainNameForPipeName(appDomainName))
.Append('.')
.Append(proc.ProcessName);
#if UNIX
int charsToTrim = pipeNameBuilder.Length - MaxNamedPipeNameSize;
if (charsToTrim > 0)
{
// TODO: In the case the pipe name is truncated, the user cannot connect to it using the cmdlet
// unless we add a `-Force` type switch as it attempts to validate the current process name
// matches the process name in the pipe name
pipeNameBuilder.Remove(MaxNamedPipeNameSize + 1, charsToTrim);
}
#endif
return pipeNameBuilder.ToString();
}
private static string CleanAppDomainNameForPipeName(string appDomainName)
{
// Pipe names cannot contain the ':' character. Remove unwanted characters.
return appDomainName.Replace(":", string.Empty).Replace(" ", string.Empty);
}
/// <summary>
/// Returns the current process AppDomain name.
/// </summary>
/// <returns>AppDomain Name string.</returns>
internal static string GetCurrentAppDomainName()
{
#if CORECLR // There is only one AppDomain per application in CoreCLR, which would be the default
return DefaultAppDomainName;
#else // Use the AppDomain in which current powershell is running
return AppDomain.CurrentDomain.IsDefaultAppDomain() ? DefaultAppDomainName : AppDomain.CurrentDomain.FriendlyName;
#endif
}
#endregion
}
/// <summary>
/// Native API for Named Pipes.
/// </summary>
internal static class NamedPipeNative
{
#region Pipe constants
// Pipe open modes
internal const uint PIPE_ACCESS_DUPLEX = 0x00000003;
internal const uint PIPE_ACCESS_OUTBOUND = 0x00000002;
internal const uint PIPE_ACCESS_INBOUND = 0x00000001;
// Pipe modes
internal const uint PIPE_TYPE_BYTE = 0x00000000;
internal const uint PIPE_TYPE_MESSAGE = 0x00000004;
internal const uint FILE_FLAG_OVERLAPPED = 0x40000000;
internal const uint FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000;
internal const uint PIPE_WAIT = 0x00000000;
internal const uint PIPE_NOWAIT = 0x00000001;
internal const uint PIPE_READMODE_BYTE = 0x00000000;
internal const uint PIPE_READMODE_MESSAGE = 0x00000002;
internal const uint PIPE_ACCEPT_REMOTE_CLIENTS = 0x00000000;
internal const uint PIPE_REJECT_REMOTE_CLIENTS = 0x00000008;
// Pipe errors
internal const uint ERROR_FILE_NOT_FOUND = 2;
internal const uint ERROR_BROKEN_PIPE = 109;
internal const uint ERROR_PIPE_BUSY = 231;
internal const uint ERROR_NO_DATA = 232;
internal const uint ERROR_MORE_DATA = 234;
internal const uint ERROR_PIPE_CONNECTED = 535;
internal const uint ERROR_IO_INCOMPLETE = 996;
internal const uint ERROR_IO_PENDING = 997;
// File function constants
internal const uint GENERIC_READ = 0x80000000;
internal const uint GENERIC_WRITE = 0x40000000;
internal const uint GENERIC_EXECUTE = 0x20000000;
internal const uint GENERIC_ALL = 0x10000000;
internal const uint CREATE_NEW = 1;
internal const uint CREATE_ALWAYS = 2;
internal const uint OPEN_EXISTING = 3;
internal const uint OPEN_ALWAYS = 4;
internal const uint TRUNCATE_EXISTING = 5;
internal const uint SECURITY_IMPERSONATIONLEVEL_ANONYMOUS = 0;
internal const uint SECURITY_IMPERSONATIONLEVEL_IDENTIFICATION = 1;
internal const uint SECURITY_IMPERSONATIONLEVEL_IMPERSONATION = 2;
internal const uint SECURITY_IMPERSONATIONLEVEL_DELEGATION = 3;
// Infinite timeout
internal const uint INFINITE = 0xFFFFFFFF;
#endregion
#region Data structures
[StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES
{
/// <summary>
/// The size, in bytes, of this structure. Set this value to the size of the SECURITY_ATTRIBUTES structure.
/// </summary>
public int NLength;
/// <summary>
/// A pointer to a security descriptor for the object that controls the sharing of it.
/// </summary>
public IntPtr LPSecurityDescriptor = IntPtr.Zero;
/// <summary>
/// A Boolean value that specifies whether the returned handle is inherited when a new process is created.
/// </summary>
public bool InheritHandle;
/// <summary>
/// Initializes a new instance of the SECURITY_ATTRIBUTES class.
/// </summary>
public SECURITY_ATTRIBUTES()
{
this.NLength = 12;
}
}
#endregion
#region Pipe methods
[DllImport(PinvokeDllNames.CreateNamedPipeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafePipeHandle CreateNamedPipe(
string lpName,
uint dwOpenMode,
uint dwPipeMode,
uint nMaxInstances,
uint nOutBufferSize,
uint nInBufferSize,
uint nDefaultTimeOut,
SECURITY_ATTRIBUTES securityAttributes);
internal static SECURITY_ATTRIBUTES GetSecurityAttributes(GCHandle securityDescriptorPinnedHandle, bool inheritHandle = false)
{
SECURITY_ATTRIBUTES securityAttributes = new NamedPipeNative.SECURITY_ATTRIBUTES();
securityAttributes.InheritHandle = inheritHandle;
securityAttributes.NLength = (int)Marshal.SizeOf(securityAttributes);
securityAttributes.LPSecurityDescriptor = securityDescriptorPinnedHandle.AddrOfPinnedObject();
return securityAttributes;
}
[DllImport(PinvokeDllNames.CreateFileDllName, SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern SafePipeHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr SecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport(PinvokeDllNames.WaitNamedPipeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool WaitNamedPipe(string lpNamedPipeName, uint nTimeOut);
[DllImport(PinvokeDllNames.ImpersonateNamedPipeClientDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ImpersonateNamedPipeClient(IntPtr hNamedPipe);
[DllImport(PinvokeDllNames.RevertToSelfDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool RevertToSelf();
#endregion
}
/// <summary>
/// Event arguments for listener thread end event.
/// </summary>
internal sealed class ListenerEndedEventArgs : EventArgs
{
#region Properties
/// <summary>
/// Exception reason for listener end event. Can be null
/// which indicates listener thread end is not due to an error.
/// </summary>
public Exception Reason { get; }
/// <summary>
/// True if listener should be restarted after ending.
/// </summary>
public bool RestartListener { get; }
#endregion
#region Constructors
private ListenerEndedEventArgs() { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="reason">Listener end reason.</param>
/// <param name="restartListener">Restart listener.</param>
public ListenerEndedEventArgs(
Exception reason,
bool restartListener)
{
Reason = reason;
RestartListener = restartListener;
}
#endregion
}
/// <summary>
/// Light wrapper class for BCL NamedPipeServerStream class, that
/// creates the named pipe server with process named pipe name,
/// having correct access restrictions, and provides a listener
/// thread loop.
/// </summary>
public sealed class RemoteSessionNamedPipeServer : IDisposable
{
#region Members
private readonly object _syncObject;
private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
private const string _threadName = "IPC Listener Thread";
private const int _namedPipeBufferSizeForRemoting = 32768;
private const int _maxPipePathLengthLinux = 108;
private const int _maxPipePathLengthMacOS = 104;
// Singleton server.
private static readonly object s_syncObject;
internal static RemoteSessionNamedPipeServer IPCNamedPipeServer;
internal static bool IPCNamedPipeServerEnabled;
// Optional custom server.
private static RemoteSessionNamedPipeServer _customNamedPipeServer;
// Access mask constant taken from PipeSecurity access rights and is equivalent to
// PipeAccessRights.FullControl.
// See: https://msdn.microsoft.com/library/vstudio/bb348408(v=vs.100).aspx
//
private const int _pipeAccessMaskFullControl = 0x1f019f;
#endregion
#region Properties
/// <summary>
/// Returns the Named Pipe stream object.
/// </summary>
internal NamedPipeServerStream Stream { get; }
/// <summary>
/// Returns the Named Pipe name.
/// </summary>
internal string PipeName { get; }
/// <summary>
/// Returns true if listener is currently running.
/// </summary>
internal bool IsListenerRunning { get; private set; }
/// <summary>
/// Name of session configuration.
/// </summary>
internal string ConfigurationName { get; set; }
/// <summary>
/// Accessor for the named pipe reader.
/// </summary>
internal StreamReader TextReader { get; private set; }
/// <summary>
/// Accessor for the named pipe writer.
/// </summary>
internal StreamWriter TextWriter { get; private set; }
/// <summary>
/// Returns true if object is currently disposed.
/// </summary>
internal bool IsDisposed { get; private set; }
/// <summary>
/// Buffer size for PSRP fragmentor.
/// </summary>
internal static int NamedPipeBufferSizeForRemoting
{
get { return _namedPipeBufferSizeForRemoting; }
}
#endregion
#region Events
/// <summary>
/// Event raised when the named pipe server listening thread
/// ends.
/// </summary>
internal event EventHandler<ListenerEndedEventArgs> ListenerEnded;
#endregion
#region Constructors
/// <summary>
/// Creates a RemoteSessionNamedPipeServer with the current process and AppDomain information.
/// </summary>
/// <returns>RemoteSessionNamedPipeServer.</returns>
internal static RemoteSessionNamedPipeServer CreateRemoteSessionNamedPipeServer()
{
string appDomainName = NamedPipeUtils.GetCurrentAppDomainName();
return new RemoteSessionNamedPipeServer(NamedPipeUtils.CreateProcessPipeName(
System.Diagnostics.Process.GetCurrentProcess(), appDomainName));
}
/// <summary>
/// Constructor. Creates named pipe server with provided pipe name.
/// </summary>
/// <param name="pipeName">Named Pipe name.</param>
internal RemoteSessionNamedPipeServer(
string pipeName)
{
if (pipeName == null)
{
throw new PSArgumentNullException(nameof(pipeName));
}
_syncObject = new object();
PipeName = pipeName;
Stream = CreateNamedPipe(
serverName: ".",
namespaceName: "pipe",
coreName: pipeName,
securityDesc: GetServerPipeSecurity());
}
/// <summary>
/// Helper method to create a PowerShell transport named pipe via native API, along
/// with a returned .Net NamedPipeServerStream object wrapping the named pipe.
/// </summary>
/// <param name="serverName">Named pipe server name.</param>
/// <param name="namespaceName">Named pipe namespace name.</param>
/// <param name="coreName">Named pipe core name.</param>
/// <param name="securityDesc"></param>
/// <returns>NamedPipeServerStream.</returns>
private static NamedPipeServerStream CreateNamedPipe(
string serverName,
string namespaceName,
string coreName,
CommonSecurityDescriptor securityDesc)
{
if (serverName == null) { throw new PSArgumentNullException(nameof(serverName)); }
if (namespaceName == null) { throw new PSArgumentNullException(nameof(namespaceName)); }
if (coreName == null) { throw new PSArgumentNullException(nameof(coreName)); }
#if !UNIX
string fullPipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName;
// Create optional security attributes based on provided PipeSecurity.
NamedPipeNative.SECURITY_ATTRIBUTES securityAttributes = null;
GCHandle? securityDescHandle = null;
if (securityDesc != null)
{
byte[] securityDescBuffer = new byte[securityDesc.BinaryLength];
securityDesc.GetBinaryForm(securityDescBuffer, 0);
securityDescHandle = GCHandle.Alloc(securityDescBuffer, GCHandleType.Pinned);
securityAttributes = NamedPipeNative.GetSecurityAttributes(securityDescHandle.Value);
}
// Create named pipe.
SafePipeHandle pipeHandle = NamedPipeNative.CreateNamedPipe(
fullPipeName,
NamedPipeNative.PIPE_ACCESS_DUPLEX | NamedPipeNative.FILE_FLAG_FIRST_PIPE_INSTANCE | NamedPipeNative.FILE_FLAG_OVERLAPPED,
NamedPipeNative.PIPE_TYPE_MESSAGE | NamedPipeNative.PIPE_READMODE_MESSAGE,
1,
_namedPipeBufferSizeForRemoting,
_namedPipeBufferSizeForRemoting,
0,
securityAttributes);
int lastError = Marshal.GetLastWin32Error();
if (securityDescHandle != null)
{
securityDescHandle.Value.Free();
}
if (pipeHandle.IsInvalid)
{
throw new PSInvalidOperationException(
StringUtil.Format(RemotingErrorIdStrings.CannotCreateNamedPipe, lastError));
}
// Create the .Net NamedPipeServerStream wrapper.
try
{
return new NamedPipeServerStream(
PipeDirection.InOut,
true, // IsAsync
false, // IsConnected
pipeHandle);
}
catch (Exception)
{
pipeHandle.Dispose();
throw;
}
#else
return new NamedPipeServerStream(
pipeName: coreName,
direction: PipeDirection.InOut,
maxNumberOfServerInstances: 1,
transmissionMode: PipeTransmissionMode.Byte,
options: PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly,
inBufferSize: _namedPipeBufferSizeForRemoting,
outBufferSize: _namedPipeBufferSizeForRemoting);
#endif
}
static RemoteSessionNamedPipeServer()
{
s_syncObject = new object();
// All PowerShell instances will start with the named pipe
// and listener created and running.
IPCNamedPipeServerEnabled = true;
CreateIPCNamedPipeServerSingleton();
CreateProcessExitHandler();
}
#endregion
#region IDisposable
/// <summary>
/// Dispose.
/// </summary>
public void Dispose()
{
lock (_syncObject)
{
if (IsDisposed) { return; }
IsDisposed = true;
}
if (TextReader != null)
{
try { TextReader.Dispose(); }
catch (ObjectDisposedException) { }
TextReader = null;
}
if (TextWriter != null)
{
try { TextWriter.Dispose(); }
catch (ObjectDisposedException) { }
TextWriter = null;
}
if (Stream != null)
{
try { Stream.Dispose(); }
catch (ObjectDisposedException) { }
}
}
#endregion
#region Public Methods
/// <summary>
/// Creates the custom named pipe server with the given pipename.
/// </summary>
/// <param name="pipeName">The name of the pipe to create.</param>
public static void CreateCustomNamedPipeServer(string pipeName)
{
lock (s_syncObject)
{
if (_customNamedPipeServer != null && !_customNamedPipeServer.IsDisposed)
{
if (pipeName == _customNamedPipeServer.PipeName)
{
// we shouldn't recreate the server object if we're using the same pipeName
return;
}
// Dispose of the current pipe server so we can create a new one with the new pipeName
_customNamedPipeServer.Dispose();
}
if (!Platform.IsWindows)
{
int maxNameLength = (Platform.IsLinux ? _maxPipePathLengthLinux : _maxPipePathLengthMacOS) - Path.GetTempPath().Length;
if (pipeName.Length > maxNameLength)
{
throw new InvalidOperationException(
string.Format(
RemotingErrorIdStrings.CustomPipeNameTooLong,
maxNameLength,
pipeName,
pipeName.Length));
}
}
try
{
try
{
_customNamedPipeServer = new RemoteSessionNamedPipeServer(pipeName);
}
catch (IOException)
{
// Expected when named pipe server for this process already exists.
// This can happen if process has multiple AppDomains hosting PowerShell (SMA.dll).
return;
}
// Listener ended callback, used to create listening new pipe server.
_customNamedPipeServer.ListenerEnded += OnCustomNamedPipeServerEnded;
// Start the pipe server listening thread, and provide client connection callback.
_customNamedPipeServer.StartListening(ClientConnectionCallback);
}
catch (Exception)
{
_customNamedPipeServer = null;
}
}
}
#endregion
#region Private Methods
/// <summary>
/// Starts named pipe server listening thread. When a client connects this thread
/// makes a callback to implement the client communication. When the thread ends
/// this object is disposed and a new RemoteSessionNamedPipeServer must be created
/// and a new listening thread started to handle subsequent client connections.
/// </summary>
/// <param name="clientConnectCallback">Connection callback.</param>
internal void StartListening(
Action<RemoteSessionNamedPipeServer> clientConnectCallback)
{
if (clientConnectCallback == null)
{
throw new PSArgumentNullException(nameof(clientConnectCallback));
}
lock (_syncObject)
{
if (IsListenerRunning)
{
throw new InvalidOperationException(RemotingErrorIdStrings.NamedPipeAlreadyListening);
}
IsListenerRunning = true;
// Create listener thread.
Thread listenerThread = new Thread(ProcessListeningThread);
listenerThread.Name = _threadName;
listenerThread.IsBackground = true;
listenerThread.Start(clientConnectCallback);
}
}
internal static CommonSecurityDescriptor GetServerPipeSecurity()
{
#if UNIX
return null;
#else
// Built-in Admin SID
SecurityIdentifier adminSID = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
DiscretionaryAcl dacl = new DiscretionaryAcl(false, false, 1);
dacl.AddAccess(
AccessControlType.Allow,
adminSID,
_pipeAccessMaskFullControl,
InheritanceFlags.None,
PropagationFlags.None);
CommonSecurityDescriptor securityDesc = new CommonSecurityDescriptor(
false, false,
ControlFlags.DiscretionaryAclPresent | ControlFlags.OwnerDefaulted | ControlFlags.GroupDefaulted,
null, null, null, dacl);
// Conditionally add User SID
bool isAdminElevated = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
if (!isAdminElevated)
{
securityDesc.DiscretionaryAcl.AddAccess(
AccessControlType.Allow,
WindowsIdentity.GetCurrent().User,
_pipeAccessMaskFullControl,
InheritanceFlags.None,
PropagationFlags.None);
}
return securityDesc;
#endif
}
/// <summary>
/// Wait for client connection.
/// </summary>
private void WaitForConnection()
{
Stream.WaitForConnection();
}
/// <summary>
/// Process listening thread.
/// </summary>
/// <param name="state">Client callback delegate.</param>
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle")]
private void ProcessListeningThread(object state)
{
string processId = Environment.ProcessId.ToString(CultureInfo.InvariantCulture);
string appDomainName = NamedPipeUtils.GetCurrentAppDomainName();
// Logging.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Listener thread started on Process {0} in AppDomainName {1}.", processId, appDomainName);
PSEtwLog.LogOperationalInformation(
PSEventId.NamedPipeIPC_ServerListenerStarted, PSOpcode.Open, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName);
Exception ex = null;
string userName = string.Empty;
bool restartListenerThread = true;
// Wait for connection.
try
{
// Begin listening for a client connect.
this.WaitForConnection();
try
{
#if UNIX
userName = System.Environment.UserName;
#else
userName = WindowsIdentity.GetCurrent().Name;
#endif
}
catch (System.Security.SecurityException) { }
// Logging.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Client connection started on Process {0} in AppDomainName {1} for User {2}.", processId, appDomainName, userName);
PSEtwLog.LogOperationalInformation(
PSEventId.NamedPipeIPC_ServerConnect, PSOpcode.Connect, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, userName);
// Create reader/writer streams.
TextReader = new StreamReader(Stream);
TextWriter = new StreamWriter(Stream);
TextWriter.AutoFlush = true;
}
catch (Exception e)
{
ex = e;
}
if (ex != null)
{
// Error during connection handling. Don't try to restart listening thread.
string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Unexpected error in listener thread on process {0} in AppDomainName {1}. Error Message: {2}", processId, appDomainName, errorMessage);
PSEtwLog.LogOperationalError(PSEventId.NamedPipeIPC_ServerListenerError, PSOpcode.Exception, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, errorMessage);
Dispose();
return;
}
// Start server session on new connection.
ex = null;
try
{
Action<RemoteSessionNamedPipeServer> clientConnectCallback = state as Action<RemoteSessionNamedPipeServer>;
Dbg.Assert(clientConnectCallback != null, "Client callback should never be null.");
// Handle a new client connect by making the callback.
// The callback must handle all exceptions except
// for a named pipe disposed or disconnected exception
// which propagates up to the thread listener loop.
clientConnectCallback(this);
}
catch (IOException)
{
// Expected connection terminated.
}
catch (ObjectDisposedException)
{
// Expected from PS transport close/dispose.
}
catch (Exception e)
{
ex = e;
restartListenerThread = false;
}
// Logging.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Client connection ended on process {0} in AppDomainName {1} for User {2}.", processId, appDomainName, userName);
PSEtwLog.LogOperationalInformation(
PSEventId.NamedPipeIPC_ServerDisconnect, PSOpcode.Close, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, userName);
if (ex == null)
{
// Normal listener exit.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Listener thread ended on process {0} in AppDomainName {1}.", processId, appDomainName);
PSEtwLog.LogOperationalInformation(PSEventId.NamedPipeIPC_ServerListenerEnded, PSOpcode.Close, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName);
}
else
{
// Unexpected error.
string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Unexpected error in listener thread on process {0} in AppDomainName {1}. Error Message: {2}", processId, appDomainName, errorMessage);
PSEtwLog.LogOperationalError(PSEventId.NamedPipeIPC_ServerListenerError, PSOpcode.Exception, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, errorMessage);
}
lock (_syncObject)
{
IsListenerRunning = false;
}
// Ensure this named pipe server object is disposed.
Dispose();
ListenerEnded.SafeInvoke(
this,
new ListenerEndedEventArgs(ex, restartListenerThread));
}
#endregion
#region Static Methods
/// <summary>
/// Ensures the namedpipe singleton server is running and waits for a client connection.
/// This is a blocking call that returns after the client connection ends.
/// This method supports PowerShell running in "NamedPipeServerMode", which is used for
/// PowerShell Direct Windows Server Container connection and management.
/// </summary>
/// <param name="configurationName">Name of the configuration to use.</param>
internal static void RunServerMode(string configurationName)
{
IPCNamedPipeServerEnabled = true;
CreateIPCNamedPipeServerSingleton();
if (IPCNamedPipeServer == null)
{
throw new RuntimeException(RemotingErrorIdStrings.NamedPipeServerCannotStart);
}
IPCNamedPipeServer.ConfigurationName = configurationName;
ManualResetEventSlim clientConnectionEnded = new ManualResetEventSlim(false);
IPCNamedPipeServer.ListenerEnded -= OnIPCNamedPipeServerEnded;
IPCNamedPipeServer.ListenerEnded += (sender, e) => clientConnectionEnded.Set();
// Wait for server to service a single client connection.
clientConnectionEnded.Wait();
clientConnectionEnded.Dispose();
IPCNamedPipeServerEnabled = false;
}
/// <summary>
/// Creates the process named pipe server object singleton and
/// starts the client listening thread.
/// </summary>
internal static void CreateIPCNamedPipeServerSingleton()
{
lock (s_syncObject)
{
if (!IPCNamedPipeServerEnabled) { return; }
if (IPCNamedPipeServer == null || IPCNamedPipeServer.IsDisposed)
{
try
{
try
{
IPCNamedPipeServer = CreateRemoteSessionNamedPipeServer();
}
catch (IOException)
{
// Expected when named pipe server for this process already exists.
// This can happen if process has multiple AppDomains hosting PowerShell (SMA.dll).
return;
}
// Listener ended callback, used to create listening new pipe server.
IPCNamedPipeServer.ListenerEnded += OnIPCNamedPipeServerEnded;
// Start the pipe server listening thread, and provide client connection callback.
IPCNamedPipeServer.StartListening(ClientConnectionCallback);
}
catch (Exception)
{
IPCNamedPipeServer = null;
}
}
}
}
private static void CreateProcessExitHandler()
{
AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
{
IPCNamedPipeServerEnabled = false;
RemoteSessionNamedPipeServer namedPipeServer = IPCNamedPipeServer;
if (namedPipeServer != null)
{
try
{
// Terminate the IPC thread.
namedPipeServer.Dispose();
}
catch (ObjectDisposedException)
{
// Ignore if object already disposed.
}
catch (Exception)
{
// Don't throw an exception on the app domain unload event thread.
}
}
};
}
private static void OnIPCNamedPipeServerEnded(object sender, ListenerEndedEventArgs args)
{
if (args.RestartListener)
{
CreateIPCNamedPipeServerSingleton();
}
}
private static void OnCustomNamedPipeServerEnded(object sender, ListenerEndedEventArgs args)
{
if (args.RestartListener && sender is RemoteSessionNamedPipeServer server)
{
CreateCustomNamedPipeServer(server.PipeName);
}
}
private static void ClientConnectionCallback(RemoteSessionNamedPipeServer pipeServer)
{
// Create server mediator object and begin remote session with client.
NamedPipeProcessMediator.Run(
string.Empty,
pipeServer);
}
#endregion
}
/// <summary>
/// Base class for RemoteSessionNamedPipeClient and ContainerSessionNamedPipeClient.
/// </summary>
internal class NamedPipeClientBase : IDisposable
{
#region Members
private NamedPipeClientStream _clientPipeStream;
private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
protected string _pipeName;
#endregion
#region Properties
/// <summary>
/// Accessor for the named pipe reader.
/// </summary>
public StreamReader TextReader { get; private set; }
/// <summary>
/// Accessor for the named pipe writer.
/// </summary>
public StreamWriter TextWriter { get; private set; }
/// <summary>
/// Name of pipe.
/// </summary>
public string PipeName
{
get { return _pipeName; }
}
#endregion
#region Constructor
public NamedPipeClientBase()
{ }
#endregion
#region IDisposable
/// <summary>
/// Dispose.
/// </summary>
public void Dispose()
{
if (TextReader != null)
{
try { TextReader.Dispose(); }
catch (ObjectDisposedException) { }
TextReader = null;
}
if (TextWriter != null)
{
try { TextWriter.Dispose(); }
catch (ObjectDisposedException) { }
TextWriter = null;
}
if (_clientPipeStream != null)
{
try { _clientPipeStream.Dispose(); }
catch (ObjectDisposedException) { }
}
}
#endregion
#region Methods
/// <summary>
/// Connect to named pipe server. This is a blocking call until a
/// connection occurs or the timeout time has elapsed.
/// </summary>
/// <param name="timeout">Connection attempt timeout in milliseconds.</param>
public void Connect(
int timeout)
{
// Uses Native API to connect to pipe and return NamedPipeClientStream object.
_clientPipeStream = DoConnect(timeout);
// Create reader/writer streams.
TextReader = new StreamReader(_clientPipeStream);
TextWriter = new StreamWriter(_clientPipeStream);
TextWriter.AutoFlush = true;
_tracer.WriteMessage("NamedPipeClientBase", "Connect", Guid.Empty,
"Connection started on pipe: {0}", _pipeName);
}
/// <summary>
/// Closes the named pipe.
/// </summary>
public void Close()
{
if (_clientPipeStream != null)
{
_clientPipeStream.Dispose();
}
}
public virtual void AbortConnect()
{ }
protected virtual NamedPipeClientStream DoConnect(int timeout)
{
return null;
}
#endregion
}
/// <summary>
/// Light wrapper class for BCL NamedPipeClientStream class, that
/// creates the named pipe name and initiates connection to
/// target named pipe server.
/// </summary>
internal sealed class RemoteSessionNamedPipeClient : NamedPipeClientBase
{
#region Members
private volatile bool _connecting;
#endregion
#region Constructors
private RemoteSessionNamedPipeClient()
{ }
/// <summary>
/// Constructor. Creates Named Pipe based on process object.
/// </summary>
/// <param name="process">Target process object for pipe.</param>
/// <param name="appDomainName">AppDomain name or null for default AppDomain.</param>
public RemoteSessionNamedPipeClient(System.Diagnostics.Process process, string appDomainName)
: this(NamedPipeUtils.CreateProcessPipeName(process, appDomainName))
{ }
/// <summary>
/// Constructor. Creates Named Pipe based on process Id.
/// </summary>
/// <param name="procId">Target process Id for pipe.</param>
/// <param name="appDomainName">AppDomain name or null for default AppDomain.</param>
public RemoteSessionNamedPipeClient(int procId, string appDomainName)
: this(NamedPipeUtils.CreateProcessPipeName(procId, appDomainName))
{ }
/// <summary>
/// Constructor. Creates Named Pipe based on name argument.
/// </summary>
/// <param name="pipeName">Named Pipe name.</param>
internal RemoteSessionNamedPipeClient(
string pipeName)
{
if (pipeName == null)
{
throw new PSArgumentNullException(nameof(pipeName));
}
_pipeName = pipeName;
// Defer creating the .Net NamedPipeClientStream object until we connect.
// _clientPipeStream == null.
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="serverName"></param>
/// <param name="namespaceName"></param>
/// <param name="coreName"></param>
internal RemoteSessionNamedPipeClient(
string serverName,
string namespaceName,
string coreName)
{
if (serverName == null) { throw new PSArgumentNullException(nameof(serverName)); }
if (namespaceName == null) { throw new PSArgumentNullException(nameof(namespaceName)); }
if (coreName == null) { throw new PSArgumentNullException(nameof(coreName)); }
_pipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName;
// Defer creating the .Net NamedPipeClientStream object until we connect.
// _clientPipeStream == null.
}
#endregion
#region Public Methods
/// <summary>
/// Abort connection attempt.
/// </summary>
public override void AbortConnect()
{
_connecting = false;
}
#endregion
#region Protected Methods
protected override NamedPipeClientStream DoConnect(int timeout)
{
// Repeatedly attempt connection to pipe until timeout expires.
int startTime = Environment.TickCount;
int elapsedTime = 0;
_connecting = true;
NamedPipeClientStream namedPipeClientStream = new NamedPipeClientStream(
serverName: ".",
pipeName: _pipeName,
direction: PipeDirection.InOut,
options: PipeOptions.Asynchronous);
namedPipeClientStream.Connect();
do
{
if (!namedPipeClientStream.IsConnected)
{
Thread.Sleep(100);
elapsedTime = unchecked(Environment.TickCount - startTime);
continue;
}
_connecting = false;
return namedPipeClientStream;
} while (_connecting && (elapsedTime < timeout));
_connecting = false;
throw new TimeoutException(RemotingErrorIdStrings.ConnectNamedPipeTimeout);
}
#endregion
}
/// <summary>
/// Light wrapper class for BCL NamedPipeClientStream class, that
/// creates the named pipe name and initiates connection to
/// target named pipe server inside Windows Server container.
/// </summary>
internal sealed class ContainerSessionNamedPipeClient : NamedPipeClientBase
{
#region Constructors
/// <summary>
/// Constructor. Creates Named Pipe based on process Id, app domain name and container object root path.
/// </summary>
/// <param name="procId">Target process Id for pipe.</param>
/// <param name="appDomainName">AppDomain name or null for default AppDomain.</param>
/// <param name="containerObRoot">Container OB root.</param>
public ContainerSessionNamedPipeClient(
int procId,
string appDomainName,
string containerObRoot)
{
if (string.IsNullOrEmpty(containerObRoot))
{
throw new PSArgumentNullException(nameof(containerObRoot));
}
//
// Named pipe inside Windows Server container is under different name space.
//
_pipeName = containerObRoot + @"\Device\NamedPipe\" +
NamedPipeUtils.CreateProcessPipeName(procId, appDomainName);
}
#endregion
#region Protected Methods
/// <summary>
/// Helper method to open a named pipe via native APIs and return in
/// .Net NamedPipeClientStream wrapper object.
/// </summary>
protected override NamedPipeClientStream DoConnect(int timeout)
{
//
// WaitNamedPipe API is not supported by Windows Server container now, so we need to repeatedly
// attempt connection to pipe server until timeout expires.
//
int startTime = Environment.TickCount;
int elapsedTime = 0;
SafePipeHandle pipeHandle = null;
do
{
// Get handle to pipe.
pipeHandle = NamedPipeNative.CreateFile(
lpFileName: _pipeName,
dwDesiredAccess: NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE,
dwShareMode: 0,
SecurityAttributes: IntPtr.Zero,
dwCreationDisposition: NamedPipeNative.OPEN_EXISTING,
dwFlagsAndAttributes: NamedPipeNative.FILE_FLAG_OVERLAPPED,
hTemplateFile: IntPtr.Zero);
int lastError = Marshal.GetLastWin32Error();
if (pipeHandle.IsInvalid)
{
if (lastError == NamedPipeNative.ERROR_FILE_NOT_FOUND)
{
elapsedTime = unchecked(Environment.TickCount - startTime);
Thread.Sleep(100);
continue;
}
else
{
throw new PSInvalidOperationException(
StringUtil.Format(RemotingErrorIdStrings.CannotConnectContainerNamedPipe, lastError));
}
}
else
{
break;
}
} while (elapsedTime < timeout);
try
{
return new NamedPipeClientStream(
PipeDirection.InOut,
true,
true,
pipeHandle);
}
catch (Exception)
{
pipeHandle.Dispose();
throw;
}
}
#endregion
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* 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 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.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// A user of the system
/// First published in XenServer 4.0.
/// </summary>
public partial class User : XenObject<User>
{
public User()
{
}
public User(string uuid,
string short_name,
string fullname,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.short_name = short_name;
this.fullname = fullname;
this.other_config = other_config;
}
/// <summary>
/// Creates a new User from a Proxy_User.
/// </summary>
/// <param name="proxy"></param>
public User(Proxy_User proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(User update)
{
uuid = update.uuid;
short_name = update.short_name;
fullname = update.fullname;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_User proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
short_name = proxy.short_name == null ? null : (string)proxy.short_name;
fullname = proxy.fullname == null ? null : (string)proxy.fullname;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_User ToProxy()
{
Proxy_User result_ = new Proxy_User();
result_.uuid = (uuid != null) ? uuid : "";
result_.short_name = (short_name != null) ? short_name : "";
result_.fullname = (fullname != null) ? fullname : "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new User from a Hashtable.
/// </summary>
/// <param name="table"></param>
public User(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
short_name = Marshalling.ParseString(table, "short_name");
fullname = Marshalling.ParseString(table, "fullname");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(User other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._short_name, other._short_name) &&
Helper.AreEqual2(this._fullname, other._fullname) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, User server)
{
if (opaqueRef == null)
{
Proxy_User p = this.ToProxy();
return session.proxy.user_create(session.uuid, p).parse();
}
else
{
if (!Helper.AreEqual2(_fullname, server._fullname))
{
User.set_fullname(session, opaqueRef, _fullname);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
User.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given user.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
[Deprecated("XenServer 5.5")]
public static User get_record(Session session, string _user)
{
return new User((Proxy_User)session.proxy.user_get_record(session.uuid, (_user != null) ? _user : "").parse());
}
/// <summary>
/// Get a reference to the user instance with the specified UUID.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
[Deprecated("XenServer 5.5")]
public static XenRef<User> get_by_uuid(Session session, string _uuid)
{
return XenRef<User>.Create(session.proxy.user_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Create a new user instance, and return its handle.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
[Deprecated("XenServer 5.5")]
public static XenRef<User> create(Session session, User _record)
{
return XenRef<User>.Create(session.proxy.user_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new user instance, and return its handle.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
[Deprecated("XenServer 5.5")]
public static XenRef<Task> async_create(Session session, User _record)
{
return XenRef<Task>.Create(session.proxy.async_user_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified user instance.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
[Deprecated("XenServer 5.5")]
public static void destroy(Session session, string _user)
{
session.proxy.user_destroy(session.uuid, (_user != null) ? _user : "").parse();
}
/// <summary>
/// Destroy the specified user instance.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
[Deprecated("XenServer 5.5")]
public static XenRef<Task> async_destroy(Session session, string _user)
{
return XenRef<Task>.Create(session.proxy.async_user_destroy(session.uuid, (_user != null) ? _user : "").parse());
}
/// <summary>
/// Get the uuid field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_uuid(Session session, string _user)
{
return (string)session.proxy.user_get_uuid(session.uuid, (_user != null) ? _user : "").parse();
}
/// <summary>
/// Get the short_name field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_short_name(Session session, string _user)
{
return (string)session.proxy.user_get_short_name(session.uuid, (_user != null) ? _user : "").parse();
}
/// <summary>
/// Get the fullname field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_fullname(Session session, string _user)
{
return (string)session.proxy.user_get_fullname(session.uuid, (_user != null) ? _user : "").parse();
}
/// <summary>
/// Get the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static Dictionary<string, string> get_other_config(Session session, string _user)
{
return Maps.convert_from_proxy_string_string(session.proxy.user_get_other_config(session.uuid, (_user != null) ? _user : "").parse());
}
/// <summary>
/// Set the fullname field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_fullname">New value to set</param>
public static void set_fullname(Session session, string _user, string _fullname)
{
session.proxy.user_set_fullname(session.uuid, (_user != null) ? _user : "", (_fullname != null) ? _fullname : "").parse();
}
/// <summary>
/// Set the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _user, Dictionary<string, string> _other_config)
{
session.proxy.user_set_other_config(session.uuid, (_user != null) ? _user : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _user, string _key, string _value)
{
session.proxy.user_add_to_other_config(session.uuid, (_user != null) ? _user : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given user. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _user, string _key)
{
session.proxy.user_remove_from_other_config(session.uuid, (_user != null) ? _user : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// short name (e.g. userid)
/// </summary>
public virtual string short_name
{
get { return _short_name; }
set
{
if (!Helper.AreEqual(value, _short_name))
{
_short_name = value;
Changed = true;
NotifyPropertyChanged("short_name");
}
}
}
private string _short_name;
/// <summary>
/// full name
/// </summary>
public virtual string fullname
{
get { return _fullname; }
set
{
if (!Helper.AreEqual(value, _fullname))
{
_fullname = value;
Changed = true;
NotifyPropertyChanged("fullname");
}
}
}
private string _fullname;
/// <summary>
/// additional configuration
/// First published in XenServer 5.0.
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
}
}
| |
using Facebook.Unity;
using PlayFab;
using PlayFab.ClientModels;
using PlayFab.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;
/// <summary>
/// PlayerData contains all the PlayFab API calls that relate to manipulating and
/// </summary>
public static class PF_PlayerData
{
// Player Level Data:
public static string PlayerId = string.Empty;
public static bool showAccountOptionsOnLogin = true;
public static bool isRegisteredForPush = false;
public static bool isPlayFabRegistered { get { return accountInfo != null && accountInfo.PrivateInfo != null && !string.IsNullOrEmpty(accountInfo.Username) && !string.IsNullOrEmpty(accountInfo.PrivateInfo.Email); } }
public static UserAccountInfo accountInfo;
public static readonly Dictionary<string, UserDataRecord> UserData = new Dictionary<string, UserDataRecord>();
// this is a sorted, collated structure built from playerInventory. By default, this will only grab items that are in the primary catalog
public static readonly Dictionary<string, InventoryCategory> inventoryByCategory = new Dictionary<string, InventoryCategory>();
public static readonly Dictionary<string, int> virtualCurrency = new Dictionary<string, int>();
public static readonly List<ItemInstance> playerInventory = new List<ItemInstance>();
public static readonly Dictionary<string, int> userStatistics = new Dictionary<string, int>();
//aggregation of player characters
public static readonly List<CharacterResult> playerCharacters = new List<CharacterResult>();
public static readonly Dictionary<string, UB_CharacterData> playerCharacterData = new Dictionary<string, UB_CharacterData>();
public static readonly Dictionary<string, List<string>> characterAchievements = new Dictionary<string, List<string>>();
public static readonly Dictionary<string, Dictionary<string, int>> characterStatistics = new Dictionary<string, Dictionary<string, int>>();
public static readonly List<FriendInfo> playerFriends = new List<FriendInfo>();
public enum PlayerClassTypes { Bucephelous = 0, Nightmare = 1, PegaZeus = 2 }
// The current character being played:
public static UB_SavedCharacter activeCharacter = null;
#region User Data
public static void GetUserData(List<string> keys, UnityAction<GetUserDataResult> callback = null)
{
var request = new GetUserDataRequest
{
Keys = keys,
PlayFabId = PlayerId,
};
//DialogCanvasController.RequestLoadingPrompt (PlayFabAPIMethods.GetUserData);
PlayFabClientAPI.GetUserReadOnlyData(request, result =>
{
if (callback != null)
callback(result);
PF_Bridge.RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.GetUserData, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
public static void UpdateUserData(Dictionary<string, string> updates, string permission = "Public", UnityAction<UpdateUserDataResult> callback = null)
{
var request = new UpdateUserDataRequest
{
Data = updates,
Permission = (UserDataPermission)Enum.Parse(typeof(UserDataPermission), permission),
};
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.UpdateUserData);
PlayFabClientAPI.UpdateUserData(request, result =>
{
if (callback != null)
callback(result);
PF_Bridge.RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.UpdateUserData, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
public static void GetUserInventory(Action callback = null)
{
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.GetUserInventory);
PlayFabClientAPI.GetUserInventory(new GetUserInventoryRequest(), (GetUserInventoryResult result) =>
{
virtualCurrency.Clear();
playerInventory.Clear();
foreach (var pair in result.VirtualCurrency)
virtualCurrency.Add(pair.Key, pair.Value);
foreach (var eachItem in result.Inventory)
playerInventory.Add(eachItem);
inventoryByCategory.Clear();
if (PF_GameData.catalogItems.Count > 0)
{
foreach (var item in playerInventory)
{
if (inventoryByCategory.ContainsKey(item.ItemId))
continue;
var catalogItem = PF_GameData.GetCatalogItemById(item.ItemId);
if (catalogItem == null)
continue;
var items = playerInventory.FindAll(x => { return x.ItemId.Equals(item.ItemId); });
var customIcon = PF_GameData.GetIconByItemById(catalogItem.ItemId);
var icon = GameController.Instance.iconManager.GetIconById(customIcon, IconManager.IconTypes.Item);
inventoryByCategory.Add(item.ItemId, new InventoryCategory(item.ItemId, catalogItem, items, icon));
}
}
if (callback != null)
callback();
PF_Bridge.RaiseCallbackSuccess("", PlayFabAPIMethods.GetUserInventory, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
#endregion
#region User Statistics
public static void GetUserStatistics()
{
GetPlayerStatisticsRequest request = new GetPlayerStatisticsRequest();
PlayFabClientAPI.GetPlayerStatistics(request, OnGetUserStatisticsSuccess, OnGetUserStatisticsError);
}
private static void OnGetUserStatisticsSuccess(GetPlayerStatisticsResult result)
{
//TODO update to use new
PF_Bridge.RaiseCallbackSuccess("", PlayFabAPIMethods.GetUserStatistics, MessageDisplayStyle.none);
foreach (var each in result.Statistics)
userStatistics[each.StatisticName] = each.Value;
}
private static void OnGetUserStatisticsError(PlayFabError error)
{
PF_Bridge.RaiseCallbackError(error.ErrorMessage, PlayFabAPIMethods.GetUserStatistics, MessageDisplayStyle.error);
}
public static void UpdateUserStatistics(Dictionary<string, int> updates)
{
var statistics = new List<StatisticUpdate>();
foreach (var eachUpdate in updates) // Copy the stats from the inputs to the request
{
int eachStat;
userStatistics.TryGetValue(eachUpdate.Key, out eachStat);
statistics.Add(new StatisticUpdate { StatisticName = eachUpdate.Key, Value = eachUpdate.Value }); // Send the value to the server
userStatistics[eachUpdate.Key] = eachStat + eachUpdate.Value; // Update the local cache so that future updates are using correct values
}
var request = new ExecuteCloudScriptRequest
{
FunctionName = "SetPlayerStats",
FunctionParameter = new { statistics = statistics },
GeneratePlayStreamEvent = true
};
PlayFabClientAPI.ExecuteCloudScript(request, OnUpdateUserStatisticsSuccess, PF_Bridge.PlayFabErrorCallback);
}
private static void OnUpdateUserStatisticsSuccess(ExecuteCloudScriptResult result)
{
if (!PF_Bridge.VerifyErrorFreeCloudScriptResult(result))
return;
PF_Bridge.RaiseCallbackSuccess("User Statistics Uploaded", PlayFabAPIMethods.UpdateUserStatistics, MessageDisplayStyle.none);
GetCharacterStatistics(); // Refresh stats that we just updated
}
#endregion
#region User Account APIs
public static void GetUserAccountInfo()
{
var request = new GetPlayerCombinedInfoRequest
{
InfoRequestParameters = new GetPlayerCombinedInfoRequestParams { GetUserData = true, GetUserReadOnlyData = true, GetUserInventory = true, GetUserVirtualCurrency = true, GetUserAccountInfo = true, GetPlayerStatistics = true }
};
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.GetAccountInfo);
PlayFabClientAPI.GetPlayerCombinedInfo(request, OnGetUserAccountInfoSuccess, PF_Bridge.PlayFabErrorCallback);
}
private static void OnGetUserAccountInfoSuccess(GetPlayerCombinedInfoResult result)
{
playerInventory.Clear();
foreach (var eachItem in result.InfoResultPayload.UserInventory)
playerInventory.Add(eachItem);
accountInfo = result.InfoResultPayload.AccountInfo;
if (result.InfoResultPayload.UserData.ContainsKey("IsRegisteredForPush"))
isRegisteredForPush = result.InfoResultPayload.UserData["IsRegisteredForPush"].Value == "1";
else
isRegisteredForPush = false;
if (result.InfoResultPayload.UserData.ContainsKey("ShowAccountOptionsOnLogin") && result.InfoResultPayload.UserData["ShowAccountOptionsOnLogin"].Value == "0")
{
showAccountOptionsOnLogin = false;
}
else //if (PF_Authentication.hasLoggedInOnce == false)
{
//PF_Authentication.hasLoggedInOnce = true;
DialogCanvasController.RequestAccountSettings();
}
inventoryByCategory.Clear();
if (PF_GameData.catalogItems.Count > 0)
{
foreach (var item in playerInventory)
{
if (inventoryByCategory.ContainsKey(item.ItemId))
continue;
var catalogItem = PF_GameData.GetCatalogItemById(item.ItemId);
if (catalogItem == null)
continue;
var items = new List<ItemInstance>(playerInventory.FindAll((x) => { return x.ItemId.Equals(item.ItemId); }));
var customIcon = PF_GameData.GetIconByItemById(catalogItem.ItemId);
var icon = GameController.Instance.iconManager.GetIconById(customIcon, IconManager.IconTypes.Item);
inventoryByCategory.Add(item.ItemId, new InventoryCategory(item.ItemId, catalogItem, items, icon));
}
}
if (PF_Authentication.GetDeviceId(true))
{
Debug.Log("Mobile Device ID Found!");
var deviceId = string.IsNullOrEmpty(PF_Authentication.android_id) ? PF_Authentication.ios_id : PF_Authentication.android_id;
PlayerPrefs.SetString("LastDeviceIdUsed", deviceId);
}
else
{
Debug.Log("Custom Device ID Found!");
if (string.IsNullOrEmpty(PF_Authentication.custom_id))
PlayerPrefs.SetString("LastDeviceIdUsed", PF_Authentication.custom_id);
}
virtualCurrency.Clear();
foreach (var eachPair in result.InfoResultPayload.UserVirtualCurrency)
virtualCurrency.Add(eachPair.Key, eachPair.Value);
PF_Bridge.RaiseCallbackSuccess("Player Account Info Loaded", PlayFabAPIMethods.GetAccountInfo, MessageDisplayStyle.none);
}
#endregion
#region Character APIs
public static void GetCharacterData()
{
var JsonUtil = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer);
playerCharacterData.Clear();
characterAchievements.Clear();
var remainingCallbacks = playerCharacters.Count;
if (remainingCallbacks == 0)
{
PF_Bridge.RaiseCallbackSuccess("", PlayFabAPIMethods.GetCharacterReadOnlyData, MessageDisplayStyle.none);
return;
}
else
{
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.GetCharacterReadOnlyData);
}
foreach (var character in playerCharacters)
{
var request = new GetCharacterDataRequest
{
PlayFabId = PlayerId,
CharacterId = character.CharacterId,
Keys = new List<string> { "CharacterData", "Achievements" }
};
PlayFabClientAPI.GetCharacterReadOnlyData(request, (result) =>
{
if (result.Data.ContainsKey("Achievements"))
characterAchievements.Add(result.CharacterId, JsonUtil.DeserializeObject<List<string>>(result.Data["Achievements"].Value));
if (!result.Data.ContainsKey("CharacterData"))
return;
playerCharacterData.Add(result.CharacterId, JsonUtil.DeserializeObject<UB_CharacterData>(result.Data["CharacterData"].Value));
remainingCallbacks--;
if (remainingCallbacks == 0)
PF_Bridge.RaiseCallbackSuccess("", PlayFabAPIMethods.GetCharacterReadOnlyData, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
}
public static void GetCharacterDataById(string characterId)
{
var JsonUtil = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer);
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.GetCharacterReadOnlyData);
var request = new GetCharacterDataRequest
{
PlayFabId = PlayerId,
CharacterId = characterId,
Keys = new List<string> { "CharacterData" }
};
PlayFabClientAPI.GetCharacterReadOnlyData(request, result =>
{
if (result.Data.ContainsKey("CharacterData"))
{
playerCharacterData[result.CharacterId] = JsonUtil.DeserializeObject<UB_CharacterData>(result.Data["CharacterData"].Value);
PF_Bridge.RaiseCallbackSuccess("", PlayFabAPIMethods.GetCharacterReadOnlyData, MessageDisplayStyle.none);
}
}, PF_Bridge.PlayFabErrorCallback);
}
public static bool DoesCharacterHaveAchievement(string charId, string achvId)
{
List<string> achievements;
characterAchievements.TryGetValue(charId, out achievements);
if (achievements == null || achievements.Count == 0)
return false;
return achievements.Any(i => { return string.Equals(i, achvId); });
}
public static void GetCharacterStatistics()
{
foreach (var each in playerCharacters)
{
var request = new GetCharacterStatisticsRequest { CharacterId = each.CharacterId };
PlayFabClientAPI.GetCharacterStatistics(request, OnGetCharacterStatisticsSuccess, PF_Bridge.PlayFabErrorCallback);
}
}
private static void OnGetCharacterStatisticsSuccess(GetCharacterStatisticsResult result)
{
var characterId = ((GetCharacterStatisticsRequest)result.Request).CharacterId;
Dictionary<string, int> activeStats;
if (!characterStatistics.TryGetValue(characterId, out activeStats))
{
activeStats = new Dictionary<string, int>();
characterStatistics[characterId] = activeStats;
}
activeStats.Clear();
foreach (var statPair in result.CharacterStatistics)
activeStats.Add(statPair.Key, statPair.Value);
if (characterStatistics.Count == playerCharacters.Count)
PF_Bridge.RaiseCallbackSuccess("", PlayFabAPIMethods.GetCharacterStatistics, MessageDisplayStyle.none);
}
public static void UpdateCharacterStatistics(string characterId, Dictionary<string, int> updates)
{
Dictionary<string, int> activeStats;
if (!characterStatistics.TryGetValue(characterId, out activeStats))
return; ;
foreach (var each in updates)
{
int temp;
activeStats.TryGetValue(each.Key, out temp);
activeStats[each.Key] = temp + each.Value;
}
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.UpdateCharacterStatistics);
var request = new ExecuteCloudScriptRequest
{
FunctionName = "SetCharacterStats",
FunctionParameter = new { characterId = characterId, statistics = activeStats },
GeneratePlayStreamEvent = true
};
PlayFabClientAPI.ExecuteCloudScript(request, OnUpdateCharacterStatisticsSuccess, PF_Bridge.PlayFabErrorCallback);
}
private static void OnUpdateCharacterStatisticsSuccess(ExecuteCloudScriptResult result)
{
if (!PF_Bridge.VerifyErrorFreeCloudScriptResult(result))
return;
PF_Bridge.RaiseCallbackSuccess("", PlayFabAPIMethods.UpdateCharacterStatistics, MessageDisplayStyle.none);
}
public static void GetPlayerCharacters()
{
var request = new ListUsersCharactersRequest();
PlayFabClientAPI.GetAllUsersCharacters(request, OnGetPlayerCharactersSuccess, PF_Bridge.PlayFabErrorCallback);
}
private static void OnGetPlayerCharactersSuccess(ListUsersCharactersResult result)
{
playerCharacters.Clear();
foreach (var eachChar in result.Characters)
playerCharacters.Add(eachChar);
PF_Bridge.RaiseCallbackSuccess("Player Characters Retrieved", PlayFabAPIMethods.GetAllUsersCharacters, MessageDisplayStyle.none);
}
public static void CreateNewCharacter(string name, UB_ClassDetail details)
{
var request = new ExecuteCloudScriptRequest
{
FunctionName = "CreateCharacter",
FunctionParameter = new { catalogCode = details.CatalogCode, characterName = name }
};
PlayFabClientAPI.ExecuteCloudScript(request, OnCreateNewCharacterSuccess, PF_Bridge.PlayFabErrorCallback);
}
private static void OnCreateNewCharacterSuccess(ExecuteCloudScriptResult result)
{
if (!PF_Bridge.VerifyErrorFreeCloudScriptResult(result))
return;
if ((bool)result.FunctionResult)
PF_Bridge.RaiseCallbackSuccess("New Character Added", PlayFabAPIMethods.GrantCharacterToUser, MessageDisplayStyle.none);
else
PF_Bridge.RaiseCallbackError("Error Creating Character" + result.Logs.ToString(), PlayFabAPIMethods.GrantCharacterToUser, MessageDisplayStyle.error);
}
public static void DeleteCharacter(string cid)
{
var request = new ExecuteCloudScriptRequest
{
FunctionName = "DeleteCharacter",
FunctionParameter = new { characterId = cid }
};
PlayFabClientAPI.ExecuteCloudScript(request, OnDeleteCharacterSuccess, PF_Bridge.PlayFabErrorCallback);
}
private static void OnDeleteCharacterSuccess(ExecuteCloudScriptResult result)
{
if (!PF_Bridge.VerifyErrorFreeCloudScriptResult(result))
return;
if ((bool)result.FunctionResult)
PF_Bridge.RaiseCallbackSuccess("Character Deleted", PlayFabAPIMethods.DeleteCharacter, MessageDisplayStyle.none);
else
PF_Bridge.RaiseCallbackError("Error Deleting Character" + result.Logs.ToString(), PlayFabAPIMethods.DeleteCharacter, MessageDisplayStyle.none);
}
public static void UpdateActiveCharacterData()
{
var id = activeCharacter.characterDetails.CharacterId;
UB_CharacterData cData;
playerCharacterData.TryGetValue(id, out cData);
if (cData != null)
activeCharacter.characterData = cData;
activeCharacter.RefillVitals();
}
#endregion
#region Inventory Utilities
/// <summary>
/// Return number of RemainingUses of an stack of itemIds in your inventory
/// </summary>
/// <returns>
/// -1 => Item does not exist in the inventory
/// 0 => The item has infinite uses
/// else, the number of remaining uses
/// </returns>
public static int GetItemQty(string itemId)
{
var output = 0;
foreach (var eachItem in playerInventory)
{
if (eachItem.ItemId != itemId)
continue;
if (eachItem.RemainingUses == null)
return -1; // Unlimited uses
if (eachItem.RemainingUses.Value > 0) // Non-Positive is probably a PlayFab api error
output += eachItem.RemainingUses.Value;
}
return output;
}
#endregion Inventory Utilities
#region Friend APIs
public static void GetFriendsList(UnityAction callback = null)
{
var request = new GetFriendsListRequest
{
IncludeFacebookFriends = true,
IncludeSteamFriends = false
};
//DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.GetFriendList);
PlayFabClientAPI.GetFriendsList(request, result =>
{
playerFriends.Clear();
foreach (var eachFriend in result.Friends)
playerFriends.Add(eachFriend);
if (callback != null)
callback();
PF_Bridge.RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.GetFriendList, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
public enum AddFriendMethod { DisplayName, Email, Username, PlayFabID }
public static void AddFriend(string input, AddFriendMethod method, UnityAction<bool> callback = null)
{
var request = new AddFriendRequest();
switch (method)
{
case AddFriendMethod.DisplayName:
request.FriendTitleDisplayName = input; break;
case AddFriendMethod.Email:
request.FriendEmail = input; break;
case AddFriendMethod.Username:
request.FriendUsername = input; break;
case AddFriendMethod.PlayFabID:
request.FriendPlayFabId = input; break;
}
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.AddFriend);
PlayFabClientAPI.AddFriend(request, result =>
{
if (callback != null)
callback(result.Created);
PF_Bridge.RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.AddFriend, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
public static void RemoveFriend(string id, UnityAction callback = null)
{
var request = new RemoveFriendRequest { FriendPlayFabId = id };
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.RemoveFriend);
PlayFabClientAPI.RemoveFriend(request, result =>
{
if (callback != null)
callback();
PF_Bridge.RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.RemoveFriend, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
public static void SetFriendTags(string id, List<string> tags, UnityAction callback = null)
{
var request = new SetFriendTagsRequest
{
FriendPlayFabId = id,
Tags = tags
};
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.SetFriendTags);
PlayFabClientAPI.SetFriendTags(request, result =>
{
if (callback != null)
callback();
PF_Bridge.RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.SetFriendTags, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
#endregion
#region misc
public static void RedeemItemOffer(CatalogItem offer, string instanceToRemove, UnityAction<string> callback = null, bool onlyRemoveInstance = false)
{
if (onlyRemoveInstance)
{
// this offer has already been rewarded, need to remove from the player's invenetory.
var request = new ExecuteCloudScriptRequest();
request.FunctionName = "RemoveOfferItem";
request.FunctionParameter = new { PFID = PlayerId, InstanceToRemove = instanceToRemove };
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.ConsumeOffer);
PlayFabClientAPI.ExecuteCloudScript(request, result =>
{
if (!PF_Bridge.VerifyErrorFreeCloudScriptResult(result))
return;
if (callback != null)
callback(null);
PF_Bridge.RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.ConsumeOffer, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
else
{
// consume the item
var removeReq = new ExecuteCloudScriptRequest
{
FunctionName = "RemoveOfferItem",
FunctionParameter = new { PFID = PlayerId, InstanceToRemove = instanceToRemove }
};
PlayFabClientAPI.ExecuteCloudScript(removeReq, result =>
{
PF_Bridge.VerifyErrorFreeCloudScriptResult(result);
}, PF_Bridge.PlayFabErrorCallback);
// make the award
var awardRequest = new ExecuteCloudScriptRequest
{
FunctionName = "RedeemItemOffer",
FunctionParameter = new { PFID = PlayerId, Offer = offer, SingleUse = offer.Tags.IndexOf("SingleUse") > -1 ? true : false }
};
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.ConsumeOffer);
PlayFabClientAPI.ExecuteCloudScript(awardRequest, result =>
{
if (!PF_Bridge.VerifyErrorFreeCloudScriptResult(result))
return;
if (callback != null)
callback(result.FunctionResult.ToString());
PF_Bridge.RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.ConsumeOffer, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
}
public static void SubtractLifeFromPlayer()
{
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.ExecuteCloudScript);
var request = new ExecuteCloudScriptRequest
{
FunctionName = "SubtractLife",
FunctionParameter = new { CharacterId = activeCharacter.characterDetails.CharacterId }
};
PlayFabClientAPI.ExecuteCloudScript(request, result =>
{
if (!PF_Bridge.VerifyErrorFreeCloudScriptResult(result))
return;
PF_Bridge.RaiseCallbackSuccess("", PlayFabAPIMethods.ExecuteCloudScript, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
public static void ClearActiveCharacter()
{
activeCharacter = null;
if (characterAchievements != null) characterAchievements.Clear();
if (characterStatistics != null) characterStatistics.Clear();
}
public static void RegisterForPushNotification(string pushToken = null, UnityAction callback = null)
{
#if UNITY_EDITOR || UNITY_EDITOR_OSX
if (callback != null)
{
callback();
return;
}
#endif
#if UNITY_IPHONE
string hexToken = string.Empty;
byte[] token = UnityEngine.iOS.NotificationServices.deviceToken;
if(token != null)
{
RegisterForIOSPushNotificationRequest request = new RegisterForIOSPushNotificationRequest();
request.DeviceToken = BitConverter.ToString(token).Replace("-", "").ToLower();
hexToken = request.DeviceToken;
Debug.Log (hexToken);
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.RegisterForPush);
PlayFabClientAPI.RegisterForIOSPushNotification(request, result =>
{
if(callback != null)
{
callback();
}
PF_Bridge.RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.RegisterForPush, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
else
{
Debug.Log("Push Token was null!");
}
#endif
#if UNITY_ANDROID
if (!string.IsNullOrEmpty(pushToken))
{
Debug.Log("GCM Init Success");
var request = new AndroidDevicePushNotificationRegistrationRequest { DeviceToken = pushToken };
DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.RegisterForPush);
PlayFabClientAPI.AndroidDevicePushNotificationRegistration(request, result =>
{
if (callback != null)
callback();
PF_Bridge.RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.RegisterForPush, MessageDisplayStyle.none);
}, PF_Bridge.PlayFabErrorCallback);
}
else
{
Debug.Log("Push Token was null or empty: ");
}
#endif
}
#endregion
}
| |
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Stratus
{
namespace AI
{
/// <summary>
/// A plan is a sequence of actions that will fulfill a specified goal world state,
/// given a starting world state.
/// </summary>
public partial class Plan
{
//------------------------------------------------------------------------/
// Declarations
//------------------------------------------------------------------------/
public class FormulatedEvent : Stratus.StratusEvent
{
public Plan Plan;
public FormulatedEvent(Plan plan) { Plan = plan; }
}
public class ExecutedEvent : Stratus.StratusEvent { }
//------------------------------------------------------------------------/
// Properties
//------------------------------------------------------------------------/
/// <summary>
/// A sequence of actions, where each action represents a state transition.
/// </summary>
public LinkedList<StatefulAction> Actions = new LinkedList<StatefulAction>();
/// <summary>
/// Whether this plan has finished running
/// </summary>
public bool IsFinished { get { return Actions.Count == 0; } }
/// <summary>
/// Whether A* should be used to formulate the plan
/// </summary>
static bool UseAstar = true;
//------------------------------------------------------------------------/
// Methods
//------------------------------------------------------------------------/
/// <summary>
/// Gets the next action in the sequence.
/// </summary>
/// <returns></returns>
public StatefulAction Next()
{
var action = Actions.First();
Actions.RemoveFirst();
return action;
}
/// <summary>
/// Adds an action to the plan
/// </summary>
/// <param name="action"></param>
public void Add(StatefulAction action)
{
Actions.AddLast(action);
}
/// <summary>
/// Given a goal, formulates a plan.
/// </summary>
/// <param name="goal"></param>
/// <returns></returns>
public static Plan Formulate(Planner planner, StatefulAction[] actions, StratusWorldState currentState, StratusGoal goal)
{
// Reset all actions
foreach (var action in actions)
action.Reset();
// Get all valid actions whose context preconditions are true
var usableActions = (from action
in actions
where action.contextPrecondition && !currentState.Satisfies(action.effects)
select action).ToArray();
if (planner.debug)
{
StratusDebug.Log("Making plan to satisfy the goal '" + goal.Name + "' with preconditions:" + goal.DesiredState.ToString(), planner.agent);
StratusDebug.Log("Actions available:", planner.agent);
foreach (var action in usableActions)
StratusDebug.Log("- " + action.description, planner.agent);
}
// The path of actions
Search.Path path;
if (Plan.UseAstar)
{
Search search = new Search(currentState, goal.DesiredState, usableActions);
search.Tracing = planner.debug;
search.Initialize();
path = search.FindSolution();
}
else
{
// Build up a tree of nodes
path = new Search.Path();
Search.Node starting = new Search.Node(null, 0f, goal.DesiredState, null);
// Look for a solution, backtracking from the goal's desired world state until
// we have fulfilled every precondition leading up to it!
var hasFoundPath = FindSolution(path, starting, usableActions, planner);
// If the path has not been found
if (!hasFoundPath)
{
if (planner.debug) StratusDebug.Log("No plan could be formulated!", planner.agent);
return new Plan();
}
}
// If no solution was found
if (path == null)
return null;
// Make the plan
var plan = new Plan();
foreach (var action in path)
plan.Add(action);
return plan;
}
/// <summary>
/// Looks for a solution, backtracking from the goal to the current world state
/// </summary>
/// <param name="parent"></param>
/// <param name="actions"></param>
/// <param name="goal"></param>
/// <param name="currentState"></param>
/// <returns></returns>
static bool FindSolution(Search.Path path, Search.Node parent, StatefulAction[] actions, Planner planner)
{
bool solutionFound = false;
Search.Node cheapestNode = null;
if (planner.debug) StratusDebug.Log("Looking to fulfill the preconditions:" + parent.State.ToString());
// Look for actions that fulfill the preconditions
foreach (var action in actions)
{
if (action.effects.Satisfies(parent.State))
{
if (planner.debug) StratusDebug.Log(action.description + " satisfies the preconditions");
// Create a new node
var node = new Search.Node(parent, parent.Cost + action.cost, action.preconditions, action);
// Replace the previous best node
if (cheapestNode == null) cheapestNode = node;
else if (cheapestNode.Cost > node.Cost) cheapestNode = node;
}
else
{
if (planner.debug) StratusDebug.Log(action.description + " does not satisfy the preconditions");
}
}
// If no satisfactory action was found
if (cheapestNode == null)
{
// If the current state is already fulfilling this condition, we are done!
if (planner.state.Satisfies(parent.State)) return true;
// Otherwise, no valid solution could be found
if (planner.debug) StratusDebug.Log("No actions could fulfill these preconditions");
return false;
}
// Add the cheapest node to the path
path.Add(cheapestNode.Action);
if (planner.debug) StratusDebug.Log("Adding " + cheapestNode.Action.description + " to the path");
// If this action has no more preconditions left to fulfill
if (cheapestNode.Action.preconditions.isEmpty)
{
//Trace.Script("No preconditions left!");
solutionFound = true;
}
// Else if it has a precondition left to fulfill, keep looking
else
{
var actionSubset = (from remainingAction in actions where !remainingAction.Equals(cheapestNode.Action) select remainingAction).ToArray();
bool found = FindSolution(path, cheapestNode, actionSubset, planner);
if (found) solutionFound = true;
}
return solutionFound;
}
/// <summary>
/// Plans all the actions in this plan.
/// </summary>
/// <returns></returns>
public string Print()
{
var builder = new StringBuilder();
foreach (var action in Actions)
{
builder.AppendLine("- " + action.description + " (" + action.cost + ")");
}
return builder.ToString();
}
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
namespace System
{
/// <summary>Provides extension methods in the System namespace for working with the Windows Runtime.<br />
/// Currently contains:<br />
/// <ul>
/// <li>Extension methods for conversion between <code>Windows.Foundation.IAsyncInfo</code> and deriving generic interfaces
/// and <code>System.Threading.Tasks.Task</code>.</li>
/// <li>Extension methods for conversion between <code>System.Threading.Tasks.Task</code>
/// and <code>Windows.Foundation.IAsyncInfo</code> and deriving generic interfaces.</li>
/// </ul></summary>
[CLSCompliant(false)]
public static class WindowsRuntimeSystemExtensions
{
#region Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task
#region Convenience Helpers
private static void ConcatenateCancelTokens(CancellationToken source, CancellationTokenSource sink, Task concatenationLifetime)
{
Contract.Requires(sink != null);
CancellationTokenRegistration ctReg = source.Register((state) => { ((CancellationTokenSource)state).Cancel(); },
sink);
concatenationLifetime.ContinueWith((_, state) => { ((CancellationTokenRegistration)state).Dispose(); },
ctReg, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
private static void ConcatenateProgress<TProgress>(IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> sink)
{
// This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null.
source.Progress += new AsyncActionProgressHandler<TProgress>((_, info) => sink.Report(info));
}
private static void ConcatenateProgress<TResult, TProgress>(IAsyncOperationWithProgress<TResult, TProgress> source, IProgress<TProgress> sink)
{
// This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null.
source.Progress += new AsyncOperationProgressHandler<TResult, TProgress>((_, info) => sink.Report(info));
}
#endregion Convenience Helpers
#region Converters from IAsyncAction to Task
/// <summary>Gets an awaiter used to await this asynchronous operation.</summary>
/// <returns>An awaiter instance.</returns>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static TaskAwaiter GetAwaiter(this IAsyncAction source)
{
return AsTask(source).GetAwaiter();
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask(this IAsyncAction source)
{
return AsTask(source, CancellationToken.None);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask(this IAsyncAction source, CancellationToken cancellationToken)
{
if (source == null)
throw new ArgumentNullException("source");
Contract.EndContractBlock();
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncActionAdapter;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
Task innerTask = wrapper.Task;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created);
if (!innerTask.IsCompleted)
{
// The race here is benign: If the task completes here, the concatination is useless, but not damaging.
if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
}
return innerTask;
}
// Fast path to return a completed Task if the operation has already completed:
switch (source.Status)
{
case AsyncStatus.Completed:
return Task.CompletedTask;
case AsyncStatus.Error:
return Task.FromException(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode));
case AsyncStatus.Canceled:
return Task.FromCancellation(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
// Benign race: source may complete here. Things still work, just not taking the fast path.
// Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
var bridge = new AsyncInfoToTaskBridge<VoidValueTypeParameter, VoidValueTypeParameter>(cancellationToken);
source.Completed = new AsyncActionCompletedHandler(bridge.CompleteFromAsyncAction);
bridge.RegisterForCancellation(source);
return bridge.Task;
}
#endregion Converters from IAsyncAction to Task
#region Converters from IAsyncOperation<TResult> to Task
/// <summary>Gets an awaiter used to await this asynchronous operation.</summary>
/// <returns>An awaiter instance.</returns>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static TaskAwaiter<TResult> GetAwaiter<TResult>(this IAsyncOperation<TResult> source)
{
return AsTask(source).GetAwaiter();
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source)
{
return AsTask(source, CancellationToken.None);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source, CancellationToken cancellationToken)
{
if (source == null)
throw new ArgumentNullException("source");
Contract.EndContractBlock();
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncOperationAdapter<TResult>;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
Task<TResult> innerTask = wrapper.Task as Task<TResult>;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment?
if (!innerTask.IsCompleted)
{
// The race here is benign: If the task completes here, the concatination is useless, but not damaging.
if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
}
return innerTask;
}
// Fast path to return a completed Task if the operation has already completed
switch (source.Status)
{
case AsyncStatus.Completed:
return Task.FromResult(source.GetResults());
case AsyncStatus.Error:
return Task.FromException<TResult>(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode));
case AsyncStatus.Canceled:
return Task.FromCancellation<TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
// Benign race: source may complete here. Things still work, just not taking the fast path.
// Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
var bridge = new AsyncInfoToTaskBridge<TResult, VoidValueTypeParameter>(cancellationToken);
source.Completed = new AsyncOperationCompletedHandler<TResult>(bridge.CompleteFromAsyncOperation);
bridge.RegisterForCancellation(source);
return bridge.Task;
}
#endregion Converters from IAsyncOperation<TResult> to Task
#region Converters from IAsyncActionWithProgress<TProgress> to Task
/// <summary>Gets an awaiter used to await this asynchronous operation.</summary>
/// <returns>An awaiter instance.</returns>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static TaskAwaiter GetAwaiter<TProgress>(this IAsyncActionWithProgress<TProgress> source)
{
return AsTask(source).GetAwaiter();
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source)
{
return AsTask(source, CancellationToken.None, null);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, CancellationToken cancellationToken)
{
return AsTask(source, cancellationToken, null);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> progress)
{
return AsTask(source, CancellationToken.None, progress);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source,
CancellationToken cancellationToken, IProgress<TProgress> progress)
{
if (source == null)
throw new ArgumentNullException("source");
Contract.EndContractBlock();
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncActionWithProgressAdapter<TProgress>;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
Task innerTask = wrapper.Task;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment?
if (!innerTask.IsCompleted)
{
// The race here is benign: If the task completes here, the concatinations are useless, but not damaging.
if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
if (progress != null)
ConcatenateProgress(source, progress);
}
return innerTask;
}
// Fast path to return a completed Task if the operation has already completed:
switch (source.Status)
{
case AsyncStatus.Completed:
return Task.CompletedTask;
case AsyncStatus.Error:
return Task.FromException(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode));
case AsyncStatus.Canceled:
return Task.FromCancellation(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
// Benign race: source may complete here. Things still work, just not taking the fast path.
// Forward progress reports:
if (progress != null)
ConcatenateProgress(source, progress);
// Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
var bridge = new AsyncInfoToTaskBridge<VoidValueTypeParameter, TProgress>(cancellationToken);
source.Completed = new AsyncActionWithProgressCompletedHandler<TProgress>(bridge.CompleteFromAsyncActionWithProgress);
bridge.RegisterForCancellation(source);
return bridge.Task;
}
#endregion Converters from IAsyncActionWithProgress<TProgress> to Task
#region Converters from IAsyncOperationWithProgress<TResult,TProgress> to Task
/// <summary>Gets an awaiter used to await this asynchronous operation.</summary>
/// <returns>An awaiter instance.</returns>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static TaskAwaiter<TResult> GetAwaiter<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source)
{
return AsTask(source).GetAwaiter();
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <returns>The Task representing the started asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source)
{
return AsTask(source, CancellationToken.None, null);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
CancellationToken cancellationToken)
{
return AsTask(source, cancellationToken, null);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
IProgress<TProgress> progress)
{
return AsTask(source, CancellationToken.None, progress);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
CancellationToken cancellationToken, IProgress<TProgress> progress)
{
if (source == null)
throw new ArgumentNullException("source");
Contract.EndContractBlock();
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
Task<TResult> innerTask = wrapper.Task as Task<TResult>;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment?
if (!innerTask.IsCompleted)
{
// The race here is benign: If the task completes here, the concatinations are useless, but not damaging.
if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
if (progress != null)
ConcatenateProgress(source, progress);
}
return innerTask;
}
// Fast path to return a completed Task if the operation has already completed
switch (source.Status)
{
case AsyncStatus.Completed:
return Task.FromResult(source.GetResults());
case AsyncStatus.Error:
return Task.FromException<TResult>(RestrictedErrorInfoHelper.AttachRestrictedErrorInfo(source.ErrorCode));
case AsyncStatus.Canceled:
return Task.FromCancellation<TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
// Benign race: source may complete here. Things still work, just not taking the fast path.
// Forward progress reports:
if (progress != null)
ConcatenateProgress(source, progress);
// Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
var bridge = new AsyncInfoToTaskBridge<TResult, TProgress>(cancellationToken);
source.Completed = new AsyncOperationWithProgressCompletedHandler<TResult, TProgress>(bridge.CompleteFromAsyncOperationWithProgress);
bridge.RegisterForCancellation(source);
return bridge.Task;
}
#endregion Converters from IAsyncOperationWithProgress<TResult,TProgress> to Task
#endregion Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task
#region Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it)
public static IAsyncAction AsAsyncAction(this Task source)
{
if (source == null)
throw new ArgumentNullException("source");
Contract.EndContractBlock();
return new TaskToAsyncActionAdapter(source, underlyingCancelTokenSource: null);
}
public static IAsyncOperation<TResult> AsAsyncOperation<TResult>(this Task<TResult> source)
{
if (source == null)
throw new ArgumentNullException("source");
Contract.EndContractBlock();
return new TaskToAsyncOperationAdapter<TResult>(source, underlyingCancelTokenSource: null);
}
#endregion Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it)
private static void CommonlyUsedGenericInstantiations()
{
// This method is an aid for NGen to save common generic
// instantiations into the ngen image.
((IAsyncOperation<bool>)null).AsTask();
((IAsyncOperation<string>)null).AsTask();
((IAsyncOperation<object>)null).AsTask();
((IAsyncOperation<uint>)null).AsTask();
((IAsyncOperationWithProgress<uint, uint>)null).AsTask();
((IAsyncOperationWithProgress<ulong, ulong>)null).AsTask();
((IAsyncOperationWithProgress<string, ulong>)null).AsTask();
}
} // class WindowsRuntimeSystemExtensions
} // namespace
// WindowsRuntimeExtensions.cs
| |
// 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;
namespace JitTest
{
internal class Test
{
private static void testNumbers(ulong a, ulong b)
{
ulong c = 0;
try
{
c = checked(a + b);
if (c < a || c < b)
throw new Exception();
}
catch (OverflowException)
{
ulong AH = a >> 32;
ulong AL = a & 0xffffffff;
ulong BH = b >> 32;
ulong BL = b & 0xffffffff;
ulong L = checked(BL + AL);
ulong H = checked(AH + BH);
if (H < 0x100000000)
{
if (L >= 0x100000000)
{
checked
{
H++;
L -= 0x100000000;
if (L >= 0x100000000)
throw new Exception();
}
}
if (checked(L <= 0xffffffffffffffff - (H << 32)))
throw new Exception();
}
return;
}
if (checked(c - b != a || c - a != b))
throw new Exception();
}
private static int Main()
{
try
{
testNumbers(0x0000000000000009, 0x00000000000000b8);
testNumbers(0x0000000000000009, 0x00000000000000f9);
testNumbers(0x000000000000006e, 0x0000000000000093);
testNumbers(0x000000000000001e, 0x0000000000000086);
testNumbers(0x00000000000000cc, 0x000000000000583f);
testNumbers(0x00000000000000c9, 0x000000000000a94c);
testNumbers(0x0000000000000054, 0x0000000000002d06);
testNumbers(0x0000000000000030, 0x0000000000009921);
testNumbers(0x000000000000001d, 0x0000000000450842);
testNumbers(0x000000000000002a, 0x0000000000999f6c);
testNumbers(0x00000000000000c5, 0x000000000090faa7);
testNumbers(0x0000000000000050, 0x000000000069de08);
testNumbers(0x000000000000009a, 0x000000000cd715be);
testNumbers(0x0000000000000039, 0x0000000016a61eb5);
testNumbers(0x00000000000000e0, 0x0000000095575fef);
testNumbers(0x0000000000000093, 0x00000000209e58c5);
testNumbers(0x000000000000003b, 0x0000000c3c34b48c);
testNumbers(0x00000000000000c2, 0x0000006a671c470f);
testNumbers(0x000000000000004b, 0x000000f538cede2b);
testNumbers(0x0000000000000099, 0x0000005ba885d43b);
testNumbers(0x0000000000000068, 0x00009f692f98ac45);
testNumbers(0x00000000000000d9, 0x00008d5eaa7f0a8e);
testNumbers(0x00000000000000ac, 0x0000ba1316512e4c);
testNumbers(0x000000000000001c, 0x00008c4fbf2f14aa);
testNumbers(0x00000000000000c0, 0x0069a9eb9a9bc822);
testNumbers(0x0000000000000074, 0x003f8f5a893de200);
testNumbers(0x0000000000000027, 0x000650eb1747a5bc);
testNumbers(0x00000000000000d9, 0x00d3d50809c70fda);
testNumbers(0x00000000000000c0, 0xac6556a4ca94513e);
testNumbers(0x0000000000000020, 0xa697fcbfd6d232d1);
testNumbers(0x000000000000009c, 0xc4421a4f5147b9b8);
testNumbers(0x000000000000009e, 0xc5ef494112a7b33f);
testNumbers(0x000000000000f7fa, 0x00000000000000af);
testNumbers(0x000000000000ad17, 0x00000000000000e8);
testNumbers(0x000000000000c9c4, 0x0000000000000045);
testNumbers(0x000000000000a704, 0x0000000000000012);
testNumbers(0x000000000000c55b, 0x000000000000a33a);
testNumbers(0x000000000000ab88, 0x0000000000009a3c);
testNumbers(0x000000000000a539, 0x000000000000cf3a);
testNumbers(0x0000000000005890, 0x000000000000eec8);
testNumbers(0x000000000000e9e2, 0x0000000000fe7c46);
testNumbers(0x0000000000007303, 0x0000000000419f2a);
testNumbers(0x000000000000e105, 0x000000000013f913);
testNumbers(0x0000000000008191, 0x0000000000fa2458);
testNumbers(0x00000000000006d9, 0x0000000091cf14f7);
testNumbers(0x000000000000bdb1, 0x0000000086c2a97c);
testNumbers(0x000000000000e905, 0x0000000064f702f4);
testNumbers(0x0000000000002fdc, 0x00000000f059caf6);
testNumbers(0x000000000000f8fd, 0x00000013f0265b1e);
testNumbers(0x000000000000e8b8, 0x0000000aa69a6308);
testNumbers(0x0000000000003d00, 0x000000fbcb67879b);
testNumbers(0x000000000000aa46, 0x00000085c3d371d5);
testNumbers(0x0000000000005f60, 0x000008cde4a63203);
testNumbers(0x00000000000092b5, 0x00007ca86ba2f30e);
testNumbers(0x00000000000093c6, 0x0000a2d73fc4eac0);
testNumbers(0x0000000000004156, 0x000006dbd08f2fda);
testNumbers(0x0000000000004597, 0x006cfb0ba5962826);
testNumbers(0x0000000000006bac, 0x001e79315071480f);
testNumbers(0x0000000000002c3a, 0x0092f12cbd82df69);
testNumbers(0x0000000000009859, 0x00b0f0cd9dc019f2);
testNumbers(0x000000000000b37f, 0x4966447d15850076);
testNumbers(0x0000000000005e34, 0x7c1869c9ed2cad38);
testNumbers(0x0000000000005c54, 0x7cee70ee82837a08);
testNumbers(0x000000000000967f, 0x4eb98adf4b8b0d32);
testNumbers(0x0000000000fd2919, 0x000000000000005d);
testNumbers(0x0000000000abd5b1, 0x0000000000000098);
testNumbers(0x0000000000ab1887, 0x00000000000000ef);
testNumbers(0x000000000096034a, 0x000000000000002f);
testNumbers(0x0000000000d5bb94, 0x00000000000057d2);
testNumbers(0x0000000000d7b2cb, 0x00000000000080f5);
testNumbers(0x00000000004ccc6d, 0x000000000000087c);
testNumbers(0x0000000000ec0c50, 0x000000000000bdff);
testNumbers(0x00000000008a6865, 0x000000000076c014);
testNumbers(0x0000000000ac38dd, 0x0000000000f12b09);
testNumbers(0x0000000000615e2a, 0x0000000000e7cbf8);
testNumbers(0x00000000000e214f, 0x00000000005b8e2f);
testNumbers(0x00000000003bd7c6, 0x00000000c1db4e46);
testNumbers(0x0000000000ae208d, 0x0000000001c9aa7a);
testNumbers(0x00000000008a9cef, 0x0000000003930b07);
testNumbers(0x000000000036b866, 0x00000000d64b7bef);
testNumbers(0x0000000000d337cd, 0x000000a2b45fb7de);
testNumbers(0x0000000000024471, 0x0000005c5de3da89);
testNumbers(0x0000000000012b15, 0x0000007cd40030fe);
testNumbers(0x0000000000d38af2, 0x0000005905921572);
testNumbers(0x0000000000aca0d7, 0x0000c632301abeb8);
testNumbers(0x00000000004eadc2, 0x00006a1ebf37403c);
testNumbers(0x00000000005d909c, 0x00004021bfa15862);
testNumbers(0x0000000000710e08, 0x0000e9a1a030b230);
testNumbers(0x0000000000478b9b, 0x00804add8afc31d9);
testNumbers(0x00000000005754ed, 0x00af85e7ebb1ce33);
testNumbers(0x00000000003ab44e, 0x00f41b9f70360f78);
testNumbers(0x00000000007aa129, 0x00eb6e4eddf7eb87);
testNumbers(0x00000000003b036f, 0x333874e4330fbfa4);
testNumbers(0x0000000000a33186, 0xec8607412503fc4c);
testNumbers(0x00000000009af471, 0xe7ad0935fdbff151);
testNumbers(0x0000000000c04e8c, 0x58ee406ab936ac24);
testNumbers(0x0000000054fdd28b, 0x0000000000000034);
testNumbers(0x0000000033736b36, 0x00000000000000fd);
testNumbers(0x0000000069cfe4b7, 0x0000000000000026);
testNumbers(0x00000000fd078d36, 0x00000000000000dc);
testNumbers(0x0000000075cc3f36, 0x0000000000001617);
testNumbers(0x00000000075d660e, 0x0000000000008511);
testNumbers(0x0000000052acb037, 0x00000000000043cb);
testNumbers(0x00000000a0db7bf5, 0x0000000000002c98);
testNumbers(0x0000000083d4be11, 0x0000000000ba37c9);
testNumbers(0x0000000083d04f94, 0x00000000003ddbd0);
testNumbers(0x000000005ed41f6a, 0x0000000000eaf1d5);
testNumbers(0x000000000e364a9a, 0x000000000085880c);
testNumbers(0x0000000012657ecb, 0x00000000a88b8a68);
testNumbers(0x000000009897a4ac, 0x0000000076707981);
testNumbers(0x00000000469cd1cf, 0x00000000cf40f67a);
testNumbers(0x00000000ee7444c8, 0x00000000d1b0d7de);
testNumbers(0x00000000fbb6f547, 0x000000c1ef3c4d9b);
testNumbers(0x000000000e20dd53, 0x000000b05833c7cf);
testNumbers(0x00000000e5733fb8, 0x0000008eae18a855);
testNumbers(0x000000005db1c271, 0x000000c4a2f7c27d);
testNumbers(0x0000000007add22a, 0x00000ed9fd23dc3e);
testNumbers(0x000000002239d1d5, 0x0000a1ae07a62635);
testNumbers(0x00000000410d4d58, 0x0000c05c5205bed2);
testNumbers(0x000000004c3c435e, 0x00001e30c1bf628a);
testNumbers(0x00000000096f44d5, 0x005488c521a6072b);
testNumbers(0x0000000017f28913, 0x00796ff3891c44ff);
testNumbers(0x0000000065be69cf, 0x00dd5c6f9b3f3119);
testNumbers(0x000000002200f221, 0x00ab6c98c90cfe9d);
testNumbers(0x00000000d48bee1a, 0x64b76d7491a58799);
testNumbers(0x000000006cb93100, 0xa515fe27402dad45);
testNumbers(0x00000000bed95abe, 0xc9924098acc74be9);
testNumbers(0x0000000092781a2e, 0x67ada9ef3f9e39b7);
testNumbers(0x000000e3aafcdae2, 0x000000000000009c);
testNumbers(0x000000d8dad80c34, 0x0000000000000099);
testNumbers(0x000000addcd074d6, 0x00000000000000ea);
testNumbers(0x00000096735bc25a, 0x00000000000000ba);
testNumbers(0x000000f492ef7446, 0x00000000000039b1);
testNumbers(0x000000bc86816119, 0x0000000000001520);
testNumbers(0x00000060a36818e7, 0x000000000000c5a8);
testNumbers(0x000000317121d508, 0x000000000000ac3d);
testNumbers(0x0000004abfdaf232, 0x00000000005cea57);
testNumbers(0x000000acc458f392, 0x0000000000a9c3e3);
testNumbers(0x0000001020993532, 0x0000000000df6042);
testNumbers(0x000000ad25b80abb, 0x0000000000cec15b);
testNumbers(0x0000002305d2c443, 0x000000002a26131c);
testNumbers(0x00000007c42e2ce0, 0x000000009768024f);
testNumbers(0x00000076f674816c, 0x000000008d33c7b4);
testNumbers(0x000000bf567b23bc, 0x00000000ef264890);
testNumbers(0x000000e3283681a0, 0x0000002e66850719);
testNumbers(0x000000011fe13754, 0x00000066fad0b407);
testNumbers(0x00000052f259009f, 0x000000a2886ef414);
testNumbers(0x000000a9ebb540fc, 0x0000009d27ba694f);
testNumbers(0x00000083af60d7eb, 0x0000b6f2a0f51f4c);
testNumbers(0x000000f2ec42d13a, 0x000046855f279407);
testNumbers(0x00000094e71cb562, 0x00002d9566618e56);
testNumbers(0x000000c0ee690ddc, 0x000054295c8ca584);
testNumbers(0x0000002683cd5206, 0x00a5a2d269bcd188);
testNumbers(0x0000002e77038305, 0x00c727f0f3787e22);
testNumbers(0x0000008323b9d026, 0x00fed29f8575c120);
testNumbers(0x0000007b3231f0fc, 0x0091080854b27d3e);
testNumbers(0x00000084522a7708, 0x91ba8f22fccd6222);
testNumbers(0x000000afb1b50d90, 0x3261a532b65c7838);
testNumbers(0x0000002c65e838c6, 0x5b858452c9bf6f39);
testNumbers(0x000000219e837734, 0x97873bed5bb0a44b);
testNumbers(0x00009f133e2f116f, 0x0000000000000073);
testNumbers(0x0000887577574766, 0x0000000000000048);
testNumbers(0x0000ba4c778d4aa8, 0x000000000000003a);
testNumbers(0x00002683df421474, 0x0000000000000056);
testNumbers(0x00006ff76294c275, 0x00000000000089f7);
testNumbers(0x0000fdf053abefa2, 0x000000000000eb65);
testNumbers(0x0000ea4b254b24eb, 0x000000000000ba27);
testNumbers(0x000009f7ce21b811, 0x000000000000e8f6);
testNumbers(0x00009cc645fa08a1, 0x0000000000a29ea3);
testNumbers(0x0000726f9a9f816e, 0x000000000070dce1);
testNumbers(0x0000a4be34825ef6, 0x0000000000bb2be7);
testNumbers(0x000057ff147cb7c1, 0x0000000000e255af);
testNumbers(0x0000ab9d6f546dd4, 0x000000007e2772a5);
testNumbers(0x0000b148e3446e89, 0x0000000051ed3c28);
testNumbers(0x00001e3abfe9725e, 0x00000000d4dec3f4);
testNumbers(0x0000f61bcaba115e, 0x00000000fade149f);
testNumbers(0x0000ae642b9a6626, 0x000000d8de0e0b9a);
testNumbers(0x00009d015a13c8ae, 0x000000afc8827997);
testNumbers(0x0000ecc72cc2df89, 0x00000070d47ec7c4);
testNumbers(0x0000fdbf05894fd2, 0x00000012aec393bd);
testNumbers(0x0000cd7675a70874, 0x0000d7d696a62cbc);
testNumbers(0x0000fad44a89216d, 0x0000cb8cfc8ada4c);
testNumbers(0x0000f41eb5363551, 0x00009c040aa7775e);
testNumbers(0x00003c02d93e01f6, 0x0000f1f4e68a14f8);
testNumbers(0x0000e0d99954b598, 0x00b2a2de4e453485);
testNumbers(0x0000a6081be866d9, 0x00f2a12e845e4f2e);
testNumbers(0x0000ae56a5680dfd, 0x00c96cd7c15d5bec);
testNumbers(0x0000360363e37938, 0x00d4ed572e1937e0);
testNumbers(0x00001f052aebf185, 0x3584e582d1c6db1a);
testNumbers(0x00003fac9c7b3d1b, 0xa4b120f080d69113);
testNumbers(0x00005330d51c3217, 0xc16dd32ffd822c0e);
testNumbers(0x0000cd0694ff5ab0, 0x29673fe67245fbfc);
testNumbers(0x0098265e5a308523, 0x000000000000007d);
testNumbers(0x00560863350df217, 0x00000000000000c8);
testNumbers(0x00798ce804d829a1, 0x00000000000000b1);
testNumbers(0x007994c0051256fd, 0x000000000000005c);
testNumbers(0x00ff1a2838e69f42, 0x0000000000003c16);
testNumbers(0x009e7e95ac5de2c7, 0x000000000000ed49);
testNumbers(0x00fd6867eabba5c0, 0x000000000000c689);
testNumbers(0x009d1632daf20de0, 0x000000000000b74f);
testNumbers(0x00ee29d8f76d4e9c, 0x00000000008020d4);
testNumbers(0x0089e03ecf8daa0a, 0x00000000003e7587);
testNumbers(0x00115763be4beb44, 0x000000000088f762);
testNumbers(0x00815cfc87c427d0, 0x00000000009eec06);
testNumbers(0x001d9c3c9ded0c1a, 0x00000000b9f6d331);
testNumbers(0x00932225412f1222, 0x00000000130ff743);
testNumbers(0x00fe82151e2e0bf3, 0x00000000781cd6f9);
testNumbers(0x002222abb5061b12, 0x000000000491f1df);
testNumbers(0x0012ce0cf0452748, 0x000000a8566274aa);
testNumbers(0x00e570484e9937e1, 0x000000ac81f171be);
testNumbers(0x00eb371f7f8f514e, 0x000000df0248189c);
testNumbers(0x003777a7cc43dfd7, 0x0000003a7b8eaf40);
testNumbers(0x00e181db76238786, 0x00004126e572a568);
testNumbers(0x00ac1df87977e122, 0x0000e1e8cfde6678);
testNumbers(0x001c858763a2c23b, 0x000004ef61f3964f);
testNumbers(0x00bd786bbb71ce46, 0x00002cda097a464f);
testNumbers(0x00a7a6de21a46360, 0x00007afda16f98c3);
testNumbers(0x006fed70a6ccfdf2, 0x009771441e8e00e8);
testNumbers(0x005ad2782dcd5e60, 0x000d170d518385f6);
testNumbers(0x001fd67b153bc9b9, 0x007b3366dff66c6c);
testNumbers(0x00bf00203beb73f4, 0x693495fefab1c77e);
testNumbers(0x002faac1b1b068f8, 0x1cb11cc5c3aaff86);
testNumbers(0x00bb63cfbffe7648, 0x84f5b0c583f9e77b);
testNumbers(0x00615db89673241c, 0x8de5f125247eba0f);
testNumbers(0x9be183a6b293dffe, 0x0000000000000072);
testNumbers(0xa3df9b76d8a51b19, 0x00000000000000c4);
testNumbers(0xb4cc300f0ea7566d, 0x000000000000007e);
testNumbers(0xfdac12a8e23e16e7, 0x0000000000000015);
testNumbers(0xc0805405aadc0f47, 0x00000000000019d4);
testNumbers(0x843a391f8d9f8972, 0x000000000000317a);
testNumbers(0x5a0d124c427ed453, 0x00000000000034fe);
testNumbers(0x8631150f34008f1b, 0x0000000000002ecd);
testNumbers(0x3ff4c18715ad3a76, 0x000000000072d22a);
testNumbers(0x3ef93e5a649422bd, 0x0000000000db5c60);
testNumbers(0x6bdd1056ae58fe0e, 0x0000000000805c75);
testNumbers(0xeff1fa30f3ad9ded, 0x00000000000c83ca);
testNumbers(0xbbc143ac147e56a9, 0x00000000161179b7);
testNumbers(0x0829dde88caa2e45, 0x000000001443ab62);
testNumbers(0x97ac43ff797a4514, 0x0000000033eef42b);
testNumbers(0x703e9cdf96a148aa, 0x000000008e08f3d8);
testNumbers(0x75cbb739b54e2ad6, 0x0000007a8b12628c);
testNumbers(0x91e42fafe97d638f, 0x0000000fbe867c51);
testNumbers(0x9159d77deec116c1, 0x00000096c0c774fc);
testNumbers(0xb59dbb4c15761d88, 0x0000004a033a73e7);
testNumbers(0xab668e9783af9617, 0x00005aa18404076c);
testNumbers(0x54c68e5b5c4127df, 0x0000f2934fd8dd1f);
testNumbers(0xf490d3936184c9f9, 0x00004007477e2110);
testNumbers(0x349e577c9d5c44e2, 0x0000bdb2235af963);
testNumbers(0x58f3ac26cdafde28, 0x0017d4f4ade9ec35);
testNumbers(0xa4a263c316d21f4c, 0x00a7ec1e6fda834b);
testNumbers(0x6ab14771c448666f, 0x005b0f49593c3a27);
testNumbers(0x15f392c3602aa4f7, 0x0018af171045f88e);
testNumbers(0xf17de69c0063f62c, 0xee2a164c2c3a46f8);
testNumbers(0xf34b743eeff8e5c6, 0x4f4067f1a0e404ad);
testNumbers(0xee0296f678756647, 0xf1bbfdc6f0280d36);
testNumbers(0x65c33db0c952b829, 0xa7ab9c39dcffbcf3);
Console.WriteLine("All tests passed.");
return 100;
}
catch (DivideByZeroException)
{
return 1;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
namespace umbraco.editorControls.tinymce
{
[Obsolete("IDataType and all other references to the legacy property editors are no longer used this will be removed from the codebase in future versions")]
public class tinyMCEPreValueConfigurator : System.Web.UI.WebControls.PlaceHolder, interfaces.IDataPrevalue
{
// UI controls
private CheckBoxList _editorButtons;
private CheckBox _enableRightClick;
private DropDownList _dropdownlist;
private CheckBoxList _advancedUsersList;
private CheckBoxList _stylesheetList;
private TextBox _width = new TextBox();
private TextBox _height = new TextBox();
private TextBox _maxImageWidth = new TextBox();
private CheckBox _fullWidth = new CheckBox();
private CheckBox _showLabel = new CheckBox();
private RegularExpressionValidator _widthValidator = new RegularExpressionValidator();
private RegularExpressionValidator _heightValidator = new RegularExpressionValidator();
private RegularExpressionValidator _maxImageWidthValidator = new RegularExpressionValidator();
// referenced datatype
private cms.businesslogic.datatype.BaseDataType _datatype;
private string _selectedButtons = "";
private string _advancedUsers = "";
private string _stylesheets = "";
public static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
public tinyMCEPreValueConfigurator(cms.businesslogic.datatype.BaseDataType DataType)
{
// state it knows its datatypedefinitionid
_datatype = DataType;
setupChildControls();
}
private void setupChildControls()
{
_dropdownlist = new DropDownList();
_dropdownlist.ID = "dbtype";
_dropdownlist.Items.Add(DBTypes.Date.ToString());
_dropdownlist.Items.Add(DBTypes.Integer.ToString());
_dropdownlist.Items.Add(DBTypes.Ntext.ToString());
_dropdownlist.Items.Add(DBTypes.Nvarchar.ToString());
_editorButtons = new CheckBoxList();
_editorButtons.ID = "editorButtons";
_editorButtons.RepeatColumns = 4;
_editorButtons.CellPadding = 3;
_enableRightClick = new CheckBox();
_enableRightClick.ID = "enableRightClick";
_advancedUsersList = new CheckBoxList();
_advancedUsersList.ID = "advancedUsersList";
_stylesheetList = new CheckBoxList();
_stylesheetList.ID = "stylesheetList";
_showLabel = new CheckBox();
_showLabel.ID = "showLabel";
_maxImageWidth = new TextBox();
_maxImageWidth.ID = "maxImageWidth";
// put the childcontrols in context - ensuring that
// the viewstate is persisted etc.
Controls.Add(_dropdownlist);
Controls.Add(_enableRightClick);
Controls.Add(_editorButtons);
Controls.Add(_advancedUsersList);
Controls.Add(_stylesheetList);
Controls.Add(_width);
Controls.Add(_widthValidator);
Controls.Add(_height);
Controls.Add(_heightValidator);
Controls.Add(_showLabel);
Controls.Add(_maxImageWidth);
Controls.Add(_maxImageWidthValidator);
// Controls.Add(_fullWidth);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad (e);
// add ids to controls
_width.ID = "width";
_height.ID = "height";
// initialize validators
_widthValidator.ValidationExpression = "0*[1-9][0-9]*";
_widthValidator.ErrorMessage = ui.Text("errorHandling", "errorIntegerWithoutTab", ui.Text("width"), new BasePages.BasePage().getUser());
_widthValidator.Display = ValidatorDisplay.Dynamic;
_widthValidator.ControlToValidate = _width.ID;
_heightValidator.ValidationExpression = "0*[1-9][0-9]*";
_heightValidator.ErrorMessage = ui.Text("errorHandling", "errorIntegerWithoutTab", ui.Text("height"), new BasePages.BasePage().getUser());
_heightValidator.ControlToValidate = _height.ID;
_heightValidator.Display = ValidatorDisplay.Dynamic;
_maxImageWidthValidator.ValidationExpression = "0*[1-9][0-9]*";
_maxImageWidthValidator.ErrorMessage = ui.Text("errorHandling", "errorIntegerWithoutTab","'" + ui.Text("rteMaximumDefaultImgSize") + "'", new BasePages.BasePage().getUser());
_maxImageWidthValidator.ControlToValidate = _maxImageWidth.ID;
_maxImageWidthValidator.Display = ValidatorDisplay.Dynamic;
if (!Page.IsPostBack)
{
if (Configuration != null)
{
string[] config = Configuration.Split("|".ToCharArray());
if (config.Length > 0)
{
_selectedButtons = config[0];
if (config.Length > 1)
if (config[1] == "1")
_enableRightClick.Checked = true;
if (config.Length > 2)
_advancedUsers = config[2];
if (config.Length > 4 && config[4].Split(',').Length > 1)
{
// if (config[3] == "1")
// _fullWidth.Checked = true;
// else
// {
_width.Text = config[4].Split(',')[0];
_height.Text = config[4].Split(',')[1];
// }
}
// if width and height are empty or lower than 0 then set default sizes:
int tempWidth, tempHeight;
int.TryParse(_width.Text, out tempWidth);
int.TryParse(_height.Text, out tempHeight);
if (_width.Text.Trim() == "" || tempWidth < 1)
_width.Text = "500";
if (_height.Text.Trim() == "" || tempHeight < 1)
_height.Text = "400";
if (config.Length > 5)
_stylesheets = config[5];
if (config.Length > 6 && config[6] != "")
_showLabel.Checked = bool.Parse(config[6]);
if (config.Length > 7 && config[7] != "")
_maxImageWidth.Text = config[7];
else
_maxImageWidth.Text = "500";
}
// add editor buttons
IDictionaryEnumerator ide = tinyMCEConfiguration.SortedCommands.GetEnumerator();
while (ide.MoveNext())
{
tinyMCECommand cmd = (tinyMCECommand) ide.Value;
ListItem li =
new ListItem(
string.Format("<img src=\"{0}\" class=\"tinymceIcon\" alt=\"{1}\" /> ", cmd.Icon,
cmd.Alias), cmd.Alias);
if (_selectedButtons.IndexOf(cmd.Alias) > -1)
li.Selected = true;
_editorButtons.Items.Add(li);
}
// add users
foreach (BusinessLogic.UserType ut in BusinessLogic.UserType.getAll)
{
ListItem li = new ListItem(ut.Name, ut.Id.ToString());
if (("," + _advancedUsers + ",").IndexOf("," + ut.Id.ToString() + ",") > -1)
li.Selected = true;
_advancedUsersList.Items.Add(li);
}
// add stylesheets
foreach (cms.businesslogic.web.StyleSheet st in cms.businesslogic.web.StyleSheet.GetAll())
{
ListItem li = new ListItem(st.Text, st.Id.ToString());
if (("," + _stylesheets + ",").IndexOf("," + st.Id.ToString() + ",") > -1)
li.Selected = true;
_stylesheetList.Items.Add(li);
}
}
// Mark the current db type
_dropdownlist.SelectedValue = _datatype.DBType.ToString();
}
}
public Control Editor
{
get
{
return this;
}
}
public virtual void Save()
{
_datatype.DBType = (cms.businesslogic.datatype.DBTypes)Enum.Parse(typeof(cms.businesslogic.datatype.DBTypes), _dropdownlist.SelectedValue, true);
// Generate data-string
string data = ",";
foreach (ListItem li in _editorButtons.Items)
if (li.Selected)
data += li.Value + ",";
data += "|";
if (_enableRightClick.Checked)
data += "1";
else
data += "0";
data += "|";
foreach (ListItem li in _advancedUsersList.Items)
if (li.Selected)
data += li.Value + ",";
data += "|";
data += "0|";
/*
if (_fullWidth.Checked)
data += "1|";
else
data += "0|";
*/
data += _width.Text + "," + _height.Text + "|";
foreach (ListItem li in _stylesheetList.Items)
if (li.Selected)
data += li.Value + ",";
data += "|";
data += _showLabel.Checked.ToString() + "|";
data += _maxImageWidth.Text + "|";
// If the add new prevalue textbox is filled out - add the value to the collection.
IParameter[] SqlParams = new IParameter[] {
SqlHelper.CreateParameter("@value",data),
SqlHelper.CreateParameter("@dtdefid",_datatype.DataTypeDefinitionId)};
SqlHelper.ExecuteNonQuery("delete from cmsDataTypePreValues where datatypenodeid = @dtdefid",SqlParams);
// we need to populate the parameters again due to an issue with SQL CE
SqlParams = new IParameter[] {
SqlHelper.CreateParameter("@value",data),
SqlHelper.CreateParameter("@dtdefid",_datatype.DataTypeDefinitionId)};
SqlHelper.ExecuteNonQuery("insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (@dtdefid,@value,0,'')",SqlParams);
}
protected override void Render(HtmlTextWriter writer)
{
writer.WriteLine("<table>");
writer.WriteLine("<tr><th>" + ui.Text("editdatatype", "dataBaseDatatype") + ":</th><td>");
_dropdownlist.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>" + ui.Text("editdatatype", "rteButtons") + ":</th><td>");
_editorButtons.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>" + ui.Text("editdatatype", "rteRelatedStylesheets") + ":</th><td>");
_stylesheetList.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>" + ui.Text("editdatatype", "rteEnableContextMenu") + ":</th><td>");
_enableRightClick.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>" + ui.Text("editdatatype", "rteEnableAdvancedSettings") + ":</th><td>");
_advancedUsersList.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>");
//"Size:</th><td>Maximum width and height: ");
// _fullWidth.RenderControl(writer);
writer.Write(ui.Text("editdatatype", "rteWidthAndHeight") + ":</th><td>");
_width.RenderControl(writer);
_widthValidator.RenderControl(writer);
writer.Write(" x ");
_height.RenderControl(writer);
_heightValidator.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>");
writer.Write(ui.Text("editdatatype", "rteMaximumDefaultImgSize") + ":</th><td>");
_maxImageWidth.RenderControl(writer);
_maxImageWidthValidator.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>" + ui.Text("editdatatype", "rteShowLabel") + ":</th><td>");
_showLabel.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("</table>");
}
public string Configuration
{
get
{
try
{
return SqlHelper.ExecuteScalar<string>("select value from cmsDataTypePreValues where datatypenodeid = @datatypenodeid", SqlHelper.CreateParameter("@datatypenodeid", _datatype.DataTypeDefinitionId));
}
catch
{
return "";
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics;
using Android.Graphics.Drawables;
using Square.Picasso;
using csfm_android.Api.Model;
using csfm_android.Activities;
using csfm_android.Utils.MaterialDesignSearchView;
using csfm_android.Api;
using csfm_android.Utils;
namespace csfm_android.Fragments
{
/// <summary>
/// The discover fragment : Match with people specially recommended for you
/// </summary>
public class DiscoverFragment : Fragment
{
private View rootView;
private ImageView likeButton;
private ImageView nextButton;
private ImageView avatar;
private TextView favoriteSong;
private TextView username;
private Button loadMore;
private List<User> recommendedUsers;
private User currentUser;
/// <summary>
/// Updates TextView that are user-dependant : Username TextView, Avatar ImageView. Also empties FavoriteSong TextView
/// </summary>
private User CurrentUser
{
get { return currentUser; }
set
{
currentUser = value;
if (currentUser != null)
{
this.AvatarUrl = currentUser.Photo;
this.username.Text = currentUser.Username;
}
else
{
this.username.Text = "";
}
this.favoriteSong.Text = "";
}
}
/// <summary>
/// Loads image url into Avatar ImageView
/// </summary>
public string AvatarUrl
{
set
{
Picasso.With(this.Activity)
.Load(value)
.Into(this.avatar);
}
}
/// <summary>
/// On fragment creation
/// </summary>
/// <param name="savedInstanceState"></param>
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
/// <summary>
/// On fragment end
/// </summary>
public override void OnStop()
{
base.OnStop();
((ToolbarActivity)Activity).Toolbar.Show();
}
/// <summary>
/// On fragment view creation
/// </summary>
/// <param name="inflater"></param>
/// <param name="container"></param>
/// <param name="savedInstanceState"></param>
/// <returns></returns>
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
this.rootView = inflater.Inflate(Resource.Layout.discover_fragment, container, false);
((ToolbarActivity)Activity).Toolbar.Hide();
this.likeButton = this.rootView.FindViewById<ImageView>(Resource.Id.match_ok);
this.nextButton = this.rootView.FindViewById<ImageView>(Resource.Id.match_cancel);
this.avatar = this.rootView.FindViewById<ImageView>(Resource.Id.match_image);
this.favoriteSong = this.rootView.FindViewById<TextView>(Resource.Id.match_song);
this.username = this.rootView.FindViewById<TextView>(Resource.Id.match_username);
this.loadMore = this.rootView.FindViewById<Button>(Resource.Id.load_more);
return this.rootView;
}
/// <summary>
/// On fragment resume
/// </summary>
public override void OnStart()
{
base.OnStart();
this.recommendedUsers = new List<User>();
InitListeners();
GetRecommendations(); //Async API Request
}
/// <summary>
/// Inits the listeners
/// </summary>
private void InitListeners()
{
this.likeButton.Click += delegate
{
if (this.currentUser != null)
{
PutMatch(true);
this.Next();
}
};
this.nextButton.Click += delegate
{
if (this.currentUser != null)
{
PutMatch(false);
this.Next();
}
};
this.loadMore.Click += delegate
{
GetRecommendations();
};
}
/// <summary>
/// Inits the buttons
/// </summary>
private void InitButtons()
{
Bitmap likeBitmap = ((BitmapDrawable)this.likeButton.Drawable).Bitmap;
this.likeButton.SetImageDrawable(new BitmapDrawable(Resources, AddGradient(likeBitmap, new Color(89, 202, 167), new Color(118, 217, 204))));
Bitmap nextBitmap = ((BitmapDrawable)this.nextButton.Drawable).Bitmap;
this.nextButton.SetImageDrawable(new BitmapDrawable(Resources, AddGradient(nextBitmap, new Color(228, 58, 115), new Color(238, 174, 162))));
}
/// <summary>
/// Adds gradient color to the buttons
/// </summary>
/// <param name="originalBitmap"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
private Bitmap AddGradient(Bitmap originalBitmap, Color start, Color end)
{
int width = originalBitmap.Width;
int height = originalBitmap.Height;
Bitmap updatedBitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
Canvas canvas = new Canvas(updatedBitmap);
canvas.DrawBitmap(originalBitmap, 0, 0, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, 0, 0, height, start, end, Shader.TileMode.Clamp);
paint.SetShader(shader);
paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.SrcIn));
canvas.DrawRect(0, 0, width, height, paint);
return updatedBitmap;
}
/// <summary>
/// API Request to match or dismatch a user
/// </summary>
/// <param name="isMatch"></param>
private async void PutMatch(bool isMatch)
{
await new ApiClient().PutUserMatch(CSFMPrefs.Username, currentUser.Id, isMatch);
}
/// <summary>
/// Loads the next recommended user
/// </summary>
private async void Next()
{
if (this.recommendedUsers.Any())
{
User user = this.recommendedUsers.First();
this.CurrentUser = user; //Sets name text, avatar to user info ; Empties favorite song text view
var topArtists = await new ApiClient().GetUserTopArtists(user.Username);
if (topArtists != null && topArtists.Any())
{
this.favoriteSong.Text = topArtists.First().Name;
}
else
{
this.favoriteSong.Text = GetString(Resource.String.no_favorite_artist);
}
this.recommendedUsers.Remove(user);
}
else
{
LoadMore();
}
}
/// <summary>
/// Displays the Load more button
/// </summary>
private void LoadMore()
{
this.avatar.SetImageResource(0);
this.CurrentUser = null; //Sets user name, and favorite text to null
this.loadMore.Visibility = ViewStates.Visible;
}
/// <summary>
/// Displays the recommended users after retrieving them from an API Request
/// </summary>
private async void GetRecommendations()
{
this.recommendedUsers = await new ApiClient().GetUserRecommendations(CSFMPrefs.Username);
if (this.recommendedUsers != null && this.recommendedUsers.Any())
{
this.loadMore.Visibility = ViewStates.Gone;
this.Next();
}
else
{
LoadMore();
}
this.InitButtons();
}
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI40;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Reflection;
using LLA40 = Net.Pkcs11Interop.LowLevelAPI40;
namespace Net.Pkcs11Interop.Tests.HighLevelAPI40
{
/// <summary>
/// Object attributes tests.
/// </summary>
[TestClass]
public class _13_ObjectAttributeTest
{
/// <summary>
/// Attribute dispose test.
/// </summary>
[TestMethod]
public void _01_DisposeAttributeTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
// Unmanaged memory for attribute value stored in low level CK_ATTRIBUTE struct
// is allocated by constructor of ObjectAttribute class.
ObjectAttribute attr1 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
// Do something interesting with attribute
// This unmanaged memory is freed by Dispose() method.
attr1.Dispose();
// ObjectAttribute class can be used in using statement which defines a scope
// at the end of which an object will be disposed (and unmanaged memory freed).
using (ObjectAttribute attr2 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA))
{
// Do something interesting with attribute
}
#pragma warning disable 0219
// Explicit calling of Dispose() method can also be ommitted.
ObjectAttribute attr3 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
// Do something interesting with attribute
// Dispose() method will be called (and unmanaged memory freed) by GC eventually
// but we cannot be sure when will this occur.
#pragma warning restore 0219
}
/// <summary>
/// Attribute with empty value test.
/// </summary>
[TestMethod]
public void _02_EmptyAttributeTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
// Create attribute without the value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_CLASS))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_CLASS);
Assert.IsTrue(attr.GetValueAsByteArray() == null);
}
}
/// <summary>
/// Attribute with uint value test.
/// </summary>
[TestMethod]
public void _03_UintAttributeTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
uint value = (uint)CKO.CKO_DATA;
// Create attribute with uint value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_CLASS, value))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_CLASS);
Assert.IsTrue(attr.GetValueAsUint() == value);
}
}
/// <summary>
/// Attribute with bool value test.
/// </summary>
[TestMethod]
public void _04_BoolAttributeTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
bool value = true;
// Create attribute with bool value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_TOKEN, value))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_TOKEN);
Assert.IsTrue(attr.GetValueAsBool() == value);
}
}
/// <summary>
/// Attribute with string value test.
/// </summary>
[TestMethod]
public void _05_StringAttributeTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
string value = "Hello world";
// Create attribute with string value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_LABEL, value))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_LABEL);
Assert.IsTrue(attr.GetValueAsString() == value);
}
value = null;
// Create attribute with null string value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_LABEL, value))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_LABEL);
Assert.IsTrue(attr.GetValueAsString() == value);
}
}
/// <summary>
/// Attribute with byte array value test.
/// </summary>
[TestMethod]
public void _06_ByteArrayAttributeTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
byte[] value = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
// Create attribute with byte array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ID, value))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_ID);
Assert.IsTrue(Convert.ToBase64String(attr.GetValueAsByteArray()) == Convert.ToBase64String(value));
}
value = null;
// Create attribute with null byte array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ID, value))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_ID);
Assert.IsTrue(attr.GetValueAsByteArray() == value);
}
}
/// <summary>
/// Attribute with DateTime (CKA_DATE) value test.
/// </summary>
[TestMethod]
public void _07_DateTimeAttributeTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
DateTime value = new DateTime(2012, 1, 30, 0, 0, 0, DateTimeKind.Utc);
// Create attribute with DateTime value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_START_DATE, value))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_START_DATE);
Assert.IsTrue(attr.GetValueAsDateTime() == value);
}
}
/// <summary>
/// Attribute with attribute array value test.
/// </summary>
[TestMethod]
public void _08_AttributeArrayAttributeTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
ObjectAttribute nestedAttribute1 = new ObjectAttribute(CKA.CKA_TOKEN, true);
ObjectAttribute nestedAttribute2 = new ObjectAttribute(CKA.CKA_PRIVATE, true);
List<ObjectAttribute> originalValue = new List<ObjectAttribute>();
originalValue.Add(nestedAttribute1);
originalValue.Add(nestedAttribute2);
// Create attribute with attribute array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_WRAP_TEMPLATE);
List<ObjectAttribute> recoveredValue = attr.GetValueAsObjectAttributeList();
Assert.IsTrue(recoveredValue.Count == 2);
Assert.IsTrue(recoveredValue[0].Type == (uint)CKA.CKA_TOKEN);
Assert.IsTrue(recoveredValue[0].GetValueAsBool() == true);
Assert.IsTrue(recoveredValue[1].Type == (uint)CKA.CKA_PRIVATE);
Assert.IsTrue(recoveredValue[1].GetValueAsBool() == true);
}
// There is the same pointer to unmanaged memory in both nestedAttribute1 and recoveredValue[0] instances
// therefore private low level attribute structure needs to be modified to prevent double free.
// This special handling is needed only in this synthetic test and should be avoided in real world application.
LLA40.CK_ATTRIBUTE ckAttribute1 = (LLA40.CK_ATTRIBUTE)typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute1);
ckAttribute1.value = IntPtr.Zero;
ckAttribute1.valueLen = 0;
typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(nestedAttribute1, ckAttribute1);
// There is the same pointer to unmanaged memory in both nestedAttribute2 and recoveredValue[1] instances
// therefore private low level attribute structure needs to be modified to prevent double free.
// This special handling is needed only in this synthetic test and should be avoided in real world application.
LLA40.CK_ATTRIBUTE ckAttribute2 = (LLA40.CK_ATTRIBUTE)typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute2);
ckAttribute2.value = IntPtr.Zero;
ckAttribute2.valueLen = 0;
typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(nestedAttribute2, ckAttribute2);
originalValue = null;
// Create attribute with null attribute array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_WRAP_TEMPLATE);
Assert.IsTrue(attr.GetValueAsObjectAttributeList() == originalValue);
}
originalValue = new List<ObjectAttribute>();
// Create attribute with empty attribute array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_WRAP_TEMPLATE);
Assert.IsTrue(attr.GetValueAsObjectAttributeList() == null);
}
}
/// <summary>
/// Attribute with uint array value test.
/// </summary>
[TestMethod]
public void _09_UintArrayAttributeTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
List<uint> originalValue = new List<uint>();
originalValue.Add(333333);
originalValue.Add(666666);
// Create attribute with uint array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_ALLOWED_MECHANISMS);
List<uint> recoveredValue = attr.GetValueAsUintList();
for (int i = 0; i < recoveredValue.Count; i++)
Assert.IsTrue(originalValue[i] == recoveredValue[i]);
}
originalValue = null;
// Create attribute with null uint array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_ALLOWED_MECHANISMS);
Assert.IsTrue(attr.GetValueAsUintList() == originalValue);
}
originalValue = new List<uint>();
// Create attribute with empty uint array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_ALLOWED_MECHANISMS);
Assert.IsTrue(attr.GetValueAsUintList() == null);
}
}
/// <summary>
/// Attribute with mechanism array value test.
/// </summary>
[TestMethod]
public void _10_MechanismArrayAttributeTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
List<CKM> originalValue = new List<CKM>();
originalValue.Add(CKM.CKM_RSA_PKCS);
originalValue.Add(CKM.CKM_AES_CBC);
// Create attribute with mechanism array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_ALLOWED_MECHANISMS);
List<CKM> recoveredValue = attr.GetValueAsCkmList();
for (int i = 0; i < recoveredValue.Count; i++)
Assert.IsTrue(originalValue[i] == recoveredValue[i]);
}
originalValue = null;
// Create attribute with null mechanism array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_ALLOWED_MECHANISMS);
Assert.IsTrue(attr.GetValueAsCkmList() == originalValue);
}
originalValue = new List<CKM>();
// Create attribute with empty mechanism array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (uint)CKA.CKA_ALLOWED_MECHANISMS);
Assert.IsTrue(attr.GetValueAsCkmList() == null);
}
}
}
}
| |
using System;
using System.Configuration;
using System.Data;
namespace Rhino.Etl.Core.Infrastructure
{
using System.Data.Common;
/// <summary>
/// Helper class to provide simple data access, when we want to access the ADO.Net
/// library directly.
/// </summary>
public static class Use
{
#region Delegates
/// <summary>
/// Delegate to execute an action with a command
/// and return a result: <typeparam name="T"/>
/// </summary>
public delegate T Func<T>(IDbCommand command);
/// <summary>
/// Delegate to execute an action with a command
/// </summary>
public delegate void Proc(IDbCommand command);
#endregion
/// <summary>
/// Gets or sets the active connection.
/// </summary>
/// <value>The active connection.</value>
[ThreadStatic]
private static IDbConnection ActiveConnection;
/// <summary>
/// Gets or sets the active transaction.
/// </summary>
/// <value>The active transaction.</value>
[ThreadStatic]
private static IDbTransaction ActiveTransaction;
/// <summary>
/// Gets or sets the transaction counter.
/// </summary>
/// <value>The transaction counter.</value>
[ThreadStatic]
private static int TransactionCounter;
/// <summary>
/// Execute the specified delegate inside a transaction and return
/// the result of the delegate.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connectionStringName">The name of the named connection string in the configuration file</param>
/// <param name="actionToExecute">The action to execute</param>
/// <returns></returns>
public static T Transaction<T>(string connectionStringName, Func<T> actionToExecute)
{
T result = default(T);
ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName];
if (connectionStringSettings == null)
throw new InvalidOperationException("Could not find connnection string: " + connectionStringName);
Transaction(connectionStringSettings, delegate(IDbCommand command) { result = actionToExecute(command); });
return result;
}
/// <summary>
/// Execute the specified delegate inside a transaction and return
/// the result of the delegate.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connectionStringSettings">The connection string settings to use for the connection</param>
/// <param name="actionToExecute">The action to execute</param>
/// <returns></returns>
public static T Transaction<T>(ConnectionStringSettings connectionStringSettings, Func<T> actionToExecute)
{
T result = default(T);
Transaction(connectionStringSettings, delegate(IDbCommand command) { result = actionToExecute(command); });
return result;
}
/// <summary>
/// Execute the specified delegate inside a transaction
/// </summary>
/// <param name="connectionStringName">Name of the connection string.</param>
/// <param name="actionToExecute">The action to execute.</param>
public static void Transaction(string connectionStringName, Proc actionToExecute)
{
ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName];
if (connectionStringSettings == null)
throw new InvalidOperationException("Could not find connnection string: " + connectionStringName);
Transaction(connectionStringSettings, IsolationLevel.Unspecified, actionToExecute);
}
/// <summary>
/// Execute the specified delegate inside a transaction
/// </summary>
/// <param name="connectionStringSettings">The connection string settings to use for the connection</param>
/// <param name="actionToExecute">The action to execute.</param>
public static void Transaction(ConnectionStringSettings connectionStringSettings, Proc actionToExecute)
{
Transaction(connectionStringSettings, IsolationLevel.Unspecified, actionToExecute);
}
/// <summary>
/// Execute the specified delegate inside a transaction with the specific
/// isolation level
/// </summary>
/// <param name="connectionStringName">Name of the connection string.</param>
/// <param name="isolationLevel">The isolation level.</param>
/// <param name="actionToExecute">The action to execute.</param>
public static void Transaction(string connectionStringName, IsolationLevel isolationLevel, Proc actionToExecute)
{
ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName];
if (connectionStringSettings == null)
throw new InvalidOperationException("Could not find connnection string: " + connectionStringName);
Transaction(connectionStringSettings, isolationLevel, actionToExecute);
}
/// <summary>
/// Execute the specified delegate inside a transaction with the specific
/// isolation level
/// </summary>
/// <param name="connectionStringSettings">Connection string settings node to use for the connection</param>
/// <param name="isolationLevel">The isolation level.</param>
/// <param name="actionToExecute">The action to execute.</param>
public static void Transaction(ConnectionStringSettings connectionStringSettings, IsolationLevel isolationLevel, Proc actionToExecute)
{
StartTransaction(connectionStringSettings, isolationLevel);
try
{
using (IDbCommand command = ActiveConnection.CreateCommand())
{
command.Transaction = ActiveTransaction;
actionToExecute(command);
}
CommitTransaction();
}
catch
{
RollbackTransaction();
throw;
}
finally
{
DisposeTransaction();
}
}
/// <summary>
/// Disposes the transaction.
/// </summary>
private static void DisposeTransaction()
{
if (TransactionCounter <= 0)
{
ActiveConnection.Dispose();
ActiveConnection = null;
}
}
/// <summary>
/// Rollbacks the transaction.
/// </summary>
private static void RollbackTransaction()
{
ActiveTransaction.Rollback();
ActiveTransaction.Dispose();
ActiveTransaction = null;
TransactionCounter = 0;
}
/// <summary>
/// Commits the transaction.
/// </summary>
private static void CommitTransaction()
{
TransactionCounter--;
if (TransactionCounter == 0 && ActiveTransaction != null)
{
ActiveTransaction.Commit();
ActiveTransaction.Dispose();
ActiveTransaction = null;
}
}
/// <summary>
/// Starts the transaction.
/// </summary>
/// <param name="connectionStringSettings">The connection string settings to use for the transaction</param>
/// <param name="isolation">The isolation.</param>
private static void StartTransaction(ConnectionStringSettings connectionStringSettings, IsolationLevel isolation)
{
if (TransactionCounter <= 0)
{
TransactionCounter = 0;
ActiveConnection = Connection(connectionStringSettings);
ActiveTransaction = ActiveConnection.BeginTransaction(isolation);
}
TransactionCounter++;
}
/// <summary>
/// Creates an open connection for a given named connection string, using the provider name
/// to select the proper implementation
/// </summary>
/// <param name="name">The name.</param>
/// <returns>The open connection</returns>
public static IDbConnection Connection(string name)
{
ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings[name];
if (connectionString == null)
throw new InvalidOperationException("Could not find connnection string: " + name);
return Connection(connectionString);
}
/// <summary>
/// Creates an open connection for a given connection string setting, using the provider
/// name of select the proper implementation
/// </summary>
/// <param name="connectionString">ConnectionStringSetting node</param>
/// <returns>The open connection</returns>
public static IDbConnection Connection(ConnectionStringSettings connectionString)
{
if (connectionString == null)
throw new InvalidOperationException("Null ConnectionStringSettings specified");
if (connectionString.ProviderName == null)
throw new InvalidOperationException("Null ProviderName specified");
IDbConnection connection = null;
string providerName = connectionString.ProviderName;
if (providerName != null)
{
// Backwards compatibility: ProviderName could be an assembly qualified connection type name.
Type connectionType = Type.GetType(providerName);
if (connectionType != null)
{
connection = Activator.CreateInstance(connectionType) as IDbConnection;
}
}
if (connection == null)
{
// ADO.NET compatible usage of provider name.
connection = DbProviderFactories.GetFactory(providerName).CreateConnection();
}
connection.ConnectionString = connectionString.ConnectionString;
connection.Open();
return connection;
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
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.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Runtime;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Utilities class for handling configuration.
/// </summary>
public static class ConfigUtilities
{
internal static void ParseTracing(ITraceConfiguration config, XmlElement root, string nodeName)
{
if (root.HasAttribute("DefaultTraceLevel"))
{
config.DefaultTraceLevel = ParseSeverity(root.GetAttribute("DefaultTraceLevel"),
"Invalid trace level DefaultTraceLevel attribute value on Tracing element for " + nodeName);
}
if (root.HasAttribute("TraceToConsole"))
{
config.TraceToConsole = ParseBool(root.GetAttribute("TraceToConsole"),
"Invalid boolean value for TraceToConsole attribute on Tracing element for " + nodeName);
}
if (root.HasAttribute("TraceToFile"))
{
config.TraceFilePattern = root.GetAttribute("TraceToFile");
}
if (root.HasAttribute("WriteMessagingTraces"))
{
config.WriteMessagingTraces = ParseBool(root.GetAttribute("WriteMessagingTraces"),
"Invalid boolean value for WriteMessagingTraces attribute on Tracing element for " + nodeName);
}
if (root.HasAttribute("LargeMessageWarningThreshold"))
{
config.LargeMessageWarningThreshold = ParseInt(root.GetAttribute("LargeMessageWarningThreshold"),
"Invalid boolean value for LargeMessageWarningThresholdattribute on Tracing element for " + nodeName);
}
if (root.HasAttribute("PropagateActivityId"))
{
config.PropagateActivityId = ParseBool(root.GetAttribute("PropagateActivityId"),
"Invalid boolean value for PropagateActivityId attribute on Tracing element for " + nodeName);
}
if (root.HasAttribute("BulkMessageLimit"))
{
config.BulkMessageLimit = ParseInt(root.GetAttribute("BulkMessageLimit"),
"Invalid int value for BulkMessageLimit attribute on Tracing element for " + nodeName);
}
foreach (XmlNode node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if (grandchild == null) continue;
if (grandchild.LocalName.Equals("TraceLevelOverride") && grandchild.HasAttribute("TraceLevel") && grandchild.HasAttribute("LogPrefix"))
{
config.TraceLevelOverrides.Add(new Tuple<string, Logger.Severity>(grandchild.GetAttribute("LogPrefix"),
ParseSeverity(grandchild.GetAttribute("TraceLevel"),
"Invalid trace level TraceLevel attribute value on TraceLevelOverride element for " + nodeName + " prefix " +
grandchild.GetAttribute("LogPrefix"))));
}
else if (grandchild.LocalName.Equals("LogConsumer"))
{
var className = grandchild.InnerText;
Assembly assembly = null;
try
{
int pos = className.IndexOf(',');
if (pos > 0)
{
var assemblyName = className.Substring(pos + 1).Trim();
className = className.Substring(0, pos).Trim();
assembly = Assembly.Load(assemblyName);
}
else
{
assembly = Assembly.GetExecutingAssembly();
}
var plugin = assembly.CreateInstance(className);
if (plugin == null) throw new TypeLoadException("Cannot locate plugin class " + className + " in assembly " + assembly.FullName);
if (plugin is ILogConsumer)
{
TraceLogger.LogConsumers.Add(plugin as ILogConsumer);
}
else
{
throw new InvalidCastException("LogConsumer class " + className + " must implement Orleans.ILogConsumer interface");
}
}
catch (Exception exc)
{
throw new TypeLoadException("Cannot load LogConsumer class " + className + " from assembly " + assembly + " - Error=" + exc);
}
}
}
SetTraceFileName(config, nodeName, DateTime.UtcNow);
}
internal static void ParseStatistics(IStatisticsConfiguration config, XmlElement root, string nodeName)
{
if (root.HasAttribute("ProviderType"))
{
config.StatisticsProviderName = root.GetAttribute("ProviderType");
}
if (root.HasAttribute("MetricsTableWriteInterval"))
{
config.StatisticsMetricsTableWriteInterval = ParseTimeSpan(root.GetAttribute("MetricsTableWriteInterval"),
"Invalid TimeSpan value for Statistics.MetricsTableWriteInterval attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("PerfCounterWriteInterval"))
{
config.StatisticsPerfCountersWriteInterval = ParseTimeSpan(root.GetAttribute("PerfCounterWriteInterval"),
"Invalid TimeSpan value for Statistics.PerfCounterWriteInterval attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("LogWriteInterval"))
{
config.StatisticsLogWriteInterval = ParseTimeSpan(root.GetAttribute("LogWriteInterval"),
"Invalid TimeSpan value for Statistics.LogWriteInterval attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("WriteLogStatisticsToTable"))
{
config.StatisticsWriteLogStatisticsToTable = ParseBool(root.GetAttribute("WriteLogStatisticsToTable"),
"Invalid bool value for Statistics.WriteLogStatisticsToTable attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("StatisticsCollectionLevel"))
{
config.StatisticsCollectionLevel = ConfigUtilities.ParseEnum<StatisticsLevel>(root.GetAttribute("StatisticsCollectionLevel"),
"Invalid value of for Statistics.StatisticsCollectionLevel attribute on Statistics element for " + nodeName);
}
}
internal static void ParseLimitValues(LimitManager limitManager, XmlElement root, string nodeName)
{
foreach (XmlNode node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if (grandchild == null) continue;
if (grandchild.LocalName.Equals("Limit") && grandchild.HasAttribute("Name")
&& (grandchild.HasAttribute("SoftLimit") || grandchild.HasAttribute("HardLimit")))
{
var limitName = grandchild.GetAttribute("Name");
limitManager.AddLimitValue(limitName, new LimitValue
{
Name = limitName,
SoftLimitThreshold = ParseInt(grandchild.GetAttribute("SoftLimit"),
"Invalid integer value for the SoftLimit attribute on the Limit element"),
HardLimitThreshold = grandchild.HasAttribute("HardLimit") ? ParseInt(grandchild.GetAttribute("HardLimit"),
"Invalid integer value for the HardLimit attribute on the Limit element") : 0,
});
}
}
}
internal static void SetTraceFileName(ITraceConfiguration config, string nodeName, DateTime timestamp)
{
const string dateFormat = "yyyy-MM-dd-HH.mm.ss.fffZ";
if (config == null) throw new ArgumentNullException("config");
if (config.TraceFilePattern == null
|| string.IsNullOrWhiteSpace(config.TraceFilePattern)
|| config.TraceFilePattern.Equals("false", StringComparison.OrdinalIgnoreCase)
|| config.TraceFilePattern.Equals("none", StringComparison.OrdinalIgnoreCase))
{
config.TraceFileName = null;
}
else if (string.Empty.Equals(config.TraceFileName))
{
config.TraceFileName = null; // normalize
}
else
{
string traceFileDir = Path.GetDirectoryName(config.TraceFilePattern);
if (!String.IsNullOrEmpty(traceFileDir) && !Directory.Exists(traceFileDir))
{
string traceFileName = Path.GetFileName(config.TraceFilePattern);
string[] alternateDirLocations = { "appdir", "." };
foreach (var d in alternateDirLocations)
{
if (Directory.Exists(d))
{
config.TraceFilePattern = Path.Combine(d, traceFileName);
break;
}
}
}
config.TraceFileName = String.Format(config.TraceFilePattern, nodeName, timestamp.ToUniversalTime().ToString(dateFormat), Dns.GetHostName());
}
}
internal static int ParseInt(string input, string errorMessage)
{
int p;
if (!Int32.TryParse(input, out p))
{
throw new FormatException(errorMessage);
}
return p;
}
internal static long ParseLong(string input, string errorMessage)
{
long p;
if (!Int64.TryParse(input, out p))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return p;
}
internal static bool ParseBool(string input, string errorMessage)
{
bool p;
if (Boolean.TryParse(input, out p)) return p;
switch (input)
{
case "0":
p = false;
break;
case "1":
p = true;
break;
default:
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return p;
}
internal static double ParseDouble(string input, string errorMessage)
{
double p;
if (!Double.TryParse(input, out p))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return p;
}
internal static Guid ParseGuid(string input, string errorMessage)
{
Guid p;
if (!Guid.TryParse(input, out p))
{
throw new FormatException(errorMessage);
}
return p;
}
// Time spans are entered as a string of decimal digits, optionally followed by a unit string: "ms", "s", "m", "hr"
internal static TimeSpan ParseTimeSpan(string input, string errorMessage)
{
int unitSize;
string numberInput;
var trimmedInput = input.Trim().ToLowerInvariant();
if (trimmedInput.EndsWith("ms", StringComparison.Ordinal))
{
unitSize = 1;
numberInput = trimmedInput.Remove(trimmedInput.Length - 2).Trim();
}
else if (trimmedInput.EndsWith("s", StringComparison.Ordinal))
{
unitSize = 1000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 1).Trim();
}
else if (trimmedInput.EndsWith("m", StringComparison.Ordinal))
{
unitSize = 60 * 1000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 1).Trim();
}
else if (trimmedInput.EndsWith("hr", StringComparison.Ordinal))
{
unitSize = 60 * 60 * 1000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 2).Trim();
}
else
{
unitSize = 1000; // Default is seconds
numberInput = trimmedInput;
}
double rawTimeSpan;
if (!double.TryParse(numberInput, out rawTimeSpan))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return TimeSpan.FromMilliseconds(rawTimeSpan * unitSize);
}
internal static byte[] ParseSubnet(string input, string errorMessage)
{
return string.IsNullOrEmpty(input) ? null : input.Split('.').Select(s => (byte) ParseInt(s, errorMessage)).ToArray();
}
internal static T ParseEnum<T>(string input, string errorMessage)
where T : struct // really, where T : enum, but there's no way to require that in C#
{
T s;
if (!Enum.TryParse<T>(input, out s))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return s;
}
internal static Logger.Severity ParseSeverity(string input, string errorMessage)
{
Logger.Severity s;
if (!Enum.TryParse<Logger.Severity>(input, out s))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return s;
}
internal static IPEndPoint ParseIPEndPoint(XmlElement root, byte[] subnet = null)
{
if (!root.HasAttribute("Address")) throw new FormatException("Missing Address attribute for " + root.LocalName + " element");
if (!root.HasAttribute("Port")) throw new FormatException("Missing Port attribute for " + root.LocalName + " element");
var family = AddressFamily.InterNetwork;
if (root.HasAttribute("Subnet"))
{
subnet = ParseSubnet(root.GetAttribute("Subnet"), "Invalid subnet");
}
if (root.HasAttribute("PreferredFamily"))
{
family = ParseEnum<AddressFamily>(root.GetAttribute("PreferredFamily"),
"Invalid preferred addressing family for " + root.LocalName + " element");
}
IPAddress addr = ClusterConfiguration.ResolveIPAddress(root.GetAttribute("Address"), subnet, family);
int port = ParseInt(root.GetAttribute("Port"), "Invalid Port attribute for " + root.LocalName + " element");
return new IPEndPoint(addr, port);
}
internal static string TraceConfigurationToString(ITraceConfiguration config)
{
var sb = new StringBuilder();
sb.Append(" Tracing: ").AppendLine();
sb.Append(" Default Trace Level: ").Append(config.DefaultTraceLevel).AppendLine();
if (config.TraceLevelOverrides.Count > 0)
{
sb.Append(" TraceLevelOverrides:").AppendLine();
foreach (var over in config.TraceLevelOverrides)
{
sb.Append(" ").Append(over.Item1).Append(" ==> ").Append(over.Item2.ToString()).AppendLine();
}
}
else
{
sb.Append(" TraceLevelOverrides: None").AppendLine();
}
sb.Append(" Trace to Console: ").Append(config.TraceToConsole).AppendLine();
sb.Append(" Trace File Name: ").Append(string.IsNullOrWhiteSpace(config.TraceFileName) ? "" : Path.GetFullPath(config.TraceFileName)).AppendLine();
sb.Append(" Write Messaging Traces: ").Append(config.WriteMessagingTraces).AppendLine();
sb.Append(" LargeMessageWarningThreshold: ").Append(config.LargeMessageWarningThreshold).AppendLine();
sb.Append(" PropagateActivityId: ").Append(config.PropagateActivityId).AppendLine();
sb.Append(" BulkMessageLimit: ").Append(config.BulkMessageLimit).AppendLine();
return sb.ToString();
}
internal static string IStatisticsConfigurationToString(IStatisticsConfiguration config)
{
var sb = new StringBuilder();
sb.Append(" Statistics: ").AppendLine();
sb.Append(" MetricsTableWriteInterval: ").Append(config.StatisticsMetricsTableWriteInterval).AppendLine();
sb.Append(" PerfCounterWriteInterval: ").Append(config.StatisticsPerfCountersWriteInterval).AppendLine();
sb.Append(" LogWriteInterval: ").Append(config.StatisticsLogWriteInterval).AppendLine();
sb.Append(" WriteLogStatisticsToTable: ").Append(config.StatisticsWriteLogStatisticsToTable).AppendLine();
sb.Append(" StatisticsCollectionLevel: ").Append(config.StatisticsCollectionLevel).AppendLine();
#if TRACK_DETAILED_STATS
sb.Append(" TRACK_DETAILED_STATS: true").AppendLine();
#endif
if (!string.IsNullOrEmpty(config.StatisticsProviderName))
sb.Append(" StatisticsProviderName:").Append(config.StatisticsProviderName).AppendLine();
return sb.ToString();
}
/// <summary>
/// Prints the the DataConnectionString,
/// without disclosing any credential info
/// such as the Azure Storage AccountKey or SqlServer password.
/// </summary>
/// <param name="dataConnectionString">The connection string to print.</param>
/// <returns>The string representation of the DataConnectionString with account credential info redacted.</returns>
public static string RedactConnectionStringInfo(string dataConnectionString)
{
return PrintSqlConnectionString(
PrintDataConnectionInfo(dataConnectionString));
}
public static string PrintDataConnectionInfo(string azureConnectionString)
{
if (String.IsNullOrEmpty(azureConnectionString)) return "null";
string azureConnectionInfo = azureConnectionString;
// Remove any Azure account keys from connection string info written to log files
int accountKeyPos = azureConnectionInfo.LastIndexOf("AccountKey=", StringComparison.Ordinal);
if (accountKeyPos > 0)
{
azureConnectionInfo = azureConnectionInfo.Remove(accountKeyPos) + "AccountKey=<--SNIP-->";
}
return azureConnectionInfo;
}
public static string PrintSqlConnectionString(string sqlConnectionString)
{
if (String.IsNullOrEmpty(sqlConnectionString))
{
return "null";
}
var sqlConnectionInfo = sqlConnectionString;
// Remove any Azure account keys from connection string info written to log files
int keyPos = sqlConnectionInfo.LastIndexOf("Password=", StringComparison.OrdinalIgnoreCase);
if (keyPos > 0)
{
sqlConnectionInfo = sqlConnectionInfo.Remove(keyPos) + "Password=<--SNIP-->";
}
return sqlConnectionInfo;
}
public static TimeSpan ParseCollectionAgeLimit(XmlElement xmlElement)
{
if (xmlElement.LocalName != "Deactivation")
throw new ArgumentException("The XML element must be a <Deactivate/> element.");
if (!xmlElement.HasAttribute("AgeLimit"))
throw new ArgumentException("The AgeLimit attribute is required for a <Deactivate/> element.");
return ParseTimeSpan(xmlElement.GetAttribute("AgeLimit"), "Invalid TimeSpan value for Deactivation.AgeLimit");
}
private static readonly string[] defaultClientConfigFileNames = { "ClientConfiguration.xml", "OrleansClientConfiguration.xml", "Client.config", "Client.xml" };
private static readonly string[] defaultSiloConfigFileNames = { "OrleansConfiguration.xml", "orleans.config", "config.xml", "orleans.config.xml" };
private static readonly string[] defaultConfigDirs =
{
null, // Will be filled in with directory location for this executing assembly
"approot", // Azure AppRoot directory
".", // Current directory
".." // Parent directory
};
public static string FindConfigFile(bool isSilo)
{
// Add directory containing Orleans binaries to the search locations for config files
defaultConfigDirs[0] = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var notFound = new List<string>();
foreach (string dir in defaultConfigDirs)
{
foreach (string file in isSilo ? defaultSiloConfigFileNames : defaultClientConfigFileNames)
{
var fileName = Path.GetFullPath(Path.Combine(dir, file));
if (File.Exists(fileName)) return fileName;
notFound.Add(fileName);
}
}
var whereWeLooked = new StringBuilder();
whereWeLooked.AppendFormat("Cannot locate Orleans {0} config file.", isSilo ? "silo" : "client").AppendLine();
whereWeLooked.AppendLine("Searched locations:");
foreach (var i in notFound)
{
whereWeLooked.AppendFormat("\t- {0}", i).AppendLine();
}
throw new FileNotFoundException(whereWeLooked.ToString());
}
/// <summary>
/// Returns the Runtime Version information.
/// </summary>
/// <returns>the Runtime Version information</returns>
public static string RuntimeVersionInfo()
{
var sb = new StringBuilder();
sb.Append(" .NET version: ").AppendLine(Environment.Version.ToString());
sb.Append(" Is .NET 4.5=").AppendLine(IsNet45OrNewer().ToString());
sb.Append(" OS version: ").AppendLine(Environment.OSVersion.ToString());
sb.AppendFormat(" GC Type={0} GCLatencyMode={1}",
GCSettings.IsServerGC ? "Server" : "Client",
Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode))
.AppendLine();
return sb.ToString();
}
internal static bool IsNet45OrNewer()
{
// From: http://stackoverflow.com/questions/8517159/how-to-detect-at-runtime-that-net-version-4-5-currently-running-your-code
// Class "ReflectionContext" exists from .NET 4.5 onwards.
return Type.GetType("System.Reflection.ReflectionContext", false) != null;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Originally based on the Bartok code base.
//
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace Microsoft.Zelig.MetaData.Importer
{
public partial class MetaDataMethod : MetaDataObject,
IMetaDataHasDeclSecurity,
IMetaDataMethodDefOrRef,
IMetaDataMemberForwarded,
IMetaDataCustomAttributeType,
IMetaDataTypeOrMethodDef,
IMetaDataNormalize
{
//
// State
//
private int m_rva;
private MethodImplAttributes m_implFlags;
private MethodAttributes m_flags;
private string m_name;
private SignatureMethod m_signature;
private List<MetaDataParam> m_paramList;
private List<MetaDataGenericParam> m_genericParamList;
private MetaDataTypeDefinition m_parent;
private Instruction[] m_instructions;
private EHClause[] m_ehTable;
private int m_maxStack;
private SignatureType[] m_locals;
private bool m_initLocals;
// information for debugging
private Debugging.MethodDebugInfo m_debugInfo;
//
// Constructor Methods
//
private MetaDataMethod( int index ) : base( TokenType.Method, index )
{
}
// Helper methods to work around limitations in generics, see Parser.InitializeTable<T>
internal static MetaDataObject.CreateInstance GetCreator()
{
return new MetaDataObject.CreateInstance( Creator );
}
private static MetaDataObject Creator( int index )
{
return new MetaDataMethod( index );
}
//--//
internal override void Parse( Parser parser ,
Parser.TableSchema ts ,
ArrayReader reader )
{
Parser.IndexReader paramReader = ts.m_columns[5].m_reader;
int signatureIndex;
int paramIndex;
m_rva = reader.ReadInt32();
m_implFlags = (MethodImplAttributes) reader.ReadInt16();
m_flags = (MethodAttributes) reader.ReadInt16();
m_name = parser.readIndexAsString ( reader );
signatureIndex = parser.readIndexAsForBlob( reader );
paramIndex = paramReader ( reader );
m_signature = SignatureMethod.Parse( parser, parser.getSignature( signatureIndex ) );
parser.SetParamIndex( this, paramIndex );
m_parent = parser.GetTypeFromMethodIndex( MetaData.UnpackTokenAsIndex( m_token ) );
m_parent.AddMethod( this );
}
//
// IMetaDataNormalize methods
//
Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context )
{
switch(context.Phase)
{
case MetaDataNormalizationPhase.CreationOfMethodDefinitions:
{
Normalized.MetaDataMethodBase mdNew;
Normalized.MetaDataTypeDefinitionBase owner = (Normalized.MetaDataTypeDefinitionBase)context.GetTypeFromContext();
if(m_genericParamList != null && m_genericParamList.Count > 0)
{
mdNew = new Normalized.MetaDataMethodGeneric( owner, m_token );
}
else
{
mdNew = new Normalized.MetaDataMethod( owner, m_token );
}
//--//
mdNew.m_implFlags = m_implFlags;
mdNew.m_flags = m_flags;
mdNew.m_name = m_name;
mdNew.m_maxStack = m_maxStack;
mdNew.m_initLocals = m_initLocals;
mdNew.m_debugInfo = m_debugInfo;
context = context.Push( mdNew );
if(mdNew is Normalized.MetaDataMethodGeneric)
{
Normalized.MetaDataMethodGeneric mdNewG = (Normalized.MetaDataMethodGeneric)mdNew;
context.GetNormalizedObjectList( m_genericParamList, out mdNewG.m_genericParams, MetaDataNormalizationMode.Default );
}
context.GetNormalizedSignature ( m_signature, out mdNew.m_signature, MetaDataNormalizationMode.Default );
context.GetNormalizedObjectList ( m_paramList, out mdNew.m_paramList, MetaDataNormalizationMode.Default );
context.GetNormalizedSignatureArray( m_locals , out mdNew.m_locals , MetaDataNormalizationMode.Default );
return mdNew;
}
}
throw context.InvalidPhase( this );
}
void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj ,
MetaDataNormalizationContext context )
{
Normalized.MetaDataMethodBase md = (Normalized.MetaDataMethodBase)obj;
context = context.Push( obj );
switch(context.Phase)
{
case MetaDataNormalizationPhase.CompletionOfMethodNormalization:
{
if(m_instructions != null)
{
md.m_instructions = new Normalized.Instruction[m_instructions.Length];
for(int i = 0; i < m_instructions.Length; i++)
{
md.m_instructions[i] = m_instructions[i].Normalize( context );
}
}
if(m_ehTable != null)
{
md.m_ehTable = new Normalized.EHClause[m_ehTable.Length];
for(int i = 0; i < m_ehTable.Length; i++)
{
md.m_ehTable[i] = m_ehTable[i].Normalize( context );
}
}
}
return;
case MetaDataNormalizationPhase.ResolutionOfCustomAttributes:
{
context.GetNormalizedObjectList( this.CustomAttributes, out md.m_customAttributes, MetaDataNormalizationMode.Allocate );
context.ProcessPhaseList( m_paramList );
}
return;
}
throw context.InvalidPhase( this );
}
//--//
// These are technically not constructor methods, but they are meant to
// be used to set up the object
internal void AddParam( MetaDataParam param )
{
if(m_paramList == null)
{
m_paramList = new List<MetaDataParam>( 2 );
}
if(m_paramList.Count > 0 && m_paramList[m_paramList.Count-1].Sequence >= param.Sequence)
{
throw IllegalMetaDataFormatException.Create( "Parameters out of order - is this allowed?" );
}
m_paramList.Add( param );
}
internal void AddGenericParam( MetaDataGenericParam genericParam )
{
if(m_genericParamList == null)
{
m_genericParamList = new List<MetaDataGenericParam>( 2 );
}
if(genericParam.Number != m_genericParamList.Count)
{
throw IllegalMetaDataFormatException.Create( "Generic parameters out of order - is this allowed?" );
}
m_genericParamList.Add( genericParam );
}
//--//
internal void loadInstructions( Parser mdLoader ,
PdbInfo.PdbFunction pdbFunction )
{
if(m_rva != 0)
{
if((m_flags & MethodAttributes.PinvokeImpl ) == 0 ||
(m_flags & MethodAttributes.UnmanagedExport) != 0 )
{
getInstructions( mdLoader, pdbFunction );
if(pdbFunction != null)
{
List<PdbInfo.PdbSlot> list = new List<PdbInfo.PdbSlot>();
pdbFunction.CollectSlots( list );
int max = -1;
foreach(PdbInfo.PdbSlot slot in list)
{
if(max < slot.Slot) max = (int)slot.Slot;
}
if(max >= 0)
{
String[] localVarNames = new String[this.Locals.Length];
foreach(PdbInfo.PdbSlot slot in list)
{
localVarNames[slot.Slot] = slot.Name;
}
m_debugInfo = new Debugging.MethodDebugInfo( localVarNames );
}
}
}
else
{
throw new NotImplementedException( "Not loading embedded native code for " + this );
}
}
}
//
// Access Methods
//
public List<MetaDataParam> ParamList
{
get
{
return m_paramList;
}
}
public List<MetaDataGenericParam> GenericParamList
{
get
{
return m_genericParamList;
}
}
public Instruction[] Instructions
{
get
{
return m_instructions;
}
}
public EHClause[] EHTable
{
get
{
return m_ehTable;
}
}
public int MaxStack
{
get
{
return m_maxStack;
}
}
public SignatureType[] Locals
{
get
{
return m_locals;
}
}
public MethodImplAttributes ImplFlags
{
get
{
return m_implFlags;
}
}
public MethodAttributes Flags
{
get
{
return m_flags;
}
}
public override string FullName
{
get
{
if(m_parent != null)
{
return m_parent.FullName + "." + this.Name;
}
else
{
return this.Name;
}
}
}
public override string FullNameWithContext
{
get
{
return "method " + this.FullName;
}
}
public string Name
{
get
{
return m_name;
}
}
public SignatureMethod Signature
{
get
{
return (SignatureMethod)m_signature;
}
}
public MetaDataTypeDefinition Parent
{
get
{
return m_parent;
}
}
public int Rva
{
get
{
return m_rva;
}
}
public bool IsEmpty
{
get
{
return (m_rva == 0);
}
}
public bool InitLocals
{
get
{
return m_initLocals;
}
}
//--//
public Debugging.MethodDebugInfo DebugInformation
{
get
{
return m_debugInfo;
}
}
//
// Debug Methods
//
public override string ToString()
{
return "MetaDataMethod(" + this.FullName + ")";
}
public override string ToStringLong()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataMethod(" );
if(m_genericParamList != null && m_genericParamList.Count > 0)
{
sb.Append( "GenericParams<" );
foreach(MetaDataGenericParam param in m_genericParamList)
{
sb.Append( param.ToString() );
sb.Append( "," );
}
sb.Remove( sb.Length - 1, 1 );
sb.Append( ">," );
}
sb.Append( m_rva );
sb.Append( "," );
sb.Append( m_implFlags.ToString( "x" ) );
sb.Append( "," );
sb.Append( m_flags.ToString( "x" ) );
sb.Append( "," );
if(m_parent != null)
{
sb.Append( m_parent.FullName );
sb.Append( "." );
}
sb.Append( m_name );
sb.Append( "," );
sb.Append( m_signature );
sb.Append( "," );
if(m_paramList == null || m_paramList.Count == 0)
{
sb.Append( "No parameters" );
}
else
{
sb.Append( "parameters(" );
foreach(MetaDataParam param in m_paramList)
{
sb.Append( param.ToString() );
sb.Append( "," );
}
sb.Remove( sb.Length - 1, 1 );
sb.Append( ")" );
}
sb.Append( ")" );
return sb.ToString();
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Collections;
namespace Axiom.Collections {
/// <summary>
/// Serves as a basis for strongly typed collections in the engine.
/// </summary>
/// <remarks>
/// Can't wait for Generics in .Net Framework 2.0!
/// </remarks>
public abstract class AxiomCollection : ICollection, IEnumerable {
/// <summary></summary>
protected SortedList objectList;
/// <summary></summary>
protected Object parent;
static protected int nextUniqueKeyCounter;
const int INITIAL_CAPACITY = 60;
#region Constructors
/// <summary>
///
/// </summary>
public AxiomCollection() {
this.parent = null;
objectList = new SortedList(INITIAL_CAPACITY);
}
/// <summary>
///
/// </summary>
/// <param name="parent"></param>
public AxiomCollection(Object parent) {
this.parent = parent;
objectList = new SortedList(INITIAL_CAPACITY);
}
#endregion
/// <summary>
///
/// </summary>
public object this[int index] {
get {
return objectList.GetByIndex(index);
}
set {
objectList.SetByIndex(index, value);
}
}
public ICollection Values { get{ return objectList.Values; } }
public ICollection Keys { get{ return objectList.Keys; } }
/// <summary>
///
/// </summary>
protected object this[object key] {
get { return objectList[key]; }
set { objectList[key] = value; }
}
/// <summary>
/// Accepts an unnamed object and names it manually.
/// </summary>
/// <param name="item"></param>
protected void Add(object item) {
objectList.Add("Object" + (nextUniqueKeyCounter++), item);
}
/// <summary>
/// Adds a named object to the collection.
/// </summary>
/// <param name="key"></param>
/// <param name="item"></param>
protected void Add(object key, object item) {
objectList.Add(key, item);
}
/// <summary>
/// Clears all objects from the collection.
/// </summary>
public void Clear() {
objectList.Clear();
}
/// <summary>
/// Removes the item from the collection.
/// </summary>
/// <param name="item"></param>
public virtual void Remove(object item) {
int index = objectList.IndexOfValue(item);
if(index != -1)
objectList.RemoveAt(index);
}
/// <summary>
/// Removes the item from the collection.
/// </summary>
/// <param name="item"></param>
public virtual void RemoveByKey(object item)
{
int index = objectList.IndexOfKey(item);
if(index != -1)
objectList.RemoveAt(index);
}
/// <summary>
/// Removes an item at the specified index.
/// </summary>
/// <param name="index"></param>
public void RemoveAt(int index) {
objectList.RemoveAt(index);
}
/// <summary>
/// Tests if there is a dupe entry in here.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool ContainsKey(object key) {
return objectList.ContainsKey(key);
}
#region Implementation of ICollection
public void CopyTo(System.Array array, int index) {
objectList.CopyTo(array, index);
}
public bool IsSynchronized {
get {
return objectList.IsSynchronized;
}
}
public int Count {
get {
return objectList.Count;
}
}
public object SyncRoot {
get {
return objectList.SyncRoot;
}
}
#endregion
#region Implementation of IEnumerable
public System.Collections.IEnumerator GetEnumerator() {
return objectList.Values.GetEnumerator();
}
#endregion
#region Implementation of IEnumerator
public class Enumerator : IEnumerator {
private int position = -1;
private AxiomCollection list;
public Enumerator(AxiomCollection list) {
this.list = list;
}
/// <summary>
/// Resets the in progress enumerator.
/// </summary>
public void Reset() {
// reset the enumerator position
position = -1;
}
/// <summary>
/// Moves to the next item in the enumeration if there is one.
/// </summary>
/// <returns></returns>
public bool MoveNext() {
position += 1;
if(position >= list.objectList.Count) {
return false;
}
else {
return true;
}
}
/// <summary>
/// Returns the current object in the enumeration.
/// </summary>
public object Current {
get {
return list.objectList.GetByIndex(position);
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Diagnostics.Tests
{
public class ProcessWaitingTests : ProcessTestBase
{
[Fact]
public void MultipleProcesses_StartAllKillAllWaitAll()
{
const int Iters = 10;
Process[] processes = Enumerable.Range(0, Iters).Select(_ => CreateProcessLong()).ToArray();
foreach (Process p in processes) p.Start();
foreach (Process p in processes) p.Kill();
foreach (Process p in processes) Assert.True(p.WaitForExit(WaitInMS));
}
[Fact]
public void MultipleProcesses_SerialStartKillWait()
{
const int Iters = 10;
for (int i = 0; i < Iters; i++)
{
Process p = CreateProcessLong();
p.Start();
p.Kill();
p.WaitForExit(WaitInMS);
}
}
[Fact]
public void MultipleProcesses_ParallelStartKillWait()
{
const int Tasks = 4, ItersPerTask = 10;
Action work = () =>
{
for (int i = 0; i < ItersPerTask; i++)
{
Process p = CreateProcessLong();
p.Start();
p.Kill();
p.WaitForExit(WaitInMS);
}
};
Task.WaitAll(Enumerable.Range(0, Tasks).Select(_ => Task.Run(work)).ToArray());
}
[Theory]
[InlineData(0)] // poll
[InlineData(10)] // real timeout
public void CurrentProcess_WaitNeverCompletes(int milliseconds)
{
Assert.False(Process.GetCurrentProcess().WaitForExit(milliseconds));
}
[Fact]
public void SingleProcess_TryWaitMultipleTimesBeforeCompleting()
{
Process p = CreateProcessLong();
p.Start();
// Verify we can try to wait for the process to exit multiple times
Assert.False(p.WaitForExit(0));
Assert.False(p.WaitForExit(0));
// Then wait until it exits and concurrently kill it.
// There's a race condition here, in that we really want to test
// killing it while we're waiting, but we could end up killing it
// before hand, in which case we're simply not testing exactly
// what we wanted to test, but everything should still work.
Task.Delay(10).ContinueWith(_ => p.Kill());
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.WaitForExit(0));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task SingleProcess_WaitAfterExited(bool addHandlerBeforeStart)
{
Process p = CreateProcessLong();
p.EnableRaisingEvents = true;
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
if (addHandlerBeforeStart)
{
p.Exited += delegate { tcs.SetResult(true); };
}
p.Start();
if (!addHandlerBeforeStart)
{
p.Exited += delegate { tcs.SetResult(true); };
}
p.Kill();
Assert.True(await tcs.Task);
Assert.True(p.WaitForExit(0));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(127)]
public async Task SingleProcess_EnableRaisingEvents_CorrectExitCode(int exitCode)
{
using (Process p = CreateProcessPortable(RemotelyInvokable.ExitWithCode, exitCode.ToString()))
{
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
p.EnableRaisingEvents = true;
p.Exited += delegate
{ tcs.SetResult(true); };
p.Start();
Assert.True(await tcs.Task);
Assert.Equal(exitCode, p.ExitCode);
}
}
[Fact]
public void SingleProcess_CopiesShareExitInformation()
{
Process p = CreateProcessLong();
p.Start();
Process[] copies = Enumerable.Range(0, 3).Select(_ => Process.GetProcessById(p.Id)).ToArray();
Assert.False(p.WaitForExit(0));
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
foreach (Process copy in copies)
{
Assert.True(copy.WaitForExit(0));
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Getting handle of child process running on UAP is not possible")]
public void WaitForPeerProcess()
{
Process child1 = CreateProcessLong();
child1.Start();
Process child2 = CreateProcess(peerId =>
{
Process peer = Process.GetProcessById(int.Parse(peerId));
Console.WriteLine("Signal");
Assert.True(peer.WaitForExit(WaitInMS));
return SuccessExitCode;
}, child1.Id.ToString());
child2.StartInfo.RedirectStandardOutput = true;
child2.Start();
char[] output = new char[6];
child2.StandardOutput.Read(output, 0, output.Length);
Assert.Equal("Signal", new string(output)); // wait for the signal before killing the peer
child1.Kill();
Assert.True(child1.WaitForExit(WaitInMS));
Assert.True(child2.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, child2.ExitCode);
}
[Fact]
public void WaitForSignal()
{
const string expectedSignal = "Signal";
const string successResponse = "Success";
const int timeout = 5 * 1000;
Process p = CreateProcessPortable(RemotelyInvokable.WriteLineReadLine);
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
var mre = new ManualResetEventSlim(false);
int linesReceived = 0;
p.OutputDataReceived += (s, e) =>
{
if (e.Data != null)
{
linesReceived++;
if (e.Data == expectedSignal)
{
mre.Set();
}
}
};
p.Start();
p.BeginOutputReadLine();
Assert.True(mre.Wait(timeout));
Assert.Equal(1, linesReceived);
// Wait a little bit to make sure process didn't exit on itself
Thread.Sleep(100);
Assert.False(p.HasExited, "Process has prematurely exited");
using (StreamWriter writer = p.StandardInput)
{
writer.WriteLine(successResponse);
}
Assert.True(p.WaitForExit(timeout), "Process has not exited");
Assert.Equal(RemotelyInvokable.SuccessExitCode, p.ExitCode);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Not applicable on uap - RemoteInvoke does not give back process handle")]
[ActiveIssue(15844, TestPlatforms.AnyUnix)]
public void WaitChain()
{
Process root = CreateProcess(() =>
{
Process child1 = CreateProcess(() =>
{
Process child2 = CreateProcess(() =>
{
Process child3 = CreateProcess(() => SuccessExitCode);
child3.Start();
Assert.True(child3.WaitForExit(WaitInMS));
return child3.ExitCode;
});
child2.Start();
Assert.True(child2.WaitForExit(WaitInMS));
return child2.ExitCode;
});
child1.Start();
Assert.True(child1.WaitForExit(WaitInMS));
return child1.ExitCode;
});
root.Start();
Assert.True(root.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, root.ExitCode);
}
[Fact]
public void WaitForSelfTerminatingChild()
{
Process child = CreateProcessPortable(RemotelyInvokable.SelfTerminate);
child.Start();
Assert.True(child.WaitForExit(WaitInMS));
Assert.NotEqual(SuccessExitCode, child.ExitCode);
}
[Fact]
public void WaitForInputIdle_NotDirected_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.WaitForInputIdle());
}
[Fact]
public void WaitForExit_NotDirected_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.WaitForExit());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using Xunit;
using Microsoft.Xunit.Performance;
namespace System.Text.Primitives.Tests
{
public partial class PrimitiveParserPerfTests
{
private static readonly string[] s_UInt32TextArray = new string[10]
{
"42",
"429496",
"429496729",
"42949",
"4",
"42949672",
"4294",
"429",
"4294967295",
"4294967"
};
private static readonly string[] s_UInt32TextArrayHex = new string[8]
{
"A2",
"A29496",
"A2949",
"A",
"A2949672",
"A294",
"A29",
"A294967"
};
[Benchmark]
[InlineData("2134567890")] // standard parse
[InlineData("4294967295")] // max value
[InlineData("0")] // min value
private static void BaselineSimpleByteStarToUInt32(string text)
{
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
uint.TryParse(text, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
[Benchmark]
private static void BaselineSimpleByteStarToUInt32_VariableLength()
{
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
uint.TryParse(s_UInt32TextArray[i % 10], out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
[Benchmark]
[InlineData("2134567890")] // standard parse
[InlineData("4294967295")] // max value
[InlineData("0")] // min value
private static void BaselineByteStarToUInt32(string text)
{
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
uint.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
[Benchmark]
private static void BaselineByteStarToUInt32_VariableLength()
{
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
uint.TryParse(s_UInt32TextArray[i % 10], NumberStyles.None, CultureInfo.InvariantCulture, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
[Benchmark]
[InlineData("abcdef")] // standard parse
[InlineData("ffffffff")] // max value
[InlineData("0")] // min value
private static void BaselineByteStarToUInt32Hex(string text)
{
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
uint.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
[Benchmark]
private static void BaselineByteStarToUInt32Hex_VariableLength()
{
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
uint.TryParse(s_UInt32TextArrayHex[i % 8], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
[Benchmark]
[InlineData("2134567890")] // standard parse
[InlineData("4294967295")] // max value
[InlineData("0")] // min value
private unsafe static void PrimitiveParserByteStarToUInt32(string text)
{
int length = text.Length;
byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text);
foreach (var iteration in Benchmark.Iterations)
{
fixed (byte* utf8ByteStar = utf8ByteArray)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteStar, length, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
}
[Benchmark]
private unsafe static void PrimitiveParserByteStarToUInt32_VariableLength()
{
List<byte[]> byteArrayList = new List<byte[]>();
foreach (string text in s_UInt32TextArray)
{
byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text);
byteArrayList.Add(utf8ByteArray);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
byte[] utf8ByteArray = byteArrayList[i % 10];
fixed (byte* utf8ByteStar = utf8ByteArray)
{
uint value;
PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteStar, utf8ByteArray.Length, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
}
[Benchmark]
[InlineData("2134567890")] // standard parse
[InlineData("4294967295")] // max value
[InlineData("0")] // min value
private unsafe static void PrimitiveParserByteStarToUInt32_BytesConsumed(string text)
{
int length = text.Length;
byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text);
foreach (var iteration in Benchmark.Iterations)
{
fixed (byte* utf8ByteStar = utf8ByteArray)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
int bytesConsumed;
PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteStar, length, out value, out bytesConsumed);
TestHelper.DoNotIgnore(value, bytesConsumed);
}
}
}
}
}
[Benchmark]
private unsafe static void PrimitiveParserByteStarToUInt32_BytesConsumed_VariableLength()
{
List<byte[]> byteArrayList = new List<byte[]>();
foreach (string text in s_UInt32TextArray)
{
byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text);
byteArrayList.Add(utf8ByteArray);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
byte[] utf8ByteArray = byteArrayList[i % 10];
fixed (byte* utf8ByteStar = utf8ByteArray)
{
uint value;
int bytesConsumed;
PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteStar, utf8ByteArray.Length, out value, out bytesConsumed);
TestHelper.DoNotIgnore(value, bytesConsumed);
}
}
}
}
}
[Benchmark]
[InlineData("2134567890")] // standard parse
[InlineData("4294967295")] // max value
[InlineData("0")] // min value
private unsafe static void PrimitiveParserByteSpanToUInt32(string text)
{
byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text);
var utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteSpan, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
[Benchmark]
private unsafe static void PrimitiveParserByteSpanToUInt32_VariableLength()
{
int textLength = s_UInt32TextArray.Length;
byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength);
for (var i = 0; i < textLength; i++)
{
utf8ByteArray[i] = Text.Encoding.UTF8.GetBytes(s_UInt32TextArray[i]);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength];
uint value;
PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteSpan, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
[Benchmark]
[InlineData("2134567890")] // standard parse
[InlineData("4294967295")] // max value
[InlineData("0")] // min value
private unsafe static void PrimitiveParserByteSpanToUInt32_BytesConsumed(string text)
{
byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text);
var utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
int bytesConsumed;
PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteSpan, out value, out bytesConsumed);
TestHelper.DoNotIgnore(value, bytesConsumed);
}
}
}
}
[Benchmark]
private unsafe static void PrimitiveParserByteSpanToUInt32_BytesConsumed_VariableLength()
{
int textLength = s_UInt32TextArray.Length;
byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength);
for (var i = 0; i < textLength; i++)
{
utf8ByteArray[i] = Text.Encoding.UTF8.GetBytes(s_UInt32TextArray[i]);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength];
uint value;
int bytesConsumed;
PrimitiveParser.InvariantUtf8.TryParseUInt32(utf8ByteSpan, out value, out bytesConsumed);
TestHelper.DoNotIgnore(value, bytesConsumed);
}
}
}
}
[Benchmark]
[InlineData("abcdef")] // standard parse
[InlineData("ffffffff")] // max value
[InlineData("0")] // min value
private unsafe static void PrimitiveParserByteStarToUInt32Hex(string text)
{
int length = text.Length;
byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text);
foreach (var iteration in Benchmark.Iterations)
{
fixed (byte* utf8ByteStar = utf8ByteArray)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteStar, length, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
}
[Benchmark]
private unsafe static void PrimitiveParserByteStarToUInt32Hex_VariableLength()
{
List<byte[]> byteArrayList = new List<byte[]>();
foreach (string text in s_UInt32TextArrayHex)
{
byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text);
byteArrayList.Add(utf8ByteArray);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
byte[] utf8ByteArray = byteArrayList[i % 8];
fixed (byte* utf8ByteStar = utf8ByteArray)
{
uint value;
PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteStar, utf8ByteArray.Length, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
}
[Benchmark]
[InlineData("abcdef")] // standard parse
[InlineData("ffffffff")] // max value
[InlineData("0")] // min value
private unsafe static void PrimitiveParserByteStarToUInt32Hex_BytesConsumed(string text)
{
int length = text.Length;
byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text);
foreach (var iteration in Benchmark.Iterations)
{
fixed (byte* utf8ByteStar = utf8ByteArray)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
int bytesConsumed;
PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteStar, length, out value, out bytesConsumed);
TestHelper.DoNotIgnore(value, bytesConsumed);
}
}
}
}
}
[Benchmark]
private unsafe static void PrimitiveParserByteStarToUInt32Hex_BytesConsumed_VariableLength()
{
List<byte[]> byteArrayList = new List<byte[]>();
foreach (string text in s_UInt32TextArrayHex)
{
byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text);
byteArrayList.Add(utf8ByteArray);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
byte[] utf8ByteArray = byteArrayList[i % 8];
fixed (byte* utf8ByteStar = utf8ByteArray)
{
uint value;
int bytesConsumed;
PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteStar, utf8ByteArray.Length, out value, out bytesConsumed);
TestHelper.DoNotIgnore(value, bytesConsumed);
}
}
}
}
}
[Benchmark]
[InlineData("abcdef")] // standard parse
[InlineData("ffffffff")] // max value
[InlineData("0")] // min value
private unsafe static void PrimitiveParserByteSpanToUInt32Hex(string text)
{
byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text);
var utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteSpan, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
[Benchmark]
private unsafe static void PrimitiveParserByteSpanToUInt32Hex_VariableLength()
{
int textLength = s_UInt32TextArrayHex.Length;
byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength);
for (var i = 0; i < textLength; i++)
{
utf8ByteArray[i] = Text.Encoding.UTF8.GetBytes(s_UInt32TextArrayHex[i]);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength];
uint value;
PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteSpan, out value);
TestHelper.DoNotIgnore(value, 0);
}
}
}
}
[Benchmark]
[InlineData("abcdef")] // standard parse
[InlineData("ffffffff")] // max value
[InlineData("0")] // min value
private unsafe static void PrimitiveParserByteSpanToUInt32Hex_BytesConsumed(string text)
{
byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text);
var utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
uint value;
int bytesConsumed;
PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteSpan, out value, out bytesConsumed);
TestHelper.DoNotIgnore(value, bytesConsumed);
}
}
}
}
[Benchmark]
private unsafe static void PrimitiveParserByteSpanToUInt32Hex_BytesConsumed_VariableLength()
{
int textLength = s_UInt32TextArrayHex.Length;
byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength);
for (var i = 0; i < textLength; i++)
{
utf8ByteArray[i] = Text.Encoding.UTF8.GetBytes(s_UInt32TextArrayHex[i]);
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < TestHelper.LoadIterations; i++)
{
ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength];
uint value;
int bytesConsumed;
PrimitiveParser.InvariantUtf8.Hex.TryParseUInt32(utf8ByteSpan, out value, out bytesConsumed);
TestHelper.DoNotIgnore(value, bytesConsumed);
}
}
}
}
}
}
| |
using System;
using UnityEngine;
namespace Zios{
using System.Collections.Generic;
public enum ColorBlend{
Normal,
Add,
Balance,
Darken,
Multiply,
ColorBurn,
LinearBurn,
//DarkerColor,
Lighten,
Screen,
ColorDodge,
LinearDodge,
//LighterColor,
Overlay,
SoftLight,
//HardLight,
VividLight,
LinearLight,
PinLight,
HardMix,
Difference,
Exclusion,
Subtract,
Divide,
//Hue,
//Saturation,
//Color,
//Luminosity
}
public static class ColorExtension{
public static Color Lerp(this Color current,Color other,float amount,bool lerpAlpha=true){
var result = new Color();
result.r = Mathf.Lerp(current.r,other.r,amount);
result.g = Mathf.Lerp(current.g,other.g,amount);
result.b = Mathf.Lerp(current.b,other.b,amount);
if(lerpAlpha){result.a = Mathf.Lerp(current.a,other.a,amount);}
return result;
}
public static bool Matches(this Color current,Color other,bool matchAlpha=true){
return matchAlpha ? current == other : (current.r == other.r && current.g == other.g && current.b == other.b);
}
public static Color Blend(this Color current,string name,float amount=1){
var mode = EnumExtension.Parse<ColorBlend>(name);
return current.Blend(current,mode,amount);
}
public static Color Blend(this Color current,Color target,string name,float amount=1){
var mode = EnumExtension.Parse<ColorBlend>(name);
return current.Blend(target,mode,amount);
}
public static Color Blend(this Color current,Color target,ColorBlend mode,float amount=1){
var white = Color.white;
var value = Color.cyan;
Func<float,float,float> formula = null;
if(mode.Matches("Balance")){
value = current;
var luma = current.GetLuminance();
var otherLuma = target.GetLuminance();
var difference = (luma-otherLuma).Abs();
if(difference <= 0.3f){value = current.Add(luma < 0.3f ? 0.5f : -0.5f);}
}
else if(mode.Matches("Darken")){value = current.Min(target);}
else if(mode.Matches("Multiply")){value = current * target;}
else if(mode.Matches("ColorBurn")){
var blend = current.Invert().Divide(target);
value = blend.Invert();
}
else if(mode.Matches("LinearBurn")){value = current+target-white;}
else if(mode.Matches("DarkerColor")){}
else if(mode.Matches("Lighten")){value = current.Max(target);}
else if(mode.Matches("Screen")){value = white-current.Invert()*target.Invert();}
else if(mode.Matches("ColorDodge")){value = current.Divide(target.Invert());}
else if(mode.Matches("Add") || mode.Matches("LinearDodge")){value = current + target;}
else if(mode.Matches("LighterColor")){}
else if(mode.Matches("Overlay")){formula = (a,b)=>{return a < 0.5f ? 2*a*b : 1 - (2 * (1-a) * (1-b));};}
else if(mode.Matches("SoftLight")){formula = (a,b)=>{return b < 0.5f ? 2*a*b+a+a*(1-2*b) : Math.Sqrt(a).ToFloat() * (2*b-1) + 2*a*(1-b);};}
else if(mode.Matches("HardLight")){}
else if(mode.MatchesAny("VividLight","LinearLight","PinLight")){
ColorBlend modeA = ColorBlend.ColorBurn;
ColorBlend modeB = ColorBlend.ColorDodge;
if(mode.Matches("LinearLight")){
modeA = ColorBlend.LinearBurn;
modeB = ColorBlend.LinearDodge;
}
if(mode.Matches("PinLight")){
modeA = ColorBlend.Darken;
modeB = ColorBlend.Lighten;
}
var blendA = current.Blend(2*target,modeA);
var blendB = current.Blend(2*(target-(white*0.5f)),modeB);
value.r = target.r < 0.5f ? blendA.r : blendB.r;
value.g = target.g < 0.5f ? blendA.g : blendB.g;
value.b = target.b < 0.5f ? blendA.b : blendB.b;
}
else if(mode.Matches("HardMix")){
var blend = current.Blend(target,ColorBlend.VividLight);
value.r = blend.r < 0.5f ? 0 : 1;
value.g = blend.g < 0.5f ? 0 : 1;
value.b = blend.b < 0.5f ? 0 : 1;
}
else if(mode.Matches("Difference")){value = (current-target).Abs();}
else if(mode.Matches("Exclusion")){value = (current + target - 2.0f * current * target);}
else if(mode.Matches("Subtract")){value = target-current;}
else if(mode.Matches("Divide")){value = target.Divide(current);}
else if(mode.Matches("Hue")){}
else if(mode.Matches("Saturation")){}
else if(mode.Matches("Color")){}
else if(mode.Matches("Luminosity")){}
if(!formula.IsNull()){
value.r = formula(current.r,target.r);
value.g = formula(current.g,target.g);
value.b = formula(current.b,target.b);
}
return current.Lerp(value.Saturate(),amount);
}
public static float Difference(this Color current,Color other){
return (current.GetLuminance()-other.GetLuminance()).Abs();
}
public static Color Saturate(this Color current){
return current.Max(Color.black).Min(Color.white);
}
public static Vector4 ToVector4(this Color current){
return new Vector4(current.r,current.g,current.b,current.a);
}
public static Vector3 ToVector3(this Color current){
return new Vector3(current.r,current.g,current.b);
}
public static Color Abs(this Color current){
current.r = Mathf.Abs(current.r);
current.g = Mathf.Abs(current.g);
current.b = Mathf.Abs(current.b);
return current;
}
public static Color Min(this Color current,Color other){
current.r = Mathf.Min(current.r,other.r);
current.g = Mathf.Min(current.g,other.g);
current.b = Mathf.Min(current.b,other.b);
current.a = Mathf.Min(current.a,other.a);
return current;
}
public static Color Max(this Color current,Color other){
current.r = Mathf.Max(current.r,other.r);
current.g = Mathf.Max(current.g,other.g);
current.b = Mathf.Max(current.b,other.b);
current.a = Mathf.Max(current.a,other.a);
return current;
}
public static Color Add(this Color current,Color amount){
current.r = Mathf.Clamp(current.r+amount.r,0,1);
current.g = Mathf.Clamp(current.g+amount.g,0,1);
current.b = Mathf.Clamp(current.b+amount.b,0,1);
return current;
}
public static Color Add(this Color current,float amount){
return current.Add(new Color(amount,amount,amount));
}
public static Color Subtract(this Color current,Color amount){
current.r = Mathf.Clamp(current.r-amount.r,0,1);
current.g = Mathf.Clamp(current.g-amount.g,0,1);
current.b = Mathf.Clamp(current.b-amount.b,0,1);
return current;
}
public static Color Subtract(this Color current,float amount){
return current.Subtract(new Color(amount,amount,amount));
}
public static Color Multiply(this Color current,Color amount){
current.r = Mathf.Clamp(current.r*amount.r,0,1);
current.g = Mathf.Clamp(current.g*amount.g,0,1);
current.b = Mathf.Clamp(current.b*amount.b,0,1);
return current;
}
public static Color Multiply(this Color current,float amount){
return current.Multiply(new Color(amount,amount,amount));
}
public static Color Divide(this Color current,Color amount){
current.r = Mathf.Clamp(current.r/amount.r,0,1);
current.g = Mathf.Clamp(current.g/amount.g,0,1);
current.b = Mathf.Clamp(current.b/amount.b,0,1);
return current;
}
public static Color Divide(this Color current,float amount){
return current.Divide(new Color(amount,amount,amount));
}
public static Color Flatten(this Color current){
current.r *= current.a;
current.g *= current.a;
current.b *= current.a;
current.a = 1;
return current;
}
public static Color Set(this Color current,float r,float g=-1,float b=-1,float a=-1){
if(r!=-1){current.r = r;}
if(g!=-1){current.g = g;}
if(b!=-1){current.b = b;}
if(a!=-1){current.a = a;}
return current;
}
public static Color SetAlpha(this Color current,float a){
current.a = a;
return current;
}
public enum ColorOrder{RGBA,ARGB,BGRA,ABGR};
public static Color Order(this Color current,string orderText){
var order = orderText.ToEnum<ColorOrder>();
return current.Order(order);
}
public static Color Order(this Color current,ColorOrder order){
var r = current.r;
var g = current.g;
var b = current.b;
var a = current.a;
if(order==ColorOrder.BGRA){return new Color(b,g,r,a);}
if(order==ColorOrder.ARGB){return new Color(a,r,g,b);}
if(order==ColorOrder.ABGR){return new Color(a,b,g,r);}
return current;
}
public static Color Random(this Color current,float intensity=1.0f){
int[] order = (new List<int>(){0,1,2}).Shuffle().ToArray();
float[] color = new float[3];
color[order[0]] = UnityEngine.Random.Range(intensity,1.0f);
color[order[1]] = UnityEngine.Random.Range(0,1.0f - intensity);
color[order[2]] = UnityEngine.Random.Range(0,1.0f);
return new Color(color[0],color[1],color[2]);
}
public static string ToHex(this Color current,bool alwaysAlpha=true){
var red = (current.r*255).ToInt().ToString("X2");
var green = (current.g*255).ToInt().ToString("X2");
var blue = (current.b*255).ToInt().ToString("X2");
var alpha = (current.a*255).ToInt().ToString("X2");
if(alpha == "FF" && !alwaysAlpha){alpha = "";}
return "#"+red+green+blue+alpha;
}
public static string ToDecimal(this Color current,bool alwaysAlpha=true){
var red = (current.r*255).ToInt();
var green = (current.g*255).ToInt();
var blue = (current.b*255).ToInt();
var alpha = " " + (current.a*255).ToInt();
if(alpha==" 255" && !alwaysAlpha){alpha = "";}
return red+" "+green+" "+blue+alpha;
}
public static string Serialize(this Color current){
return current.ToHex(false);
}
public static Color Deserialize(this Color current,string value){
return value.ToColor("-");
}
public static float GetIntensity(this Color current){
return (current.r+current.g+current.b)/3;
}
public static float GetLuminance(this Color current){
return 0.2126f*current.r + 0.7152f*current.g + 0.0722f*current.b;
}
public static Color Invert(this Color current){
var color = new Color();
color.r = 1 - current.r;
color.g = 1 - current.b;
color.b = 1 - current.g;
color.a = current.a;
return color;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Storage
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for CheckNameAvailabilityOperations.
/// </summary>
public static partial class CheckNameAvailabilityOperationsExtensions
{
/// <summary>
/// Checks that the account name has sufficient cowbell (in order to prevent
/// fevers).
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
public static CheckNameAvailabilityResult CheckNameAvailability(this ICheckNameAvailabilityOperations operations, StorageAccountCheckNameAvailabilityParameters accountName)
{
return operations.CheckNameAvailabilityAsync(accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Checks that the account name has sufficient cowbell (in order to prevent
/// fevers).
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CheckNameAvailabilityResult> CheckNameAvailabilityAsync(this ICheckNameAvailabilityOperations operations, StorageAccountCheckNameAvailabilityParameters accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Asynchronously creates a new storage account with the specified parameters.
/// Existing accounts cannot be updated with this API and should instead use
/// the Update Storage Account API. If an account is already created and
/// subsequent PUT request is issued with exact same set of properties, then
/// HTTP 200 would be returned. Make sure you add that extra cowbell.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to provide for the created account.
/// </param>
public static StorageAccount Create(this ICheckNameAvailabilityOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters)
{
return operations.CreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Asynchronously creates a new storage account with the specified parameters.
/// Existing accounts cannot be updated with this API and should instead use
/// the Update Storage Account API. If an account is already created and
/// subsequent PUT request is issued with exact same set of properties, then
/// HTTP 200 would be returned. Make sure you add that extra cowbell.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to provide for the created account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageAccount> CreateAsync(this ICheckNameAvailabilityOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a storage account in Microsoft Azure.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
public static void Delete(this ICheckNameAvailabilityOperations operations, string resourceGroupName, string accountName)
{
operations.DeleteAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a storage account in Microsoft Azure.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ICheckNameAvailabilityOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Returns the properties for the specified storage account including but not
/// limited to name, account type, location, and account status. The ListKeys
/// operation should be used to retrieve storage keys.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
public static StorageAccount GetProperty(this ICheckNameAvailabilityOperations operations, string resourceGroupName, string accountName)
{
return operations.GetPropertyAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns the properties for the specified storage account including but not
/// limited to name, account type, location, and account status. The ListKeys
/// operation should be used to retrieve storage keys.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageAccount> GetPropertyAsync(this ICheckNameAvailabilityOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPropertyWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the account type or tags for a storage account. It can also be used
/// to add a custom domain (note that custom domains cannot be added via the
/// Create operation). Only one custom domain is supported per storage account.
/// In order to replace a custom domain, the old value must be cleared before a
/// new value may be set. To clear a custom domain, simply update the custom
/// domain with empty string. Then call update again with the new cutsom domain
/// name. The update API can only be used to update one of tags, accountType,
/// or customDomain per call. To update multiple of these properties, call the
/// API multiple times with one change per call. This call does not change the
/// storage keys for the account. If you want to change storage account keys,
/// use the RegenerateKey operation. The location and name of the storage
/// account cannot be changed after creation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to update on the account. Note that only one property can be
/// changed at a time using this API.
/// </param>
public static StorageAccount Update(this ICheckNameAvailabilityOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters)
{
return operations.UpdateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the account type or tags for a storage account. It can also be used
/// to add a custom domain (note that custom domains cannot be added via the
/// Create operation). Only one custom domain is supported per storage account.
/// In order to replace a custom domain, the old value must be cleared before a
/// new value may be set. To clear a custom domain, simply update the custom
/// domain with empty string. Then call update again with the new cutsom domain
/// name. The update API can only be used to update one of tags, accountType,
/// or customDomain per call. To update multiple of these properties, call the
/// API multiple times with one change per call. This call does not change the
/// storage keys for the account. If you want to change storage account keys,
/// use the RegenerateKey operation. The location and name of the storage
/// account cannot be changed after creation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to update on the account. Note that only one property can be
/// changed at a time using this API.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageAccount> UpdateAsync(this ICheckNameAvailabilityOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the access keys for the specified storage account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the storage account.
/// </param>
public static StorageAccountKeys ListKeys(this ICheckNameAvailabilityOperations operations, string resourceGroupName, string accountName)
{
return operations.ListKeysAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the access keys for the specified storage account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the storage account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageAccountKeys> ListKeysAsync(this ICheckNameAvailabilityOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the storage accounts available under the subscription. Note that
/// storage keys are not returned; use the ListKeys operation for this.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IEnumerable<StorageAccount> List(this ICheckNameAvailabilityOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the storage accounts available under the subscription. Note that
/// storage keys are not returned; use the ListKeys operation for this.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<StorageAccount>> ListAsync(this ICheckNameAvailabilityOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the storage accounts available under the given resource group.
/// Note that storage keys are not returned; use the ListKeys operation for
/// this.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
public static IEnumerable<StorageAccount> ListByResourceGroup(this ICheckNameAvailabilityOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the storage accounts available under the given resource group.
/// Note that storage keys are not returned; use the ListKeys operation for
/// this.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<StorageAccount>> ListByResourceGroupAsync(this ICheckNameAvailabilityOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerates the access keys for the specified storage account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
/// <param name='regenerateKey'>
/// Specifies name of the key which should be regenerated. key1 or key2 for the
/// default keys
/// </param>
public static StorageAccountKeys RegenerateKey(this ICheckNameAvailabilityOperations operations, string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey)
{
return operations.RegenerateKeyAsync(resourceGroupName, accountName, regenerateKey).GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the access keys for the specified storage account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
/// <param name='regenerateKey'>
/// Specifies name of the key which should be regenerated. key1 or key2 for the
/// default keys
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageAccountKeys> RegenerateKeyAsync(this ICheckNameAvailabilityOperations operations, string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, accountName, regenerateKey, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
public static partial class VirtualMachineImagesOperationsExtensions
{
/// <summary>
/// Gets a virtual machine image.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// </param>
/// <param name='publisherName'>
/// </param>
/// <param name='offer'>
/// </param>
/// <param name='skus'>
/// </param>
/// <param name='version'>
/// </param>
public static VirtualMachineImage Get(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, string version)
{
return Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).GetAsync(location, publisherName, offer, skus, version), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a virtual machine image.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// </param>
/// <param name='publisherName'>
/// </param>
/// <param name='offer'>
/// </param>
/// <param name='skus'>
/// </param>
/// <param name='version'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachineImage> GetAsync( this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, string version, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.GetWithHttpMessagesAsync(location, publisherName, offer, skus, version, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// Gets a list of virtual machine images.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// </param>
/// <param name='publisherName'>
/// </param>
/// <param name='offer'>
/// </param>
/// <param name='skus'>
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IList<VirtualMachineImageResource> List(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, ODataQuery<VirtualMachineImageResource> odataQuery = default(ODataQuery<VirtualMachineImageResource>))
{
return Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).ListAsync(location, publisherName, offer, skus, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of virtual machine images.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// </param>
/// <param name='publisherName'>
/// </param>
/// <param name='offer'>
/// </param>
/// <param name='skus'>
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<VirtualMachineImageResource>> ListAsync( this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, string skus, ODataQuery<VirtualMachineImageResource> odataQuery = default(ODataQuery<VirtualMachineImageResource>), CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ListWithHttpMessagesAsync(location, publisherName, offer, skus, odataQuery, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// Gets a list of virtual machine image offers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// </param>
/// <param name='publisherName'>
/// </param>
public static IList<VirtualMachineImageResource> ListOffers(this IVirtualMachineImagesOperations operations, string location, string publisherName)
{
return Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).ListOffersAsync(location, publisherName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of virtual machine image offers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// </param>
/// <param name='publisherName'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<VirtualMachineImageResource>> ListOffersAsync( this IVirtualMachineImagesOperations operations, string location, string publisherName, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ListOffersWithHttpMessagesAsync(location, publisherName, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// Gets a list of virtual machine image publishers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// </param>
public static IList<VirtualMachineImageResource> ListPublishers(this IVirtualMachineImagesOperations operations, string location)
{
return Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).ListPublishersAsync(location), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of virtual machine image publishers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<VirtualMachineImageResource>> ListPublishersAsync( this IVirtualMachineImagesOperations operations, string location, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ListPublishersWithHttpMessagesAsync(location, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
/// <summary>
/// Gets a list of virtual machine image skus.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// </param>
/// <param name='publisherName'>
/// </param>
/// <param name='offer'>
/// </param>
public static IList<VirtualMachineImageResource> ListSkus(this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer)
{
return Task.Factory.StartNew(s => ((IVirtualMachineImagesOperations)s).ListSkusAsync(location, publisherName, offer), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of virtual machine image skus.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// </param>
/// <param name='publisherName'>
/// </param>
/// <param name='offer'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<VirtualMachineImageResource>> ListSkusAsync( this IVirtualMachineImagesOperations operations, string location, string publisherName, string offer, CancellationToken cancellationToken = default(CancellationToken))
{
var _result = await operations.ListSkusWithHttpMessagesAsync(location, publisherName, offer, null, cancellationToken).ConfigureAwait(false);
return _result.Body;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="AOTSupportUtilities.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>
//-----------------------------------------------------------------------
#if UNITY_EDITOR
namespace Stratus.OdinSerializer.Editor
{
using Stratus.OdinSerializer.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Scripting;
public static class AOTSupportUtilities
{
/// <summary>
/// Scans the project's build scenes and resources, plus their dependencies, for serialized types to support. Progress bars are shown during the scan.
/// </summary>
/// <param name="serializedTypes">The serialized types to support.</param>
/// <param name="scanBuildScenes">Whether to scan the project's build scenes.</param>
/// <param name="scanAllAssetBundles">Whether to scan all the project's asset bundles.</param>
/// <param name="scanPreloadedAssets">Whether to scan the project's preloaded assets.</param>
/// <param name="scanResources">Whether to scan the project's resources.</param>
/// <param name="resourcesToScan">An optional list of the resource paths to scan. Only has an effect if the scanResources argument is true. All the resources will be scanned if null.</param>
/// <returns>true if the scan succeeded, false if the scan failed or was cancelled</returns>
public static bool ScanProjectForSerializedTypes(out List<Type> serializedTypes, bool scanBuildScenes = true, bool scanAllAssetBundles = true, bool scanPreloadedAssets = true, bool scanResources = true, List<string> resourcesToScan = null)
{
using (var scanner = new AOTSupportScanner())
{
scanner.BeginScan();
if (scanBuildScenes && !scanner.ScanBuildScenes(includeSceneDependencies: true, showProgressBar: true))
{
Debug.Log("Project scan canceled while scanning scenes and their dependencies.");
serializedTypes = null;
return false;
}
if (scanResources && !scanner.ScanAllResources(includeResourceDependencies: true, showProgressBar: true, resourcesPaths: resourcesToScan))
{
Debug.Log("Project scan canceled while scanning resources and their dependencies.");
serializedTypes = null;
return false;
}
if (scanAllAssetBundles && !scanner.ScanAllAssetBundles(showProgressBar: true))
{
Debug.Log("Project scan canceled while scanning asset bundles and their dependencies.");
serializedTypes = null;
return false;
}
if (scanPreloadedAssets && !scanner.ScanPreloadedAssets(showProgressBar: true))
{
Debug.Log("Project scan canceled while scanning preloaded assets and their dependencies.");
serializedTypes = null;
return false;
}
serializedTypes = scanner.EndScan();
}
return true;
}
/// <summary>
/// Generates an AOT DLL, using the given parameters.
/// </summary>
public static void GenerateDLL(string dirPath, string assemblyName, List<Type> supportSerializedTypes, bool generateLinkXml = true)
{
if (!dirPath.EndsWith("/")) dirPath += "/";
var newDllPath = dirPath + assemblyName;
var fullDllPath = newDllPath + ".dll";
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName() { Name = assemblyName }, AssemblyBuilderAccess.Save, dirPath);
var module = assembly.DefineDynamicModule(assemblyName);
assembly.SetCustomAttribute(new CustomAttributeBuilder(typeof(EmittedAssemblyAttribute).GetConstructor(new Type[0]), new object[0]));
// The following is a fix for Unity's crappy Mono runtime that doesn't know how to do this sort
// of stuff properly
//
// We must manually remove the "Default Dynamic Assembly" module that is automatically defined,
// otherwise a reference to that non-existent module will be saved into the assembly's IL, and
// that will cause a multitude of issues.
//
// We do this by forcing there to be only one module - the one we just defined, and we set the
// manifest module to be that module as well.
{
var modulesField = assembly.GetType().GetField("modules", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var manifestModuleField = assembly.GetType().GetField("manifest_module", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (modulesField != null)
{
modulesField.SetValue(assembly, new ModuleBuilder[] { module });
}
if (manifestModuleField != null)
{
manifestModuleField.SetValue(assembly, module);
}
}
var type = module.DefineType(assemblyName + ".PreventCodeStrippingViaReferences", TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.NotPublic);
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(typeof(PreserveAttribute).GetConstructor(Type.EmptyTypes), new object[0]);
type.SetCustomAttribute(attributeBuilder);
var staticConstructor = type.DefineTypeInitializer();
var il = staticConstructor.GetILGenerator();
var falseLocal = il.DeclareLocal(typeof(bool));
il.Emit(OpCodes.Ldc_I4_0); // Load false
il.Emit(OpCodes.Stloc, falseLocal); // Set to falseLocal
HashSet<Type> seenTypes = new HashSet<Type>();
if (UnityVersion.Major == 2019 && UnityVersion.Minor == 2)
{
// This here is a hack that fixes Unity's assembly updater triggering faultily in Unity 2019.2
// (and in early 2019.3 alphas/betas, but we're not handling those). When it triggers, it edits
// the generated AOT assembly such that it immediately causes Unity to hard crash. Having this
// type reference present in the assembly prevents that from happening. (Any concrete type in
// the serialization assembly would work, this one is just a random pick.)
//
// Unity should have fixed this in 2019.3, but said that a backport to 2019.2 is not guaranteed
// to occur, though it might.
supportSerializedTypes.Add(typeof(DateTimeFormatter));
}
//var endPoint = il.DefineLabel();
//il.Emit(OpCodes.Br, endPoint);
foreach (var serializedType in supportSerializedTypes)
{
if (serializedType == null) continue;
bool isAbstract = serializedType.IsAbstract || serializedType.IsInterface;
if (serializedType.IsGenericType && (serializedType.IsGenericTypeDefinition || !serializedType.IsFullyConstructedGenericType()))
{
Debug.LogError("Skipping type '" + serializedType.GetNiceFullName() + "'! Type is a generic type definition, or its arguments contain generic parameters; type must be a fully constructed generic type.");
continue;
}
if (seenTypes.Contains(serializedType)) continue;
seenTypes.Add(serializedType);
// Reference serialized type
{
if (serializedType.IsValueType)
{
var local = il.DeclareLocal(serializedType);
il.Emit(OpCodes.Ldloca, local);
il.Emit(OpCodes.Initobj, serializedType);
}
else if (!isAbstract)
{
var constructor = serializedType.GetConstructor(Type.EmptyTypes);
if (constructor != null)
{
il.Emit(OpCodes.Newobj, constructor);
il.Emit(OpCodes.Pop);
}
}
}
// Reference and/or create formatter type
if (!FormatterUtilities.IsPrimitiveType(serializedType) && !typeof(UnityEngine.Object).IsAssignableFrom(serializedType) && !isAbstract)
{
var actualFormatter = FormatterLocator.GetFormatter(serializedType, SerializationPolicies.Unity);
if (actualFormatter.GetType().IsDefined<EmittedFormatterAttribute>())
{
//TODO: Make emitted formatter code compatible with IL2CPP
//// Emit an actual AOT formatter into the generated assembly
//if (this.emitAOTFormatters)
//{
// var emittedFormatter = FormatterEmitter.EmitAOTFormatter(typeEntry.Type, module, SerializationPolicies.Unity);
// var emittedFormatterConstructor = emittedFormatter.GetConstructor(Type.EmptyTypes);
// il.Emit(OpCodes.Newobj, emittedFormatterConstructor);
// il.Emit(OpCodes.Pop);
//}
}
var formatters = FormatterLocator.GetAllCompatiblePredefinedFormatters(serializedType, SerializationPolicies.Unity);
foreach (var formatter in formatters)
{
// Reference the pre-existing formatter
var formatterConstructor = formatter.GetType().GetConstructor(Type.EmptyTypes);
if (formatterConstructor != null)
{
il.Emit(OpCodes.Newobj, formatterConstructor);
il.Emit(OpCodes.Pop);
}
}
//// Make sure we have a proper reflection formatter variant if all else goes wrong
//il.Emit(OpCodes.Newobj, typeof(ReflectionFormatter<>).MakeGenericType(serializedType).GetConstructor(Type.EmptyTypes));
//il.Emit(OpCodes.Pop);
}
ConstructorInfo serializerConstructor;
// Reference serializer variant
if (serializedType.IsValueType)
{
serializerConstructor = Serializer.Get(serializedType).GetType().GetConstructor(Type.EmptyTypes);
il.Emit(OpCodes.Newobj, serializerConstructor);
// The following section is a fix for an issue on IL2CPP for PS4, where sometimes bytecode isn't
// generated for methods in base types of needed types - FX, Serializer<T>.ReadValueWeak()
// may be missing. This only seems to happen in a relevant way for value types.
{
var endLabel = il.DefineLabel();
// Load a false local value, then jump to the end of this segment of code due to that
// false value. This is an attempt to trick any potential code flow analysis made
// by IL2CPP that checks whether this segment of code is actually run.
//
// We don't run the code because if we did, that would actually throw a bunch of
// exceptions from invalid calls to ReadValueWeak and WriteValueWeak.
il.Emit(OpCodes.Ldloc, falseLocal);
il.Emit(OpCodes.Brfalse, endLabel);
var baseSerializerType = typeof(Serializer<>).MakeGenericType(serializedType);
var readValueWeakMethod = baseSerializerType.GetMethod("ReadValueWeak", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, new Type[] { typeof(IDataReader) }, null);
var writeValueWeakMethod = baseSerializerType.GetMethod("WriteValueWeak", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, new Type[] { typeof(string), typeof(object), typeof(IDataWriter) }, null);
il.Emit(OpCodes.Dup); // Duplicate serializer instance
il.Emit(OpCodes.Ldnull); // Load null argument for IDataReader reader
il.Emit(OpCodes.Callvirt, readValueWeakMethod); // Call ReadValueWeak on serializer instance
il.Emit(OpCodes.Pop); // Pop result of ReadValueWeak
il.Emit(OpCodes.Dup); // Duplicate serializer instance
il.Emit(OpCodes.Ldnull); // Load null argument for string name
il.Emit(OpCodes.Ldnull); // Load null argument for object value
il.Emit(OpCodes.Ldnull); // Load null argument for IDataWriter writer
il.Emit(OpCodes.Callvirt, writeValueWeakMethod); // Call WriteValueWeak on serializer instance
il.MarkLabel(endLabel); // This is where the code always jumps to, skipping the above
}
il.Emit(OpCodes.Pop); // Pop the serializer instance
}
else
{
serializerConstructor = typeof(ComplexTypeSerializer<>).MakeGenericType(serializedType).GetConstructor(Type.EmptyTypes);
il.Emit(OpCodes.Newobj, serializerConstructor);
il.Emit(OpCodes.Pop);
}
}
//il.MarkLabel(endPoint);
il.Emit(OpCodes.Ret);
type.CreateType();
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
if (File.Exists(fullDllPath))
{
File.Delete(fullDllPath);
}
if (File.Exists(fullDllPath + ".meta"))
{
File.Delete(fullDllPath + ".meta");
}
try
{
AssetDatabase.Refresh();
}
catch (Exception)
{
// Sigh, Unity 5.3.0
}
assembly.Save(assemblyName);
File.Move(newDllPath, fullDllPath);
if (generateLinkXml)
{
File.WriteAllText(dirPath + "link.xml",
@"<linker>
<assembly fullname=""" + assemblyName + @""" preserve=""all""/>
</linker>");
}
try
{
AssetDatabase.Refresh();
}
catch (Exception)
{
// Sigh, Unity 5.3.0
}
var pluginImporter = PluginImporter.GetAtPath(fullDllPath) as PluginImporter;
if (pluginImporter != null)
{
//pluginImporter.ClearSettings();
pluginImporter.SetCompatibleWithEditor(false);
pluginImporter.SetCompatibleWithAnyPlatform(true);
// Disable for all standalones
pluginImporter.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false);
pluginImporter.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false);
pluginImporter.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false);
// StandaloneOSXUniversal (<= 2017.2) / StandaloneOSX (>= 2017.3)
pluginImporter.SetCompatibleWithPlatform((BuildTarget)2, false);
if (!UnityVersion.IsVersionOrGreater(2017, 3))
{
pluginImporter.SetCompatibleWithPlatform((BuildTarget)4, false); // StandaloneOSXIntel
pluginImporter.SetCompatibleWithPlatform((BuildTarget)27, false); // StandaloneOSXIntel64
}
pluginImporter.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false);
pluginImporter.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false);
//pluginImporter.SetCompatibleWithPlatform(BuildTarget.Android, false);
pluginImporter.SaveAndReimport();
}
AssetDatabase.SaveAssets();
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
namespace System.Xml
{
public class XmlNamespaceManager : IXmlNamespaceResolver, IEnumerable
{
private struct NamespaceDeclaration
{
public string prefix;
public string uri;
public int scopeId;
public int previousNsIndex;
public void Set(string prefix, string uri, int scopeId, int previousNsIndex)
{
this.prefix = prefix;
this.uri = uri;
this.scopeId = scopeId;
this.previousNsIndex = previousNsIndex;
}
}
// array with namespace declarations
private NamespaceDeclaration[] _nsdecls;
// index of last declaration
private int _lastDecl = 0;
// name table
private XmlNameTable _nameTable;
// ID (depth) of the current scope
private int _scopeId;
// hash table for faster lookup when there is lots of namespaces
private Dictionary<string, int> _hashTable;
private bool _useHashtable;
// atomized prefixes for "xml" and "xmlns"
private string _xml;
private string _xmlNs;
// Constants
private const int MinDeclsCountForHashtable = 16;
public XmlNamespaceManager(XmlNameTable nameTable)
{
_nameTable = nameTable;
_xml = nameTable.Add("xml");
_xmlNs = nameTable.Add("xmlns");
_nsdecls = new NamespaceDeclaration[8];
string emptyStr = nameTable.Add(string.Empty);
_nsdecls[0].Set(emptyStr, emptyStr, -1, -1);
_nsdecls[1].Set(_xmlNs, nameTable.Add(XmlReservedNs.NsXmlNs), -1, -1);
_nsdecls[2].Set(_xml, nameTable.Add(XmlReservedNs.NsXml), 0, -1);
_lastDecl = 2;
_scopeId = 1;
}
public virtual XmlNameTable NameTable
{
get
{
return _nameTable;
}
}
public virtual string DefaultNamespace
{
get
{
string defaultNs = LookupNamespace(string.Empty);
return (defaultNs == null) ? string.Empty : defaultNs;
}
}
public virtual void PushScope()
{
_scopeId++;
}
public virtual bool PopScope()
{
int decl = _lastDecl;
if (_scopeId == 1)
{
return false;
}
while (_nsdecls[decl].scopeId == _scopeId)
{
if (_useHashtable)
{
_hashTable[_nsdecls[decl].prefix] = _nsdecls[decl].previousNsIndex;
}
decl--;
Debug.Assert(decl >= 2);
}
_lastDecl = decl;
_scopeId--;
return true;
}
public virtual void AddNamespace(string prefix, string uri)
{
if (uri == null)
throw new ArgumentNullException("uri");
if (prefix == null)
throw new ArgumentNullException("prefix");
prefix = _nameTable.Add(prefix);
uri = _nameTable.Add(uri);
if ((Ref.Equal(_xml, prefix) && !uri.Equals(XmlReservedNs.NsXml)))
{
throw new ArgumentException(SR.Xml_XmlPrefix);
}
if (Ref.Equal(_xmlNs, prefix))
{
throw new ArgumentException(SR.Xml_XmlnsPrefix);
}
int declIndex = LookupNamespaceDecl(prefix);
int previousDeclIndex = -1;
if (declIndex != -1)
{
if (_nsdecls[declIndex].scopeId == _scopeId)
{
// redefine if in the same scope
_nsdecls[declIndex].uri = uri;
return;
}
else
{
// othewise link
previousDeclIndex = declIndex;
}
}
// set new namespace declaration
if (_lastDecl == _nsdecls.Length - 1)
{
NamespaceDeclaration[] newNsdecls = new NamespaceDeclaration[_nsdecls.Length * 2];
Array.Copy(_nsdecls, 0, newNsdecls, 0, _nsdecls.Length);
_nsdecls = newNsdecls;
}
_nsdecls[++_lastDecl].Set(prefix, uri, _scopeId, previousDeclIndex);
// add to hashTable
if (_useHashtable)
{
_hashTable[prefix] = _lastDecl;
}
// or create a new hashTable if the threashold has been reached
else if (_lastDecl >= MinDeclsCountForHashtable)
{
// add all to hash table
Debug.Assert(_hashTable == null);
_hashTable = new Dictionary<string, int>(_lastDecl);
for (int i = 0; i <= _lastDecl; i++)
{
_hashTable[_nsdecls[i].prefix] = i;
}
_useHashtable = true;
}
}
public virtual void RemoveNamespace(string prefix, string uri)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
if (prefix == null)
{
throw new ArgumentNullException("prefix");
}
int declIndex = LookupNamespaceDecl(prefix);
while (declIndex != -1)
{
if (String.Equals(_nsdecls[declIndex].uri, uri) && _nsdecls[declIndex].scopeId == _scopeId)
{
_nsdecls[declIndex].uri = null;
}
declIndex = _nsdecls[declIndex].previousNsIndex;
}
}
public virtual IEnumerator GetEnumerator()
{
Dictionary<string, string> prefixes = new Dictionary<string, string>(_lastDecl + 1);
for (int thisDecl = 0; thisDecl <= _lastDecl; thisDecl++)
{
if (_nsdecls[thisDecl].uri != null)
{
prefixes[_nsdecls[thisDecl].prefix] = _nsdecls[thisDecl].prefix;
}
}
return prefixes.Keys.GetEnumerator();
}
// This pragma disables a warning that the return type is not CLS-compliant, but generics are part of CLS in Whidbey.
#pragma warning disable 3002
public virtual IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
#pragma warning restore 3002
int i = 0;
switch (scope)
{
case XmlNamespaceScope.All:
i = 2;
break;
case XmlNamespaceScope.ExcludeXml:
i = 3;
break;
case XmlNamespaceScope.Local:
i = _lastDecl;
while (_nsdecls[i].scopeId == _scopeId)
{
i--;
Debug.Assert(i >= 2);
}
i++;
break;
}
Dictionary<string, string> dict = new Dictionary<string, string>(_lastDecl - i + 1);
for (; i <= _lastDecl; i++)
{
string prefix = _nsdecls[i].prefix;
string uri = _nsdecls[i].uri;
Debug.Assert(prefix != null);
if (uri != null)
{
if (uri.Length > 0 || prefix.Length > 0 || scope == XmlNamespaceScope.Local)
{
dict[prefix] = uri;
}
else
{
// default namespace redeclared to "" -> remove from list for all scopes other than local
dict.Remove(prefix);
}
}
}
return dict;
}
public virtual string LookupNamespace(string prefix)
{
int declIndex = LookupNamespaceDecl(prefix);
return (declIndex == -1) ? null : _nsdecls[declIndex].uri;
}
private int LookupNamespaceDecl(string prefix)
{
if (_useHashtable)
{
int declIndex;
if (_hashTable.TryGetValue(prefix, out declIndex))
{
while (declIndex != -1 && _nsdecls[declIndex].uri == null)
{
declIndex = _nsdecls[declIndex].previousNsIndex;
}
return declIndex;
}
return -1;
}
else
{
// First assume that prefix is atomized
for (int thisDecl = _lastDecl; thisDecl >= 0; thisDecl--)
{
if ((object)_nsdecls[thisDecl].prefix == (object)prefix && _nsdecls[thisDecl].uri != null)
{
return thisDecl;
}
}
// Non-atomized lookup
for (int thisDecl = _lastDecl; thisDecl >= 0; thisDecl--)
{
if (String.Equals(_nsdecls[thisDecl].prefix, prefix) && _nsdecls[thisDecl].uri != null)
{
return thisDecl;
}
}
}
return -1;
}
public virtual string LookupPrefix(string uri)
{
// Don't assume that prefix is atomized
for (int thisDecl = _lastDecl; thisDecl >= 0; thisDecl--)
{
if (String.Equals(_nsdecls[thisDecl].uri, uri))
{
string prefix = _nsdecls[thisDecl].prefix;
if (String.Equals(LookupNamespace(prefix), uri))
{
return prefix;
}
}
}
return null;
}
public virtual bool HasNamespace(string prefix)
{
// Don't assume that prefix is atomized
for (int thisDecl = _lastDecl; _nsdecls[thisDecl].scopeId == _scopeId; thisDecl--)
{
if (String.Equals(_nsdecls[thisDecl].prefix, prefix) && _nsdecls[thisDecl].uri != null)
{
if (prefix.Length > 0 || _nsdecls[thisDecl].uri.Length > 0)
{
return true;
}
return false;
}
}
return false;
}
} //XmlNamespaceManager
}
| |
#region copyright
// VZF
// Copyright (C) 2014-2016 Vladimir Zakharov
//
// http://www.code.coolhobby.ru/
// File DB.cs created on 2.6.2015 in 6:31 AM.
// Last changed on 5.21.2016 in 1:12 PM.
// 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
namespace YAF.Providers.Profile
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.IO;
using System.Text;
using VZF.Data.Common;
using VZF.Data.DAL;
using VZF.Data.MySql.Mappers;
using VZF.Data.Utils;
using YAF.Classes;
using YAF.Classes.Pattern;
public class MySQLDB
{
public static MySQLDB Current
{
get
{
return PageSingleton<MySQLDB>.Instance;
}
}
#region Utilities
private static int PackProfileData(SettingsPropertyValueCollection collection, bool isAuthenticated,
ref string index, ref string stringData, ref byte[] binaryData)
{
bool itemsToSave = false;
// first we need to determine if there are any items that need saving
// this is an optimization
foreach (SettingsPropertyValue value in collection)
{
if (!value.IsDirty) continue;
if (value.Property.Attributes["AllowAnonymous"].Equals(false) &&
!isAuthenticated) continue;
itemsToSave = true;
break;
}
if (!itemsToSave) return 0;
StringBuilder indexBuilder = new StringBuilder();
StringBuilder stringDataBuilder = new StringBuilder();
MemoryStream binaryBuilder = new MemoryStream();
int count = 0;
// ok, we have some values that need to be saved so we go back through
foreach (SettingsPropertyValue value in collection)
{
// if the value has not been written to and is still using the default value
// no need to save it
if (value.UsingDefaultValue && !value.IsDirty) continue;
// we don't save properties that require the user to be authenticated when the
// current user is not authenticated.
if (value.Property.Attributes["AllowAnonymous"].Equals(false) &&
!isAuthenticated) continue;
count++;
object propValue = value.SerializedValue;
if ((value.Deserialized && value.PropertyValue == null) ||
value.SerializedValue == null)
indexBuilder.AppendFormat("{0}//0/-1:", value.Name);
else if (propValue is string)
{
indexBuilder.AppendFormat("{0}/0/{1}/{2}:", value.Name,
stringDataBuilder.Length, (propValue as string).Length);
stringDataBuilder.Append(propValue);
}
else
{
byte[] binaryValue = (byte[])propValue;
indexBuilder.AppendFormat("{0}/1/{1}/{2}:", value.Name,
binaryBuilder.Position, binaryValue.Length);
binaryBuilder.Write(binaryValue, 0, binaryValue.Length);
}
}
index = indexBuilder.ToString();
stringData = stringDataBuilder.ToString();
binaryData = binaryBuilder.ToArray();
return count;
}
public static void UnpackProfileData(DataRow profileRow, SettingsPropertyValueCollection values)
{
byte[] binaryData = null;
string indexData = null;
string stringData = null;
indexData = profileRow["valueindex"].ToString();
stringData = profileRow["stringData"].ToString();
if (profileRow["binaryData"] != DBNull.Value)
{
binaryData = (byte[])profileRow["binaryData"];
}
string[] indexes = indexData.Split(':');
foreach (string index in indexes)
{
string[] parts = index.Split('/');
SettingsPropertyValue value = values[parts[0]];
if (value == null)
{
continue;
}
int pos = int.Parse(parts[2], CultureInfo.InvariantCulture);
int len = int.Parse(parts[3], CultureInfo.InvariantCulture);
if (len == -1)
{
value.PropertyValue = null;
value.IsDirty = false;
value.Deserialized = true;
}
else if (parts[1].Equals("0"))
{
value.SerializedValue = stringData.Substring(pos, len);
}
else
{
byte[] buf = new byte[len];
Buffer.BlockCopy(binaryData, pos, buf, 0, len);
value.SerializedValue = buf;
}
}
}
#endregion
public DataTable GetProfiles(string connectionStringName, object appName, object pageIndex, object pageSize, object userNameToMatch, object inactiveSinceDate)
{
int TotalCountNew = 0;
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_PageIndex", pageIndex));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_PageSize", pageSize));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserNameToMatch", userNameToMatch));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_InactiveSinceDate", inactiveSinceDate));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_TotalCount", TotalCountNew, ParameterDirection.Output));
sc.CommandText.AppendObjectQuery("prov_profile_getprofiles", connectionStringName);
var dt = sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false);
TotalCountNew = (int)sc.Parameters["i_TotalCount"].Value;
if (dt.Rows.Count > 0) dt.Rows[0]["TotalCount"] = TotalCountNew;
return dt;
}
}
public DataTable GetProfileStructure(string connectionStringName)
{
return CommonDb.GetProfileStructure(connectionStringName, "prov_Profile");
}
/// <summary>
/// The add profile column.
/// </summary>
/// <param name="connectionStringName">
/// The connection string name.
/// </param>
/// <param name="name">
/// The name.
/// </param>
/// <param name="type">
/// The type.
/// </param>
/// <param name="size">
/// The size.
/// </param>
public void AddProfileColumn(string connectionStringName, string name, string type, int size)
{
type = DataTypeMappers.typeToDbValueMap(name, type, size);
if (type.ToLowerInvariant().Contains("varchar") && Config.DatabaseEncoding != null)
{
type += " CHARACTER SET " + Config.DatabaseEncoding;
if (Config.DatabaseCollation != null)
{
type += " COLLATE " + Config.DatabaseEncoding + "_" + Config.DatabaseCollation;
}
}
using (var sc = new VzfSqlCommand(connectionStringName))
{
string sql = string.Format("ALTER TABLE {0} ADD `{1}` {2};", SqlDbAccess.GetVzfObjectNameFromConnectionString("prov_Profile", connectionStringName), name, type);
sc.CommandText.AppendQuery(sql);
sc.ExecuteNonQuery(CommandType.Text, false);
}
}
public object GetProviderUserKey(string ConnectionStringName, object appName, object username)
{
DataRow row = YAF.Providers.Membership.MySQLDB.Current.GetUser(ConnectionStringName, appName.ToString(), null, username.ToString(), false);
if (row != null)
{
return row["UserID"];
}
return null;
}
public void SetProfilePropertiesOld(string connectionStringName, object appName, object userID, SettingsPropertyValueCollection values, List<SettingsPropertyColumn> settingsColumnsList)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
bool profileExists = false;
string table =
SqlDbAccess.GetVzfObjectNameFromConnectionString("prov_Profile", connectionStringName);
using (var sc1 = new VzfSqlCommand(connectionStringName))
{
// cmd.Parameters.Add(new FbParameter("@I_USERID", FbDbType.VarChar)).Value = userID;
sc1.CommandText.AppendQuery(string.Format("SELECT COUNT(1) FROM {0} WHERE UserID =UNHEX(REPLACE('{1}','-',''));", table, MySqlHelpers.GuidConverter(new Guid(userID.ToString())).ToString()));
profileExists = Convert.ToBoolean(sc1.ExecuteScalar(CommandType.Text, false));
}
StringBuilder MySqlCommandTextMain =
new StringBuilder("");
sc.Parameters.Add(sc.CreateParameter(DbType.String, "?i_UserID", MySqlHelpers.GuidConverter(new Guid(userID.ToString())).ToString()));
// Build up strings used in the query
StringBuilder columnStr = new StringBuilder();
StringBuilder valueStr = new StringBuilder();
StringBuilder setStr = new StringBuilder();
int count = 0;
foreach (SettingsPropertyColumn column in settingsColumnsList)
{
// only write if it's dirty
if (values[column.Settings.Name].IsDirty)
{
columnStr.Append(", ");
valueStr.Append(", ");
columnStr.Append(column.Settings.Name);
string valueParam = "?Value" + count;
valueStr.Append(valueParam);
sc.Parameters.Add(sc.CreateParameter(column.DataType, valueParam, values[column.Settings.Name].PropertyValue));
if (column.DataType != DbType.DateTime)
{
if (count > 0)
{
setStr.Append(",");
}
setStr.Append(column.Settings.Name);
setStr.Append("=");
setStr.Append(valueParam);
}
count++;
}
}
columnStr.Append(",LastUpdatedDate ");
valueStr.Append(",?LastUpdatedDate");
setStr.Append(",LastUpdatedDate=?LastUpdatedDate");
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "?LastUpdatedDate", DateTime.UtcNow));
if (profileExists)
{
MySqlCommandTextMain.Append(" UPDATE ").Append(table).Append(" SET ").Append(setStr.ToString());
MySqlCommandTextMain.Append(" WHERE UserID =UNHEX(REPLACE(@i_UserID,'-',''))");
MySqlCommandTextMain.Append(";");
}
else
{
MySqlCommandTextMain.Append("INSERT INTO ").Append(table).Append(" (UserID").Append(columnStr.ToString());
MySqlCommandTextMain.Append(") VALUES (UNHEX(REPLACE(@i_UserID,'-',''))").Append(valueStr.ToString()).Append(");");
}
sc.Parameters.Add(sc.CreateParameter(DbType.String, "@i_UserID", MySqlHelpers.GuidConverter(new Guid(userID.ToString())).ToString()));
sc.CommandText.AppendQuery(MySqlCommandTextMain.ToString());
sc.ExecuteNonQuery(CommandType.Text, false);
}
}
public void SetProfileProperties(string connectionStringName, object appName, object userID, SettingsPropertyValueCollection values, List<SettingsPropertyColumn> settingsColumnsList)
{
if (YAF.Classes.Config.GetConfigValueAsBool("YAF.OldProfileProvider", true))
SetProfilePropertiesOld(connectionStringName, appName, userID, values, settingsColumnsList);
// Apply here new profile properties
SettingsContext sctxt = new SettingsContext();
sctxt.Add("IsAuthenticated", true);
sctxt.Add("UserID", userID);
sctxt.Add("ApplicationName", appName);
bool isAuthenticated = true;
if (string.IsNullOrEmpty(userID.ToString())) return;
if (values.Count < 1) return;
string index = string.Empty;
string stringData = string.Empty;
byte[] binaryData = null;
if (PackProfileData(values, isAuthenticated, ref index, ref stringData, ref binaryData) < 1) return;
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_userId", MySqlHelpers.GuidConverter(new Guid(userID.ToString())).ToString()));
sc.Parameters.Add(sc.CreateParameter(DbType.Binary, "I_index", index));
sc.Parameters.Add(sc.CreateParameter(DbType.Binary, "I_stringdata", stringData));
sc.Parameters.Add(sc.CreateParameter(DbType.Binary, "I_binarydata", binaryData));
// cmd.Parameters.Add(new FbParameter("@I_USERID", FbDbType.VarChar)).Value = userID;
sc.CommandText.AppendObjectQuery("prov_setprofileproperties", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure, false);
}
// EOF 'apply new profile properties'
}
public int DeleteProfiles(string connectionStringName, object appName, object userNames)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName)); ;
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_UserNames", userNames));
sc.CommandText.AppendObjectQuery("prov_profile_deleteprofiles", connectionStringName);
return Convert.ToInt32(sc.ExecuteScalar(CommandType.StoredProcedure, false));
}
}
public int DeleteInactiveProfiles(string connectionStringName, object appName, object inactiveSinceDate)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_InactiveSinceDate", inactiveSinceDate));
sc.CommandText.AppendObjectQuery("prov_profile_deleteinactive", connectionStringName);
return Convert.ToInt32(sc.ExecuteScalar(CommandType.StoredProcedure, false));
}
}
public int GetNumberInactiveProfiles(string connectionStringName, object appName, object inactiveSinceDate)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_ApplicationName", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_InactiveSinceDate", inactiveSinceDate));
sc.CommandText.AppendObjectQuery("prov_profile_getnumberinactiveprofiles", connectionStringName);
return Convert.ToInt32(sc.ExecuteScalar(CommandType.StoredProcedure, false));
}
}
}
}
| |
#region Copyright
/*
Copyright 2014 Cluster Reply s.r.l.
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
/// -----------------------------------------------------------------------------------------------------------
/// Module : FileAdapterInboundHandler.cs
/// Description : This class implements an interface for listening or polling for data.
/// -----------------------------------------------------------------------------------------------------------
///
#region Using Directives
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.ServiceModel.Channels.Common;
using System.Collections.Concurrent;
using System.Threading;
using System.IO;
using System.ServiceModel.Channels;
using Reply.Cluster.Mercury.Adapters.Helpers;
#endregion
namespace Reply.Cluster.Mercury.Adapters.File
{
public class FileAdapterInboundHandler : FileAdapterHandlerBase, IInboundHandler
{
private class FileItem
{
public FileItem(string path, FileStream stream)
{
Path = path;
Stream = stream;
}
public string Path { get; private set; }
public FileStream Stream { get; private set; }
}
/// <summary>
/// Initializes a new instance of the FileAdapterInboundHandler class
/// </summary>
public FileAdapterInboundHandler(FileAdapterConnection connection
, MetadataLookup metadataLookup)
: base(connection, metadataLookup)
{
connectionUri = connection.ConnectionFactory.ConnectionUri;
pollingType = connection.ConnectionFactory.Adapter.PollingType;
if (pollingType == PollingType.Event || pollingType == PollingType.Simple)
{
if (pollingType == PollingType.Event)
{
watcher = new FileSystemWatcher(connectionUri.Path, connectionUri.FileName);
watcher.Changed += FileEvent;
}
pollingInterval = connection.ConnectionFactory.Adapter.PollingInterval;
pollingTimer = new Timer(new TimerCallback(t => GetFiles()));
}
else
scheduleName = connection.ConnectionFactory.Adapter.ScheduleName;
}
#region Private Fields
private FileAdapterConnectionUri connectionUri;
private FileSystemWatcher watcher;
private PollingType pollingType;
private int pollingInterval;
private Timer pollingTimer;
private string scheduleName;
private BlockingCollection<FileItem> queue = new BlockingCollection<FileItem>();
private CancellationTokenSource cancelSource = new CancellationTokenSource();
#endregion Private Fields
#region IInboundHandler Members
/// <summary>
/// Start the listener
/// </summary>
public void StartListener(string[] actions, TimeSpan timeout)
{
if (pollingType == PollingType.Event || pollingType == PollingType.Simple)
{
pollingTimer.Change(0, pollingInterval * 1000);
if (pollingType == PollingType.Event)
watcher.EnableRaisingEvents = true;
}
else
ScheduleHelper.RegisterEvent(scheduleName, () => GetFiles());
}
/// <summary>
/// Stop the listener
/// </summary>
public void StopListener(TimeSpan timeout)
{
if (pollingType == PollingType.Event || pollingType == PollingType.Simple)
{
pollingTimer.Change(Timeout.Infinite, Timeout.Infinite);
if (pollingType == PollingType.Event)
watcher.EnableRaisingEvents = false;
}
else
ScheduleHelper.CancelEvent(scheduleName);
queue.CompleteAdding();
cancelSource.Cancel();
}
/// <summary>
/// Tries to receive a message within a specified interval of time.
/// </summary>
public bool TryReceive(TimeSpan timeout, out System.ServiceModel.Channels.Message message, out IInboundReply reply)
{
reply = null;
message = null;
if (queue.IsCompleted)
return false;
FileItem item = null;
bool result = queue.TryTake(out item, (int)Math.Min(timeout.TotalMilliseconds, (long)int.MaxValue), cancelSource.Token);
if (result)
{
message = ByteStreamMessage.CreateMessage(item.Stream);
message.Headers.Action = new UriBuilder(item.Path).Uri.ToString();
reply = new FileAdapterInboundReply(item.Path, item.Stream);
}
return result;
}
/// <summary>
/// Returns a value that indicates whether a message has arrived within a specified interval of time.
/// </summary>
public bool WaitForMessage(TimeSpan timeout)
{
return true;
}
#endregion IInboundHandler Members
#region IDisposable Members
protected override void Dispose(bool disposing)
{
if (disposing)
watcher.Dispose();
base.Dispose(disposing);
}
#endregion
#region Private Members
private void GetFiles()
{
var files = Directory.GetFiles(connectionUri.Path, connectionUri.FileName);
foreach (string file in files)
AddFileToQueue(file);
}
private void FileEvent(object sender, FileSystemEventArgs e)
{
AddFileToQueue(e.FullPath);
}
private void AddFileToQueue(string path)
{
try
{
if (System.IO.File.Exists(path))
{
var stream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Delete);
queue.Add(new FileItem(path, stream));
}
}
catch (IOException) { }
}
#endregion
}
internal class FileAdapterInboundReply : InboundReply
{
private FileStream stream;
private string path;
public FileAdapterInboundReply(string path, FileStream stream)
{
this.path = path;
this.stream = stream;
}
#region InboundReply Members
/// <summary>
/// Abort the inbound reply call
/// </summary>
public override void Abort()
{
stream.Close();
}
/// <summary>
/// Reply message implemented
/// </summary>
public override void Reply(System.ServiceModel.Channels.Message message
, TimeSpan timeout)
{
System.IO.File.Delete(path);
stream.Close();
}
#endregion InboundReply Members
}
}
| |
//Authors: Roman Ivantsov, Philipp Serr
using System;
using System.Collections.Generic;
using System.Text;
using Irony.Parsing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Irony.Tests {
[TestClass]
public class NumberLiteralTests : TerminalTestsBase {
[TestMethod]
public void GeneralTest() {
NumberLiteral number = new NumberLiteral("Number");
number.DefaultIntTypes = new TypeCode[] { TypeCode.Int32, TypeCode.Int64, NumberLiteral.TypeCodeBigInt };
SetTerminal(number);
TryMatch("123");
CheckType(typeof(int));
Assert.IsTrue((int)_token.Value == 123, "Failed to read int value");
TryMatch("123.4");
Assert.IsTrue(Math.Abs(Convert.ToDouble(_token.Value) - 123.4) < 0.000001, "Failed to read float value");
//100 digits
string sbig = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
TryMatch(sbig);
Assert.IsTrue(_token.Value.ToString() == sbig, "Failed to read big integer value");
}//method
//The following "sign" test methods and a fix are contributed by ashmind codeplex user
[TestMethod]
public void TestSignedDoesNotMatchSingleMinus() {
var number = new NumberLiteral("number", NumberOptions.AllowSign);
SetTerminal(number);
TryMatch("-");
Assert.IsNull(_token, "Parsed single '-' as a number value.");
}
[TestMethod]
public void TestSignedDoesNotMatchSinglePlus() {
var number = new NumberLiteral("number", NumberOptions.AllowSign);
SetTerminal(number);
TryMatch("+");
Assert.IsNull(_token, "Parsed single '+' as a number value.");
}
[TestMethod]
public void TestSignedMatchesNegativeCorrectly() {
var number = new NumberLiteral("number", NumberOptions.AllowSign);
SetTerminal(number);
TryMatch("-500");
Assert.AreEqual(-500, _token.Value, "Negative number was parsed incorrectly; expected: {0}, scanned: {1}", "-500", _token.Value);
}
[TestMethod]
public void TestCSharpNumber() {
double eps = 0.0001;
SetTerminal(TerminalFactory.CreateCSharpNumber("Number"));
//Simple integers and suffixes
TryMatch("123 ");
CheckType(typeof(int));
Assert.IsTrue(_token.Details != null, "ScanDetails object not found in token.");
Assert.IsTrue((int)_token.Value == 123, "Failed to read int value");
TryMatch(Int32.MaxValue.ToString());
CheckType(typeof(int));
Assert.IsTrue((int)_token.Value == Int32.MaxValue, "Failed to read Int32.MaxValue.");
TryMatch(UInt64.MaxValue.ToString());
CheckType(typeof(ulong));
Assert.IsTrue((ulong)_token.Value == UInt64.MaxValue, "Failed to read int value");
TryMatch("123U ");
CheckType(typeof(UInt32));
Assert.IsTrue((UInt32)_token.Value == 123, "Failed to read uint value");
TryMatch("123L ");
CheckType(typeof(long));
Assert.IsTrue((long)_token.Value == 123, "Failed to read long value");
TryMatch("123uL ");
CheckType(typeof(ulong));
Assert.IsTrue((ulong)_token.Value == 123, "Failed to read ulong value");
//Hex representation
TryMatch("0x012 ");
CheckType(typeof(Int32));
Assert.IsTrue((Int32)_token.Value == 0x012, "Failed to read hex int value");
TryMatch("0x12U ");
CheckType(typeof(UInt32));
Assert.IsTrue((UInt32)_token.Value == 0x012, "Failed to read hex uint value");
TryMatch("0x012L ");
CheckType(typeof(long));
Assert.IsTrue((long)_token.Value == 0x012, "Failed to read hex long value");
TryMatch("0x012uL ");
CheckType(typeof(ulong));
Assert.IsTrue((ulong)_token.Value == 0x012, "Failed to read hex ulong value");
//Floating point types
TryMatch("123.4 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #1");
TryMatch("1234e-1 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 1234e-1) < eps, "Failed to read double value #2");
TryMatch("12.34e+01 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #3");
TryMatch("0.1234E3 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #4");
TryMatch("123.4f ");
CheckType(typeof(float));
Assert.IsTrue(Math.Abs((Single)_token.Value - 123.4) < eps, "Failed to read float(single) value");
TryMatch("123.4m ");
CheckType(typeof(decimal));
Assert.IsTrue(Math.Abs((decimal)_token.Value - 123.4m) < Convert.ToDecimal(eps), "Failed to read decimal value");
TryMatch("123. "); //should ignore dot and read number as int. compare it to python numbers - see below
CheckType(typeof(int));
Assert.IsTrue((int)_token.Value == 123, "Failed to read int value with trailing dot");
//Quick parse
TryMatch("1 ");
CheckType(typeof(int));
//When going through quick parse path (for one-digit numbers), the NumberScanInfo record is not created and hence is absent in Attributes
Assert.IsTrue(_token.Details == null, "Quick parse test failed: ScanDetails object is found in token - quick parse path should not produce this object.");
Assert.IsTrue((int)_token.Value == 1, "Failed to read quick-parse value");
}
[TestMethod]
public void TestVBNumber() {
double eps = 0.0001;
SetTerminal(TerminalFactory.CreateVbNumber("Number"));
//Simple integer
TryMatch("123 ");
CheckType(typeof(int));
Assert.IsTrue(_token.Details != null, "ScanDetails object not found in token.");
Assert.IsTrue((int)_token.Value == 123, "Failed to read int value");
//Test all suffixes
TryMatch("123S ");
CheckType(typeof(Int16));
Assert.IsTrue((Int16)_token.Value == 123, "Failed to read short value");
TryMatch("123I ");
CheckType(typeof(Int32));
Assert.IsTrue((Int32)_token.Value == 123, "Failed to read int value");
TryMatch("123% ");
CheckType(typeof(Int32));
Assert.IsTrue((Int32)_token.Value == 123, "Failed to read int value");
TryMatch("123L ");
CheckType(typeof(long));
Assert.IsTrue((long)_token.Value == 123, "Failed to read long value");
TryMatch("123& ");
CheckType(typeof(Int64));
Assert.IsTrue((Int64)_token.Value == 123, "Failed to read long value");
TryMatch("123us ");
CheckType(typeof(UInt16));
Assert.IsTrue((UInt16)_token.Value == 123, "Failed to read ushort value");
TryMatch("123ui ");
CheckType(typeof(UInt32));
Assert.IsTrue((UInt32)_token.Value == 123, "Failed to read uint value");
TryMatch("123ul ");
CheckType(typeof(ulong));
Assert.IsTrue((ulong)_token.Value == 123, "Failed to read ulong value");
//Hex and octal
TryMatch("&H012 ");
CheckType(typeof(int));
Assert.IsTrue((int)_token.Value == 0x012, "Failed to read hex int value");
TryMatch("&H012L ");
CheckType(typeof(long));
Assert.IsTrue((long)_token.Value == 0x012, "Failed to read hex long value");
TryMatch("&O012 ");
CheckType(typeof(int));
Assert.IsTrue((int)_token.Value == 10, "Failed to read octal int value"); //12(oct) = 10(dec)
TryMatch("&o012L ");
CheckType(typeof(long));
Assert.IsTrue((long)_token.Value == 10, "Failed to read octal long value");
//Floating point types
TryMatch("123.4 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #1");
TryMatch("1234e-1 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 1234e-1) < eps, "Failed to read double value #2");
TryMatch("12.34e+01 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #3");
TryMatch("0.1234E3 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #4");
TryMatch("123.4R ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #5");
TryMatch("123.4# ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #6");
TryMatch("123.4f ");
CheckType(typeof(float));
Assert.IsTrue(Math.Abs((Single)_token.Value - 123.4) < eps, "Failed to read float(single) value");
TryMatch("123.4! ");
CheckType(typeof(float));
Assert.IsTrue(Math.Abs((Single)_token.Value - 123.4) < eps, "Failed to read float(single) value");
TryMatch("123.4D ");
CheckType(typeof(decimal));
Assert.IsTrue(Math.Abs((decimal)_token.Value - 123.4m) < Convert.ToDecimal(eps), "Failed to read decimal value");
TryMatch("123.4@ ");
CheckType(typeof(decimal));
Assert.IsTrue(Math.Abs((decimal)_token.Value - 123.4m) < Convert.ToDecimal(eps), "Failed to read decimal value");
//Quick parse
TryMatch("1 ");
CheckType(typeof(int));
//When going through quick parse path (for one-digit numbers), the NumberScanInfo record is not created and hence is absent in Attributes
Assert.IsTrue(_token.Details == null, "Quick parse test failed: ScanDetails object is found in token - quick parse path should not produce this object.");
Assert.IsTrue((int)_token.Value == 1, "Failed to read quick-parse value");
}
[TestMethod]
public void TestPythonNumber() {
double eps = 0.0001;
SetTerminal(TerminalFactory.CreatePythonNumber("Number"));
//Simple integers and suffixes
TryMatch("123 ");
CheckType(typeof(int));
Assert.IsTrue(_token.Details != null, "ScanDetails object not found in token.");
Assert.IsTrue((int)_token.Value == 123, "Failed to read int value");
TryMatch("123L ");
CheckType(typeof(long));
Assert.IsTrue((long)_token.Value == 123, "Failed to read long value");
//Hex representation
TryMatch("0x012 ");
CheckType(typeof(int));
Assert.IsTrue((int)_token.Value == 0x012, "Failed to read hex int value");
TryMatch("0x012l "); //with small "L"
CheckType(typeof(long));
Assert.IsTrue((long)_token.Value == 0x012, "Failed to read hex long value");
//Floating point types
TryMatch("123.4 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #1");
TryMatch("1234e-1 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 1234e-1) < eps, "Failed to read double value #2");
TryMatch("12.34e+01 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #3");
TryMatch("0.1234E3 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #4");
TryMatch(".1234 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 0.1234) < eps, "Failed to read double value with leading dot");
TryMatch("123. ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.0) < eps, "Failed to read double value with trailing dot");
//Big integer
string sbig = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; //100 digits
TryMatch(sbig);
Assert.IsTrue(_token.Value.ToString() == sbig, "Failed to read big integer value");
//Quick parse
TryMatch("1,");
CheckType(typeof(int));
Assert.IsTrue(_token.Details == null, "Quick parse test failed: ScanDetails object is found in token - quick parse path should produce this object.");
Assert.IsTrue((int)_token.Value == 1, "Failed to read quick-parse value");
}
[TestMethod]
public void TestSchemeNumber() {
double eps = 0.0001;
SetTerminal(TerminalFactory.CreateSchemeNumber("Number"));
//Just test default float value (double), and exp symbols (e->double, s->single, d -> double)
TryMatch("123.4 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #1");
TryMatch("1234e-1 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 1234e-1) < eps, "Failed to read single value #2");
TryMatch("1234s-1 ");
CheckType(typeof(Single));
Assert.IsTrue(Math.Abs((Single)_token.Value - 1234e-1) < eps, "Failed to read single value #3");
TryMatch("12.34d+01 ");
CheckType(typeof(double));
Assert.IsTrue(Math.Abs((double)_token.Value - 123.4) < eps, "Failed to read double value #4");
}//method
[TestMethod]
public void TestNumberWithUnderscore() {
var number = new NumberLiteral("number", NumberOptions.AllowUnderscore);
SetTerminal(number);
//Simple integers and suffixes
TryMatch("1_234_567");
CheckType(typeof(int));
Assert.IsTrue((int)_token.Value == 1234567, "Failed to read int value with underscores in it");
}//method
}//class
}//namespace
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.UserModel
{
/**
* All known types of automatic shapes in DrawingML
*
* @author Yegor Kozlov
*/
internal enum ShapeTypes:int
{
/// <summary>
/// Allow accessing the Initial value.
/// </summary>
None = 0,
LINE = 1,
LINE_INV = 2,
TRIANGLE = 3,
RT_TRIANGLE = 4,
RECT = 5,
DIAMOND = 6,
PARALLELOGRAM = 7,
TRAPEZOID = 8,
NON_ISOSCELES_TRAPEZOID = 9,
PENTAGON = 10,
HEXAGON = 11,
HEPTAGON = 12,
OCTAGON = 13,
DECAGON = 14,
DODECAGON = 15,
STAR_4 = 16,
STAR_5 = 17,
STAR_6 = 18,
STAR_7 = 19,
STAR_8 = 20,
STAR_10 = 21,
STAR_12 = 22,
STAR_16 = 23,
STAR_24 = 24,
STAR_32 = 25,
ROUND_RECT = 26,
ROUND_1_RECT = 27,
ROUND_2_SAME_RECT = 28,
ROUND_2_DIAG_RECT = 29,
SNIP_ROUND_RECT = 30,
SNIP_1_RECT = 31,
SNIP_2_SAME_RECT = 32,
SNIP_2_DIAG_RECT = 33,
PLAQUE = 34,
ELLIPSE = 35,
TEARDROP = 36,
HOME_PLATE = 37,
CHEVRON = 38,
PIE_WEDGE = 39,
PIE = 40,
BLOCK_ARC = 41,
DONUT = 42,
NO_SMOKING = 43,
RIGHT_ARROW = 44,
LEFT_ARROW = 45,
UP_ARROW = 46,
DOWN_ARROW = 47,
STRIPED_RIGHT_ARROW = 48,
NOTCHED_RIGHT_ARROW = 49,
BENT_UP_ARROW = 50,
LEFT_RIGHT_ARROW = 51,
UP_DOWN_ARROW = 52,
LEFT_UP_ARROW = 53,
LEFT_RIGHT_UP_ARROW = 54,
QUAD_ARROW = 55,
LEFT_ARROW_CALLOUT = 56,
RIGHT_ARROW_CALLOUT = 57,
UP_ARROW_CALLOUT = 58,
DOWN_ARROW_CALLOUT = 59,
LEFT_RIGHT_ARROW_CALLOUT = 60,
UP_DOWN_ARROW_CALLOUT = 61,
QUAD_ARROW_CALLOUT = 62,
BENT_ARROW = 63,
UTURN_ARROW = 64,
CIRCULAR_ARROW = 65,
LEFT_CIRCULAR_ARROW = 66,
LEFT_RIGHT_CIRCULAR_ARROW = 67,
CURVED_RIGHT_ARROW = 68,
CURVED_LEFT_ARROW = 69,
CURVED_UP_ARROW = 70,
CURVED_DOWN_ARROW = 71,
SWOOSH_ARROW = 72,
CUBE = 73,
CAN = 74,
LIGHTNING_BOLT = 75,
HEART = 76,
SUN = 77,
MOON = 78,
SMILEY_FACE = 79,
IRREGULAR_SEAL_1 = 80,
IRREGULAR_SEAL_2 = 81,
FOLDED_CORNER = 82,
BEVEL = 83,
FRAME = 84,
HALF_FRAME = 85,
CORNER = 86,
DIAG_STRIPE = 87,
CHORD = 88,
ARC = 89,
LEFT_BRACKET = 90,
RIGHT_BRACKET = 91,
LEFT_BRACE = 92,
RIGHT_BRACE = 93,
BRACKET_PAIR = 94,
BRACE_PAIR = 95,
STRAIGHT_CONNECTOR_1 = 96,
BENT_CONNECTOR_2 = 97,
BENT_CONNECTOR_3 = 98,
BENT_CONNECTOR_4 = 99,
BENT_CONNECTOR_5 = 100,
CURVED_CONNECTOR_2 = 101,
CURVED_CONNECTOR_3 = 102,
CURVED_CONNECTOR_4 = 103,
CURVED_CONNECTOR_5 = 104,
CALLOUT_1 = 105,
CALLOUT_2 = 106,
CALLOUT_3 = 107,
ACCENT_CALLOUT_1 = 108,
ACCENT_CALLOUT_2 = 109,
ACCENT_CALLOUT_3 = 110,
BORDER_CALLOUT_1 = 111,
BORDER_CALLOUT_2 = 112,
BORDER_CALLOUT_3 = 113,
ACCENT_BORDER_CALLOUT_1 = 114,
ACCENT_BORDER_CALLOUT_2 = 115,
ACCENT_BORDER_CALLOUT_3 = 116,
WEDGE_RECT_CALLOUT = 117,
WEDGE_ROUND_RECT_CALLOUT = 118,
WEDGE_ELLIPSE_CALLOUT = 119,
CLOUD_CALLOUT = 120,
CLOUD = 121,
RIBBON = 122,
RIBBON_2 = 123,
ELLIPSE_RIBBON = 124,
ELLIPSE_RIBBON_2 = 125,
LEFT_RIGHT_RIBBON = 126,
VERTICAL_SCROLL = 127,
HORIZONTAL_SCROLL = 128,
WAVE = 129,
DOUBLE_WAVE = 130,
PLUS = 131,
FLOW_CHART_PROCESS = 132,
FLOW_CHART_DECISION = 133,
FLOW_CHART_INPUT_OUTPUT = 134,
FLOW_CHART_PREDEFINED_PROCESS = 135,
FLOW_CHART_INTERNAL_STORAGE = 136,
FLOW_CHART_DOCUMENT = 137,
FLOW_CHART_MULTIDOCUMENT = 138,
FLOW_CHART_TERMINATOR = 139,
FLOW_CHART_PREPARATION = 140,
FLOW_CHART_MANUAL_INPUT = 141,
FLOW_CHART_MANUAL_OPERATION = 142,
FLOW_CHART_CONNECTOR = 143,
FLOW_CHART_PUNCHED_CARD = 144,
FLOW_CHART_PUNCHED_TAPE = 145,
FLOW_CHART_SUMMING_JUNCTION = 146,
FLOW_CHART_OR = 147,
FLOW_CHART_COLLATE = 148,
FLOW_CHART_SORT = 149,
FLOW_CHART_EXTRACT = 150,
FLOW_CHART_MERGE = 151,
FLOW_CHART_OFFLINE_STORAGE = 152,
FLOW_CHART_ONLINE_STORAGE = 153,
FLOW_CHART_MAGNETIC_TAPE = 154,
FLOW_CHART_MAGNETIC_DISK = 155,
FLOW_CHART_MAGNETIC_DRUM = 156,
FLOW_CHART_DISPLAY = 157,
FLOW_CHART_DELAY = 158,
FLOW_CHART_ALTERNATE_PROCESS = 159,
FLOW_CHART_OFFPAGE_CONNECTOR = 160,
ACTION_BUTTON_BLANK = 161,
ACTION_BUTTON_HOME = 162,
ACTION_BUTTON_HELP = 163,
ACTION_BUTTON_INFORMATION = 164,
ACTION_BUTTON_FORWARD_NEXT = 165,
ACTION_BUTTON_BACK_PREVIOUS = 166,
ACTION_BUTTON_END = 167,
ACTION_BUTTON_BEGINNING = 168,
ACTION_BUTTON_RETURN = 169,
ACTION_BUTTON_DOCUMENT = 170,
ACTION_BUTTON_SOUND = 171,
ACTION_BUTTON_MOVIE = 172,
GEAR_6 = 173,
GEAR_9 = 174,
FUNNEL = 175,
MATH_PLUS = 176,
MATH_MINUS = 177,
MATH_MULTIPLY = 178,
MATH_DIVIDE = 179,
MATH_EQUAL = 180,
MATH_NOT_EQUAL = 181,
CORNER_TABS = 182,
SQUARE_TABS = 183,
PLAQUE_TABS = 184,
CHART_X = 185,
CHART_STAR = 186,
CHART_PLUS = 187,
}
}
| |
using System;
using System.Collections;
/// <summary>
/// Sinh(System.Double)
/// </summary>
public class MathSinh
{
public static int Main(string[] args)
{
MathSinh test = new MathSinh();
TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Sinh(System.Double).");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify the result when radian is 0.");
try
{
Double d = Math.Sinh(0);
if (!MathTestLib.DoubleIsWithinEpsilon(d, 0))
{
TestLibrary.TestFramework.LogError("P01.1", "The result is error when radian is 0!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify the result when radian is Math.PI/2.");
try
{
Double d = Math.Sinh(Math.PI / 2);
if (!MathTestLib.DoubleIsWithinEpsilon(d ,2.3012989023072947))
{
TestLibrary.TestFramework.LogError("P02.1", "The result is error when radian is Math.PI/2!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P02.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify the result when radian is -Math.PI/2.");
try
{
Double d = Math.Sinh(-Math.PI / 2);
if (!MathTestLib.DoubleIsWithinEpsilon(d ,-2.3012989023072947))
{
TestLibrary.TestFramework.LogError("P03.1", "The result is error when radian is -Math.PI/2!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P03.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify the result when radian is Math.PI/6.");
try
{
Double d = Math.Sinh(Math.PI / 6);
if (!MathTestLib.DoubleIsWithinEpsilon(d,0.54785347388803973))
{
TestLibrary.TestFramework.LogError("P04.1", "The result is error when radian is Math.PI/6!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P04.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify the result when radian is -Math.PI/6.");
try
{
Double d = Math.Sinh(-Math.PI / 6);
if (!MathTestLib.DoubleIsWithinEpsilon(d ,-0.54785347388803973))
{
TestLibrary.TestFramework.LogError("P05.1", "The result is error when radian is -Math.PI/6!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P05.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Verify the result is PositiveInfinity when radian is PositiveInfinity.");
try
{
Double d = Math.Sinh(Double.PositiveInfinity);
if (d.CompareTo(Double.PositiveInfinity) != 0)
{
TestLibrary.TestFramework.LogError("P06.1", "The result is error when radian is PositiveInfinity!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P06.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest7: Verify the result is NegativeInfinity when radian is NegativeInfinity.");
try
{
Double d = Math.Sinh(Double.NegativeInfinity);
if (d.CompareTo(Double.NegativeInfinity) != 0)
{
TestLibrary.TestFramework.LogError("P07.1", "The result is error when radian is NegativeInfinity!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P07.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest8: Verify the result is NaN when radian is NaN.");
try
{
Double d = Math.Sinh(Double.NaN);
if (d.CompareTo(Double.NaN) != 0)
{
TestLibrary.TestFramework.LogError("P08.1", "The result is error when radian is NaN!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P08.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DebugExtendedPropertyDescriptor.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
#if DEBUG
/*
This class exists in debug only. It is a complete copy of the
V1.0 TypeDescriptor object and is used to validate that the
behavior of the V2.0 TypeDescriptor matches 1.0 behavior.
*/
namespace System.ComponentModel {
using System.Diagnostics;
using System;
using System.ComponentModel.Design;
using System.Collections;
using Microsoft.Win32;
using System.Security.Permissions;
/// <internalonly/>
/// <devdoc>
/// <para>
/// This class wraps an PropertyDescriptor with something that looks like a property. It
/// allows you to treat extended properties the same as regular properties.
/// </para>
/// </devdoc>
[HostProtection(SharedState = true)]
internal sealed class DebugExtendedPropertyDescriptor : PropertyDescriptor {
private readonly DebugReflectPropertyDescriptor extenderInfo; // the extender property
private readonly IExtenderProvider provider; // the guy providing it
private TypeConverter converter;
private object[] editors;
private Type[] editorTypes;
private int editorCount;
/// <devdoc>
/// Creates a new extended property info. Callers can then treat this as
/// a standard property.
/// </devdoc>
public DebugExtendedPropertyDescriptor(DebugReflectPropertyDescriptor extenderInfo, Type receiverType, IExtenderProvider provider) : this(extenderInfo, receiverType, provider, null) {
}
/// <devdoc>
/// Creates a new extended property info. Callers can then treat this as
/// a standard property.
/// </devdoc>
public DebugExtendedPropertyDescriptor(DebugReflectPropertyDescriptor extenderInfo, Type receiverType, IExtenderProvider provider, Attribute[] attributes)
: base(extenderInfo, attributes) {
Debug.Assert(extenderInfo != null, "DebugExtendedPropertyDescriptor must have extenderInfo");
Debug.Assert(provider != null, "DebugExtendedPropertyDescriptor must have provider");
ArrayList attrList = new ArrayList(AttributeArray);
attrList.Add(ExtenderProvidedPropertyAttribute.Create(extenderInfo, receiverType, provider));
if (extenderInfo.IsReadOnly) {
attrList.Add(ReadOnlyAttribute.Yes);
}
Attribute[] temp = new Attribute[attrList.Count];
attrList.CopyTo(temp, 0);
AttributeArray = temp;
this.extenderInfo = extenderInfo;
this.provider = provider;
}
public DebugExtendedPropertyDescriptor(PropertyDescriptor extender, Attribute[] attributes) : base(extender, attributes) {
Debug.Assert(extender != null, "The original PropertyDescriptor must be non-null");
ExtenderProvidedPropertyAttribute attr = extender.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute;
Debug.Assert(attr != null, "The original PropertyDescriptor does not have an ExtenderProvidedPropertyAttribute");
DebugReflectPropertyDescriptor reflectDesc = attr.ExtenderProperty as DebugReflectPropertyDescriptor;
Debug.Assert(reflectDesc != null, "The original PropertyDescriptor has an invalid ExtenderProperty");
this.extenderInfo = reflectDesc;
this.provider = attr.Provider;
}
/// <devdoc>
/// Determines if the the component will allow its value to be reset.
/// </devdoc>
public override bool CanResetValue(object comp) {
return extenderInfo.ExtenderCanResetValue(provider, comp);
}
/// <devdoc>
/// Retrieves the type of the component this PropertyDescriptor is bound to.
/// </devdoc>
public override Type ComponentType {
get {
return extenderInfo.ComponentType;
}
}
public override TypeConverter Converter {
get {
if (converter == null) {
TypeConverterAttribute attr = (TypeConverterAttribute)Attributes[typeof(TypeConverterAttribute)];
if (attr.ConverterTypeName != null && attr.ConverterTypeName.Length > 0) {
Type converterType = GetTypeFromName(attr.ConverterTypeName);
if (converterType != null && typeof(TypeConverter).IsAssignableFrom(converterType)) {
converter = (TypeConverter)CreateInstance(converterType);
}
}
if (converter == null) {
converter = DebugTypeDescriptor.GetConverter(PropertyType);
}
}
return converter;
}
}
/// <devdoc>
/// Determines if the property can be written to.
/// </devdoc>
public override bool IsReadOnly {
get {
return Attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes);
}
}
/// <devdoc>
/// Retrieves the data type of the property.
/// </devdoc>
public override Type PropertyType {
get {
return extenderInfo.ExtenderGetType(provider);
}
}
/// <devdoc>
/// Retrieves the display name of the property. This is the name that will
/// be displayed in a properties window. This will be the same as the property
/// name for most properties.
/// </devdoc>
public override string DisplayName {
get {
string name = Name;
ISite site = GetSite(provider);
if (site != null) {
string providerName = site.Name;
if (providerName != null && providerName.Length > 0) {
name = SR.GetString(SR.MetaExtenderName, name, providerName);
}
}
return name;
}
}
/// <devdoc>
/// Retrieves the properties
/// </devdoc>
public override PropertyDescriptorCollection GetChildProperties(object instance, Attribute[] filter) {
if (instance == null) {
return DebugTypeDescriptor.GetProperties(PropertyType, filter);
}
else {
return DebugTypeDescriptor.GetProperties(instance, filter);
}
}
/// <devdoc>
/// <para>
/// Gets an editor of the specified type.
/// </para>
/// </devdoc>
public override object GetEditor(Type editorBaseType) {
object editor = null;
// Check the editors we've already created for this type.
//
if (editorTypes != null) {
for (int i = 0; i < editorCount; i++) {
if (editorTypes[i] == editorBaseType) {
return editors[i];
}
}
}
// If one wasn't found, then we must go through the attributes.
//
if (editor == null) {
for (int i = 0; i < Attributes.Count; i++) {
if (!(Attributes[i] is EditorAttribute)) {
continue;
}
EditorAttribute attr = (EditorAttribute)Attributes[i];
Type editorType = GetTypeFromName(attr.EditorBaseTypeName);
if (editorBaseType == editorType) {
Type type = GetTypeFromName(attr.EditorTypeName);
if (type != null) {
editor = CreateInstance(type);
break;
}
}
}
// Now, if we failed to find it in our own attributes, go to the
// component descriptor.
//
if (editor == null) {
editor = DebugTypeDescriptor.GetEditor(PropertyType, editorBaseType);
}
// Now, another slot in our editor cache for next time
//
if (editorTypes == null) {
editorTypes = new Type[5];
editors = new object[5];
}
if (editorCount >= editorTypes.Length) {
Type[] newTypes = new Type[editorTypes.Length * 2];
object[] newEditors = new object[editors.Length * 2];
Array.Copy(editorTypes, newTypes, editorTypes.Length);
Array.Copy(editors, newEditors, editors.Length);
editorTypes = newTypes;
editors = newEditors;
}
editorTypes[editorCount] = editorBaseType;
editors[editorCount++] = editor;
}
return editor;
}
/// <devdoc>
/// Retrieves the value of the property for the given component. This will
/// throw an exception if the component does not have this property.
/// </devdoc>
public override object GetValue(object comp) {
return extenderInfo.ExtenderGetValue(provider, comp);
}
/// <devdoc>
/// Resets the value of this property on comp to the default value.
/// </devdoc>
public override void ResetValue(object comp) {
extenderInfo.ExtenderResetValue(provider, comp, this);
}
/// <devdoc>
/// Sets the value of this property on the given component.
/// </devdoc>
public override void SetValue(object component, object value) {
extenderInfo.ExtenderSetValue(provider, component, value, this);
}
/// <devdoc>
/// Determines if this property should be persisted. A property is
/// to be persisted if it is marked as persistable through a
/// PersistableAttribute, and if the property contains something other
/// than the default value. Note, however, that this method will
/// return true for design time properties as well, so callers
/// should also check to see if a property is design time only before
/// persisting to runtime storage.
/// </devdoc>
public override bool ShouldSerializeValue(object comp) {
return extenderInfo.ExtenderShouldSerializeValue(provider, comp);
}
}
}
#endif
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.Admin.BO;
using PCSComUtils.Common;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
namespace PCSComUtils.Admin.DS
{
public class sys_RolePartyDS
{
public sys_RolePartyDS()
{
}
private const string THIS = "PCSComUtils.Admin.DS.sys_RolePartyDS";
string strPKColumnName, strFKColumnName;
//**************************************************************************
/// <Description>
/// This method uses to add data to sys_RoleParty
/// </Description>
/// <Inputs>
/// sys_RolePartyVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, November 16, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
sys_RolePartyVO objObject = (sys_RolePartyVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO sys_RoleParty("
+ sys_RolePartyTable.ROLEID_FLD + ","
+ sys_RolePartyTable.PARTYID_FLD + ")"
+ "VALUES(?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(sys_RolePartyTable.ROLEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_RolePartyTable.ROLEID_FLD].Value = objObject.RoleID;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_RolePartyTable.PARTYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_RolePartyTable.PARTYID_FLD].Value = objObject.PartyID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from sys_RoleParty
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + sys_RolePartyTable.TABLE_NAME + " WHERE " + "RolePartyID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from sys_RoleParty
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// sys_RolePartyVO
/// </Outputs>
/// <Returns>
/// sys_RolePartyVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, November 16, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ sys_RolePartyTable.ROLEPARTYID_FLD + ","
+ sys_RolePartyTable.ROLEID_FLD + ","
+ sys_RolePartyTable.PARTYID_FLD
+ " FROM " + sys_RolePartyTable.TABLE_NAME
+" WHERE " + sys_RolePartyTable.ROLEPARTYID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
sys_RolePartyVO objObject = new sys_RolePartyVO();
while (odrPCS.Read())
{
objObject.RolePartyID = int.Parse(odrPCS[sys_RolePartyTable.ROLEPARTYID_FLD].ToString().Trim());
objObject.RoleID = int.Parse(odrPCS[sys_RolePartyTable.ROLEID_FLD].ToString().Trim());
objObject.PartyID = int.Parse(odrPCS[sys_RolePartyTable.PARTYID_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to sys_RoleParty
/// </Description>
/// <Inputs>
/// sys_RolePartyVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
sys_RolePartyVO objObject = (sys_RolePartyVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE sys_RoleParty SET "
+ sys_RolePartyTable.ROLEID_FLD + "= ?" + ","
+ sys_RolePartyTable.PARTYID_FLD + "= ?"
+" WHERE " + sys_RolePartyTable.ROLEPARTYID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(sys_RolePartyTable.ROLEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_RolePartyTable.ROLEID_FLD].Value = objObject.RoleID;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_RolePartyTable.PARTYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_RolePartyTable.PARTYID_FLD].Value = objObject.PartyID;
ocmdPCS.Parameters.Add(new OleDbParameter(sys_RolePartyTable.ROLEPARTYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[sys_RolePartyTable.ROLEPARTYID_FLD].Value = objObject.RolePartyID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from sys_RoleParty
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, November 16, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ sys_RolePartyTable.ROLEPARTYID_FLD + ","
+ sys_RolePartyTable.ROLEID_FLD + ","
+ sys_RolePartyTable.PARTYID_FLD
+ " FROM " + sys_RolePartyTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,sys_RolePartyTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// GetDataByRoleID
/// </summary>
/// <param name="pintRoleID"></param>
/// <param name="pstrSecurityTableName"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Thursday, Nov 17 2005</date>
public DataSet GetDataByRoleID(int pintRoleID, string pstrSecurityTableName, string pstrSourceTableName)
{
const string METHOD_NAME = THIS + ".GetDataByRoleID()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
CommonBO boCommon = new CommonBO();
strPKColumnName = boCommon.GetPKColumnName(pstrSecurityTableName);
strFKColumnName = boCommon.GetFKColumnName(pstrSourceTableName, pstrSecurityTableName);
strSql= "SELECT "
+ strPKColumnName + ","
+ sys_RolePartyTable.ROLEID_FLD + ","
+ strFKColumnName
+ " FROM " + pstrSecurityTableName
+ " WHERE " + sys_RolePartyTable.ROLEID_FLD + " = " + pintRoleID.ToString();
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, pstrSecurityTableName);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, November 16, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ sys_RolePartyTable.ROLEPARTYID_FLD + ","
+ sys_RolePartyTable.ROLEID_FLD + ","
+ sys_RolePartyTable.PARTYID_FLD
+ " FROM " + sys_RolePartyTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,sys_RolePartyTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if(ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// UpdateSecurityTable
/// </summary>
/// <param name="pdstSecurityTable"></param>
/// <param name="pstrSecurityTableName"></param>
/// <author>Trada</author>
/// <date>Friday, Nov 18 2005</date>
public void UpdateSecurityTable(DataSet pdstSecurityTable, string pstrSecurityTableName, string pstrSourceTableName)
{
const string METHOD_NAME = THIS + ".UpdateSecurityTable()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
CommonBO boCommon = new CommonBO();
//strPKColumnName = boCommon.GetPKColumnName(pstrSecurityTableName);
//strFKColumnName = boCommon.GetFKColumnName(pstrSourceTableName, pstrSecurityTableName);
const string FKTABLE_NAME = "FKTABLE_NAME";
const string FKCOLUMN_NAME = "FKCOLUMN_NAME";
const string PKCOLUMN_NAME = "COLUMN_NAME";
// HACK: Trada 12-12-2005 Get FK Column Name
DataTable dtbFKTable = GetFKColumnName(pstrSourceTableName);
foreach (DataRow drow in dtbFKTable.Rows)
{
if (drow[FKTABLE_NAME].ToString() == pstrSecurityTableName)
{
strFKColumnName = drow[FKCOLUMN_NAME].ToString();
}
}
// END: Trada 12-12-2005
dtbFKTable = GetPKColumnName(pstrSecurityTableName);
if (dtbFKTable.Rows.Count == 0)
{
strPKColumnName = string.Empty;
}
else
{
strPKColumnName = dtbFKTable.Rows[0][PKCOLUMN_NAME].ToString();
}
strSql= "SELECT "
+ strPKColumnName + ","
+ sys_RolePartyTable.ROLEID_FLD + ","
+ strFKColumnName
+ " FROM " + pstrSecurityTableName;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pdstSecurityTable.EnforceConstraints = false;
odadPCS.Update(pdstSecurityTable, pstrSecurityTableName);
}
catch(OleDbException ex)
{
if(ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// GetFKColumnName
/// </summary>
/// <param name="pstrPKTable_Name"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Thursday, Nov 17 2005</date>
public DataTable GetFKColumnName(string pstrPKTable_Name)
{
const string METHOD_NAME = THIS + ".GetFKColumnName()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "EXEC sp_fkeys @pktable_name = N'" + pstrPKTable_Name + "'";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,sys_RolePartyTable.TABLE_NAME);
return dstPCS.Tables[0];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// GetPKColumnName
/// </summary>
/// <param name="pstrPKTable_Name"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Thursday, Nov 17 2005</date>
public DataTable GetPKColumnName(string pstrPKTable_Name)
{
const string METHOD_NAME = THIS + ".GetPKColumnName()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "EXEC sp_pkeys @table_name = N'" + pstrPKTable_Name + "'";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,sys_RolePartyTable.TABLE_NAME);
return dstPCS.Tables[0];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
#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;
#if !(NET20 || NET35 || PORTABLE || ASPNETCORE50)
using System.Numerics;
#endif
using System.Text;
using Newtonsoft.Json.Converters;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif ASPNETCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Linq;
using System.IO;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
using Newtonsoft.Json.Utilities;
#endif
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class JTokenTests : TestFixtureBase
{
[Test]
public void ReadFrom()
{
JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(new StringReader("{'pie':true}")));
Assert.AreEqual(true, (bool)o["pie"]);
JArray a = (JArray)JToken.ReadFrom(new JsonTextReader(new StringReader("[1,2,3]")));
Assert.AreEqual(1, (int)a[0]);
Assert.AreEqual(2, (int)a[1]);
Assert.AreEqual(3, (int)a[2]);
JsonReader reader = new JsonTextReader(new StringReader("{'pie':true}"));
reader.Read();
reader.Read();
JProperty p = (JProperty)JToken.ReadFrom(reader);
Assert.AreEqual("pie", p.Name);
Assert.AreEqual(true, (bool)p.Value);
JConstructor c = (JConstructor)JToken.ReadFrom(new JsonTextReader(new StringReader("new Date(1)")));
Assert.AreEqual("Date", c.Name);
Assert.IsTrue(JToken.DeepEquals(new JValue(1), c.Values().ElementAt(0)));
JValue v;
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""stringvalue""")));
Assert.AreEqual("stringvalue", (string)v);
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1")));
Assert.AreEqual(1, (int)v);
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1.1")));
Assert.AreEqual(1.1, (double)v);
#if !NET20
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""1970-01-01T00:00:00+12:31"""))
{
DateParseHandling = DateParseHandling.DateTimeOffset
});
Assert.AreEqual(typeof(DateTimeOffset), v.Value.GetType());
Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, new TimeSpan(12, 31, 0)), v.Value);
#endif
}
[Test]
public void Load()
{
JObject o = (JObject)JToken.Load(new JsonTextReader(new StringReader("{'pie':true}")));
Assert.AreEqual(true, (bool)o["pie"]);
}
[Test]
public void Parse()
{
JObject o = (JObject)JToken.Parse("{'pie':true}");
Assert.AreEqual(true, (bool)o["pie"]);
}
[Test]
public void Parent()
{
JArray v = new JArray(new JConstructor("TestConstructor"), new JValue(new DateTime(2000, 12, 20)));
Assert.AreEqual(null, v.Parent);
JObject o =
new JObject(
new JProperty("Test1", v),
new JProperty("Test2", "Test2Value"),
new JProperty("Test3", "Test3Value"),
new JProperty("Test4", null)
);
Assert.AreEqual(o.Property("Test1"), v.Parent);
JProperty p = new JProperty("NewProperty", v);
// existing value should still have same parent
Assert.AreEqual(o.Property("Test1"), v.Parent);
// new value should be cloned
Assert.AreNotSame(p.Value, v);
Assert.AreEqual((DateTime)((JValue)p.Value[1]).Value, (DateTime)((JValue)v[1]).Value);
Assert.AreEqual(v, o["Test1"]);
Assert.AreEqual(null, o.Parent);
JProperty o1 = new JProperty("O1", o);
Assert.AreEqual(o, o1.Value);
Assert.AreNotEqual(null, o.Parent);
JProperty o2 = new JProperty("O2", o);
Assert.AreNotSame(o1.Value, o2.Value);
Assert.AreEqual(o1.Value.Children().Count(), o2.Value.Children().Count());
Assert.AreEqual(false, JToken.DeepEquals(o1, o2));
Assert.AreEqual(true, JToken.DeepEquals(o1.Value, o2.Value));
}
[Test]
public void Next()
{
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
JToken next = a[0].Next;
Assert.AreEqual(6, (int)next);
next = next.Next;
Assert.IsTrue(JToken.DeepEquals(new JArray(7, 8), next));
next = next.Next;
Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), next));
next = next.Next;
Assert.IsNull(next);
}
[Test]
public void Previous()
{
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
JToken previous = a[3].Previous;
Assert.IsTrue(JToken.DeepEquals(new JArray(7, 8), previous));
previous = previous.Previous;
Assert.AreEqual(6, (int)previous);
previous = previous.Previous;
Assert.AreEqual(5, (int)previous);
previous = previous.Previous;
Assert.IsNull(previous);
}
[Test]
public void Children()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
Assert.AreEqual(4, a.Count());
Assert.AreEqual(3, a.Children<JArray>().Count());
}
[Test]
public void BeforeAfter()
{
JArray a =
new JArray(
5,
new JArray(1, 2, 3),
new JArray(1, 2, 3),
new JArray(1, 2, 3)
);
Assert.AreEqual(5, (int)a[1].Previous);
Assert.AreEqual(2, a[2].BeforeSelf().Count());
//Assert.AreEqual(2, a[2].AfterSelf().Count());
}
[Test]
public void Casting()
{
Assert.AreEqual(1L, (long)(new JValue(1)));
Assert.AreEqual(2L, (long)new JArray(1, 2, 3)[1]);
Assert.AreEqual(new DateTime(2000, 12, 20), (DateTime)new JValue(new DateTime(2000, 12, 20)));
#if !NET20
Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 0, 0, 0, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTime(2000, 12, 20, 0, 0, 0, DateTimeKind.Utc)));
Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)));
Assert.AreEqual(null, (DateTimeOffset?)new JValue((DateTimeOffset?)null));
Assert.AreEqual(null, (DateTimeOffset?)(JValue)null);
#endif
Assert.AreEqual(true, (bool)new JValue(true));
Assert.AreEqual(true, (bool?)new JValue(true));
Assert.AreEqual(null, (bool?)((JValue)null));
Assert.AreEqual(null, (bool?)JValue.CreateNull());
Assert.AreEqual(10, (long)new JValue(10));
Assert.AreEqual(null, (long?)new JValue((long?)null));
Assert.AreEqual(null, (long?)(JValue)null);
Assert.AreEqual(null, (int?)new JValue((int?)null));
Assert.AreEqual(null, (int?)(JValue)null);
Assert.AreEqual(null, (DateTime?)new JValue((DateTime?)null));
Assert.AreEqual(null, (DateTime?)(JValue)null);
Assert.AreEqual(null, (short?)new JValue((short?)null));
Assert.AreEqual(null, (short?)(JValue)null);
Assert.AreEqual(null, (float?)new JValue((float?)null));
Assert.AreEqual(null, (float?)(JValue)null);
Assert.AreEqual(null, (double?)new JValue((double?)null));
Assert.AreEqual(null, (double?)(JValue)null);
Assert.AreEqual(null, (decimal?)new JValue((decimal?)null));
Assert.AreEqual(null, (decimal?)(JValue)null);
Assert.AreEqual(null, (uint?)new JValue((uint?)null));
Assert.AreEqual(null, (uint?)(JValue)null);
Assert.AreEqual(null, (sbyte?)new JValue((sbyte?)null));
Assert.AreEqual(null, (sbyte?)(JValue)null);
Assert.AreEqual(null, (byte?)new JValue((byte?)null));
Assert.AreEqual(null, (byte?)(JValue)null);
Assert.AreEqual(null, (ulong?)new JValue((ulong?)null));
Assert.AreEqual(null, (ulong?)(JValue)null);
Assert.AreEqual(null, (uint?)new JValue((uint?)null));
Assert.AreEqual(null, (uint?)(JValue)null);
Assert.AreEqual(11.1f, (float)new JValue(11.1));
Assert.AreEqual(float.MinValue, (float)new JValue(float.MinValue));
Assert.AreEqual(1.1, (double)new JValue(1.1));
Assert.AreEqual(uint.MaxValue, (uint)new JValue(uint.MaxValue));
Assert.AreEqual(ulong.MaxValue, (ulong)new JValue(ulong.MaxValue));
Assert.AreEqual(ulong.MaxValue, (ulong)new JProperty("Test", new JValue(ulong.MaxValue)));
Assert.AreEqual(null, (string)new JValue((string)null));
Assert.AreEqual(5m, (decimal)(new JValue(5L)));
Assert.AreEqual(5m, (decimal?)(new JValue(5L)));
Assert.AreEqual(5f, (float)(new JValue(5L)));
Assert.AreEqual(5f, (float)(new JValue(5m)));
Assert.AreEqual(5f, (float?)(new JValue(5m)));
Assert.AreEqual(5, (byte)(new JValue(5)));
Assert.AreEqual(null, (sbyte?)JValue.CreateNull());
Assert.AreEqual("1", (string)(new JValue(1)));
Assert.AreEqual("1", (string)(new JValue(1.0)));
Assert.AreEqual("1.0", (string)(new JValue(1.0m)));
Assert.AreEqual("True", (string)(new JValue(true)));
Assert.AreEqual(null, (string)(JValue.CreateNull()));
Assert.AreEqual(null, (string)(JValue)null);
Assert.AreEqual("12/12/2000 12:12:12", (string)(new JValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc))));
#if !NET20
Assert.AreEqual("12/12/2000 12:12:12 +00:00", (string)(new JValue(new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero))));
#endif
Assert.AreEqual(true, (bool)(new JValue(1)));
Assert.AreEqual(true, (bool)(new JValue(1.0)));
Assert.AreEqual(true, (bool)(new JValue("true")));
Assert.AreEqual(true, (bool)(new JValue(true)));
Assert.AreEqual(1, (int)(new JValue(1)));
Assert.AreEqual(1, (int)(new JValue(1.0)));
Assert.AreEqual(1, (int)(new JValue("1")));
Assert.AreEqual(1, (int)(new JValue(true)));
Assert.AreEqual(1m, (decimal)(new JValue(1)));
Assert.AreEqual(1m, (decimal)(new JValue(1.0)));
Assert.AreEqual(1m, (decimal)(new JValue("1")));
Assert.AreEqual(1m, (decimal)(new JValue(true)));
Assert.AreEqual(TimeSpan.FromMinutes(1), (TimeSpan)(new JValue(TimeSpan.FromMinutes(1))));
Assert.AreEqual("00:01:00", (string)(new JValue(TimeSpan.FromMinutes(1))));
Assert.AreEqual(TimeSpan.FromMinutes(1), (TimeSpan)(new JValue("00:01:00")));
Assert.AreEqual("46efe013-b56a-4e83-99e4-4dce7678a5bc", (string)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"))));
Assert.AreEqual("http://www.google.com/", (string)(new JValue(new Uri("http://www.google.com"))));
Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")));
Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"))));
Assert.AreEqual(new Uri("http://www.google.com"), (Uri)(new JValue("http://www.google.com")));
Assert.AreEqual(new Uri("http://www.google.com"), (Uri)(new JValue(new Uri("http://www.google.com"))));
Assert.AreEqual(null, (Uri)(JValue.CreateNull()));
Assert.AreEqual(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")), (string)(new JValue(Encoding.UTF8.GetBytes("hi"))));
CollectionAssert.AreEquivalent((byte[])Encoding.UTF8.GetBytes("hi"), (byte[])(new JValue(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")))));
Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC").ToByteArray())));
Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid?)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC").ToByteArray())));
Assert.AreEqual((sbyte?)1, (sbyte?)(new JValue((short?)1)));
Assert.AreEqual(null, (Uri)(JValue)null);
Assert.AreEqual(null, (int?)(JValue)null);
Assert.AreEqual(null, (uint?)(JValue)null);
Assert.AreEqual(null, (Guid?)(JValue)null);
Assert.AreEqual(null, (TimeSpan?)(JValue)null);
Assert.AreEqual(null, (byte[])(JValue)null);
Assert.AreEqual(null, (bool?)(JValue)null);
Assert.AreEqual(null, (char?)(JValue)null);
Assert.AreEqual(null, (DateTime?)(JValue)null);
#if !NET20
Assert.AreEqual(null, (DateTimeOffset?)(JValue)null);
#endif
Assert.AreEqual(null, (short?)(JValue)null);
Assert.AreEqual(null, (ushort?)(JValue)null);
Assert.AreEqual(null, (byte?)(JValue)null);
Assert.AreEqual(null, (byte?)(JValue)null);
Assert.AreEqual(null, (sbyte?)(JValue)null);
Assert.AreEqual(null, (sbyte?)(JValue)null);
Assert.AreEqual(null, (long?)(JValue)null);
Assert.AreEqual(null, (ulong?)(JValue)null);
Assert.AreEqual(null, (double?)(JValue)null);
Assert.AreEqual(null, (float?)(JValue)null);
byte[] data = new byte[0];
Assert.AreEqual(data, (byte[])(new JValue(data)));
Assert.AreEqual(5, (int)(new JValue(StringComparison.OrdinalIgnoreCase)));
#if !(NET20 || NET35 || PORTABLE || ASPNETCORE50 || PORTABLE40)
string bigIntegerText = "1234567899999999999999999999999999999999999999999999999999999999999990";
Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(BigInteger.Parse(bigIntegerText))).Value);
Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(bigIntegerText)).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(long.MaxValue), (new JValue(long.MaxValue)).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(4.5d), (new JValue((4.5d))).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(4.5f), (new JValue((4.5f))).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(byte.MaxValue), (new JValue(byte.MaxValue)).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(123), (new JValue(123)).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(123), (new JValue(123)).ToObject<BigInteger?>());
Assert.AreEqual(null, (JValue.CreateNull()).ToObject<BigInteger?>());
byte[] intData = BigInteger.Parse(bigIntegerText).ToByteArray();
Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(intData)).ToObject<BigInteger>());
Assert.AreEqual(4.0d, (double)(new JValue(new BigInteger(4.5d))));
Assert.AreEqual(true, (bool)(new JValue(new BigInteger(1))));
Assert.AreEqual(long.MaxValue, (long)(new JValue(new BigInteger(long.MaxValue))));
Assert.AreEqual(long.MaxValue, (long)(new JValue(new BigInteger(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 }))));
Assert.AreEqual("9223372036854775807", (string)(new JValue(new BigInteger(long.MaxValue))));
intData = (byte[])(new JValue(new BigInteger(long.MaxValue)));
CollectionAssert.AreEqual(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 }, intData);
#endif
}
[Test]
public void FailedCasting()
{
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(true); }, "Can not convert Boolean to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1); }, "Can not convert Integer to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1.1); }, "Can not convert Float to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1.1m); }, "Can not convert Float to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(TimeSpan.Zero); }, "Can not convert TimeSpan to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)JValue.CreateNull(); }, "Can not convert Null to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(Guid.NewGuid()); }, "Can not convert Guid to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1); }, "Can not convert Integer to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1.1); }, "Can not convert Float to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1.1m); }, "Can not convert Float to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(TimeSpan.Zero); }, "Can not convert TimeSpan to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(Guid.NewGuid()); }, "Can not convert Guid to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(DateTime.Now); }, "Can not convert Date to Uri.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(DateTimeOffset.Now); }, "Can not convert Date to Uri.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(true); }, "Can not convert Boolean to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1); }, "Can not convert Integer to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1.1); }, "Can not convert Float to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1.1m); }, "Can not convert Float to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)JValue.CreateNull(); }, "Can not convert Null to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(Guid.NewGuid()); }, "Can not convert Guid to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(DateTime.Now); }, "Can not convert Date to TimeSpan.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(DateTimeOffset.Now); }, "Can not convert Date to TimeSpan.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(true); }, "Can not convert Boolean to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1); }, "Can not convert Integer to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1.1); }, "Can not convert Float to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1.1m); }, "Can not convert Float to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)JValue.CreateNull(); }, "Can not convert Null to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(DateTime.Now); }, "Can not convert Date to Guid.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(DateTimeOffset.Now); }, "Can not convert Date to Guid.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(TimeSpan.FromMinutes(1)); }, "Can not convert TimeSpan to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to Guid.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTimeOffset)new JValue(true); }, "Can not convert Boolean to DateTimeOffset.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri.");
#if !(NET20 || NET35 || PORTABLE || ASPNETCORE50 || PORTABLE40)
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(new Uri("http://www.google.com"))).ToObject<BigInteger>(); }, "Can not convert Uri to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (JValue.CreateNull()).ToObject<BigInteger>(); }, "Can not convert Null to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger>(); }, "Can not convert Guid to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger?>(); }, "Can not convert Guid to BigInteger.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (sbyte?)new JValue(DateTime.Now); }, "Can not convert Date to SByte.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (sbyte)new JValue(DateTime.Now); }, "Can not convert Date to SByte.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue("Ordinal1")).ToObject<StringComparison>(); }, "Could not convert 'Ordinal1' to StringComparison.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue("Ordinal1")).ToObject<StringComparison?>(); }, "Could not convert 'Ordinal1' to StringComparison.");
}
[Test]
public void ToObject()
{
#if !(NET20 || NET35 || PORTABLE || ASPNETCORE50)
Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger))));
Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger?))));
Assert.AreEqual((BigInteger?)null, (JValue.CreateNull().ToObject(typeof(BigInteger?))));
#endif
Assert.AreEqual((ushort)1, (new JValue(1).ToObject(typeof(ushort))));
Assert.AreEqual((ushort)1, (new JValue(1).ToObject(typeof(ushort?))));
Assert.AreEqual((uint)1L, (new JValue(1).ToObject(typeof(uint))));
Assert.AreEqual((uint)1L, (new JValue(1).ToObject(typeof(uint?))));
Assert.AreEqual((ulong)1L, (new JValue(1).ToObject(typeof(ulong))));
Assert.AreEqual((ulong)1L, (new JValue(1).ToObject(typeof(ulong?))));
Assert.AreEqual((sbyte)1L, (new JValue(1).ToObject(typeof(sbyte))));
Assert.AreEqual((sbyte)1L, (new JValue(1).ToObject(typeof(sbyte?))));
Assert.AreEqual((byte)1L, (new JValue(1).ToObject(typeof(byte))));
Assert.AreEqual((byte)1L, (new JValue(1).ToObject(typeof(byte?))));
Assert.AreEqual((short)1L, (new JValue(1).ToObject(typeof(short))));
Assert.AreEqual((short)1L, (new JValue(1).ToObject(typeof(short?))));
Assert.AreEqual(1, (new JValue(1).ToObject(typeof(int))));
Assert.AreEqual(1, (new JValue(1).ToObject(typeof(int?))));
Assert.AreEqual(1L, (new JValue(1).ToObject(typeof(long))));
Assert.AreEqual(1L, (new JValue(1).ToObject(typeof(long?))));
Assert.AreEqual((float)1, (new JValue(1.0).ToObject(typeof(float))));
Assert.AreEqual((float)1, (new JValue(1.0).ToObject(typeof(float?))));
Assert.AreEqual((double)1, (new JValue(1.0).ToObject(typeof(double))));
Assert.AreEqual((double)1, (new JValue(1.0).ToObject(typeof(double?))));
Assert.AreEqual(1m, (new JValue(1).ToObject(typeof(decimal))));
Assert.AreEqual(1m, (new JValue(1).ToObject(typeof(decimal?))));
Assert.AreEqual(true, (new JValue(true).ToObject(typeof(bool))));
Assert.AreEqual(true, (new JValue(true).ToObject(typeof(bool?))));
Assert.AreEqual('b', (new JValue('b').ToObject(typeof(char))));
Assert.AreEqual('b', (new JValue('b').ToObject(typeof(char?))));
Assert.AreEqual(TimeSpan.MaxValue, (new JValue(TimeSpan.MaxValue).ToObject(typeof(TimeSpan))));
Assert.AreEqual(TimeSpan.MaxValue, (new JValue(TimeSpan.MaxValue).ToObject(typeof(TimeSpan?))));
Assert.AreEqual(DateTime.MaxValue, (new JValue(DateTime.MaxValue).ToObject(typeof(DateTime))));
Assert.AreEqual(DateTime.MaxValue, (new JValue(DateTime.MaxValue).ToObject(typeof(DateTime?))));
#if !NET20
Assert.AreEqual(DateTimeOffset.MaxValue, (new JValue(DateTimeOffset.MaxValue).ToObject(typeof(DateTimeOffset))));
Assert.AreEqual(DateTimeOffset.MaxValue, (new JValue(DateTimeOffset.MaxValue).ToObject(typeof(DateTimeOffset?))));
#endif
Assert.AreEqual("b", (new JValue("b").ToObject(typeof(string))));
Assert.AreEqual(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C"), (new JValue(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C")).ToObject(typeof(Guid))));
Assert.AreEqual(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C"), (new JValue(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C")).ToObject(typeof(Guid?))));
Assert.AreEqual(new Uri("http://www.google.com/"), (new JValue(new Uri("http://www.google.com/")).ToObject(typeof(Uri))));
Assert.AreEqual(StringComparison.Ordinal, (new JValue("Ordinal").ToObject(typeof(StringComparison))));
Assert.AreEqual(StringComparison.Ordinal, (new JValue("Ordinal").ToObject(typeof(StringComparison?))));
Assert.AreEqual(null, (JValue.CreateNull().ToObject(typeof(StringComparison?))));
}
[Test]
public void ImplicitCastingTo()
{
Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTime(2000, 12, 20)), (JValue)new DateTime(2000, 12, 20)));
#if !NET20
Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)), (JValue)new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTimeOffset?)null), (JValue)(DateTimeOffset?)null));
#endif
#if !(NET20 || NET35 || PORTABLE || ASPNETCORE50 || PORTABLE40)
// had to remove implicit casting to avoid user reference to System.Numerics.dll
Assert.IsTrue(JToken.DeepEquals(new JValue(new BigInteger(1)), new JValue(new BigInteger(1))));
Assert.IsTrue(JToken.DeepEquals(new JValue((BigInteger?)null), new JValue((BigInteger?)null)));
#endif
Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true));
Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true));
Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)(bool?)true));
Assert.IsTrue(JToken.DeepEquals(new JValue((bool?)null), (JValue)(bool?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(10), (JValue)10));
Assert.IsTrue(JToken.DeepEquals(new JValue((long?)null), (JValue)(long?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(long.MaxValue), (JValue)long.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue((int?)null), (JValue)(int?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((short?)null), (JValue)(short?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((double?)null), (JValue)(double?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((uint?)null), (JValue)(uint?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((decimal?)null), (JValue)(decimal?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((ulong?)null), (JValue)(ulong?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte?)null), (JValue)(sbyte?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte)1), (JValue)(sbyte)1));
Assert.IsTrue(JToken.DeepEquals(new JValue((byte?)null), (JValue)(byte?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((byte)1), (JValue)(byte)1));
Assert.IsTrue(JToken.DeepEquals(new JValue((ushort?)null), (JValue)(ushort?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(short.MaxValue), (JValue)short.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ushort.MaxValue), (JValue)ushort.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(11.1f), (JValue)11.1f));
Assert.IsTrue(JToken.DeepEquals(new JValue(float.MinValue), (JValue)float.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(double.MinValue), (JValue)double.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(uint.MaxValue), (JValue)uint.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MaxValue), (JValue)ulong.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MinValue), (JValue)ulong.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue((string)null), (JValue)(string)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)decimal.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)(decimal?)decimal.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MinValue), (JValue)decimal.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(float.MaxValue), (JValue)(float?)float.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(double.MaxValue), (JValue)(double?)double.MaxValue));
Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(double?)null));
Assert.IsFalse(JToken.DeepEquals(new JValue(true), (JValue)(bool?)null));
Assert.IsFalse(JToken.DeepEquals(JValue.CreateNull(), (JValue)(object)null));
byte[] emptyData = new byte[0];
Assert.IsTrue(JToken.DeepEquals(new JValue(emptyData), (JValue)emptyData));
Assert.IsFalse(JToken.DeepEquals(new JValue(emptyData), (JValue)new byte[1]));
Assert.IsTrue(JToken.DeepEquals(new JValue(Encoding.UTF8.GetBytes("Hi")), (JValue)Encoding.UTF8.GetBytes("Hi")));
Assert.IsTrue(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)TimeSpan.FromMinutes(1)));
Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(TimeSpan?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)(TimeSpan?)TimeSpan.FromMinutes(1)));
Assert.IsTrue(JToken.DeepEquals(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")), (JValue)new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")));
Assert.IsTrue(JToken.DeepEquals(new JValue(new Uri("http://www.google.com")), (JValue)new Uri("http://www.google.com")));
Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(Uri)null));
Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(Guid?)null));
}
[Test]
public void Root()
{
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
Assert.AreEqual(a, a.Root);
Assert.AreEqual(a, a[0].Root);
Assert.AreEqual(a, ((JArray)a[2])[0].Root);
}
[Test]
public void Remove()
{
JToken t;
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
a[0].Remove();
Assert.AreEqual(6, (int)a[0]);
a[1].Remove();
Assert.AreEqual(6, (int)a[0]);
Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), a[1]));
Assert.AreEqual(2, a.Count());
t = a[1];
t.Remove();
Assert.AreEqual(6, (int)a[0]);
Assert.IsNull(t.Next);
Assert.IsNull(t.Previous);
Assert.IsNull(t.Parent);
t = a[0];
t.Remove();
Assert.AreEqual(0, a.Count());
Assert.IsNull(t.Next);
Assert.IsNull(t.Previous);
Assert.IsNull(t.Parent);
}
[Test]
public void AfterSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[1];
List<JToken> afterTokens = t.AfterSelf().ToList();
Assert.AreEqual(2, afterTokens.Count);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2), afterTokens[0]));
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), afterTokens[1]));
}
[Test]
public void BeforeSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[2];
List<JToken> beforeTokens = t.BeforeSelf().ToList();
Assert.AreEqual(2, beforeTokens.Count);
Assert.IsTrue(JToken.DeepEquals(new JValue(5), beforeTokens[0]));
Assert.IsTrue(JToken.DeepEquals(new JArray(1), beforeTokens[1]));
}
[Test]
public void HasValues()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
Assert.IsTrue(a.HasValues);
}
[Test]
public void Ancestors()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[1][0];
List<JToken> ancestors = t.Ancestors().ToList();
Assert.AreEqual(2, ancestors.Count());
Assert.AreEqual(a[1], ancestors[0]);
Assert.AreEqual(a, ancestors[1]);
}
[Test]
public void Descendants()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
List<JToken> descendants = a.Descendants().ToList();
Assert.AreEqual(10, descendants.Count());
Assert.AreEqual(5, (int)descendants[0]);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendants[descendants.Count - 4]));
Assert.AreEqual(1, (int)descendants[descendants.Count - 3]);
Assert.AreEqual(2, (int)descendants[descendants.Count - 2]);
Assert.AreEqual(3, (int)descendants[descendants.Count - 1]);
}
[Test]
public void CreateWriter()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JsonWriter writer = a.CreateWriter();
Assert.IsNotNull(writer);
Assert.AreEqual(4, a.Count());
writer.WriteValue("String");
Assert.AreEqual(5, a.Count());
Assert.AreEqual("String", (string)a[4]);
writer.WriteStartObject();
writer.WritePropertyName("Property");
writer.WriteValue("PropertyValue");
writer.WriteEnd();
Assert.AreEqual(6, a.Count());
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("Property", "PropertyValue")), a[5]));
}
[Test]
public void AddFirst()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a.AddFirst("First");
Assert.AreEqual("First", (string)a[0]);
Assert.AreEqual(a, a[0].Parent);
Assert.AreEqual(a[1], a[0].Next);
Assert.AreEqual(5, a.Count());
a.AddFirst("NewFirst");
Assert.AreEqual("NewFirst", (string)a[0]);
Assert.AreEqual(a, a[0].Parent);
Assert.AreEqual(a[1], a[0].Next);
Assert.AreEqual(6, a.Count());
Assert.AreEqual(a[0], a[0].Next.Previous);
}
[Test]
public void RemoveAll()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken first = a.First;
Assert.AreEqual(5, (int)first);
a.RemoveAll();
Assert.AreEqual(0, a.Count());
Assert.IsNull(first.Parent);
Assert.IsNull(first.Next);
}
[Test]
public void AddPropertyToArray()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JArray a = new JArray();
a.Add(new JProperty("PropertyName"));
}, "Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.");
}
[Test]
public void AddValueToObject()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o.Add(5);
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void Replace()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a[0].Replace(new JValue(int.MaxValue));
Assert.AreEqual(int.MaxValue, (int)a[0]);
Assert.AreEqual(4, a.Count());
a[1][0].Replace(new JValue("Test"));
Assert.AreEqual("Test", (string)a[1][0]);
a[2].Replace(new JValue(int.MaxValue));
Assert.AreEqual(int.MaxValue, (int)a[2]);
Assert.AreEqual(4, a.Count());
Assert.IsTrue(JToken.DeepEquals(new JArray(int.MaxValue, new JArray("Test"), int.MaxValue, new JArray(1, 2, 3)), a));
}
[Test]
public void ToStringWithConverters()
{
JArray a =
new JArray(
new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc))
);
string json = a.ToString(Formatting.Indented, new IsoDateTimeConverter());
StringAssert.AreEqual(@"[
""2009-02-15T00:00:00Z""
]", json);
json = JsonConvert.SerializeObject(a, new IsoDateTimeConverter());
Assert.AreEqual(@"[""2009-02-15T00:00:00Z""]", json);
}
[Test]
public void ToStringWithNoIndenting()
{
JArray a =
new JArray(
new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc))
);
string json = a.ToString(Formatting.None, new IsoDateTimeConverter());
Assert.AreEqual(@"[""2009-02-15T00:00:00Z""]", json);
}
[Test]
public void AddAfterSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a[1].AddAfterSelf("pie");
Assert.AreEqual(5, (int)a[0]);
Assert.AreEqual(1, a[1].Count());
Assert.AreEqual("pie", (string)a[2]);
Assert.AreEqual(5, a.Count());
a[4].AddAfterSelf("lastpie");
Assert.AreEqual("lastpie", (string)a[5]);
Assert.AreEqual("lastpie", (string)a.Last);
}
[Test]
public void AddBeforeSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a[1].AddBeforeSelf("pie");
Assert.AreEqual(5, (int)a[0]);
Assert.AreEqual("pie", (string)a[1]);
Assert.AreEqual(a, a[1].Parent);
Assert.AreEqual(a[2], a[1].Next);
Assert.AreEqual(5, a.Count());
a[0].AddBeforeSelf("firstpie");
Assert.AreEqual("firstpie", (string)a[0]);
Assert.AreEqual(5, (int)a[1]);
Assert.AreEqual("pie", (string)a[2]);
Assert.AreEqual(a, a[0].Parent);
Assert.AreEqual(a[1], a[0].Next);
Assert.AreEqual(6, a.Count());
a.Last.AddBeforeSelf("secondlastpie");
Assert.AreEqual("secondlastpie", (string)a[5]);
Assert.AreEqual(7, a.Count());
}
[Test]
public void DeepClone()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3),
new JObject(
new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))),
new JProperty("Second", 1),
new JProperty("Third", null),
new JProperty("Fourth", new JConstructor("Date", 12345)),
new JProperty("Fifth", double.PositiveInfinity),
new JProperty("Sixth", double.NaN)
)
);
JArray a2 = (JArray)a.DeepClone();
Console.WriteLine(a2.ToString(Formatting.Indented));
Assert.IsTrue(a.DeepEquals(a2));
}
#if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40)
[Test]
public void Clone()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3),
new JObject(
new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))),
new JProperty("Second", 1),
new JProperty("Third", null),
new JProperty("Fourth", new JConstructor("Date", 12345)),
new JProperty("Fifth", double.PositiveInfinity),
new JProperty("Sixth", double.NaN)
)
);
ICloneable c = a;
JArray a2 = (JArray)c.Clone();
Assert.IsTrue(a.DeepEquals(a2));
}
#endif
[Test]
public void DoubleDeepEquals()
{
JArray a =
new JArray(
double.NaN,
double.PositiveInfinity,
double.NegativeInfinity
);
JArray a2 = (JArray)a.DeepClone();
Assert.IsTrue(a.DeepEquals(a2));
double d = 1 + 0.1 + 0.1 + 0.1;
JValue v1 = new JValue(d);
JValue v2 = new JValue(1.3);
Assert.IsTrue(v1.DeepEquals(v2));
}
[Test]
public void ParseAdditionalContent()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string json = @"[
""Small"",
""Medium"",
""Large""
],";
JToken.Parse(json);
}, "Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.");
}
[Test]
public void Path()
{
JObject o =
new JObject(
new JProperty("Test1", new JArray(1, 2, 3)),
new JProperty("Test2", "Test2Value"),
new JProperty("Test3", new JObject(new JProperty("Test1", new JArray(1, new JObject(new JProperty("Test1", 1)), 3)))),
new JProperty("Test4", new JConstructor("Date", new JArray(1, 2, 3)))
);
JToken t = o.SelectToken("Test1[0]");
Assert.AreEqual("Test1[0]", t.Path);
t = o.SelectToken("Test2");
Assert.AreEqual("Test2", t.Path);
t = o.SelectToken("");
Assert.AreEqual("", t.Path);
t = o.SelectToken("Test4[0][0]");
Assert.AreEqual("Test4[0][0]", t.Path);
t = o.SelectToken("Test4[0]");
Assert.AreEqual("Test4[0]", t.Path);
t = t.DeepClone();
Assert.AreEqual("", t.Path);
t = o.SelectToken("Test3.Test1[1].Test1");
Assert.AreEqual("Test3.Test1[1].Test1", t.Path);
JArray a = new JArray(1);
Assert.AreEqual("", a.Path);
Assert.AreEqual("[0]", a[0].Path);
}
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
//
// Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// 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.Diagnostics;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.IO;
#if GDI
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
#endif
#if WPF
using System.Windows.Media;
#endif
using PdfSharp.Internal;
using PdfSharp.Drawing.Pdf;
using PdfSharp.Fonts.OpenType;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.Advanced;
using PdfSharp.Pdf.Filters;
using PdfSharp.Pdf.Internal;
namespace PdfSharp.Drawing
{
/// <summary>
/// Represents a graphical object that can be used to render retained graphics on it.
/// In GDI+ it is represented by a Metafile, in WPF by a DrawingVisual, and in PDF by a Form XObjects.
/// </summary>
public class XForm : XImage, IContentStream
{
internal enum FormState
{
/// <summary>
/// The form is an imported PDF page.
/// </summary>
NotATemplate,
/// <summary>
/// The template is just created.
/// </summary>
Created,
/// <summary>
/// XGraphics.FromForm() was called.
/// </summary>
UnderConstruction,
/// <summary>
/// The form was drawn at least once and is 'frozen' now.
/// </summary>
Finished,
}
/// <summary>
/// Initializes a new instance of the <see cref="XForm"/> class.
/// </summary>
protected XForm()
{ }
#if GDI
/// <summary>
/// Initializes a new instance of the XForm class such that it can be drawn on the specified graphics
/// object.
/// </summary>
/// <param name="gfx">The graphics object that later is used to draw this form.</param>
/// <param name="size">The size in points of the form.</param>
public XForm(XGraphics gfx, XSize size)
{
if (gfx == null)
throw new ArgumentNullException("gfx");
if (size.width < 1 || size.height < 1)
throw new ArgumentNullException("size", "The size of the XPdfForm is to small.");
this.formState = FormState.Created;
//this.templateSize = size;
this.viewBox.width = size.width;
this.viewBox.height = size.height;
// If gfx belongs to a PdfPage also create the PdfFormXObject
if (gfx.PdfPage != null)
{
this.document = gfx.PdfPage.Owner;
this.pdfForm = new PdfFormXObject(this.document, this);
PdfRectangle rect = new PdfRectangle(new XPoint(), size);
this.pdfForm.Elements.SetRectangle(PdfFormXObject.Keys.BBox, rect);
}
}
#endif
#if GDI
/// <summary>
/// Initializes a new instance of the XForm class such that it can be drawn on the specified graphics
/// object.
/// </summary>
/// <param name="gfx">The graphics object that later is used to draw this form.</param>
/// <param name="width">The width of the form.</param>
/// <param name="height">The height of the form.</param>
public XForm(XGraphics gfx, XUnit width, XUnit height)
: this(gfx, new XSize(width, height))
{ }
#endif
/// <summary>
/// Initializes a new instance of the <see cref="XForm"/> class that represents a page of a PDF document.
/// </summary>
/// <param name="document">The PDF document.</param>
/// <param name="viewBox">The view box of the page.</param>
public XForm(PdfDocument document, XRect viewBox)
{
if (viewBox.width < 1 || viewBox.height < 1)
throw new ArgumentNullException("viewBox", "The size of the XPdfForm is to small.");
// I must tie the XPdfForm to a document immediately, because otherwise I would have no place where
// to store the resources.
if (document == null)
throw new ArgumentNullException("document", "An XPdfForm template must be associated with a document at creation time.");
this.formState = FormState.Created;
this.document = document;
this.pdfForm = new PdfFormXObject(document, this);
//this.templateSize = size;
this.viewBox = viewBox;
PdfRectangle rect = new PdfRectangle(viewBox);
this.pdfForm.Elements.SetRectangle(PdfFormXObject.Keys.BBox, rect);
}
/// <summary>
/// Initializes a new instance of the <see cref="XForm"/> class that represents a page of a PDF document.
/// </summary>
/// <param name="document">The PDF document.</param>
/// <param name="size">The size of the page.</param>
public XForm(PdfDocument document, XSize size)
: this(document, new XRect(0, 0, size.width, size.height))
{
////if (size.width < 1 || size.height < 1)
//// throw new ArgumentNullException("size", "The size of the XPdfForm is to small.");
////// I must tie the XPdfForm to a document immediately, because otherwise I would have no place where
////// to store the resources.
////if (document == null)
//// throw new ArgumentNullException("document", "An XPdfForm template must be associated with a document.");
////this.formState = FormState.Created;
////this.document = document;
////this.pdfForm = new PdfFormXObject(document, this);
////this.templateSize = size;
////PdfRectangle rect = new PdfRectangle(new XPoint(), size);
////this.pdfForm.Elements.SetRectangle(PdfFormXObject.Keys.BBox, rect);
}
/// <summary>
/// Initializes a new instance of the <see cref="XForm"/> class that represents a page of a PDF document.
/// </summary>
/// <param name="document">The PDF document.</param>
/// <param name="width">The width of the page.</param>
/// <param name="height">The height of the page</param>
public XForm(PdfDocument document, XUnit width, XUnit height)
: this(document, new XRect(0, 0, width, height))
{ }
/// <summary>
/// This function should be called when drawing the content of this form is finished.
/// The XGraphics object used for drawing the content is disposed by this function and
/// cannot be used for any further drawing operations.
/// PDFsharp automatically calls this function when this form was used the first time
/// in a DrawImage function.
/// </summary>
public void DrawingFinished()
{
if (this.formState == FormState.Finished)
return;
if (this.formState == FormState.NotATemplate)
throw new InvalidOperationException("This object is an imported PDF page and you cannot finish drawing on it because you must not draw on it at all.");
Finish();
}
/// <summary>
/// Called from XGraphics constructor that creates an instance that work on this form.
/// </summary>
internal void AssociateGraphics(XGraphics gfx)
{
if (this.formState == FormState.NotATemplate)
throw new NotImplementedException("The current version of PDFsharp cannot draw on an imported page.");
if (this.formState == FormState.UnderConstruction)
throw new InvalidOperationException("An XGraphics object already exists for this form.");
if (this.formState == FormState.Finished)
throw new InvalidOperationException("After drawing a form it cannot be modified anymore.");
Debug.Assert(this.formState == FormState.Created);
this.formState = FormState.UnderConstruction;
this.gfx = gfx;
}
internal XGraphics gfx;
/// <summary>
/// Disposes this instance.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
/// <summary>
/// Sets the form in the state FormState.Finished.
/// </summary>
internal virtual void Finish()
{
#if GDI
if (this.formState == FormState.NotATemplate || this.formState == FormState.Finished)
return;
if (this.gfx.metafile != null)
this.gdiImage = this.gfx.metafile;
Debug.Assert(this.formState == FormState.Created || this.formState == FormState.UnderConstruction);
this.formState = FormState.Finished;
this.gfx.Dispose();
this.gfx = null;
if (this.pdfRenderer != null)
{
//this.pdfForm.CreateStream(PdfEncoders.RawEncoding.GetBytes(this.pdfRenderer.GetContent()));
this.pdfRenderer.Close();
Debug.Assert(this.pdfRenderer == null);
if (this.document.Options.CompressContentStreams)
{
this.pdfForm.Stream.Value = Filtering.FlateDecode.Encode(this.pdfForm.Stream.Value);
this.pdfForm.Elements["/Filter"] = new PdfName("/FlateDecode");
}
int length = this.pdfForm.Stream.Length;
this.pdfForm.Elements.SetInteger("/Length", length);
}
#endif
#if WPF
#endif
}
/// <summary>
/// Gets the owning document.
/// </summary>
internal PdfDocument Owner
{
get { return this.document; }
}
PdfDocument document;
/// <summary>
/// Gets the color model used in the underlying PDF document.
/// </summary>
internal PdfColorMode ColorMode
{
get
{
if (this.document == null)
return PdfColorMode.Undefined;
return this.document.Options.ColorMode;
}
}
/// <summary>
/// Gets a value indicating whether this instance is a template.
/// </summary>
internal bool IsTemplate
{
get { return this.formState != FormState.NotATemplate; }
}
internal FormState formState;
/// <summary>
/// Get the width of the page identified by the property PageNumber.
/// </summary>
[Obsolete("Use either PixelWidth or PointWidth. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelWidth, but will become PointWidth in future releases of PDFsharp.")]
public override double Width
{
//get { return this.templateSize.width; }
get { return this.viewBox.Width; }
}
/// <summary>
/// Get the width of the page identified by the property PageNumber.
/// </summary>
[Obsolete("Use either PixelHeight or PointHeight. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelHeight, but will become PointHeight in future releases of PDFsharp.")]
public override double Height
{
//get { return this.templateSize.height; }
get { return this.viewBox.height; }
}
/// <summary>
/// Get the width in point of this image.
/// </summary>
public override double PointWidth
{
//get { return this.templateSize.width; }
get { return this.viewBox.width; }
}
/// <summary>
/// Get the height in point of this image.
/// </summary>
public override double PointHeight
{
//get { return this.templateSize.height; }
get { return this.viewBox.height; }
}
/// <summary>
/// Get the width of the page identified by the property PageNumber.
/// </summary>
public override int PixelWidth
{
//get { return (int)this.templateSize.width; }
get { return (int)this.viewBox.width; }
}
/// <summary>
/// Get the height of the page identified by the property PageNumber.
/// </summary>
public override int PixelHeight
{
//get { return (int)this.templateSize.height; }
get { return (int)this.viewBox.height; }
}
/// <summary>
/// Get the size of the page identified by the property PageNumber.
/// </summary>
public override XSize Size
{
//get { return this.templateSize; }
get { return this.viewBox.Size; }
}
//XSize templateSize;
/// <summary>
/// Gets the view box of the form.
/// </summary>
public XRect ViewBox
{
get { return this.viewBox; }
}
XRect viewBox;
/// <summary>
/// Gets 72, the horizontal resolution by design of a form object.
/// </summary>
public override double HorizontalResolution
{
get { return 72; }
}
/// <summary>
/// Gets 72 always, the vertical resolution by design of a form object.
/// </summary>
public override double VerticalResolution
{
get { return 72; }
}
/// <summary>
/// Gets or sets the bounding box.
/// </summary>
public XRect BoundingBox
{
get { return this.boundingBox; }
set { this.boundingBox = value; } // TODO: pdfForm = null
}
XRect boundingBox;
/// <summary>
/// Gets or sets the transformation matrix.
/// </summary>
public virtual XMatrix Transform
{
get { return this.transform; }
set
{
if (this.formState == FormState.Finished)
throw new InvalidOperationException("After a XPdfForm was once drawn it must not be modified.");
this.transform = value;
}
}
internal XMatrix transform = new XMatrix(); //XMatrix.Identity;
internal PdfResources Resources
{
get
{
Debug.Assert(IsTemplate, "This function is for form templates only.");
return PdfForm.Resources;
//if (this.resources == null)
// this.resources = (PdfResources)this.pdfForm.Elements.GetValue(PdfFormXObject.Keys.Resources, VCF.Create); // VCF.CreateIndirect
//return this.resources;
}
}
//PdfResources resources;
/// <summary>
/// Implements the interface because the primary function is internal.
/// </summary>
PdfResources IContentStream.Resources
{
get { return Resources; }
}
/// <summary>
/// Gets the resource name of the specified font within this form.
/// </summary>
internal string GetFontName(XFont font, out PdfFont pdfFont)
{
Debug.Assert(IsTemplate, "This function is for form templates only.");
pdfFont = this.document.FontTable.GetFont(font);
Debug.Assert(pdfFont != null);
string name = Resources.AddFont(pdfFont);
return name;
}
string IContentStream.GetFontName(XFont font, out PdfFont pdfFont)
{
return GetFontName(font, out pdfFont);
}
/// <summary>
/// Tries to get the resource name of the specified font data within this form.
/// Returns null if no such font exists.
/// </summary>
internal string TryGetFontName(string idName, out PdfFont pdfFont)
{
Debug.Assert(IsTemplate, "This function is for form templates only.");
pdfFont = this.document.FontTable.TryGetFont(idName);
string name = null;
if (pdfFont != null)
name = Resources.AddFont(pdfFont);
return name;
}
/// <summary>
/// Gets the resource name of the specified font data within this form.
/// </summary>
internal string GetFontName(string idName, byte[] fontData, out PdfFont pdfFont)
{
Debug.Assert(IsTemplate, "This function is for form templates only.");
pdfFont = this.document.FontTable.GetFont(idName, fontData);
//pdfFont = new PdfType0Font(Owner, idName, fontData);
//pdfFont.Document = this.document;
Debug.Assert(pdfFont != null);
string name = Resources.AddFont(pdfFont);
return name;
}
string IContentStream.GetFontName(string idName, byte[] fontData, out PdfFont pdfFont)
{
return GetFontName(idName, fontData, out pdfFont);
}
/// <summary>
/// Gets the resource name of the specified image within this form.
/// </summary>
internal string GetImageName(XImage image)
{
Debug.Assert(IsTemplate, "This function is for form templates only.");
PdfImage pdfImage = this.document.ImageTable.GetImage(image);
Debug.Assert(pdfImage != null);
string name = Resources.AddImage(pdfImage);
return name;
}
/// <summary>
/// Implements the interface because the primary function is internal.
/// </summary>
string IContentStream.GetImageName(XImage image)
{
return GetImageName(image);
}
internal PdfFormXObject PdfForm
{
get
{
Debug.Assert(IsTemplate, "This function is for form templates only.");
if (this.pdfForm.Reference == null)
this.document.irefTable.Add(this.pdfForm);
return this.pdfForm;
}
}
/// <summary>
/// Gets the resource name of the specified form within this form.
/// </summary>
internal string GetFormName(XForm form)
{
Debug.Assert(IsTemplate, "This function is for form templates only.");
PdfFormXObject pdfForm = this.document.FormTable.GetForm(form);
Debug.Assert(pdfForm != null);
string name = Resources.AddForm(pdfForm);
return name;
}
/// <summary>
/// Implements the interface because the primary function is internal.
/// </summary>
string IContentStream.GetFormName(XForm form)
{
return GetFormName(form);
}
/// <summary>
/// The PdfFormXObject gets invalid when PageNumber or transform changed. This is because a modification
/// of an XPdfForm must not change objects that are already been drawn.
/// </summary>
internal PdfFormXObject pdfForm;
internal XGraphicsPdfRenderer pdfRenderer;
#if WPF && !SILVERLIGHT
/// <summary>
/// Gets a value indicating whether this image is cmyk.
/// </summary>
/// <value><c>true</c> if this image is cmyk; otherwise, <c>false</c>.</value>
public override bool IsCmyk
{
get { return false; } // not supported and not relevant
}
/// <summary>
/// Gets a value indicating whether this image is JPEG.
/// </summary>
/// <value><c>true</c> if this image is JPEG; otherwise, <c>false</c>.</value>
public override bool IsJpeg
{
get { return base.IsJpeg; }// not supported and not relevant
}
/// <summary>
/// Gets the JPEG memory stream (if IsJpeg returns true).
/// </summary>
/// <value>The memory.</value>
public override MemoryStream Memory
{
get { throw new NotImplementedException(); }
}
#endif
}
}
| |
/*
* BinaryValueReader.cs - Implementation of the
* "System.Runtime.Serialization.Formatters.Binary.BinaryValueReader" class.
*
* Copyright (C) 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.Runtime.Serialization.Formatters.Binary
{
#if CONFIG_SERIALIZATION
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
/*
* unsupported features:
* - BinaryElementType.MethodCall: not needed by me :-)
* - BinaryElementType.MethodResponse: not needed by me :-)
* - user defined serialization headers
*
* unsupported array types:
* - Arrays of Enums
* - BinaryArrayType.Jagged
* - BinaryArrayType.Multidimensional
* - BinaryArrayType.SingleWithLowerBounds
* - BinaryArrayType.JaggedWithLowerBounds
* - BinaryArrayType.MultidimensionalWithLowerBounds
*/
/*
* this class contains all context info for a single deserialization.
*/
internal class DeserializationContext
{
// the manager used for unresolved references
public ObjectManager Manager;
// the reader supplying the data
public BinaryReader Reader;
// meta-info for already deserialized types is stored here
private Hashtable mTypeStore;
// meta-info for already loaded assemblies is stored here
private Hashtable mAssemblyStore;
// the calling BinaryFormatter (not used for now)
public BinaryFormatter Formatter;
// info if there are user defined headers (not used for now as
// headers are not supported for now)
public bool IsHeaderPresent;
// major and minor version used for serialization
public uint MajorVersion, MinorVersion;
public DeserializationContext(BinaryFormatter formatter,
BinaryReader reader)
{
Formatter = formatter;
Reader = reader;
mTypeStore = new Hashtable();
mAssemblyStore = new Hashtable();
Manager = new ObjectManager(formatter.SurrogateSelector,
formatter.Context);
}
public void SetAssembly(uint id, Assembly val)
{
mAssemblyStore[id] = val;
}
public Assembly GetAssembly(uint id)
{
if(!mAssemblyStore.ContainsKey(id))
{
throw new SerializationException("unknown assembly id:"+id);
}
else
{
return (Assembly) mAssemblyStore[id];
}
}
public void SetTypeInfo(uint id, TypeInfo val)
{
mTypeStore[id] = val;
}
public TypeInfo GetTypeInfo(uint id)
{
if(!mTypeStore.ContainsKey(id))
{
throw new SerializationException("unknown typeinfo id:"+id);
}
else
{
return (TypeInfo) mTypeStore[id];
}
}
}
/*
* stores information about the type of a field.
*/
internal class TypeSpecification
{
private BinaryTypeTag mTag;
private BinaryPrimitiveTypeCode mPrimitiveType;
private String mClassName;
private uint mAssembly;
public TypeSpecification(BinaryPrimitiveTypeCode primitive)
{
mPrimitiveType = primitive;
mTag = BinaryTypeTag.PrimitiveType;
}
public TypeSpecification(String name, uint ass)
{
mClassName = name;
mAssembly = ass;
mTag = BinaryTypeTag.GenericType;
}
public TypeSpecification(String name)
{
mClassName = name;
mTag = BinaryTypeTag.RuntimeType;
}
public BinaryPrimitiveTypeCode GetPrimitiveType()
{
if(mTag != BinaryTypeTag.PrimitiveType)
{
throw new SerializationException("illegal usage if type-spec");
}
else
{
return mPrimitiveType;
}
}
public Type GetObjectType(DeserializationContext context)
{
if(mTag == BinaryTypeTag.PrimitiveType)
{
return BinaryValueReader.GetPrimitiveType(mPrimitiveType);
}
else if(mTag == BinaryTypeTag.RuntimeType)
{
return Type.GetType(mClassName, true);
}
else
{
Assembly assembly = context.GetAssembly(mAssembly);
return assembly.GetType(mClassName, true);
}
}
}
/*
* stores info about an already deserialized Type
*/
internal class TypeInfo
{
private String[] mFieldNames;
private BinaryTypeTag[] mTypeTag;
private TypeSpecification[] mTypeSpec;
private Type mObjectType;
private MemberInfo[] mMembers;
private bool mIsIserializable;
private FormatterConverter mConverter;
public TypeInfo(DeserializationContext context, String name, String[] fieldNames,
BinaryTypeTag[] tt, TypeSpecification[] ts, Assembly assembly)
{
mConverter = context.Formatter.converter;
mFieldNames = fieldNames;
mTypeTag = tt;
mTypeSpec = ts;
// lookup our type in the right assembly
if(assembly == null)
{
mObjectType = Type.GetType(name, true);
}
else
{
mObjectType = assembly.GetType(name, true);
}
if(typeof(ISerializable).IsAssignableFrom(mObjectType))
{
mIsIserializable = true;
}
else
{
mIsIserializable = false;
// lookup all members once
mMembers = new MemberInfo[NumMembers];
for(int i = 0; i < NumMembers; i++)
{
// ms and mono have their values for boxed primitive types called 'm_value', we need a fix for that
if(mObjectType.IsPrimitive && (mFieldNames[i] == "m_value"))
{
mFieldNames[i] = "value_";
}
else if (mObjectType == typeof(DateTime) &&
(mFieldNames[i] == "ticks"))
{
// this is for DateTime
mFieldNames[i] = "value_";
}
else if (mObjectType == typeof(TimeSpan) &&
(mFieldNames[i] == "_ticks"))
{
// this is for TimeSpan
mFieldNames[i] = "value_";
}
else if (mObjectType == typeof(Decimal))
{
switch(mFieldNames[i])
{
case "hi":
{
mFieldNames[i] = "high";
}
break;
case "lo":
{
mFieldNames[i] = "low";
}
break;
case "mid":
{
mFieldNames[i] = "middle";
}
break;
}
}
Type memberType;
String memberName;
int classSeparator = mFieldNames[i].IndexOf('+');
if(classSeparator != -1)
{
/*
* TODO: check if there are constraints in which assembly
* the Type may be looked up! for now just look it up
* generally
*/
String baseName = mFieldNames[i].Substring(0, classSeparator);
memberName = mFieldNames[i].Substring(classSeparator+1, mFieldNames[i].Length-classSeparator-1);
memberType = mObjectType;
// MS does NOT store the FullQualifiedTypename if there
// is no collision but only the Typename :-(
while(!memberType.FullName.EndsWith(baseName))
{
// check if we reached System.Object
if(memberType == memberType.BaseType || memberType == null)
{
// TODO : I18n
throw new SerializationException("Can't find member "+mFieldNames[i]);
}
memberType = memberType.BaseType;
}
}
else
{
memberType = mObjectType;
memberName = mFieldNames[i];
}
// get member from object
MemberInfo[] members = memberType.GetMember(memberName,
MemberTypes.Field |
MemberTypes.Property,
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic);
if((members == null) || (members.Length < 1))
{
// TODO: I18n
throw new SerializationException("Can't find member "+mFieldNames[i]);
}
else
{
mMembers[i] = members[0];
}
}
}
}
public BinaryTypeTag GetTypeTag(uint index)
{
return mTypeTag[index];
}
public TypeSpecification GetTypeSpecification(uint index)
{
return mTypeSpec[index];
}
public MemberInfo GetMember(uint index)
{
return mMembers[index];
}
public String GetFieldName(uint index)
{
return mFieldNames[index];
}
public SerializationInfo GetSerializationInfo()
{
return new SerializationInfo(mObjectType, mConverter);
}
public Type ObjectType
{
get {return mObjectType; }
}
public int NumMembers
{
get { return mTypeTag.Length; }
}
public bool IsISerializable
{
get { return mIsIserializable; }
}
}
/*
* internal class that is passed arround to indicate that not a
* 'real' object was read, but only a reference to one.
*/
internal class DelayedReferenceHolder
{
private uint mReferenceId;
public DelayedReferenceHolder(uint refId)
{
mReferenceId = refId;
}
public uint ReferenceId
{
get { return mReferenceId; }
}
}
/*
* internal class that is passed arround to indicate that not a
* 'real' object was read, but a value indicating that an array
* should be filled with NULL values.
*/
internal class ArrayNullValueHolder
{
private uint mNumNullValues;
public ArrayNullValueHolder(uint num)
{
mNumNullValues = num;
}
public uint NumNullValues
{
get { return mNumNullValues; }
}
}
/*
* mother of all reading classes
*/
abstract class BinaryValueReader
{
private static BinaryValueReader sHeaderReader = new HeaderReader();
private static BinaryValueReader sEndReader = new EndReader();
private static BinaryValueReader sStringReader = new StringReader();
private static BinaryValueReader sNullReader = new NullReader();
private static BinaryValueReader sPrimitiveArrayReader = new PrimitiveArrayReader();
private static BinaryValueReader sStringArrayReader = new StringArrayReader();
private static BinaryValueReader sObjectArrayReader = new ObjectArrayReader();
private static BinaryValueReader sAssemblyReader = new AssemblyReader();
private static BinaryValueReader sExternalObjectReader = new ExternalObjectReader();
private static BinaryValueReader sRuntimeObjectReader = new RuntimeObjectReader();
private static BinaryValueReader sRefObjectReader = new RefObjectReader();
private static BinaryValueReader sObjectReferenceReader = new ObjectReferenceReader();
private static BinaryValueReader sGenericArrayReader = new GenericArrayReader();
private static BinaryValueReader sArrayFiller8bReader = new ArrayFiller8bReader();
private static BinaryValueReader sArrayFiller32bReader = new ArrayFiller32bReader();
private static BinaryValueReader sBoxedPrimitiveTypeValue = new BoxedPrimitiveTypeValue();
private static TypeSpecification sBooleanSpec = new TypeSpecification(BinaryPrimitiveTypeCode.Boolean);
private static TypeSpecification sByteSpec = new TypeSpecification(BinaryPrimitiveTypeCode.Byte);
private static TypeSpecification sCharSpec = new TypeSpecification(BinaryPrimitiveTypeCode.Char);
private static TypeSpecification sDecimalSpec = new TypeSpecification(BinaryPrimitiveTypeCode.Decimal);
private static TypeSpecification sDoubleSpec = new TypeSpecification(BinaryPrimitiveTypeCode.Double);
private static TypeSpecification sInt16Spec = new TypeSpecification(BinaryPrimitiveTypeCode.Int16);
private static TypeSpecification sInt32Spec = new TypeSpecification(BinaryPrimitiveTypeCode.Int32);
private static TypeSpecification sInt64Spec = new TypeSpecification(BinaryPrimitiveTypeCode.Int64);
private static TypeSpecification sSByteSpec = new TypeSpecification(BinaryPrimitiveTypeCode.SByte);
private static TypeSpecification sSingleSpec = new TypeSpecification(BinaryPrimitiveTypeCode.Single);
private static TypeSpecification sTimeSpanSpec = new TypeSpecification(BinaryPrimitiveTypeCode.TimeSpan);
private static TypeSpecification sDateTimeSpec = new TypeSpecification(BinaryPrimitiveTypeCode.DateTime);
private static TypeSpecification sUInt16Spec = new TypeSpecification(BinaryPrimitiveTypeCode.UInt16);
private static TypeSpecification sUInt32Spec = new TypeSpecification(BinaryPrimitiveTypeCode.UInt32);
private static TypeSpecification sUInt64Spec = new TypeSpecification(BinaryPrimitiveTypeCode.UInt64);
private static TypeSpecification sStringSpec = new TypeSpecification(BinaryPrimitiveTypeCode.String);
private static TypeSpecification sStringSpecObject = new TypeSpecification("System.String");
private static TypeSpecification sObjectSpec = new TypeSpecification("System.Object");
private static TypeSpecification sStringArraySpec = new TypeSpecification("System.String[]");
private static TypeSpecification sObjectArraySpec = new TypeSpecification("System.Object[]");
public static BinaryValueReader GetReader(BinaryElementType type)
{
switch(type)
{
case BinaryElementType.Header:
return sHeaderReader;
case BinaryElementType.RefTypeObject:
return sRefObjectReader;
case BinaryElementType.RuntimeObject:
return sRuntimeObjectReader;
case BinaryElementType.ExternalObject:
return sExternalObjectReader;
case BinaryElementType.String:
return sStringReader;
case BinaryElementType.GenericArray:
return sGenericArrayReader;
case BinaryElementType.BoxedPrimitiveTypeValue:
return sBoxedPrimitiveTypeValue;
case BinaryElementType.ObjectReference:
return sObjectReferenceReader;
case BinaryElementType.NullValue:
return sNullReader;
case BinaryElementType.End:
return sEndReader;
case BinaryElementType.Assembly:
return sAssemblyReader;
case BinaryElementType.ArrayFiller8b:
return sArrayFiller8bReader;
case BinaryElementType.ArrayFiller32b:
return sArrayFiller32bReader;
case BinaryElementType.ArrayOfPrimitiveType:
return sPrimitiveArrayReader;
case BinaryElementType.ArrayOfObject:
return sObjectArrayReader;
case BinaryElementType.ArrayOfString:
return sStringArrayReader;
case BinaryElementType.MethodCall:
throw new SerializationException("NYI element type:"+type);
case BinaryElementType.MethodResponse:
throw new SerializationException("NYI element type:"+type);
default:
throw new SerializationException("NYI element type:"+type);
}
}
public static Object ReadPrimitiveType(DeserializationContext context, BinaryPrimitiveTypeCode typeCode)
{
switch(typeCode)
{
case BinaryPrimitiveTypeCode.Boolean:
return context.Reader.ReadBoolean();
case BinaryPrimitiveTypeCode.Byte:
return context.Reader.ReadByte();
case BinaryPrimitiveTypeCode.Char:
return context.Reader.ReadChar();
case BinaryPrimitiveTypeCode.Decimal:
return Decimal.Parse(context.Reader.ReadString());
case BinaryPrimitiveTypeCode.Double:
return context.Reader.ReadDouble();
case BinaryPrimitiveTypeCode.Int16:
return context.Reader.ReadInt16();
case BinaryPrimitiveTypeCode.Int32:
return context.Reader.ReadInt32();
case BinaryPrimitiveTypeCode.Int64:
return context.Reader.ReadInt64();
case BinaryPrimitiveTypeCode.SByte:
return context.Reader.ReadSByte();
case BinaryPrimitiveTypeCode.Single:
return context.Reader.ReadSingle();
case BinaryPrimitiveTypeCode.TimeSpan:
return new TimeSpan(context.Reader.ReadInt64());
case BinaryPrimitiveTypeCode.DateTime:
return new DateTime(context.Reader.ReadInt64());
case BinaryPrimitiveTypeCode.UInt16:
return context.Reader.ReadUInt16();
case BinaryPrimitiveTypeCode.UInt32:
return context.Reader.ReadUInt32();
case BinaryPrimitiveTypeCode.UInt64:
return context.Reader.ReadUInt64();
case BinaryPrimitiveTypeCode.String:
return context.Reader.ReadString();
default:
throw new SerializationException("unknown primitive type code:"+typeCode);
}
}
public static void ReadPrimitiveTypeArray(DeserializationContext context, BinaryPrimitiveTypeCode typeCode, Array array)
{
int count = array.GetLength(0);
switch(typeCode)
{
case BinaryPrimitiveTypeCode.Boolean:
bool[] boolArray = (bool[]) array;
for(int i = 0; i < count; i++) {
boolArray[i] = context.Reader.ReadBoolean();
}
break;
case BinaryPrimitiveTypeCode.Byte:
byte[] byteArray = (byte[]) array;
for(int i = 0; i < count; i++) {
byteArray[i] = context.Reader.ReadByte();
}
break;
case BinaryPrimitiveTypeCode.Char:
char[] charArray = (char[]) array;
for(int i = 0; i < count; i++) {
charArray[i] = context.Reader.ReadChar();
}
break;
case BinaryPrimitiveTypeCode.Decimal:
decimal[] decimalArray = (decimal[]) array;
for(int i = 0; i < count; i++) {
decimalArray[i] = Decimal.Parse(context.Reader.ReadString());
}
break;
case BinaryPrimitiveTypeCode.Double:
double[] doubleArray = (double[]) array;
for(int i = 0; i < count; i++) {
doubleArray[i] = context.Reader.ReadDouble();
}
break;
case BinaryPrimitiveTypeCode.Int16:
short[] shortArray = (short[]) array;
for(int i = 0; i < count; i++) {
shortArray[i] = context.Reader.ReadInt16();
}
break;
case BinaryPrimitiveTypeCode.Int32:
int[] intArray = (int[]) array;
for(int i = 0; i < count; i++) {
intArray[i] = context.Reader.ReadInt32();
}
break;
case BinaryPrimitiveTypeCode.Int64:
long[] longArray = (long[]) array;
for(int i = 0; i < count; i++) {
longArray[i] = context.Reader.ReadInt64();
}
break;
case BinaryPrimitiveTypeCode.SByte:
sbyte[] sbyteArray = (sbyte[]) array;
for(int i = 0; i < count; i++) {
sbyteArray[i] = context.Reader.ReadSByte();
}
break;
case BinaryPrimitiveTypeCode.Single:
float[] singleArray = (float[]) array;
for(int i = 0; i < count; i++) {
singleArray[i] = context.Reader.ReadChar();
}
break;
case BinaryPrimitiveTypeCode.TimeSpan:
TimeSpan[] tsArray = (TimeSpan[]) array;
for(int i = 0; i < count; i++) {
tsArray[i] = new TimeSpan(context.Reader.ReadInt64());
}
break;
case BinaryPrimitiveTypeCode.DateTime:
DateTime[] dtArray = (DateTime[]) array;
for(int i = 0; i < count; i++) {
dtArray[i] = new DateTime(context.Reader.ReadInt64());
}
break;
case BinaryPrimitiveTypeCode.UInt16:
ushort[] ushortArray = (ushort[]) array;
for(int i = 0; i < count; i++) {
ushortArray[i] = context.Reader.ReadUInt16();
}
break;
case BinaryPrimitiveTypeCode.UInt32:
uint[] uintArray = (uint[]) array;
for(int i = 0; i < count; i++) {
uintArray[i] = context.Reader.ReadUInt32();
}
break;
case BinaryPrimitiveTypeCode.UInt64:
ulong[] ulongArray = (ulong[]) array;
for(int i = 0; i < count; i++) {
ulongArray[i] = context.Reader.ReadUInt64();
}
break;
case BinaryPrimitiveTypeCode.String:
string[] stringArray = (string[]) array;
for(int i = 0; i < count; i++) {
stringArray[i] = context.Reader.ReadString();
}
break;
default:
throw new SerializationException("unknown primitive type code:"+typeCode);
}
}
public static Type GetPrimitiveType(BinaryPrimitiveTypeCode typeCode)
{
switch(typeCode)
{
case BinaryPrimitiveTypeCode.Boolean:
return typeof(bool);
case BinaryPrimitiveTypeCode.Byte:
return typeof(byte);
case BinaryPrimitiveTypeCode.Char:
return typeof(char);
case BinaryPrimitiveTypeCode.Decimal:
return typeof(decimal);
case BinaryPrimitiveTypeCode.Double:
return typeof(double);
case BinaryPrimitiveTypeCode.Int16:
return typeof(Int16);
case BinaryPrimitiveTypeCode.Int32:
return typeof(Int32);
case BinaryPrimitiveTypeCode.Int64:
return typeof(Int64);
case BinaryPrimitiveTypeCode.SByte:
return typeof(sbyte);
case BinaryPrimitiveTypeCode.Single:
return typeof(Single);
case BinaryPrimitiveTypeCode.TimeSpan:
return typeof(TimeSpan);
case BinaryPrimitiveTypeCode.DateTime:
return typeof(DateTime);
case BinaryPrimitiveTypeCode.UInt16:
return typeof(UInt16);
case BinaryPrimitiveTypeCode.UInt32:
return typeof(UInt32);
case BinaryPrimitiveTypeCode.UInt64:
return typeof(UInt64);
case BinaryPrimitiveTypeCode.String:
return typeof(String);
default:
throw new SerializationException("unknown primitive type code:"+typeCode);
}
}
public static Object Deserialize(DeserializationContext context)
{
bool keepGoing = true;
Object tree = null;
// TODO: find better solution for finding the root of the object tree
do
{
Object other;
keepGoing = ReadValue(context, out other);
if(tree == null && other != null)
{
tree = other;
}
} while(keepGoing);
return tree;
}
public static bool ReadValue(DeserializationContext context, out Object outVal)
{
BinaryElementType element = (BinaryElementType) context.Reader.ReadByte();
BinaryValueReader reader = GetReader(element);
return reader.Read(context, out outVal);
}
public static TypeSpecification ReadTypeSpec(DeserializationContext context, BinaryTypeTag typeTag)
{
switch(typeTag)
{
case BinaryTypeTag.PrimitiveType:
case BinaryTypeTag.ArrayOfPrimitiveType:
BinaryPrimitiveTypeCode typeCode = (BinaryPrimitiveTypeCode) context.Reader.ReadByte();
switch(typeCode)
{
case BinaryPrimitiveTypeCode.Boolean:
return sBooleanSpec;
case BinaryPrimitiveTypeCode.Byte:
return sByteSpec;
case BinaryPrimitiveTypeCode.Char:
return sCharSpec;
case BinaryPrimitiveTypeCode.Decimal:
return sDecimalSpec;
case BinaryPrimitiveTypeCode.Double:
return sDoubleSpec;
case BinaryPrimitiveTypeCode.Int16:
return sInt16Spec;
case BinaryPrimitiveTypeCode.Int32:
return sInt32Spec;
case BinaryPrimitiveTypeCode.Int64:
return sInt64Spec;
case BinaryPrimitiveTypeCode.SByte:
return sSByteSpec;
case BinaryPrimitiveTypeCode.Single:
return sSingleSpec;
case BinaryPrimitiveTypeCode.TimeSpan:
return sTimeSpanSpec;
case BinaryPrimitiveTypeCode.DateTime:
return sDateTimeSpec;
case BinaryPrimitiveTypeCode.UInt16:
return sUInt16Spec;
case BinaryPrimitiveTypeCode.UInt32:
return sUInt32Spec;
case BinaryPrimitiveTypeCode.UInt64:
return sUInt64Spec;
case BinaryPrimitiveTypeCode.String:
return sStringArraySpec;
default:
throw new SerializationException("unknown primitive type code:"+typeCode);
}
throw new SerializationException("unknown primitive type code:"+typeCode);
case BinaryTypeTag.RuntimeType:
return new TypeSpecification(context.Reader.ReadString());
case BinaryTypeTag.GenericType:
String typeName = context.Reader.ReadString();
uint assId = context.Reader.ReadUInt32();
return new TypeSpecification(typeName, assId);
case BinaryTypeTag.String:
return sStringSpecObject;
case BinaryTypeTag.ObjectType:
return sObjectSpec;
case BinaryTypeTag.ArrayOfString:
return sStringArraySpec;
case BinaryTypeTag.ArrayOfObject:
return sObjectArraySpec;
default:
return null;
}
}
public abstract bool Read(DeserializationContext context, out Object outVal);
}
class NullReader : BinaryValueReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
outVal = null;
return true;
}
}
class EndReader : BinaryValueReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
context.Manager.DoFixups();
outVal = null;
return false;
}
}
class HeaderReader : BinaryValueReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
uint id = context.Reader.ReadUInt32();
// check if there is a serialization header
int hasHeader = context.Reader.ReadInt32();
if(hasHeader == 2)
{
context.IsHeaderPresent = true;
}
else if(hasHeader == -1)
{
context.IsHeaderPresent = false;
}
else
{
throw new SerializationException("unknown header specification:"+hasHeader);
}
// read major/minor version
context.MajorVersion = context.Reader.ReadUInt32();
context.MinorVersion = context.Reader.ReadUInt32();
outVal = null;
return true;
}
}
class StringReader : BinaryValueReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
uint id = context.Reader.ReadUInt32();
String str = context.Reader.ReadString();
context.Manager.RegisterObject(str, id);
outVal = str;
return true;
}
}
abstract class ArrayReader : BinaryValueReader
{
public bool Read(DeserializationContext context, uint id, uint count, Object type, out Object outVal)
{
bool ret = true;
Type convertedType;
Array array;
if(type is BinaryPrimitiveTypeCode)
{
// this is a primitive array
convertedType = GetPrimitiveType((BinaryPrimitiveTypeCode) type);
array = Array.CreateInstance(convertedType, (int) count);
ReadPrimitiveTypeArray(context, (BinaryPrimitiveTypeCode) type, array);
}
else if(type is Type)
{
// this is an object array
convertedType = (Type) type;
array = Array.CreateInstance(convertedType, (int) count);
for(int i = 0; i < count; i++)
{
Object val;
ret &= ReadValue(context, out val);
if(val is DelayedReferenceHolder)
{
// record this index for fixup
DelayedReferenceHolder holder = (DelayedReferenceHolder) val;
context.Manager.RecordArrayElementFixup(id, i, holder.ReferenceId);
}
else if(val is ArrayNullValueHolder)
{
ArrayNullValueHolder holder = (ArrayNullValueHolder) val;
for(int j = 0; j < holder.NumNullValues; j++)
{
array.SetValue(null, i);
i++;
}
}
else
{
// set this value
array.SetValue(val, i);
}
}
}
else
{
throw new SerializationException("illegal call with:"+type);
}
context.Manager.RegisterObject(array, id);
outVal = array;
return ret;
}
}
class StringArrayReader : ArrayReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
uint id = context.Reader.ReadUInt32();
uint count = context.Reader.ReadUInt32();
return Read(context, id, count, typeof(String), out outVal);
}
}
class ObjectArrayReader : ArrayReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
uint id = context.Reader.ReadUInt32();
uint count = context.Reader.ReadUInt32();
return Read(context, id, count, typeof(Object), out outVal);
}
}
class PrimitiveArrayReader : ArrayReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
uint id = context.Reader.ReadUInt32();
uint count = context.Reader.ReadUInt32();
BinaryPrimitiveTypeCode typeCode = (BinaryPrimitiveTypeCode) context.Reader.ReadByte();
return Read(context, id, count, typeCode, out outVal);
}
}
class GenericArrayReader : ArrayReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
uint id = context.Reader.ReadUInt32();
uint arrayType = context.Reader.ReadByte();
uint dimensions = context.Reader.ReadUInt32();
uint[] dimSizes = new uint[dimensions];
for(int i = 0; i < dimensions; i++)
{
dimSizes[i] = context.Reader.ReadUInt32();
}
// TODO: up to now we only support single dimension arrays
if(dimensions > 1 || ((BinaryArrayType) arrayType != BinaryArrayType.Single))
{
throw new SerializationException("array dimmensions > 1 || jagged arrays NYI!");
}
BinaryTypeTag typeTag = (BinaryTypeTag) context.Reader.ReadByte();
TypeSpecification typeSpec = ReadTypeSpec(context, typeTag);
if(typeTag == BinaryTypeTag.PrimitiveType)
{
return Read(context, id, dimSizes[0], typeSpec.GetPrimitiveType(), out outVal);
}
else
{
return Read(context, id, dimSizes[0], typeSpec.GetObjectType(context), out outVal);
}
}
}
class AssemblyReader : BinaryValueReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
uint id = context.Reader.ReadUInt32();
String name = context.Reader.ReadString();
// load specified assembly
Assembly assembly = Assembly.Load(name);
context.SetAssembly(id, assembly);
/*
* registering an assembly leads to instanciating at fixup which will not work
* context.mObjManager.RegisterObject(assembly, id);
*
* returning the assembly would break the (much to simple!) alg. in Deserialize()
* which chooses the first object
* outVal = assembly;
*/
outVal = null;
return true;
}
}
abstract class ObjectReader : BinaryValueReader
{
public bool Read(DeserializationContext context, out Object outVal, uint id, TypeInfo typeInfo)
{
bool ret = true;
// create instance
Object obj = null;
SerializationInfo info = null;
if(typeInfo.IsISerializable)
{
info = typeInfo.GetSerializationInfo();
// create instance
obj = FormatterServices.GetUninitializedObject(typeInfo.ObjectType);
// read and set values
for(uint i = 0; i < typeInfo.NumMembers; i++)
{
// first get inlined data
Object memberValue;
if(typeInfo.GetTypeTag(i) == BinaryTypeTag.PrimitiveType)
{
memberValue = ReadPrimitiveType(context, typeInfo.GetTypeSpecification(i).GetPrimitiveType());
}
else
{
ret &= ReadValue(context, out memberValue);
}
// set value
String field = typeInfo.GetFieldName(i);
if(memberValue is DelayedReferenceHolder)
{
// this is a reference
DelayedReferenceHolder holder = (DelayedReferenceHolder) memberValue;
context.Manager.RecordDelayedFixup(id, field, holder.ReferenceId);
}
else
{
// this is a real value
info.AddValue(field, memberValue, typeInfo.GetTypeSpecification(i).GetObjectType(context));
}
}
context.Manager.RegisterObject(obj, id, info);
}
else
{
// create instance
obj = FormatterServices.GetUninitializedObject(typeInfo.ObjectType);
// read and set values
for(uint i = 0; i < typeInfo.NumMembers; i++)
{
// first get inlined data
Object memberValue;
if(typeInfo.GetTypeTag(i) == BinaryTypeTag.PrimitiveType)
{
memberValue = ReadPrimitiveType(context, typeInfo.GetTypeSpecification(i).GetPrimitiveType());
}
else
{
ret &= ReadValue(context, out memberValue);
}
// set value
MemberInfo field = typeInfo.GetMember(i);
if(memberValue is DelayedReferenceHolder)
{
// this is a reference
DelayedReferenceHolder holder = (DelayedReferenceHolder) memberValue;
context.Manager.RecordFixup(id, field, holder.ReferenceId);
}
else
{
// this is a real value
if(field is FieldInfo)
{
FieldInfo fi = (FieldInfo) field;
fi.SetValue(obj, memberValue);
}
// TODO: i'm not sure if I have to cover that case, too!
// I just noticed that Mono does this
// else if(field is PropertyInfo)
// {
// PropertyInfo pi = (PropertyInfo) field;
// pi.SetValue();
else
{
throw new SerializationException("unknown memeber type:"+field.GetType());
}
}
}
context.Manager.RegisterObject(obj, id);
}
outVal = obj;
return ret;
}
}
abstract class FullObjectReader : ObjectReader
{
public bool Read(DeserializationContext context, out Object outVal, bool external)
{
uint id = context.Reader.ReadUInt32();
String name = context.Reader.ReadString();
uint fieldCount = context.Reader.ReadUInt32();
// collect the names of the fields
String[] fieldNames = new String[fieldCount];
for(int i = 0; i < fieldCount; i++)
{
fieldNames[i] = context.Reader.ReadString();
}
// collect the type-tags of the fields
BinaryTypeTag[] typeTags = new BinaryTypeTag[fieldCount];
for(int i = 0; i < fieldCount; i++)
{
typeTags[i] = (BinaryTypeTag) context.Reader.ReadByte();
}
// collect the type-specifications of the fields if necessary
TypeSpecification[] typeSpecs = new TypeSpecification[fieldCount];
for(int i = 0; i < fieldCount; i++)
{
typeSpecs[i] = ReadTypeSpec(context, typeTags[i]);
}
// read assembly-id if this is no runtime object
Assembly assembly = null;
if(external)
{
assembly = context.GetAssembly(context.Reader.ReadUInt32());
}
// store type-information for later usage
TypeInfo typeInfo = new TypeInfo(context, name, fieldNames, typeTags, typeSpecs, assembly);
context.SetTypeInfo(id, typeInfo);
// let our parent read the inlined values
return Read(context, out outVal, id, typeInfo);
}
}
class ExternalObjectReader : FullObjectReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
return Read(context, out outVal, true);
}
}
class RuntimeObjectReader : FullObjectReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
return Read(context, out outVal, false);
}
}
class RefObjectReader : ObjectReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
uint id = context.Reader.ReadUInt32();
uint refId = context.Reader.ReadUInt32();
// get type-information from context
TypeInfo typeInfo = context.GetTypeInfo(refId);
return Read(context, out outVal, id, typeInfo);
}
}
class ObjectReferenceReader : BinaryValueReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
uint refId = context.Reader.ReadUInt32();
// this 'special' object indicates that we haven't read a real object, but will read it later on
outVal = new DelayedReferenceHolder(refId);
return true;
}
}
class ArrayFiller8bReader : BinaryValueReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
uint numNulls = context.Reader.ReadByte();
// this 'special' object indicates that we haven't read a real object,
// but should insert a number of NULL values.
outVal = new ArrayNullValueHolder(numNulls);
return true;
}
}
class ArrayFiller32bReader : BinaryValueReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
uint numNulls = context.Reader.ReadUInt32();
// this 'special' object indicates that we haven't read a real object,
// but should insert a number of NULL values.
outVal = new ArrayNullValueHolder(numNulls);
return true;
}
}
class BoxedPrimitiveTypeValue : BinaryValueReader
{
public override bool Read(DeserializationContext context, out Object outVal)
{
TypeSpecification typeSpec = ReadTypeSpec(context, BinaryTypeTag.PrimitiveType);
outVal = ReadPrimitiveType(context, typeSpec.GetPrimitiveType());
return true;
}
}
#endif // CONFIG_SERIALIZATION
}; // namespace System.Runtime.Serialization.Formatters.Binary
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using System.Collections.Immutable;
using System.Linq;
using Xunit;
using Roslyn.Test.PdbUtilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class ResultPropertiesTests : ExpressionCompilerTestBase
{
[Fact]
public void Category()
{
var source = @"
class C
{
int P { get; set; }
int F;
int M() { return 0; }
void Test(int p)
{
int l;
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
foreach (var expr in new[] { "this", "null", "1", "F", "p", "l" })
{
Assert.Equal(DkmEvaluationResultCategory.Data, GetResultProperties(context, expr).Category);
}
Assert.Equal(DkmEvaluationResultCategory.Method, GetResultProperties(context, "M()").Category);
Assert.Equal(DkmEvaluationResultCategory.Property, GetResultProperties(context, "P").Category);
}
[Fact]
public void StorageType()
{
var source = @"
class C
{
int P { get; set; }
int F;
int M() { return 0; }
static int SP { get; set; }
static int SF;
static int SM() { return 0; }
void Test(int p)
{
int l;
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
foreach (var expr in new[] { "this", "null", "1", "P", "F", "M()", "p", "l" })
{
Assert.Equal(DkmEvaluationResultStorageType.None, GetResultProperties(context, expr).StorageType);
}
foreach (var expr in new[] { "SP", "SF", "SM()" })
{
Assert.Equal(DkmEvaluationResultStorageType.Static, GetResultProperties(context, expr).StorageType);
}
}
[Fact]
public void AccessType()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field private int32 Private
.field family int32 Protected
.field assembly int32 Internal
.field public int32 Public
.field famorassem int32 ProtectedInternal
.field famandassem int32 ProtectedAndInternal
.method public hidebysig instance void
Test() cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
} // end of method C::.ctor
} // end of class C
";
ImmutableArray<byte> exeBytes;
ImmutableArray<byte> pdbBytes;
EmitILToArray(ilSource, appendDefaultHeader: true, includePdb: true, assemblyBytes: out exeBytes, pdbBytes: out pdbBytes);
var runtime = CreateRuntimeInstance(
assemblyName: GetUniqueName(),
references: ImmutableArray.Create(MscorlibRef),
exeBytes: exeBytes.ToArray(),
symReader: SymReaderFactory.CreateReader(pdbBytes));
var context = CreateMethodContext(runtime, methodName: "C.Test");
Assert.Equal(DkmEvaluationResultAccessType.Private, GetResultProperties(context, "Private").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Protected, GetResultProperties(context, "Protected").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "Internal").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Public, GetResultProperties(context, "Public").AccessType);
// As in dev12.
Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "ProtectedInternal").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "ProtectedAndInternal").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.None, GetResultProperties(context, "null").AccessType);
}
[Fact]
public void AccessType_Nested()
{
var source = @"
using System;
internal class C
{
public int F;
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
// Used the declared accessibility, rather than the effective accessibility.
Assert.Equal(DkmEvaluationResultAccessType.Public, GetResultProperties(context, "F").AccessType);
}
[Fact]
public void ModifierFlags_Virtual()
{
var source = @"
using System;
class C
{
public int P { get; set; }
public int M() { return 0; }
public event Action E;
public virtual int VP { get; set; }
public virtual int VM() { return 0; }
public virtual event Action VE;
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "P").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "VP").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "M()").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "VM()").ModifierFlags);
// Field-like events are borderline since they bind as event accesses, but get emitted as field accesses.
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "E").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "VE").ModifierFlags);
}
[Fact]
public void ModifierFlags_Virtual_Variations()
{
var source = @"
using System;
abstract class Base
{
public abstract int Override { get; set; }
}
abstract class Derived : Base
{
public override int Override { get; set; }
public abstract int Abstract { get; set; }
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "Derived.Test");
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "Abstract").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "Override").ModifierFlags);
}
[Fact]
public void ModifierFlags_Constant()
{
var source = @"
using System;
class C
{
int F = 1;
const int CF = 1;
static readonly int SRF = 1;
void Test(int p)
{
int l = 2;
const int cl = 2;
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
foreach (var expr in new[] { "null", "1", "1 + 1", "CF", "cl" })
{
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Constant, GetResultProperties(context, expr).ModifierFlags);
}
foreach (var expr in new[] { "this", "F", "SRF", "p", "l" })
{
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, expr).ModifierFlags);
}
}
[Fact]
public void ModifierFlags_Volatile()
{
var source = @"
using System;
class C
{
int F = 1;
volatile int VF = 1;
void Test(int p)
{
int l;
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "F").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Volatile, GetResultProperties(context, "VF").ModifierFlags);
}
[Fact]
public void Assignment()
{
var source = @"
class C
{
public virtual int P { get; set; }
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
context.CompileAssignment("P", "1", NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData);
Assert.Null(error);
Assert.Empty(missingAssemblyIdentities);
Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect, resultProperties.Flags);
Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); // Not Data
Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType); // Not Public
Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType);
Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags); // Not Virtual
}
[Fact]
public void LocalDeclaration()
{
var source = @"
class C
{
public virtual int P { get; set; }
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
context.CompileExpression(
"int z = 1;",
DkmEvaluationFlags.None,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Null(error);
Assert.Empty(missingAssemblyIdentities);
Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags);
Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); // Not Data
Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType);
Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType);
Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags);
}
[Fact]
public void Error()
{
var source = @"
class C
{
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
VerifyErrorResultProperties(context, "x => x");
VerifyErrorResultProperties(context, "Test");
VerifyErrorResultProperties(context, "Missing");
VerifyErrorResultProperties(context, "C");
}
private static ResultProperties GetResultProperties(EvaluationContext context, string expr)
{
ResultProperties resultProperties;
string error;
context.CompileExpression(expr, out resultProperties, out error);
Assert.Null(error);
return resultProperties;
}
private static void VerifyErrorResultProperties(EvaluationContext context, string expr)
{
ResultProperties resultProperties;
string error;
context.CompileExpression(expr, out resultProperties, out error);
Assert.NotNull(error);
Assert.Equal(default(ResultProperties), resultProperties);
}
}
}
| |
// 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.ComponentModel;
using System.Globalization;
using System.IO;
using System.Net.NetworkInformation;
using System.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Mail
{
public delegate void SendCompletedEventHandler(object sender, AsyncCompletedEventArgs e);
public enum SmtpDeliveryMethod
{
Network,
SpecifiedPickupDirectory,
PickupDirectoryFromIis
}
// EAI Settings
public enum SmtpDeliveryFormat
{
SevenBit = 0, // Legacy
International = 1, // SMTPUTF8 - Email Address Internationalization (EAI)
}
public class SmtpClient : IDisposable
{
private string _host;
private int _port;
private bool _inCall;
private bool _cancelled;
private bool _timedOut;
private string _targetName = null;
private SmtpDeliveryMethod _deliveryMethod = SmtpDeliveryMethod.Network;
private SmtpDeliveryFormat _deliveryFormat = SmtpDeliveryFormat.SevenBit; // Non-EAI default
private string _pickupDirectoryLocation = null;
private SmtpTransport _transport;
private MailMessage _message; //required to prevent premature finalization
private MailWriter _writer;
private MailAddressCollection _recipients;
private SendOrPostCallback _onSendCompletedDelegate;
private Timer _timer;
private ContextAwareResult _operationCompletedResult = null;
private AsyncOperation _asyncOp = null;
private static AsyncCallback s_contextSafeCompleteCallback = new AsyncCallback(ContextSafeCompleteCallback);
private const int DefaultPort = 25;
internal string clientDomain = null;
private bool _disposed = false;
private ServicePoint _servicePoint;
// (async only) For when only some recipients fail. We still send the e-mail to the others.
private SmtpFailedRecipientException _failedRecipientException;
// ports above this limit are invalid
private const int MaxPortValue = 65535;
public event SendCompletedEventHandler SendCompleted;
public SmtpClient()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
Initialize();
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
public SmtpClient(string host)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host);
try
{
_host = host;
Initialize();
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
public SmtpClient(string host, int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host, port);
try
{
if (port < 0)
{
throw new ArgumentOutOfRangeException(nameof(port));
}
_host = host;
_port = port;
Initialize();
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
private void Initialize()
{
if (_port == DefaultPort || _port == 0)
{
new SmtpPermission(SmtpAccess.Connect).Demand();
}
else
{
new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort).Demand();
}
_transport = new SmtpTransport(this);
if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _transport);
_onSendCompletedDelegate = new SendOrPostCallback(SendCompletedWaitCallback);
if (_host != null && _host.Length != 0)
{
_host = _host.Trim();
}
if (_port == 0)
{
_port = DefaultPort;
}
if (_targetName == null)
_targetName = "SMTPSVC/" + _host;
if (clientDomain == null)
{
// We use the local host name as the default client domain
// for the client's EHLO or HELO message. This limits the
// information about the host that we share. Additionally, the
// FQDN is not available to us or useful to the server (internal
// machine connecting to public server).
// SMTP RFC's require ASCII only host names in the HELO/EHLO message.
string clientDomainRaw = IPGlobalProperties.GetIPGlobalProperties().HostName;
IdnMapping mapping = new IdnMapping();
try
{
clientDomainRaw = mapping.GetAscii(clientDomainRaw);
}
catch (ArgumentException) { }
// For some inputs GetAscii may fail (bad Unicode, etc). If that happens
// we must strip out any non-ASCII characters.
// If we end up with no characters left, we use the string "LocalHost". This
// matches Outlook behavior.
StringBuilder sb = new StringBuilder();
char ch;
for (int i = 0; i < clientDomainRaw.Length; i++)
{
ch = clientDomainRaw[i];
if ((ushort)ch <= 0x7F)
sb.Append(ch);
}
if (sb.Length > 0)
clientDomain = sb.ToString();
else
clientDomain = "LocalHost";
}
}
public string Host
{
get
{
return _host;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value == string.Empty)
{
throw new ArgumentException(SR.net_emptystringset, nameof(value));
}
value = value.Trim();
if (value != _host)
{
_host = value;
_servicePoint = null;
}
}
}
public int Port
{
get
{
return _port;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (value != DefaultPort)
{
new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort).Demand();
}
if (value != _port)
{
_port = value;
_servicePoint = null;
}
}
}
public bool UseDefaultCredentials
{
get
{
return ReferenceEquals(_transport.Credentials, CredentialCache.DefaultNetworkCredentials);
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
_transport.Credentials = value ? CredentialCache.DefaultNetworkCredentials : null;
}
}
public ICredentialsByHost Credentials
{
get
{
return _transport.Credentials;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
_transport.Credentials = value;
}
}
public int Timeout
{
get
{
return _transport.Timeout;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_transport.Timeout = value;
}
}
public ServicePoint ServicePoint
{
get
{
CheckHostAndPort();
if (_servicePoint == null)
{
// This differs from desktop, where it uses an internal overload of FindServicePoint that just
// takes a string host and an int port, bypassing the need for a Uri. We workaround that here by
// creating an http Uri, simply for the purposes of getting an appropriate ServicePoint instance.
// This has some subtle impact on behavior, e.g. the returned ServicePoint's Address property will
// be usable, whereas in desktop it throws an exception that "This property is not supported for
// protocols that do not use URI."
_servicePoint = ServicePointManager.FindServicePoint(new Uri("mailto:" + _host + ":" + _port));
}
return _servicePoint;
}
}
public SmtpDeliveryMethod DeliveryMethod
{
get
{
return _deliveryMethod;
}
set
{
_deliveryMethod = value;
}
}
public SmtpDeliveryFormat DeliveryFormat
{
get
{
return _deliveryFormat;
}
set
{
_deliveryFormat = value;
}
}
public string PickupDirectoryLocation
{
get
{
return _pickupDirectoryLocation;
}
set
{
_pickupDirectoryLocation = value;
}
}
/// <summary>
/// <para>Set to true if we need SSL</para>
/// </summary>
public bool EnableSsl
{
get
{
return _transport.EnableSsl;
}
set
{
_transport.EnableSsl = value;
}
}
/// <summary>
/// Certificates used by the client for establishing an SSL connection with the server.
/// </summary>
public X509CertificateCollection ClientCertificates
{
get
{
return _transport.ClientCertificates;
}
}
public string TargetName
{
set { _targetName = value; }
get { return _targetName; }
}
private bool ServerSupportsEai
{
get
{
return _transport.ServerSupportsEai;
}
}
private bool IsUnicodeSupported()
{
if (DeliveryMethod == SmtpDeliveryMethod.Network)
{
return (ServerSupportsEai && (DeliveryFormat == SmtpDeliveryFormat.International));
}
else
{ // Pickup directories
return (DeliveryFormat == SmtpDeliveryFormat.International);
}
}
internal MailWriter GetFileMailWriter(string pickupDirectory)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"{nameof(pickupDirectory)}={pickupDirectory}");
if (!Path.IsPathRooted(pickupDirectory))
throw new SmtpException(SR.SmtpNeedAbsolutePickupDirectory);
string filename;
string pathAndFilename;
while (true)
{
filename = Guid.NewGuid().ToString() + ".eml";
pathAndFilename = Path.Combine(pickupDirectory, filename);
if (!File.Exists(pathAndFilename))
break;
}
FileStream fileStream = new FileStream(pathAndFilename, FileMode.CreateNew);
return new MailWriter(fileStream);
}
protected void OnSendCompleted(AsyncCompletedEventArgs e)
{
SendCompleted?.Invoke(this, e);
}
private void SendCompletedWaitCallback(object operationState)
{
OnSendCompleted((AsyncCompletedEventArgs)operationState);
}
public void Send(string from, string recipients, string subject, string body)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
//validation happends in MailMessage constructor
MailMessage mailMessage = new MailMessage(from, recipients, subject, body);
Send(mailMessage);
}
public void Send(MailMessage message)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, message);
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
try
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"DeliveryMethod={DeliveryMethod}");
NetEventSource.Associate(this, message);
}
SmtpFailedRecipientException recipientException = null;
if (InCall)
{
throw new InvalidOperationException(SR.net_inasync);
}
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (DeliveryMethod == SmtpDeliveryMethod.Network)
CheckHostAndPort();
MailAddressCollection recipients = new MailAddressCollection();
if (message.From == null)
{
throw new InvalidOperationException(SR.SmtpFromRequired);
}
if (message.To != null)
{
foreach (MailAddress address in message.To)
{
recipients.Add(address);
}
}
if (message.Bcc != null)
{
foreach (MailAddress address in message.Bcc)
{
recipients.Add(address);
}
}
if (message.CC != null)
{
foreach (MailAddress address in message.CC)
{
recipients.Add(address);
}
}
if (recipients.Count == 0)
{
throw new InvalidOperationException(SR.SmtpRecipientRequired);
}
_transport.IdentityRequired = false; // everything completes on the same thread.
try
{
InCall = true;
_timedOut = false;
_timer = new Timer(new TimerCallback(TimeOutCallback), null, Timeout, Timeout);
bool allowUnicode = false;
string pickupDirectory = PickupDirectoryLocation;
MailWriter writer;
switch (DeliveryMethod)
{
case SmtpDeliveryMethod.PickupDirectoryFromIis:
throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
case SmtpDeliveryMethod.SpecifiedPickupDirectory:
if (EnableSsl)
{
throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
}
allowUnicode = IsUnicodeSupported(); // Determend by the DeliveryFormat paramiter
ValidateUnicodeRequirement(message, recipients, allowUnicode);
writer = GetFileMailWriter(pickupDirectory);
break;
case SmtpDeliveryMethod.Network:
default:
GetConnection();
// Detected durring GetConnection(), restrictable using the DeliveryFormat paramiter
allowUnicode = IsUnicodeSupported();
ValidateUnicodeRequirement(message, recipients, allowUnicode);
writer = _transport.SendMail(message.Sender ?? message.From, recipients,
message.BuildDeliveryStatusNotificationString(), allowUnicode, out recipientException);
break;
}
_message = message;
message.Send(writer, DeliveryMethod != SmtpDeliveryMethod.Network, allowUnicode);
writer.Close();
_transport.ReleaseConnection();
//throw if we couldn't send to any of the recipients
if (DeliveryMethod == SmtpDeliveryMethod.Network && recipientException != null)
{
throw recipientException;
}
}
catch (Exception e)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e);
if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
{
throw;
}
Abort();
if (_timedOut)
{
throw new SmtpException(SR.net_timeout);
}
if (e is SecurityException ||
e is AuthenticationException ||
e is SmtpException)
{
throw;
}
throw new SmtpException(SR.SmtpSendMailFailure, e);
}
finally
{
InCall = false;
if (_timer != null)
{
_timer.Dispose();
}
}
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
[HostProtection(ExternalThreading = true)]
public void SendAsync(string from, string recipients, string subject, string body, object userToken)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
SendAsync(new MailMessage(from, recipients, subject, body), userToken);
}
[HostProtection(ExternalThreading = true)]
public void SendAsync(MailMessage message, object userToken)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, message, userToken, _transport);
try
{
if (InCall)
{
throw new InvalidOperationException(SR.net_inasync);
}
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (DeliveryMethod == SmtpDeliveryMethod.Network)
CheckHostAndPort();
_recipients = new MailAddressCollection();
if (message.From == null)
{
throw new InvalidOperationException(SR.SmtpFromRequired);
}
if (message.To != null)
{
foreach (MailAddress address in message.To)
{
_recipients.Add(address);
}
}
if (message.Bcc != null)
{
foreach (MailAddress address in message.Bcc)
{
_recipients.Add(address);
}
}
if (message.CC != null)
{
foreach (MailAddress address in message.CC)
{
_recipients.Add(address);
}
}
if (_recipients.Count == 0)
{
throw new InvalidOperationException(SR.SmtpRecipientRequired);
}
try
{
InCall = true;
_cancelled = false;
_message = message;
string pickupDirectory = PickupDirectoryLocation;
CredentialCache cache;
// Skip token capturing if no credentials are used or they don't include a default one.
// Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
_transport.IdentityRequired = Credentials != null && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null || IsSystemNetworkCredentialInCache(cache));
_asyncOp = AsyncOperationManager.CreateOperation(userToken);
switch (DeliveryMethod)
{
case SmtpDeliveryMethod.PickupDirectoryFromIis:
throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
case SmtpDeliveryMethod.SpecifiedPickupDirectory:
{
if (EnableSsl)
{
throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
}
_writer = GetFileMailWriter(pickupDirectory);
bool allowUnicode = IsUnicodeSupported();
ValidateUnicodeRequirement(message, _recipients, allowUnicode);
message.Send(_writer, true, allowUnicode);
if (_writer != null)
_writer.Close();
_transport.ReleaseConnection();
AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, _asyncOp.UserSuppliedState);
InCall = false;
_asyncOp.PostOperationCompleted(_onSendCompletedDelegate, eventArgs);
break;
}
case SmtpDeliveryMethod.Network:
default:
_operationCompletedResult = new ContextAwareResult(_transport.IdentityRequired, true, null, this, s_contextSafeCompleteCallback);
lock (_operationCompletedResult.StartPostingAsyncOp())
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
_transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host, Port);
_operationCompletedResult.FinishPostingAsyncOp();
}
break;
}
}
catch (Exception e)
{
InCall = false;
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e);
if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
{
throw;
}
Abort();
if (_timedOut)
{
throw new SmtpException(SR.net_timeout);
}
if (e is SecurityException ||
e is AuthenticationException ||
e is SmtpException)
{
throw;
}
throw new SmtpException(SR.SmtpSendMailFailure, e);
}
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
private bool IsSystemNetworkCredentialInCache(CredentialCache cache)
{
// Check if SystemNetworkCredential is in given cache.
foreach (NetworkCredential credential in cache)
{
if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
{
return true;
}
}
return false;
}
public void SendAsyncCancel()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
if (!InCall || _cancelled)
{
return;
}
_cancelled = true;
Abort();
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
//************* Task-based async public methods *************************
[HostProtection(ExternalThreading = true)]
public Task SendMailAsync(string from, string recipients, string subject, string body)
{
var message = new MailMessage(from, recipients, subject, body);
return SendMailAsync(message);
}
[HostProtection(ExternalThreading = true)]
public Task SendMailAsync(MailMessage message)
{
// Create a TaskCompletionSource to represent the operation
var tcs = new TaskCompletionSource<object>();
// Register a handler that will transfer completion results to the TCS Task
SendCompletedEventHandler handler = null;
handler = (sender, e) => HandleCompletion(tcs, e, handler);
SendCompleted += handler;
// Start the async operation.
try
{
SendAsync(message, tcs);
}
catch
{
SendCompleted -= handler;
throw;
}
// Return the task to represent the asynchronous operation
return tcs.Task;
}
private void HandleCompletion(TaskCompletionSource<object> tcs, AsyncCompletedEventArgs e, SendCompletedEventHandler handler)
{
if (e.UserState == tcs)
{
try { SendCompleted -= handler; }
finally
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(null);
}
}
}
//*********************************
// private methods
//********************************
internal bool InCall
{
get
{
return _inCall;
}
set
{
_inCall = value;
}
}
private void CheckHostAndPort()
{
if (_host == null || _host.Length == 0)
{
throw new InvalidOperationException(SR.UnspecifiedHost);
}
if (_port <= 0 || _port > MaxPortValue)
{
throw new InvalidOperationException(SR.InvalidPort);
}
}
private void TimeOutCallback(object state)
{
if (!_timedOut)
{
_timedOut = true;
Abort();
}
}
private void Complete(Exception exception, IAsyncResult result)
{
ContextAwareResult operationCompletedResult = (ContextAwareResult)result.AsyncState;
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
if (_cancelled)
{
//any exceptions were probably caused by cancellation, clear it.
exception = null;
Abort();
}
// An individual failed recipient exception is benign, only abort here if ALL the recipients failed.
else if (exception != null && (!(exception is SmtpFailedRecipientException) || ((SmtpFailedRecipientException)exception).fatal))
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
Abort();
if (!(exception is SmtpException))
{
exception = new SmtpException(SR.SmtpSendMailFailure, exception);
}
}
else
{
if (_writer != null)
{
try
{
_writer.Close();
}
// Close may result in a DataStopCommand and the server may return error codes at this time.
catch (SmtpException se)
{
exception = se;
}
}
_transport.ReleaseConnection();
}
}
finally
{
operationCompletedResult.InvokeCallback(exception);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Complete");
}
private static void ContextSafeCompleteCallback(IAsyncResult ar)
{
ContextAwareResult result = (ContextAwareResult)ar;
SmtpClient client = (SmtpClient)ar.AsyncState;
Exception exception = result.Result as Exception;
AsyncOperation asyncOp = client._asyncOp;
AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(exception, client._cancelled, asyncOp.UserSuppliedState);
client.InCall = false;
client._failedRecipientException = null; // Reset before the next send.
asyncOp.PostOperationCompleted(client._onSendCompletedDelegate, eventArgs);
}
private void SendMessageCallback(IAsyncResult result)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
_message.EndSend(result);
// If some recipients failed but not others, throw AFTER sending the message.
Complete(_failedRecipientException, result);
}
catch (Exception e)
{
Complete(e, result);
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
private void SendMailCallback(IAsyncResult result)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
_writer = _transport.EndSendMail(result);
// If some recipients failed but not others, send the e-mail anyways, but then return the
// "Non-fatal" exception reporting the failures. The sync code path does it this way.
// Fatal exceptions would have thrown above at transport.EndSendMail(...)
SendMailAsyncResult sendResult = (SendMailAsyncResult)result;
// Save these and throw them later in SendMessageCallback, after the message has sent.
_failedRecipientException = sendResult.GetFailedRecipientException();
}
catch (Exception e)
{
Complete(e, result);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return;
}
try
{
if (_cancelled)
{
Complete(null, result);
}
else
{
_message.BeginSend(_writer, DeliveryMethod != SmtpDeliveryMethod.Network,
ServerSupportsEai, new AsyncCallback(SendMessageCallback), result.AsyncState);
}
}
catch (Exception e)
{
Complete(e, result);
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
private void ConnectCallback(IAsyncResult result)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
_transport.EndGetConnection(result);
if (_cancelled)
{
Complete(null, result);
}
else
{
// Detected durring Begin/EndGetConnection, restrictable using DeliveryFormat
bool allowUnicode = IsUnicodeSupported();
ValidateUnicodeRequirement(_message, _recipients, allowUnicode);
_transport.BeginSendMail(_message.Sender ?? _message.From, _recipients,
_message.BuildDeliveryStatusNotificationString(), allowUnicode,
new AsyncCallback(SendMailCallback), result.AsyncState);
}
}
catch (Exception e)
{
Complete(e, result);
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
// After we've estabilished a connection and initilized ServerSupportsEai,
// check all the addresses for one that contains unicode in the username/localpart.
// The localpart is the only thing we cannot succesfully downgrade.
private void ValidateUnicodeRequirement(MailMessage message, MailAddressCollection recipients, bool allowUnicode)
{
// Check all recipients, to, from, sender, bcc, cc, etc...
// GetSmtpAddress will throw if !allowUnicode and the username contains non-ascii
foreach (MailAddress address in recipients)
{
address.GetSmtpAddress(allowUnicode);
}
if (message.Sender != null)
{
message.Sender.GetSmtpAddress(allowUnicode);
}
message.From.GetSmtpAddress(allowUnicode);
}
private void GetConnection()
{
if (!_transport.IsConnected)
{
_transport.GetConnection(_host, _port);
}
}
private void Abort()
{
try
{
_transport.Abort();
}
catch
{
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
if (InCall && !_cancelled)
{
_cancelled = true;
Abort();
}
if ((_transport != null))
{
_transport.ReleaseConnection();
}
if (_timer != null)
{
_timer.Dispose();
}
_disposed = true;
}
}
}
}
| |
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using Amib.Threading;
using osu.Framework.Extensions;
using osu.Framework.Logging;
namespace osu.Framework.IO.Network
{
public class WebRequest : IDisposable
{
/// <summary>
/// Update has progressed.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="current">Total bytes processed.</param>
/// <param name="total">Total bytes required.</param>
public delegate void RequestUpdateHandler(WebRequest request, long current, long total);
/// <summary>
/// Request has completed.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="e">An error, if an error occurred, else null.</param>
public delegate void RequestCompleteHandler(WebRequest request, Exception e);
/// <summary>
/// Request has completed.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="e">An error, if an error occurred, else null.</param>
public delegate void RequestCompleteHandler<T>(JsonWebRequest<T> request, Exception e);
/// <summary>
/// Request has started.
/// </summary>
/// <param name="request">The request.</param>
public delegate void RequestStartedHandler(WebRequest request);
private string url;
/// <summary>
/// The URL of this request.
/// </summary>
public string Url
{
get { return url; }
set
{
#if !DEBUG
if (!value.StartsWith(@"https://"))
value = @"https://" + value.Replace(@"http://", @"");
#endif
url = value;
}
}
/// <summary>
/// The request has been aborted by the user or due to an exception.
/// </summary>
public bool Aborted { get; private set; }
/// <summary>
/// The request has been executed and successfully completed.
/// </summary>
public bool Completed { get; private set; }
/// <summary>
/// Monitor upload progress.
/// </summary>
public event RequestUpdateHandler UploadProgress;
/// <summary>
/// Monitor download progress.
/// </summary>
public event RequestUpdateHandler DownloadProgress;
/// <summary>
/// Request has finished with success or failure. Check exception == null for success.
/// </summary>
public event RequestCompleteHandler Finished;
/// <summary>
/// Request has started.
/// </summary>
public event RequestStartedHandler Started;
/// <summary>
/// To avoid memory leaks due to delegates being bound to events, on request completion events are removed by default.
/// This controls whether they should be kept to allow for further requests.
/// </summary>
public bool KeepEventsBound;
/// <summary>
/// POST parameters.
/// </summary>
public Dictionary<string, string> Parameters = new Dictionary<string, string>();
/// <summary>
/// FILE parameters.
/// </summary>
public Dictionary<string, byte[]> Files = new Dictionary<string, byte[]>();
/// <summary>
/// Headers.
/// </summary>
public Dictionary<string, string> Headers = new Dictionary<string, string>();
public const int DEFAULT_TIMEOUT = 10000;
public HttpMethod Method;
/// <summary>
/// The amount of time from last sent or received data to trigger a timeout and abort the request.
/// </summary>
public int Timeout = DEFAULT_TIMEOUT;
static Logger logger;
static SmartThreadPool threadPool;
private IWorkItemResult workItem;
/// <summary>
/// The remote IP address used for this connection.
/// </summary>
private string address;
static WebRequest()
{
threadPool = new SmartThreadPool(new STPStartInfo
{
MaxWorkerThreads = 64,
AreThreadsBackground = true,
IdleTimeout = 300000
});
//set some sane defaults for ServicePoints
ServicePointManager.Expect100Continue = false;
ServicePointManager.DefaultConnectionLimit = 12;
ServicePointManager.CheckCertificateRevocationList = false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
logger = Logger.GetLogger(LoggingTarget.Network, true);
}
public WebRequest(string url = null, params object[] args)
{
if (!string.IsNullOrEmpty(url))
Url = args.Length == 0 ? url : string.Format(url, args);
}
~WebRequest()
{
Dispose(false);
}
private HttpWebRequest request;
private HttpWebResponse response;
private Stream internalResponseStream;
private static AddressFamily? preferredNetwork = AddressFamily.InterNetwork;
/// <summary>
/// Does a manual DNS lookup and forcefully uses IPv4 by shoving IP addresses where the host normally is.
/// Unreliable for HTTPS+Cloudflare? Only use when necessary.
/// </summary>
public static bool UseExplicitIPv4Requests = false;
static bool? useFallbackPath;
private bool didGetIPv6IP;
protected virtual HttpWebRequest CreateWebRequest(string requestString = null)
{
HttpWebRequest req;
string requestUrl = string.IsNullOrEmpty(requestString) ? Url : $@"{Url}?{requestString}";
if (useFallbackPath != true && !UseExplicitIPv4Requests)
{
req = (HttpWebRequest)System.Net.WebRequest.Create(requestUrl);
req.ServicePoint.BindIPEndPointDelegate += bindEndPoint;
}
else
{
string baseHost = requestUrl.Split('/', ':')[3];
var addresses = Dns.GetHostAddresses(baseHost);
address = null;
foreach (var ip in addresses)
{
bool preferred = ip.AddressFamily == preferredNetwork;
if (!preferred && address != null)
continue;
switch (ip.AddressFamily)
{
case AddressFamily.InterNetwork:
address = $@"{ip}";
break;
case AddressFamily.InterNetworkV6:
address = $@"[{ip}]";
break;
}
if (preferred)
//always use first preferred network address for now.
break;
}
req = System.Net.WebRequest.Create(requestUrl.Replace(baseHost, $"{address}:443")) as HttpWebRequest;
}
Debug.Assert(req != null);
req.UserAgent = @"osu!";
req.KeepAlive = useFallbackPath != true;
req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
req.Host = requestUrl.Split('/')[2];
req.ReadWriteTimeout = System.Threading.Timeout.Infinite;
req.Timeout = System.Threading.Timeout.Infinite;
return req;
}
private IPEndPoint bindEndPoint(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retries)
{
didGetIPv6IP |= remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6;
return null;
}
private int responseBytesRead;
private const int buffer_size = 32768;
private byte[] buffer;
private MemoryStream requestBody;
protected virtual Stream CreateOutputStream()
{
return new MemoryStream();
}
public Stream ResponseStream;
public string ResponseString
{
get
{
try
{
ResponseStream.Seek(0, SeekOrigin.Begin);
StreamReader r = new StreamReader(ResponseStream, Encoding.UTF8);
return r.ReadToEnd();
}
catch
{
return null;
}
}
}
public byte[] ResponseData
{
get
{
try
{
using (MemoryStream ms = new MemoryStream((int)ResponseStream.Length))
{
ResponseStream.Seek(0, SeekOrigin.Begin);
ResponseStream.CopyTo(ms);
return ms.ToArray();
}
}
catch
{
return null;
}
}
}
public WebHeaderCollection ResponseHeaders => response?.Headers;
/// <summary>
/// Start the request asynchronously.
/// </summary>
public void Perform()
{
Debug.Assert(workItem == null);
workItem = threadPool.QueueWorkItem(perform);
if (threadPool.InUseThreads == threadPool.MaxThreads)
logger.Add(@"WARNING: ThreadPool is saturated!", LogLevel.Error);
}
private void perform()
{
Aborted = false;
abortRequest();
PrePerform();
try
{
reportForwardProgress();
threadPool.QueueWorkItem(checkTimeoutLoop);
requestBody = new MemoryStream();
switch (Method)
{
case HttpMethod.GET:
Debug.Assert(Files.Count == 0);
StringBuilder requestParameters = new StringBuilder();
foreach (var p in Parameters)
requestParameters.Append($@"{p.Key}={p.Value}&");
request = CreateWebRequest(requestParameters.ToString().TrimEnd('&'));
request.Method = @"GET";
break;
case HttpMethod.POST:
request = CreateWebRequest();
request.Method = @"POST";
if (Parameters.Count + Files.Count == 0)
break;
const string boundary = @"-----------------------------28947758029299";
request.ContentType = $@"multipart/form-data; boundary={boundary}";
foreach (KeyValuePair<string, string> p in Parameters)
{
requestBody.WriteLineExplicit($@"--{boundary}");
requestBody.WriteLineExplicit($@"Content-Disposition: form-data; name=""{p.Key}""");
requestBody.WriteLineExplicit();
requestBody.WriteLineExplicit(p.Value);
}
foreach (KeyValuePair<string, byte[]> p in Files)
{
requestBody.WriteLineExplicit($@"--{boundary}");
requestBody.WriteLineExplicit($@"Content-Disposition: form-data; name=""{p.Key}""; filename=""{p.Key}""");
requestBody.WriteLineExplicit(@"Content-Type: application/octet-stream");
requestBody.WriteLineExplicit();
requestBody.Write(p.Value, 0, p.Value.Length);
requestBody.WriteLineExplicit();
}
requestBody.WriteLineExplicit($@"--{boundary}--");
requestBody.Flush();
break;
}
request.UserAgent = @"osu!";
request.KeepAlive = useFallbackPath != true;
request.Host = Url.Split('/')[2];
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ReadWriteTimeout = System.Threading.Timeout.Infinite;
request.Timeout = Timeout; //todo: make sure this works correctly for long-lasting transfers.
foreach (KeyValuePair<string, string> h in Headers)
request.Headers.Add(h.Key, h.Value);
ResponseStream = CreateOutputStream();
switch (Method)
{
case HttpMethod.GET:
//GETs are easy
beginResponse();
break;
case HttpMethod.POST:
request.ContentLength = requestBody.Length;
UploadProgress?.Invoke(this, 0, request.ContentLength);
reportForwardProgress();
beginRequestOutput();
break;
}
}
catch (Exception e)
{
Complete(e);
}
}
/// <summary>
/// Task to run direct before performing the request.
/// </summary>
protected virtual void PrePerform()
{
}
private void beginRequestOutput()
{
try
{
using (Stream requestStream = request.GetRequestStream())
{
reportForwardProgress();
requestBody.Position = 0;
byte[] buff = new byte[buffer_size];
int read;
int totalRead = 0;
while ((read = requestBody.Read(buff, 0, buffer_size)) > 0)
{
reportForwardProgress();
requestStream.Write(buff, 0, read);
requestStream.Flush();
totalRead += read;
UploadProgress?.Invoke(this, totalRead, request.ContentLength);
}
}
beginResponse();
}
catch (Exception e)
{
Complete(e);
}
}
private void beginResponse()
{
try
{
response = request.GetResponse() as HttpWebResponse;
Debug.Assert(response != null);
Started?.Invoke(this);
internalResponseStream = response.GetResponseStream();
Debug.Assert(internalResponseStream != null);
#if !DEBUG
checkCertificate();
#endif
buffer = new byte[buffer_size];
reportForwardProgress();
while (true)
{
int read = internalResponseStream.Read(buffer, 0, buffer_size);
reportForwardProgress();
if (read > 0)
{
ResponseStream.Write(buffer, 0, read);
responseBytesRead += read;
DownloadProgress?.Invoke(this, responseBytesRead, response.ContentLength);
}
else
{
ResponseStream.Seek(0, SeekOrigin.Begin);
Complete();
break;
}
}
}
catch (Exception e)
{
Complete(e);
}
}
[Obfuscation(Feature = @"virtualization", Exclude = false)]
private void checkCertificate()
{
if (request.ServicePoint.Certificate == null && request.RequestUri.Host != request.Address.Host && request.Address.Host.EndsWith(@".ppy.sh"))
//osu!direct downloads happen over http at the moment. we should probably move them across to https.
return;
//if it's null at this point we don't mind throwing an exception.
Debug.Assert(request.ServicePoint.Certificate != null);
//this is enough for now to assume we have a valid certificate.
if (new X509Certificate2(request.ServicePoint.Certificate).Subject.Contains(@"CN=*.ppy.sh"))
return;
//else we should just destroy the response and no.
response?.Close();
response = null;
throw new WebException(@"SSL failures");
}
public virtual void BlockingPerform()
{
Exception exc = null;
bool completed = false;
Finished += delegate(WebRequest r, Exception e)
{
exc = e;
completed = true;
};
perform();
while (!completed && !Aborted)
Thread.Sleep(10);
if (exc != null)
throw exc;
}
protected virtual void Complete(Exception e = null)
{
if (Aborted)
return;
WebException we = e as WebException;
if (we != null)
{
bool allowRetry = true;
HttpStatusCode? statusCode = (we.Response as HttpWebResponse)?.StatusCode ?? HttpStatusCode.RequestTimeout;
switch (statusCode)
{
case HttpStatusCode.RequestTimeout:
if (hasExceededTimeout)
{
logger.Add($@"Timeout exceeded ({timeSinceLastAction} > {DEFAULT_TIMEOUT})");
e = new WebException($"Timeout to {Url} ({address}) after {timeSinceLastAction / 1000} seconds idle (read {responseBytesRead} bytes).", WebExceptionStatus.Timeout);
}
break;
case HttpStatusCode.NotFound:
case HttpStatusCode.MethodNotAllowed:
case HttpStatusCode.Forbidden:
allowRetry = false;
break;
case HttpStatusCode.Unauthorized:
allowRetry = false;
break;
}
if (allowRetry && retriesRemaining-- > 0 && responseBytesRead == 0)
{
logger.Add($@"Request to {Url} ({address}) failed with {statusCode} (retrying {default_retry_count - retriesRemaining}/{default_retry_count}).");
//do a retry
perform();
return;
}
if (useFallbackPath == null && allowRetry && didGetIPv6IP)
{
useFallbackPath = true;
logger.Add(@"---------------------- USING FALLBACK PATH! ---------------------");
}
logger.Add($@"Request to {Url} ({address}) failed with {statusCode} (FAILED).");
}
else if (e == null)
{
if (useFallbackPath == null)
useFallbackPath = false;
logger.Add($@"Request to {Url} ({address}) successfully completed!");
}
response?.Close();
Finished?.Invoke(this, e);
if (!KeepEventsBound)
unbindEvents();
if (e != null)
Aborted = true;
else
Completed = true;
}
private void abortRequest()
{
try
{
request?.Abort();
response?.Close();
}
catch
{
//This *can* throw random exceptions internally from inside ServicePointManager.
}
}
/// <summary>
/// Forcefully abort the request.
/// </summary>
public void Abort()
{
if (Aborted) return;
Aborted = true;
abortRequest();
workItem?.Cancel();
workItem = null;
if (!KeepEventsBound)
unbindEvents();
}
/// <summary>
/// Add a header to this request.
/// </summary>
public void AddHeader(string key, string val)
{
Headers.Add(key, val);
}
/// <summary>
/// Adds a raw POST body to this request.
/// </summary>
public void AddRaw(Stream stream)
{
stream.CopyTo(requestBody);
}
/// <summary>
/// Add a new FILE parameter to this request.
/// </summary>
public void AddFile(string name, byte[] data)
{
Files.Add(name, data);
}
/// <summary>
/// Add a new POST parameter to this request.
/// </summary>
public void AddParameter(string name, string value)
{
Parameters.Add(name, value);
}
private void unbindEvents()
{
UploadProgress = null;
DownloadProgress = null;
Finished = null;
Started = null;
try
{
if (request?.ServicePoint.BindIPEndPointDelegate != null)
request.ServicePoint.BindIPEndPointDelegate -= bindEndPoint;
}
catch
{
}
}
#region Timeout Handling
long lastAction;
long timeSinceLastAction => (DateTime.Now.Ticks - lastAction) / TimeSpan.TicksPerMillisecond;
bool hasExceededTimeout => timeSinceLastAction > Timeout;
private object checkTimeoutLoop(object state)
{
while (!Aborted && !Completed)
{
if (hasExceededTimeout) abortRequest();
Thread.Sleep(500);
}
return state;
}
private void reportForwardProgress()
{
lastAction = DateTime.Now.Ticks;
}
#endregion
#region IDisposable Support
private bool isDisposed;
protected void Dispose(bool disposing)
{
if (isDisposed) return;
isDisposed = true;
if (!(ResponseStream is MemoryStream))
ResponseStream?.Dispose();
internalResponseStream?.Dispose();
response?.Close();
unbindEvents();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Retry Logic
private const int default_retry_count = 2;
private int retryCount = default_retry_count;
public int RetryCount
{
get { return retryCount; }
set { retriesRemaining = retryCount = value; }
}
private int retriesRemaining = default_retry_count;
#endregion
}
}
| |
// 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!
namespace Google.Cloud.Speech.V1.Snippets
{
using Google.Api.Gax.Grpc;
using Google.LongRunning;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedSpeechClientSnippets
{
/// <summary>Snippet for Recognize</summary>
public void RecognizeRequestObject()
{
// Snippet: Recognize(RecognizeRequest, CallSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize request argument(s)
RecognizeRequest request = new RecognizeRequest
{
Config = new RecognitionConfig(),
Audio = new RecognitionAudio(),
};
// Make the request
RecognizeResponse response = speechClient.Recognize(request);
// End snippet
}
/// <summary>Snippet for RecognizeAsync</summary>
public async Task RecognizeRequestObjectAsync()
{
// Snippet: RecognizeAsync(RecognizeRequest, CallSettings)
// Additional: RecognizeAsync(RecognizeRequest, CancellationToken)
// Create client
SpeechClient speechClient = await SpeechClient.CreateAsync();
// Initialize request argument(s)
RecognizeRequest request = new RecognizeRequest
{
Config = new RecognitionConfig(),
Audio = new RecognitionAudio(),
};
// Make the request
RecognizeResponse response = await speechClient.RecognizeAsync(request);
// End snippet
}
/// <summary>Snippet for Recognize</summary>
public void Recognize()
{
// Snippet: Recognize(RecognitionConfig, RecognitionAudio, CallSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize request argument(s)
RecognitionConfig config = new RecognitionConfig();
RecognitionAudio audio = new RecognitionAudio();
// Make the request
RecognizeResponse response = speechClient.Recognize(config, audio);
// End snippet
}
/// <summary>Snippet for RecognizeAsync</summary>
public async Task RecognizeAsync()
{
// Snippet: RecognizeAsync(RecognitionConfig, RecognitionAudio, CallSettings)
// Additional: RecognizeAsync(RecognitionConfig, RecognitionAudio, CancellationToken)
// Create client
SpeechClient speechClient = await SpeechClient.CreateAsync();
// Initialize request argument(s)
RecognitionConfig config = new RecognitionConfig();
RecognitionAudio audio = new RecognitionAudio();
// Make the request
RecognizeResponse response = await speechClient.RecognizeAsync(config, audio);
// End snippet
}
/// <summary>Snippet for LongRunningRecognize</summary>
public void LongRunningRecognizeRequestObject()
{
// Snippet: LongRunningRecognize(LongRunningRecognizeRequest, CallSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize request argument(s)
LongRunningRecognizeRequest request = new LongRunningRecognizeRequest
{
Config = new RecognitionConfig(),
Audio = new RecognitionAudio(),
OutputConfig = new TranscriptOutputConfig(),
};
// Make the request
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = speechClient.LongRunningRecognize(request);
// Poll until the returned long-running operation is complete
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
LongRunningRecognizeResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = speechClient.PollOnceLongRunningRecognize(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for LongRunningRecognizeAsync</summary>
public async Task LongRunningRecognizeRequestObjectAsync()
{
// Snippet: LongRunningRecognizeAsync(LongRunningRecognizeRequest, CallSettings)
// Additional: LongRunningRecognizeAsync(LongRunningRecognizeRequest, CancellationToken)
// Create client
SpeechClient speechClient = await SpeechClient.CreateAsync();
// Initialize request argument(s)
LongRunningRecognizeRequest request = new LongRunningRecognizeRequest
{
Config = new RecognitionConfig(),
Audio = new RecognitionAudio(),
OutputConfig = new TranscriptOutputConfig(),
};
// Make the request
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = await speechClient.LongRunningRecognizeAsync(request);
// Poll until the returned long-running operation is complete
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
LongRunningRecognizeResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = await speechClient.PollOnceLongRunningRecognizeAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for LongRunningRecognize</summary>
public void LongRunningRecognize()
{
// Snippet: LongRunningRecognize(RecognitionConfig, RecognitionAudio, CallSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize request argument(s)
RecognitionConfig config = new RecognitionConfig();
RecognitionAudio audio = new RecognitionAudio();
// Make the request
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = speechClient.LongRunningRecognize(config, audio);
// Poll until the returned long-running operation is complete
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
LongRunningRecognizeResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = speechClient.PollOnceLongRunningRecognize(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for LongRunningRecognizeAsync</summary>
public async Task LongRunningRecognizeAsync()
{
// Snippet: LongRunningRecognizeAsync(RecognitionConfig, RecognitionAudio, CallSettings)
// Additional: LongRunningRecognizeAsync(RecognitionConfig, RecognitionAudio, CancellationToken)
// Create client
SpeechClient speechClient = await SpeechClient.CreateAsync();
// Initialize request argument(s)
RecognitionConfig config = new RecognitionConfig();
RecognitionAudio audio = new RecognitionAudio();
// Make the request
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = await speechClient.LongRunningRecognizeAsync(config, audio);
// Poll until the returned long-running operation is complete
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
LongRunningRecognizeResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = await speechClient.PollOnceLongRunningRecognizeAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for StreamingRecognize</summary>
public async Task StreamingRecognize()
{
// Snippet: StreamingRecognize(CallSettings, BidirectionalStreamingSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize streaming call, retrieving the stream object
SpeechClient.StreamingRecognizeStream response = speechClient.StreamingRecognize();
// Sending requests and retrieving responses can be arbitrarily interleaved
// Exact sequence will depend on client/server behavior
// Create task to do something with responses from server
Task responseHandlerTask = Task.Run(async () =>
{
// Note that C# 8 code can use await foreach
AsyncResponseStream<StreamingRecognizeResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
StreamingRecognizeResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
});
// Send requests to the server
bool done = false;
while (!done)
{
// Initialize a request
StreamingRecognizeRequest request = new StreamingRecognizeRequest
{
StreamingConfig = new StreamingRecognitionConfig(),
};
// Stream a request to the server
await response.WriteAsync(request);
// Set "done" to true when sending requests is complete
}
// Complete writing requests to the stream
await response.WriteCompleteAsync();
// Await the response handler
// This will complete once all server responses have been processed
await responseHandlerTask;
// End snippet
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Text.Utf8;
using System.Text.Utf16;
namespace System.Text
{
public abstract class TextEncoder
{
#region EncodingName enum
public enum EncodingName : byte
{
Utf16 = 0,
Utf8 = 1,
//Ascii = 2,
//Utf16BE = 3,
//ISO8859_1 = 4,
}
#endregion EncodingName enum
#region Symbol enum
public enum Symbol : ushort
{
D0 = 0,
D1 = 1,
D2 = 2,
D3 = 3,
D4 = 4,
D5 = 5,
D6 = 6,
D7 = 7,
D8 = 8,
D9 = 9,
DecimalSeparator = 10,
GroupSeparator = 11,
InfinitySign = 12,
MinusSign = 13,
PlusSign = 14,
NaN = 15,
Exponent = 16,
}
#endregion Symbol enum
#region Static instances
public readonly static TextEncoder Utf8 = new Utf8TextEncoder();
public readonly static TextEncoder Utf16 = new Utf16TextEncoderLE();
#endregion Static instances
#region Private data
private readonly EncodingName _encoding;
private readonly byte[][] _symbols; // this could be flattened into a single array
private readonly ParsingTrie.Node[] _parsingTrie; // prefix tree used for parsing
#endregion Private data
#region Properties
public EncodingName Encoding => _encoding;
public bool IsInvariantUtf8 => this == Utf8;
public bool IsInvariantUtf16 => this == Utf16;
#endregion Properties
#region Constructors
protected TextEncoder(byte[][] symbols, EncodingName encoding)
{
_encoding = encoding;
_symbols = symbols;
_parsingTrie = ParsingTrie.Create(symbols);
}
#endregion Constructors
#region Decode Methods
/// <summary>
/// Decodes a span containing a sequence of bytes into a UTF-16 string value.
/// </summary>
/// <param name="encodedBytes">The data span to consume for decoding. The encoded data should be relative to the concrete instance of the class used.</param>
/// <param name="text">An output parameter to capture the decoded string.</param>
/// <param name="bytesConsumed">An output parameter to capture the number of bytes successfully consumed during decoding from <paramref name="encodedBytes"/></param>
/// <returns>
/// True if successfully able to consume the entire data span in the decoding process.
/// False if decoding failed. <paramref name="text"/> will contain as much of the string as possible to decode with
/// <paramref name="bytesConsumed"> set to the number of bytes used.
///
/// It is possible to continue decoding from the stop point by slicing off the processed part of <paramref name="encodedBytes"/>, fixing
/// errors (reading more data, patching encoded bytes, etc.) and calling this method again.
/// </returns>
public abstract bool TryDecode(ReadOnlySpan<byte> encodedBytes, out string text, out int bytesConsumed);
/// <summary>
/// Decodes a span containing a sequence of bytes into UTF-8 bytes.
/// </summary>
/// <param name="encodedBytes">The data span to consume for decoding. The encoded data should be relative to the concrete instance of the class used.</param>
/// <param name="utf8">A span buffer to capture the decoded UTF-8 bytes.</param>
/// <param name="bytesConsumed">An output parameter to capture the number of bytes successfully consumed during decoding from <paramref name="encodedBytes"/></param>
/// <param name="bytesWritten">A output parameter to capture the number of bytes written to <paramref name="utf8"/></param>
/// <returns>
/// True if successfully able to consume the entire data span in the decoding process.
/// False if decoding failed. <paramref name="utf8"/> will contain as much of the data as possible to decode with
/// <paramref name="bytesConsumed"> set to the number of bytes used.
///
/// It is possible to continue decoding from the stop point by slicing off the processed part of <paramref name="encodedBytes"/>, fixing
/// errors (reading more data, patching encoded bytes, etc.) and calling this method again.
/// </returns>
public abstract bool TryDecode(ReadOnlySpan<byte> encodedBytes, Span<byte> utf8, out int bytesConsumed, out int bytesWritten);
/// <summary>
/// Decodes a span containing a sequence of bytes into UTF-16 characters.
/// </summary>
/// <param name="encodedBytes">The data span to consume for decoding. The encoded data should be relative to the concrete instance of the class used.</param>
/// <param name="utf16">A span buffer to capture the decoded UTF-16 characters.</param>
/// <param name="bytesConsumed">An output parameter to capture the number of bytes successfully consumed during decoding from <paramref name="encodedBytes"/></param>
/// <param name="charactersWritten">A output parameter to capture the number of bytes written to <paramref name="utf16"/></param>
/// <returns>
/// True if successfully able to consume the entire data span in the decoding process.
/// False if decoding failed. <paramref name="utf16"/> will contain as much of the data as possible to decode with
/// <paramref name="bytesConsumed"> set to the number of bytes used.
///
/// It is possible to continue decoding from the stop point by slicing off the processed part of <paramref name="encodedBytes"/>, fixing
/// errors (reading more data, patching encoded bytes, etc.) and calling this method again.
/// </returns>
public abstract bool TryDecode(ReadOnlySpan<byte> encodedBytes, Span<char> utf16, out int bytesConsumed, out int charactersWritten);
/// <summary>
/// Decodes a span containing a sequence of bytes into UTF-32 characters.
/// </summary>
/// <param name="encodedBytes">The data span to consume for decoding. The encoded data should be relative to the concrete instance of the class used.</param>
/// <param name="utf32">A span buffer to capture the decoded UTF-32 characters.</param>
/// <param name="bytesConsumed">An output parameter to capture the number of bytes successfully consumed during decoding from <paramref name="encodedBytes"/></param>
/// <param name="codeUnitsWritten">A output parameter to capture the number of code units written to <paramref name="utf32"/></param>
/// <returns>
/// True if successfully able to consume the entire data span in the decoding process.
/// False if decoding failed. <paramref name="utf32"/> will contain as much of the data as possible to decode with
/// <paramref name="bytesConsumed"> set to the number of bytes used.
///
/// It is possible to continue decoding from the stop point by slicing off the processed part of <paramref name="encodedBytes"/>, fixing
/// errors (reading more data, patching encoded bytes, etc.) and calling this method again.
/// </returns>
public abstract bool TryDecode(ReadOnlySpan<byte> encodedBytes, Span<uint> utf32, out int bytesConsumed, out int codeUnitsWritten);
#endregion Decode Methods
#region Encode Methods
/// <summary>
/// Encodes a span containing a sequence of UTF-8 bytes. The target encoding is relative to the concrete class being executed.
/// </summary>
/// <param name="utf8">The data span to consume for encoding.</param>
/// <param name="encodedBytes">A span buffer to write the encoded bytes.</param>
/// <param name="bytesConsumed">An output parameter to capture the number of bytes successfully consumed during encoding from <paramref name="utf8"/></param>
/// <param name="bytesWritten">A output parameter to capture the number of bytes written to <paramref name="encodedBytes"/></param>
/// <returns>
/// True if successfully able to consume the entire data span in the encoding process.
/// False if encoding failed. <paramref name="encodedBytes"/> will contain as much of the data as possible to encode with
/// <paramref name="bytesConsumed"> set to the number of bytes used.
///
/// It is possible to continue encoding from the stop point by slicing off the processed part of <paramref name="utf8"/>, fixing
/// errors (reading more data, new output buffer, etc.) and calling this method again.
/// </returns>
public abstract bool TryEncode(ReadOnlySpan<byte> utf8, Span<byte> encodedBytes, out int bytesConsumed, out int bytesWritten);
/// <summary>
/// Encodes a span containing a sequence of UTF-16 characters. The target encoding is relative to the concrete class being executed.
/// </summary>
/// <param name="utf16">The data span to consume for encoding.</param>
/// <param name="encodedBytes">A span buffer to write the encoded bytes.</param>
/// <param name="charactersConsumed">An output parameter to capture the number of characters successfully consumed during encoding from <paramref name="utf8"/></param>
/// <param name="bytesWritten">A output parameter to capture the number of bytes written to <paramref name="encodedBytes"/></param>
/// <returns>
/// True if successfully able to consume the entire data span in the encoding process.
/// False if encoding failed. <paramref name="encodedBytes"/> will contain as much of the data as possible to encode with
/// <paramref name="charactersConsumed"> set to the number of characters used.
///
/// It is possible to continue encoding from the stop point by slicing off the processed part of <paramref name="utf16"/>, fixing
/// errors (reading more data, new output buffer, etc.) and calling this method again.
/// </returns>
public abstract bool TryEncode(ReadOnlySpan<char> utf16, Span<byte> encodedBytes, out int charactersConsumed, out int bytesWritten);
/// <summary>
/// Encodes a span containing a sequence of UTF-32 characters. The target encoding is relative to the concrete class being executed.
/// </summary>
/// <param name="utf32">The data span to consume for encoding.</param>
/// <param name="encodedBytes">A span buffer to write the encoded bytes.</param>
/// <param name="codeUnitsConsumed">An output parameter to capture the number of code units successfully consumed during encoding from <paramref name="utf8"/></param>
/// <param name="bytesWritten">A output parameter to capture the number of bytes written to <paramref name="encodedBytes"/></param>
/// <returns>
/// True if successfully able to consume the entire data span in the encoding process.
/// False if encoding failed. <paramref name="encodedBytes"/> will contain as much of the data as possible to encode with
/// <paramref name="codeUnitsConsumed"> set to the number of code units used.
///
/// It is possible to continue encoding from the stop point by slicing off the processed part of <paramref name="utf32"/>, fixing
/// errors (reading more data, new output buffer, etc.) and calling this method again.
/// </returns>
public abstract bool TryEncode(ReadOnlySpan<uint> utf32, Span<byte> encodedBytes, out int codeUnitsConsumed, out int bytesWritten);
/// <summary>
/// Encodes a UTF-16 string. The target encoding is relative to the concrete class being executed.
/// </summary>
/// <param name="text">A string containing the characters to encode.</param>
/// <param name="encodedBytes">A span buffer to write the encoded bytes.</param>
/// <param name="bytesWritten">A output parameter to capture the number of bytes written to <paramref name="encodedBytes"/></param>
/// <returns>
/// True if successfully able to encode the entire string of characters, else false.
///
/// A failure likely means the output buffer is too small.
/// </returns>
public abstract bool TryEncode(string text, Span<byte> encodedBytes, out int bytesWritten);
/// <summary>
/// Computes the number of bytes necessary to encode a given string.
/// </summary>
/// <param name="text">A string containing the characters to encode.</param>
/// <param name="bytesNeeded">An output parameter to hold the number of bytes needed for encoding.</param>
/// <returns>Returns true is the span is capable of being fully encoded, else false.</returns>
public virtual unsafe bool TryComputeEncodedBytes(string text, out int bytesNeeded)
{
fixed(char* c = text)
{
return TryComputeEncodedBytes(new ReadOnlySpan<char>(c, text.Length), out bytesNeeded);
}
}
/// <summary>
/// Computes the number of bytes necessary to encode a given UTF-8 sequence.
/// </summary>
/// <param name="utf8">A span containing a sequence of UTF-8 characters to encode.</param>
/// <param name="bytesNeeded">An output parameter to hold the number of bytes needed for encoding.</param>
/// <returns>Returns true is the span is capable of being fully encoded, else false.</returns>
public abstract bool TryComputeEncodedBytes(ReadOnlySpan<byte> utf8, out int bytesNeeded);
/// <summary>
/// Computes the number of bytes necessary to encode a given UTF-16 sequence.
/// </summary>
/// <param name="utf16">A span containing a sequence of UTF-16 characters to encode.</param>
/// <param name="bytesNeeded">An output parameter to hold the number of bytes needed for encoding.</param>
/// <returns>Returns true is the span is capable of being fully encoded, else false.</returns>
public abstract bool TryComputeEncodedBytes(ReadOnlySpan<char> utf16, out int bytesNeeded);
/// <summary>
/// Computes the number of bytes necessary to encode a given UTF-32 character sequence.
/// </summary>
/// <param name="utf32">A span containing a sequence of UTF-32 characters to encode.</param>
/// <param name="bytesNeeded">An output parameter to hold the number of bytes needed for encoding.</param>
/// <returns>Returns true is the span is capable of being fully encoded , else false.</returns>
public abstract bool TryComputeEncodedBytes(ReadOnlySpan<uint> utf32, out int bytesNeeded);
#endregion Encode Methods
#region Symbol Parsing / Formatting
public bool TryParseSymbol(ReadOnlySpan<byte> encodedBytes, out Symbol symbol, out int bytesConsumed)
{
int trieIndex = 0;
int bufferIndex = 0;
bytesConsumed = 0;
while (true)
{
var node = _parsingTrie[trieIndex];
if (node.ValueOrNumChildren == 0) // if numChildren == 0, we're on a leaf & we've found our value
{
symbol = (Symbol)node.IndexOrSymbol;
if (VerifySuffix(encodedBytes, bufferIndex, symbol))
{
bytesConsumed = _symbols[node.IndexOrSymbol].Length - bufferIndex;
return true;
}
else
{
symbol = 0;
bytesConsumed = 0;
return false;
}
}
else
{
int search = BinarySearch(trieIndex, bufferIndex, encodedBytes[0]); // we search the _parsingTrie for the nextByte
if (search > 0) // if we found a node
{
trieIndex = _parsingTrie[search].IndexOrSymbol;
bytesConsumed++;
bufferIndex++;
}
else
{
symbol = 0;
bytesConsumed = 0;
return false;
}
}
}
}
public bool TryEncode(Symbol symbol, Span<byte> encodedBytes, out int bytesWritten)
{
byte[] bytes = _symbols[(int)symbol];
bytesWritten = bytes.Length;
if (bytesWritten > encodedBytes.Length)
{
bytesWritten = 0;
return false;
}
if (bytesWritten == 2)
{
encodedBytes[0] = bytes[0];
encodedBytes[1] = bytes[1];
return true;
}
if (bytesWritten == 1)
{
encodedBytes[0] = bytes[0];
return true;
}
new Span<byte>(bytes).CopyTo(encodedBytes);
return true;
}
// TODO: this should be removed
/// <summary>
/// Parse the next byte in a byte array. Will return either a DigitOrSymbol value, an InvalidCharacter, or a Continue
/// </summary>
/// <param name="nextByte">The next byte to be parsed</param>
/// <param name="bytesParsed">The total number of bytes parsed (will be zero until a code unit is deciphered)</param>
/// <returns></returns>
internal bool TryParseSymbol(ReadOnlySpan<byte> encodedBytes, out uint symbol, out int consumed)
{
int trieIndex = 0;
int codeUnitIndex = 0;
consumed = 0;
while (true)
{
if (_parsingTrie[trieIndex].ValueOrNumChildren == 0) // if numChildren == 0, we're on a leaf & we've found our value and completed the code unit
{
symbol = (uint)_parsingTrie[trieIndex].IndexOrSymbol; // return the parsed value
if (VerifySuffix(encodedBytes, codeUnitIndex, (Symbol)symbol))
{
consumed = _symbols[(int)symbol].Length;
return true;
}
else
{
symbol = 0;
consumed = 0;
return false;
}
}
else
{
int search = BinarySearch(trieIndex, codeUnitIndex, encodedBytes[codeUnitIndex]); // we search the _parsingTrie for the nextByte
if (search > 0) // if we found a node
{
trieIndex = _parsingTrie[search].IndexOrSymbol;
consumed++;
codeUnitIndex++;
}
else
{
symbol = 0;
consumed = 0;
return false;
}
}
}
}
#endregion Symbol Parsing / Formatting
#region Private helpers
// This binary search implementation returns an int representing either:
// - the index of the item searched for (if the value is positive)
// - the index of the location where the item should be placed to maintain a sorted list (if the value is negative)
private int BinarySearch(int nodeIndex, int level, byte value)
{
int maxMinLimits = _parsingTrie[nodeIndex].IndexOrSymbol;
if (maxMinLimits != 0 && value > (uint)maxMinLimits >> 24 && value < (uint)(maxMinLimits << 16) >> 24)
{
// See the comments on the struct above for more information about this format
return (int)(nodeIndex + ((uint)(maxMinLimits << 8) >> 24) + value - ((uint)maxMinLimits >> 24));
}
int leftBound = nodeIndex + 1, rightBound = nodeIndex + _parsingTrie[nodeIndex].ValueOrNumChildren;
int midIndex = 0;
while (true)
{
if (leftBound > rightBound) // if the search failed
{
// this loop is necessary because binary search takes the floor
// of the middle, which means it can give incorrect indices for insertion.
// we should never iterate up more than two indices.
while (midIndex < nodeIndex + _parsingTrie[nodeIndex].ValueOrNumChildren
&& _parsingTrie[midIndex].ValueOrNumChildren < value)
{
midIndex++;
}
return -midIndex;
}
midIndex = (leftBound + rightBound) / 2; // find the middle value
byte mValue = _parsingTrie[midIndex].ValueOrNumChildren;
if (mValue < value)
leftBound = midIndex + 1;
else if (mValue > value)
rightBound = midIndex - 1;
else
return midIndex;
}
}
private bool VerifySuffix(ReadOnlySpan<byte> buffer, int codeUnitIndex, Symbol symbol)
{
int codeUnitLength = _symbols[(int)symbol].Length;
if (codeUnitIndex == codeUnitLength - 1)
return true;
for (int i = 0; i < codeUnitLength - codeUnitIndex; i++)
{
if (buffer[i + codeUnitIndex] != _symbols[(int)symbol][i + codeUnitIndex])
return false;
}
return true;
}
#endregion Private helpers
#region Static factory methods
public static TextEncoder CreateUtf8Encoder(byte[][] symbols)
{
return new Utf8TextEncoder(symbols);
}
public static TextEncoder CreateUtf16Encoder(byte[][] symbols)
{
return new Utf16TextEncoderLE(symbols);
}
#endregion Static factory methods
}
}
| |
/*
* ToolkitManager.cs - Implementation of the
* "System.Drawing.Toolkit.ToolkitManager" class.
*
* Copyright (C) 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.Drawing.Toolkit
{
using System.Drawing.Printing;
using System.Reflection;
using System.IO;
using DotGNU.Images;
[NonStandardExtra]
public sealed class ToolkitManager
{
// Global state.
private static IToolkit toolkit;
private static IToolkitPrintingSystem printingSystem;
public ToolkitManager() {}
// Get or set the active graphical display toolkit.
public static IToolkit Toolkit
{
get
{
lock(typeof(ToolkitManager))
{
if(toolkit == null)
{
toolkit = CreateDefaultToolkit();
}
return toolkit;
}
}
set
{
lock(typeof(ToolkitManager))
{
toolkit = value;
}
}
}
// Determine if we currently have a graphical toolkit.
public static bool HasToolkit
{
get
{
lock(typeof(ToolkitManager))
{
return (toolkit != null);
}
}
}
// Determine if this platform appears to be Unix-ish.
private static bool IsUnix()
{
#if !ECMA_COMPAT
if(Environment.OSVersion.Platform != (PlatformID)128) /* Unix */
#else
if(Path.DirectorySeparatorChar == '\\' ||
Path.AltDirectorySeparatorChar == '\\')
#endif
{
return false;
}
else
{
return true;
}
}
// Get or set the active printing system.
public static IToolkitPrintingSystem PrintingSystem
{
get
{
lock(typeof(ToolkitManager))
{
if(printingSystem == null)
{
if(IsUnix())
{
printingSystem = new UnixPrintingSystem();
}
else
{
// TODO: Win32 printing system.
printingSystem = new NullPrintingSystem();
}
}
return printingSystem;
}
}
set
{
lock(typeof(ToolkitManager))
{
printingSystem = value;
}
}
}
// Get a standard paper size object.
public static PaperSize GetStandardPaperSize(PaperKind kind)
{
return new PaperSize(kind);
}
// Get a standard paper source object.
public static PaperSource GetStandardPaperSource(PaperSourceKind kind)
{
return new PaperSource(kind, null);
}
// Get a standard printer resolution object.
public static PrinterResolution GetStandardPrinterResolution
(PrinterResolutionKind kind, int x, int y)
{
return new PrinterResolution(kind, x, y);
}
// Create a "Graphics" object from an "IToolkitGraphics" handler.
public static Graphics CreateGraphics(IToolkitGraphics graphics)
{
if(graphics == null)
{
throw new ArgumentNullException("graphics");
}
return new Graphics(graphics);
}
// Create a "Graphics" object from an "IToolkitGraphics" handler.
public static Graphics CreateGraphics(IToolkitGraphics graphics, Rectangle baseWindow)
{
if(graphics == null)
{
throw new ArgumentNullException("graphics");
}
return new Graphics(graphics, baseWindow);
}
// Create a "Graphics" object from an "IToolkitGraphics" handler.
public static Graphics CreateGraphics(Graphics graphics, Rectangle baseWindow)
{
if(graphics == null)
{
throw new ArgumentNullException("graphics");
}
return new Graphics(graphics, baseWindow);
}
// Create a "Graphics" object from an "IToolkitGraphics" handler.
// Start with a clip that has already been set in the underlying IToolkitGraphics.
public static Graphics CreateGraphics(IToolkitGraphics graphics, Region clip)
{
if(graphics == null)
{
throw new ArgumentNullException("graphics");
}
Graphics createdGraphics = new Graphics(graphics);
createdGraphics.SetClipInternal(clip);
return createdGraphics;
}
// Draw a bitmap-based glyph to a "Graphics" object. "bits" must be
// in the form of an xbm bitmap.
public static void DrawGlyph(Graphics graphics, int x, int y,
byte[] bits, int bitsWidth, int bitsHeight,
Color color)
{
if(graphics == null)
{
throw new ArgumentNullException("graphics", "Argument cannot be null");
}
graphics.DrawGlyph(x, y, bits, bitsWidth, bitsHeight, color);
}
// Get the raw frame data for an "Image" or "Icon" object.
public static DotGNU.Images.Frame GetImageFrame(Object image)
{
if(image is System.Drawing.Image)
{
return ((System.Drawing.Image)image).dgImage.GetFrame(0);
}
else if(image is System.Drawing.Icon)
{
return ((System.Drawing.Icon)image).frame;
}
else
{
return null;
}
}
// Convert a brush into an exclusive-OR brush which XOR's the brush
// against a drawing surface, and also includes inferior child
// windows in the draw operation.
public static Brush CreateXorBrush(Brush brush)
{
return new XorBrush(brush);
}
// Get the override toolkit name.
private static String GetToolkitOverride()
{
String name;
// Search for "--toolkit" in the command-line options.
String[] args = Environment.GetCommandLineArgs();
int index;
name = null;
for(index = 1; index < args.Length; ++index)
{
if(args[index] == "--toolkit")
{
if((index + 1) < args.Length)
{
name = args[index + 1];
break;
}
}
else if(args[index].StartsWith("--toolkit="))
{
name = args[index].Substring(10);
break;
}
}
// Check the environment next.
if(name == null)
{
name = Environment.GetEnvironmentVariable
("PNET_WINFORMS_TOOLKIT");
}
// Bail out if no toolkit name specified.
if(name == null || name.Length == 0)
{
return null;
}
// Prepend "System.Drawing." if necessary.
if(name.IndexOf('.') == -1)
{
name = "System.Drawing." + name;
}
return name;
}
// Create the default toolkit.
private static IToolkit CreateDefaultToolkit()
{
#if CONFIG_REFLECTION
// Determine the name of the toolkit we wish to use.
String name = GetToolkitOverride();
if(name == null)
{
if(IsUnix())
{
name = "System.Drawing.Xsharp";
}
else
{
name = "System.Drawing.Win32";
}
}
// Load the toolkit's assembly.
Assembly assembly = Assembly.Load(name);
// Find the "System.Drawing.Toolkit.DrawingToolkit" class.
Type type = assembly.GetType
("System.Drawing.Toolkit.DrawingToolkit");
if(type == null)
{
throw new NotSupportedException();
}
// Instantiate "DrawingToolkit" and return it.
ConstructorInfo ctor = type.GetConstructor(new Type [0]);
return (IToolkit)(ctor.Invoke(new Object [0]));
#else
return new NullToolkit();
#endif
}
}; // class ToolkitManager
}; // namespace System.Drawing.Toolkit
| |
//-----------------------------------------------------------------------
// <copyright file="FtpServer.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>
// <author>Mark Junker</author>
//-----------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using FubarDev.FtpServer.ConnectionChecks;
using FubarDev.FtpServer.Features;
using FubarDev.FtpServer.Localization;
using FubarDev.FtpServer.ServerCommands;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace FubarDev.FtpServer
{
/// <summary>
/// The portable FTP server.
/// </summary>
public sealed class FtpServer : IFtpServer, IDisposable
{
private readonly FtpServerStatistics _statistics = new FtpServerStatistics();
private readonly IServiceProvider _serviceProvider;
private readonly List<IFtpConnectionConfigurator> _connectionConfigurators;
private readonly List<IFtpControlStreamAdapter> _controlStreamAdapters;
private readonly ConcurrentDictionary<IFtpConnection, FtpConnectionInfo> _connections = new ConcurrentDictionary<IFtpConnection, FtpConnectionInfo>();
private readonly IFtpListenerService _serverListener;
private readonly ILogger<FtpServer>? _log;
private readonly Task _clientReader;
private readonly Timer? _connectionTimeoutChecker;
/// <summary>
/// Initializes a new instance of the <see cref="FtpServer"/> class.
/// </summary>
/// <param name="serverOptions">The server options.</param>
/// <param name="serviceProvider">The service provider used to query services.</param>
/// <param name="controlStreamAdapters">Adapters for the control connection stream.</param>
/// <param name="connectionConfigurators">Configurators for FTP connections.</param>
/// <param name="ftpListenerService">Listener service for FTP connections.</param>
/// <param name="logger">The FTP server logger.</param>
public FtpServer(
IOptions<FtpServerOptions> serverOptions,
IServiceProvider serviceProvider,
IEnumerable<IFtpControlStreamAdapter> controlStreamAdapters,
IEnumerable<IFtpConnectionConfigurator> connectionConfigurators,
IFtpListenerService ftpListenerService,
ILogger<FtpServer>? logger = null)
{
_serviceProvider = serviceProvider;
_connectionConfigurators = connectionConfigurators.ToList();
_controlStreamAdapters = controlStreamAdapters.ToList();
_log = logger;
ServerAddress = serverOptions.Value.ServerAddress;
Port = serverOptions.Value.Port;
MaxActiveConnections = serverOptions.Value.MaxActiveConnections;
_serverListener = ftpListenerService;
_serverListener.ListenerStarted += (s, e) =>
{
Port = e.Port;
OnListenerStarted(e);
};
_clientReader = ReadClientsAsync(
_serverListener.Channel,
_serverListener.ListenerShutdown.Token);
if (serverOptions.Value.ConnectionInactivityCheckInterval is TimeSpan checkInterval)
{
_connectionTimeoutChecker = new Timer(
_ => CloseExpiredConnections(),
null,
checkInterval,
checkInterval);
}
}
/// <inheritdoc />
public event EventHandler<ConnectionEventArgs>? ConfigureConnection;
/// <inheritdoc />
public event EventHandler<ListenerStartedEventArgs>? ListenerStarted;
/// <inheritdoc />
public IFtpServerStatistics Statistics => _statistics;
/// <inheritdoc />
public string? ServerAddress { get; }
/// <inheritdoc />
public int Port { get; private set; }
/// <inheritdoc />
public int MaxActiveConnections { get; }
/// <inheritdoc />
public FtpServiceStatus Status => _serverListener.Status;
/// <inheritdoc />
public bool Ready => Status == FtpServiceStatus.Running;
/// <inheritdoc/>
public void Dispose()
{
if (Status != FtpServiceStatus.Stopped)
{
StopAsync(CancellationToken.None).Wait();
}
_connectionTimeoutChecker?.Dispose();
(_serverListener as IDisposable)?.Dispose();
foreach (var connectionInfo in _connections.Values)
{
connectionInfo.Scope.Dispose();
}
}
/// <summary>
/// Returns all connections.
/// </summary>
/// <returns>The currently active connections.</returns>
/// <remarks>
/// The connection might be closed between calling this function and
/// using/querying the connection by the client.
/// </remarks>
public IEnumerable<IFtpConnection> GetConnections()
{
return _connections.Keys.ToList();
}
/// <inheritdoc />
[Obsolete("Use IFtpServerHost.StartAsync instead.")]
void IFtpServer.Start()
{
var host = _serviceProvider.GetRequiredService<IFtpServerHost>();
host.StartAsync(CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <inheritdoc />
[Obsolete("Use IFtpServerHost.StopAsync instead.")]
void IFtpServer.Stop()
{
var host = _serviceProvider.GetRequiredService<IFtpServerHost>();
host.StopAsync(CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <inheritdoc />
public Task PauseAsync(CancellationToken cancellationToken)
{
return _serverListener.PauseAsync(cancellationToken);
}
/// <inheritdoc />
public Task ContinueAsync(CancellationToken cancellationToken)
{
return _serverListener.ContinueAsync(cancellationToken);
}
/// <inheritdoc />
public async Task StartAsync(CancellationToken cancellationToken)
{
await _serverListener.StartAsync(cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task StopAsync(CancellationToken cancellationToken)
{
if (!_serverListener.ListenerShutdown.IsCancellationRequested)
{
_serverListener.ListenerShutdown.Cancel(true);
}
await _serverListener.StopAsync(cancellationToken).ConfigureAwait(false);
await _clientReader.ConfigureAwait(false);
}
/// <summary>
/// Close expired FTP connections.
/// </summary>
/// <remarks>
/// This will always happen when the FTP client is idle (without sending notifications) or
/// when the client was disconnected due to an undetectable network error.
/// </remarks>
private void CloseExpiredConnections()
{
foreach (var connection in GetConnections())
{
try
{
var keepAliveFeature = connection.Features.Get<IFtpConnectionStatusCheck>();
var isAlive = keepAliveFeature.CheckIfAlive();
if (isAlive)
{
// Ignore connections that are still alive.
continue;
}
var serverCommandFeature = connection.Features.Get<IServerCommandFeature>();
// Just ignore a failed write operation. We'll try again later.
serverCommandFeature.ServerCommandWriter.TryWrite(
new CloseConnectionServerCommand());
}
catch
{
// Errors are most likely indicating a closed connection. Nothing to do here...
}
}
}
private IEnumerable<ConnectionInitAsyncDelegate> OnConfigureConnection(IFtpConnection connection)
{
var eventArgs = new ConnectionEventArgs(connection);
ConfigureConnection?.Invoke(this, eventArgs);
return eventArgs.AsyncInitFunctions;
}
private async Task ReadClientsAsync(
ChannelReader<TcpClient> tcpClientReader,
CancellationToken cancellationToken)
{
try
{
while (!cancellationToken.IsCancellationRequested)
{
var hasClient = await tcpClientReader.WaitToReadAsync(cancellationToken)
.ConfigureAwait(false);
if (!hasClient)
{
return;
}
while (tcpClientReader.TryRead(out var client))
{
await AddClientAsync(client)
.ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
var exception = ex;
while (exception is AggregateException aggregateException && aggregateException.InnerException != null)
{
exception = aggregateException.InnerException;
}
switch (exception)
{
case OperationCanceledException _:
// Cancelled
break;
default:
throw;
}
}
finally
{
_log?.LogDebug("Stopped accepting connections");
}
}
private async Task AddClientAsync(TcpClient client)
{
var scope = _serviceProvider.CreateScope();
try
{
Stream socketStream = client.GetStream();
foreach (var controlStreamAdapter in _controlStreamAdapters)
{
socketStream = await controlStreamAdapter.WrapAsync(socketStream, CancellationToken.None)
.ConfigureAwait(false);
}
// Initialize information about the socket
var socketAccessor = scope.ServiceProvider.GetRequiredService<TcpSocketClientAccessor>();
socketAccessor.TcpSocketClient = client;
socketAccessor.TcpSocketStream = socketStream;
// Create the connection
var connection = scope.ServiceProvider.GetRequiredService<IFtpConnection>();
var connectionAccessor = scope.ServiceProvider.GetRequiredService<IFtpConnectionAccessor>();
connectionAccessor.FtpConnection = connection;
// Remember connection
if (!_connections.TryAdd(connection, new FtpConnectionInfo(scope)))
{
_log.LogCritical("A new scope was created, but the connection couldn't be added to the list");
client.Dispose();
scope.Dispose();
return;
}
// Send initial message
var serverCommandWriter = connection.Features.Get<IServerCommandFeature>().ServerCommandWriter;
var blockConnection = MaxActiveConnections != 0
&& _statistics.ActiveConnections >= MaxActiveConnections;
if (blockConnection)
{
// Send response
var response = new FtpResponse(421, "Too many users, server is full.");
await serverCommandWriter.WriteAsync(new SendResponseServerCommand(response))
.ConfigureAwait(false);
// Send close
await serverCommandWriter.WriteAsync(new CloseConnectionServerCommand())
.ConfigureAwait(false);
}
else
{
var serverMessages = scope.ServiceProvider.GetRequiredService<IFtpServerMessages>();
var response = new FtpResponseTextBlock(220, serverMessages.GetBannerMessage());
// Send initial response
await serverCommandWriter.WriteAsync(
new SendResponseServerCommand(response),
connection.CancellationToken)
.ConfigureAwait(false);
}
// Statistics
_statistics.AddConnection();
// Statistics and cleanup
connection.Closed += ConnectionOnClosed;
// Connection configuration by host
var asyncInitFunctions = OnConfigureConnection(connection);
foreach (var asyncInitFunction in asyncInitFunctions)
{
await asyncInitFunction(connection, CancellationToken.None)
.ConfigureAwait(false);
}
// Configure the connection
foreach (var connectionConfigurator in _connectionConfigurators)
{
await connectionConfigurator.Configure(connection, CancellationToken.None)
.ConfigureAwait(false);
}
// Start connection
await connection.StartAsync()
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Dispose();
_log?.LogError(ex, "Failed to start the client connection: {ErrorMessage}", ex.Message);
}
}
private void ConnectionOnClosed(object? sender, EventArgs eventArgs)
{
var connection = (IFtpConnection)(sender ?? throw new InvalidOperationException("Missing sender information."));
if (!_connections.TryRemove(connection, out var info))
{
return;
}
info.Scope.Dispose();
_statistics.CloseConnection();
}
private void OnListenerStarted(ListenerStartedEventArgs e)
{
ListenerStarted?.Invoke(this, e);
}
private class FtpConnectionInfo
{
public FtpConnectionInfo(IServiceScope scope)
{
Scope = scope;
}
public IServiceScope Scope { get; }
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement;
using Cassandra.Tests;
using NUnit.Framework;
namespace Cassandra.IntegrationTests.Core
{
[TestFixture, Category(TestCategory.Short), Category(TestCategory.RealCluster), Category(TestCategory.ServerApi)]
public class UdfTests : TestGlobals
{
private ITestCluster _testCluster;
private readonly List<ICluster> _clusters = new List<ICluster>();
private ICluster GetCluster(bool metadataSync)
{
var cluster = ClusterBuilder()
.AddContactPoint(_testCluster.InitialContactPoint)
.WithSocketOptions(new SocketOptions().SetConnectTimeoutMillis(60000))
.WithMetadataSyncOptions(new MetadataSyncOptions().SetMetadataSyncEnabled(metadataSync).SetRefreshSchemaDelayIncrement(1).SetMaxTotalRefreshSchemaDelay(5))
.Build();
_clusters.Add(cluster);
return cluster;
}
[OneTimeSetUp]
public void TestFixtureSetup()
{
if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.2"), Comparison.LessThan))
{
return;
}
_testCluster = TestClusterManager.GetTestCluster(1, 0, false, DefaultMaxClusterCreateRetries, false, false);
_testCluster.UpdateConfig("enable_user_defined_functions: true");
_testCluster.Start(1);
using (var cluster = ClusterBuilder().AddContactPoint(_testCluster.InitialContactPoint).Build())
{
var session = cluster.Connect();
var queries = new List<string>
{
"CREATE KEYSPACE ks_udf WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}",
"CREATE FUNCTION ks_udf.return_one() RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return 1;'",
"CREATE FUNCTION ks_udf.plus(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return s+v;'",
"CREATE FUNCTION ks_udf.plus(s bigint, v bigint) RETURNS NULL ON NULL INPUT RETURNS bigint LANGUAGE java AS 'return s+v;'",
"CREATE AGGREGATE ks_udf.sum(int) SFUNC plus STYPE int INITCOND 1",
"CREATE AGGREGATE ks_udf.sum(bigint) SFUNC plus STYPE bigint INITCOND 2"
};
if (TestClusterManager.CheckDseVersion(new Version(6, 0), Comparison.GreaterThanOrEqualsTo))
{
queries.Add("CREATE FUNCTION ks_udf.deterministic(dividend int, divisor int) " +
"CALLED ON NULL INPUT RETURNS int DETERMINISTIC LANGUAGE java AS " +
"'return dividend / divisor;'");
queries.Add("CREATE FUNCTION ks_udf.monotonic(dividend int, divisor int) " +
"CALLED ON NULL INPUT RETURNS int MONOTONIC LANGUAGE java AS " +
"'return dividend / divisor;'");
queries.Add("CREATE FUNCTION ks_udf.md(dividend int, divisor int) " +
"CALLED ON NULL INPUT RETURNS int DETERMINISTIC MONOTONIC LANGUAGE java AS " +
"'return dividend / divisor;'");
queries.Add("CREATE FUNCTION ks_udf.monotonic_on(dividend int, divisor int) " +
"CALLED ON NULL INPUT RETURNS int MONOTONIC ON dividend LANGUAGE java AS " +
"'return dividend / divisor;'");
queries.Add("CREATE AGGREGATE ks_udf.deta(int) SFUNC plus STYPE int INITCOND 0 DETERMINISTIC;");
}
foreach (var q in queries)
{
session.Execute(q);
}
}
}
[TearDown]
public void TearDown()
{
foreach (var cluster in _clusters)
{
try
{
cluster.Shutdown();
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
}
}
_clusters.Clear();
}
[Test, TestCase(true), TestCase(false), TestCassandraVersion(2, 2)]
public void GetFunction_Should_Retrieve_Metadata_Of_Cql_Function(bool metadataSync)
{
var cluster = GetCluster(metadataSync);
var ks = cluster.Metadata.GetKeyspace("ks_udf");
Assert.NotNull(ks);
var func = ks.GetFunction("plus", new [] {"int", "int"});
if (metadataSync)
{
//it is the same as retrieving from Metadata, it gets cached
Assert.AreEqual(func, cluster.Metadata.GetFunction("ks_udf", "plus", new [] {"int", "int"}));
}
else
{
Assert.AreNotEqual(func, cluster.Metadata.GetFunction("ks_udf", "plus", new [] {"int", "int"}));
}
Assert.NotNull(func);
Assert.AreEqual("plus", func.Name);
Assert.AreEqual("ks_udf", func.KeyspaceName);
CollectionAssert.AreEqual(new [] {"s", "v"}, func.ArgumentNames);
Assert.AreEqual(2, func.ArgumentTypes.Length);
Assert.AreEqual(ColumnTypeCode.Int, func.ArgumentTypes[0].TypeCode);
Assert.AreEqual(ColumnTypeCode.Int, func.ArgumentTypes[1].TypeCode);
Assert.AreEqual("return s+v;", func.Body);
Assert.AreEqual("java", func.Language);
Assert.AreEqual(ColumnTypeCode.Int, func.ReturnType.TypeCode);
Assert.AreEqual(false, func.CalledOnNullInput);
}
[Test, TestCase(true), TestCase(false), TestCassandraVersion(2, 2)]
public void GetFunction_Should_Retrieve_Metadata_Of_Cql_Function_Without_Parameters(bool metadataSync)
{
var ks = GetCluster(metadataSync).Metadata.GetKeyspace("ks_udf");
Assert.NotNull(ks);
var func = ks.GetFunction("return_one", new string[0]);
Assert.NotNull(func);
Assert.AreEqual("return_one", func.Name);
Assert.AreEqual("ks_udf", func.KeyspaceName);
Assert.AreEqual(0, func.ArgumentNames.Length);
Assert.AreEqual(0, func.ArgumentTypes.Length);
Assert.AreEqual(0, func.Signature.Length);
Assert.AreEqual("return 1;", func.Body);
Assert.AreEqual("java", func.Language);
Assert.AreEqual(ColumnTypeCode.Int, func.ReturnType.TypeCode);
Assert.AreEqual(false, func.CalledOnNullInput);
Assert.False(func.Monotonic);
Assert.False(func.Deterministic);
Assert.AreEqual(func.MonotonicOn, new string[0]);
}
[Test, TestCase(true), TestCase(false), TestCassandraVersion(2, 2)]
public void GetFunction_Should_Be_Case_Sensitive(bool metadataSync)
{
var cluster = GetCluster(metadataSync);
var ks = cluster.Metadata.GetKeyspace("ks_udf");
Assert.NotNull(ks);
Assert.NotNull(ks.GetFunction("plus", new[] { "bigint", "bigint" }));
Assert.Null(ks.GetFunction("PLUS", new[] { "bigint", "bigint" }));
Assert.Null(ks.GetFunction("plus", new[] { "BIGINT", "bigint" }));
}
[Test, TestCase(true), TestCase(false), TestCassandraVersion(2, 2)]
public void GetFunction_Should_Return_Null_When_Not_Found(bool metadataSync)
{
var ks = GetCluster(metadataSync).Metadata.GetKeyspace("ks_udf");
Assert.NotNull(ks);
var func = ks.GetFunction("func_does_not_exists", new string[0]);
Assert.Null(func);
}
[Test, TestCase(true), TestCase(false), TestCassandraVersion(2, 2)]
public void GetFunction_Should_Return_Null_When_Not_Found_By_Signature(bool metadataSync)
{
var ks = GetCluster(metadataSync).Metadata.GetKeyspace("ks_udf");
Assert.NotNull(ks);
var func = ks.GetFunction("plus", new[] { "text", "text" });
Assert.Null(func);
}
[Test, TestCase(true), TestCase(false), TestCassandraVersion(2, 2)]
public void GetFunction_Should_Cache_The_Metadata(bool metadataSync)
{
var ks = GetCluster(metadataSync).Metadata.GetKeyspace("ks_udf");
Assert.NotNull(ks);
Assert.AreEqual(ks.GetFunction("plus", new[] { "text", "text" }), ks.GetFunction("plus", new[] { "text", "text" }));
}
[Test, TestCase(true), TestCase(false), TestCassandraVersion(2, 2)]
public void GetFunction_Should_Return_Most_Up_To_Date_Metadata_Via_Events(bool metadataSync)
{
var cluster = GetCluster(metadataSync);
var session = cluster.Connect("ks_udf");
var cluster2 = GetCluster(metadataSync);
var session2 = cluster.Connect("ks_udf");
session.Execute("CREATE OR REPLACE FUNCTION stringify(i int) RETURNS NULL ON NULL INPUT RETURNS text LANGUAGE java AS 'return Integer.toString(i);'");
cluster2.RefreshSchema("ks_udf");
Task.Delay(500).GetAwaiter().GetResult(); // wait for events to be processed
var _ = cluster2.Metadata.KeyspacesSnapshot // cache
.Single(kvp => kvp.Key == "ks_udf")
.Value
.GetFunction("stringify", new[] { "int" });
var ks = cluster.Metadata.GetKeyspace("ks_udf");
Assert.NotNull(ks);
var func = cluster.Metadata.GetFunction("ks_udf", "stringify", new[] { "int" });
Assert.NotNull(func);
Assert.AreEqual("return Integer.toString(i);", func.Body);
session.Execute("CREATE OR REPLACE FUNCTION stringify(i int) RETURNS NULL ON NULL INPUT RETURNS text LANGUAGE java AS 'return Integer.toString(i) + \"hello\";'");
if (metadataSync)
{
TestHelper.RetryAssert(() =>
{
func = cluster2.Metadata.GetFunction("ks_udf", "stringify", new[] { "int" });
Assert.NotNull(func);
Assert.AreEqual("return Integer.toString(i) + \"hello\";", func.Body);
}, 100, 100);
}
else
{
Task.Delay(2000).GetAwaiter().GetResult();
func = cluster2.Metadata.KeyspacesSnapshot
.Single(kvp => kvp.Key == "ks_udf")
.Value
.GetFunction("stringify", new[] { "int" });
Assert.IsNotNull(func);
Assert.AreEqual("return Integer.toString(i);", func.Body); // event wasnt processed
}
}
[Test, TestCase(true), TestCase(false), TestCassandraVersion(2, 2)]
public void GetAggregate_Should_Retrieve_Metadata_Of_Aggregate(bool metadataSync)
{
var cluster = GetCluster(metadataSync);
var ks = cluster.Metadata.GetKeyspace("ks_udf");
Assert.NotNull(ks);
var aggregate = ks.GetAggregate("sum", new[] { "bigint" });
Assert.NotNull(aggregate);
Assert.AreEqual("sum", aggregate.Name);
Assert.AreEqual("ks_udf", aggregate.KeyspaceName);
Assert.AreEqual(1, aggregate.ArgumentTypes.Length);
CollectionAssert.AreEqual(new[] { "bigint" }, aggregate.Signature);
Assert.AreEqual(ColumnTypeCode.Bigint, aggregate.ArgumentTypes[0].TypeCode);
Assert.AreEqual(ColumnTypeCode.Bigint, aggregate.ReturnType.TypeCode);
Assert.AreEqual(ColumnTypeCode.Bigint, aggregate.StateType.TypeCode);
Assert.AreEqual("2", aggregate.InitialCondition);
Assert.AreEqual("plus", aggregate.StateFunction);
Assert.False(aggregate.Deterministic);
}
[Test, TestCase(true), TestCase(false), TestCassandraVersion(2, 2)]
public void GetAggregate_Should_Return_Null_When_Not_Found(bool metadataSync)
{
var cluster = GetCluster(metadataSync);
var ks = cluster.Metadata.GetKeyspace("ks_udf");
Assert.NotNull(ks);
Assert.Null(ks.GetAggregate("aggr_does_not_exists", new[] { "bigint" }));
}
[Test, TestCase(true), TestCase(false), TestCassandraVersion(2, 2)]
public void GetAggregate_Should_Be_Case_Sensitive(bool metadataSync)
{
var cluster = GetCluster(metadataSync);
var ks = cluster.Metadata.GetKeyspace("ks_udf");
Assert.NotNull(ks);
Assert.NotNull(ks.GetAggregate("sum", new[] { "bigint" }));
Assert.Null(ks.GetAggregate("SUM", new[] { "bigint" }));
Assert.Null(ks.GetAggregate("sum", new[] { "BIGINT" }));
}
[Test, TestCase(true), TestCase(false), TestCassandraVersion(2, 2)]
public void GetAggregate_Should_Cache_The_Metadata(bool metadataSync)
{
var ks = GetCluster(metadataSync).Metadata.GetKeyspace("ks_udf");
Assert.NotNull(ks);
Assert.AreEqual(ks.GetAggregate("sum", new[] { "int" }), ks.GetAggregate("sum", new[] { "int" }));
}
[Test, TestCase(true), TestCase(false), TestCassandraVersion(2, 2)]
public void GetAggregate_Should_Return_Most_Up_To_Date_Metadata_Via_Events(bool metadataSync)
{
var cluster = GetCluster(metadataSync);
var session = cluster.Connect("ks_udf");
var cluster2 = GetCluster(metadataSync);
var session2 = cluster2.Connect("ks_udf");
session.Execute("CREATE OR REPLACE AGGREGATE ks_udf.sum2(int) SFUNC plus STYPE int INITCOND 0");
cluster2.RefreshSchema("ks_udf");
Task.Delay(500).GetAwaiter().GetResult(); // wait for events to be processed
var _ = cluster2.Metadata.KeyspacesSnapshot // cache
.Single(kvp => kvp.Key == "ks_udf")
.Value
.GetAggregate("sum2", new[] { "int" });
var ks = cluster.Metadata.GetKeyspace("ks_udf");
Assert.NotNull(ks);
var aggregate = cluster.Metadata.GetAggregate("ks_udf", "sum2", new[] {"int"});
Assert.AreEqual("0", aggregate.InitialCondition);
session.Execute("CREATE OR REPLACE AGGREGATE ks_udf.sum2(int) SFUNC plus STYPE int INITCOND 200");
TestUtils.WaitForSchemaAgreement(cluster);
if (metadataSync)
{
TestHelper.RetryAssert(() =>
{
aggregate = cluster.Metadata.GetAggregate("ks_udf", "sum2", new[] { "int" });
Assert.NotNull(aggregate);
Assert.AreEqual("200", aggregate.InitialCondition);
}, 100, 100);
}
else
{
Task.Delay(2000).GetAwaiter().GetResult();
aggregate = cluster2.Metadata.KeyspacesSnapshot
.Single(kvp => kvp.Key == "ks_udf")
.Value
.GetAggregate("sum2", new[] { "int" });
Assert.IsNotNull(aggregate);
Assert.AreEqual("0", aggregate.InitialCondition); // event wasnt processed
}
}
[Test, TestCase(true), TestCase(false)]
[TestDseVersion(6, 0)]
public void GetAggregate_Should_Retrieve_Metadata_Of_A_Determinitic_Cql_Aggregate(bool metadataSync)
{
var cluster = GetCluster(metadataSync);
var aggregate = cluster.Metadata.GetAggregate("ks_udf", "deta", new[] {"int"});
Assert.AreEqual("plus", aggregate.StateFunction);
Assert.True(aggregate.Deterministic);
}
[Test, TestCase(true), TestCase(false)]
[TestDseVersion(6, 0)]
public void GetFunction_Should_Retrieve_Metadata_Of_A_Determinitic_And_Monotonic_Cql_Function(bool metadataSync)
{
var cluster = GetCluster(metadataSync);
var fn = cluster.Metadata.GetFunction("ks_udf", "md", new[] {"int", "int"});
Assert.True(fn.Deterministic);
Assert.True(fn.Monotonic);
Assert.AreEqual(new []{ "dividend", "divisor"}, fn.MonotonicOn);
}
[Test, TestCase(true), TestCase(false)]
[TestDseVersion(6, 0)]
public void GetFunction_Should_Retrieve_Metadata_Of_Partially_Monotonic_Cql_Function(bool metadataSync)
{
var cluster = GetCluster(metadataSync);
var fn = cluster.Metadata.GetFunction("ks_udf", "monotonic_on", new[] {"int", "int"});
Assert.False(fn.Deterministic);
Assert.False(fn.Monotonic);
Assert.AreEqual(new []{ "dividend"}, fn.MonotonicOn);
}
}
}
| |
//
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Couchbase.Lite;
using Couchbase.Lite.Util;
using NUnit.Framework;
using Sharpen;
namespace Couchbase.Lite
{
/// <summary>Created by andrey on 12/3/13.</summary>
/// <remarks>Created by andrey on 12/3/13.</remarks>
public class ApiTest : LiteTestCase
{
private int changeCount = 0;
//SERVER & DOCUMENTS
/// <exception cref="System.Exception"></exception>
public virtual void TestAPIManager()
{
Manager manager = this.manager;
NUnit.Framework.Assert.IsTrue(manager != null);
foreach (string dbName in manager.GetAllDatabaseNames())
{
Database db = manager.GetDatabase(dbName);
Log.I(Tag, "Database '" + dbName + "':" + db.GetDocumentCount() + " documents");
}
ManagerOptions options = new ManagerOptions();
options.SetReadOnly(true);
Manager roManager = new Manager(new LiteTestContext(), options);
NUnit.Framework.Assert.IsTrue(roManager != null);
Database db_1 = roManager.GetDatabase("foo");
NUnit.Framework.Assert.IsNull(db_1);
IList<string> dbNames = manager.GetAllDatabaseNames();
NUnit.Framework.Assert.IsFalse(dbNames.Contains("foo"));
NUnit.Framework.Assert.IsTrue(dbNames.Contains(DefaultTestDb));
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
public virtual void TestCreateDocument()
{
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("testName", "testCreateDocument");
properties.Put("tag", 1337);
Database db = StartDatabase();
Document doc = CreateDocumentWithProperties(db, properties);
string docID = doc.GetId();
NUnit.Framework.Assert.IsTrue("Invalid doc ID: " + docID, docID.Length > 10);
string currentRevisionID = doc.GetCurrentRevisionId();
NUnit.Framework.Assert.IsTrue("Invalid doc revision: " + docID, currentRevisionID
.Length > 10);
NUnit.Framework.Assert.AreEqual(doc.GetUserProperties(), properties);
NUnit.Framework.Assert.AreEqual(db.GetDocument(docID), doc);
db.ClearDocumentCache();
// so we can load fresh copies
Document doc2 = db.GetExistingDocument(docID);
NUnit.Framework.Assert.AreEqual(doc2.GetId(), docID);
NUnit.Framework.Assert.AreEqual(doc2.GetCurrentRevisionId(), currentRevisionID);
NUnit.Framework.Assert.IsNull(db.GetExistingDocument("b0gus"));
}
/// <exception cref="System.Exception"></exception>
public virtual void TestDeleteDatabase()
{
Database deleteme = manager.GetDatabase("deleteme");
NUnit.Framework.Assert.IsTrue(deleteme.Exists());
string dbPath = deleteme.GetPath();
NUnit.Framework.Assert.IsTrue(new FilePath(dbPath).Exists());
NUnit.Framework.Assert.IsTrue(new FilePath(Sharpen.Runtime.Substring(dbPath, 0, dbPath
.LastIndexOf('.'))).Exists());
deleteme.Delete();
NUnit.Framework.Assert.IsFalse(deleteme.Exists());
NUnit.Framework.Assert.IsFalse(new FilePath(dbPath).Exists());
NUnit.Framework.Assert.IsFalse(new FilePath(dbPath + "-journal").Exists());
NUnit.Framework.Assert.IsFalse(new FilePath(Sharpen.Runtime.Substring(dbPath, 0,
dbPath.LastIndexOf('.'))).Exists());
deleteme.Delete();
// delete again, even though already deleted
Database deletemeFetched = manager.GetExistingDatabase("deleteme");
NUnit.Framework.Assert.IsNull(deletemeFetched);
}
/// <exception cref="System.Exception"></exception>
public virtual void TestDatabaseCompaction()
{
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("testName", "testDatabaseCompaction");
properties.Put("tag", 1337);
Document doc = CreateDocumentWithProperties(database, properties);
SavedRevision rev1 = doc.GetCurrentRevision();
IDictionary<string, object> properties2 = new Dictionary<string, object>(properties
);
properties2.Put("tag", 4567);
SavedRevision rev2 = rev1.CreateRevision(properties2);
database.Compact();
Document fetchedDoc = database.GetDocument(doc.GetId());
IList<SavedRevision> revisions = fetchedDoc.GetRevisionHistory();
foreach (SavedRevision revision in revisions)
{
if (revision.GetId().Equals(rev1))
{
NUnit.Framework.Assert.IsFalse(revision.ArePropertiesAvailable());
}
if (revision.GetId().Equals(rev2))
{
NUnit.Framework.Assert.IsTrue(revision.ArePropertiesAvailable());
}
}
}
/// <exception cref="System.Exception"></exception>
public virtual void TestDocumentCache()
{
Database db = StartDatabase();
Document doc = db.CreateDocument();
UnsavedRevision rev1 = doc.CreateRevision();
IDictionary<string, object> rev1Properties = new Dictionary<string, object>();
rev1Properties.Put("foo", "bar");
rev1.SetUserProperties(rev1Properties);
SavedRevision savedRev1 = rev1.Save();
string documentId = savedRev1.GetDocument().GetId();
// getting the document puts it in cache
Document docRev1 = db.GetExistingDocument(documentId);
UnsavedRevision rev2 = docRev1.CreateRevision();
IDictionary<string, object> rev2Properties = rev2.GetProperties();
rev2Properties.Put("foo", "baz");
rev2.SetUserProperties(rev2Properties);
rev2.Save();
Document docRev2 = db.GetExistingDocument(documentId);
NUnit.Framework.Assert.AreEqual("baz", docRev2.GetProperty("foo"));
}
/// <exception cref="System.Exception"></exception>
public virtual void TestCreateRevisions()
{
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("testName", "testCreateRevisions");
properties.Put("tag", 1337);
Database db = StartDatabase();
Document doc = CreateDocumentWithProperties(db, properties);
NUnit.Framework.Assert.IsFalse(doc.IsDeleted());
SavedRevision rev1 = doc.GetCurrentRevision();
NUnit.Framework.Assert.IsTrue(rev1.GetId().StartsWith("1-"));
NUnit.Framework.Assert.AreEqual(1, rev1.GetSequence());
NUnit.Framework.Assert.AreEqual(0, rev1.GetAttachments().Count);
// Test -createRevisionWithProperties:
IDictionary<string, object> properties2 = new Dictionary<string, object>(properties
);
properties2.Put("tag", 4567);
SavedRevision rev2 = rev1.CreateRevision(properties2);
NUnit.Framework.Assert.IsNotNull("Put failed", rev2);
NUnit.Framework.Assert.IsTrue("Document revision ID is still " + doc.GetCurrentRevisionId
(), doc.GetCurrentRevisionId().StartsWith("2-"));
NUnit.Framework.Assert.AreEqual(rev2.GetId(), doc.GetCurrentRevisionId());
NUnit.Framework.Assert.IsNotNull(rev2.ArePropertiesAvailable());
NUnit.Framework.Assert.AreEqual(rev2.GetUserProperties(), properties2);
NUnit.Framework.Assert.AreEqual(rev2.GetDocument(), doc);
NUnit.Framework.Assert.AreEqual(rev2.GetProperty("_id"), doc.GetId());
NUnit.Framework.Assert.AreEqual(rev2.GetProperty("_rev"), rev2.GetId());
// Test -createRevision:
UnsavedRevision newRev = rev2.CreateRevision();
NUnit.Framework.Assert.IsNull(newRev.GetId());
NUnit.Framework.Assert.AreEqual(newRev.GetParent(), rev2);
NUnit.Framework.Assert.AreEqual(newRev.GetParentId(), rev2.GetId());
NUnit.Framework.Assert.AreEqual(doc.GetCurrentRevision(), rev2);
NUnit.Framework.Assert.IsFalse(doc.IsDeleted());
IList<SavedRevision> listRevs = new AList<SavedRevision>();
listRevs.AddItem(rev1);
listRevs.AddItem(rev2);
NUnit.Framework.Assert.AreEqual(newRev.GetRevisionHistory(), listRevs);
NUnit.Framework.Assert.AreEqual(newRev.GetProperties(), rev2.GetProperties());
NUnit.Framework.Assert.AreEqual(newRev.GetUserProperties(), rev2.GetUserProperties
());
IDictionary<string, object> userProperties = new Dictionary<string, object>();
userProperties.Put("because", "NoSQL");
newRev.SetUserProperties(userProperties);
NUnit.Framework.Assert.AreEqual(newRev.GetUserProperties(), userProperties);
IDictionary<string, object> expectProperties = new Dictionary<string, object>();
expectProperties.Put("because", "NoSQL");
expectProperties.Put("_id", doc.GetId());
expectProperties.Put("_rev", rev2.GetId());
NUnit.Framework.Assert.AreEqual(newRev.GetProperties(), expectProperties);
SavedRevision rev3 = newRev.Save();
NUnit.Framework.Assert.IsNotNull(rev3);
NUnit.Framework.Assert.AreEqual(rev3.GetUserProperties(), newRev.GetUserProperties
());
}
/// <exception cref="System.Exception"></exception>
public virtual void TestCreateNewRevisions()
{
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("testName", "testCreateRevisions");
properties.Put("tag", 1337);
Database db = StartDatabase();
Document doc = db.CreateDocument();
UnsavedRevision newRev = doc.CreateRevision();
Document newRevDocument = newRev.GetDocument();
NUnit.Framework.Assert.AreEqual(doc, newRevDocument);
NUnit.Framework.Assert.AreEqual(db, newRev.GetDatabase());
NUnit.Framework.Assert.IsNull(newRev.GetParentId());
NUnit.Framework.Assert.IsNull(newRev.GetParent());
IDictionary<string, object> expectProperties = new Dictionary<string, object>();
expectProperties.Put("_id", doc.GetId());
NUnit.Framework.Assert.AreEqual(expectProperties, newRev.GetProperties());
NUnit.Framework.Assert.IsTrue(!newRev.IsDeletion());
NUnit.Framework.Assert.AreEqual(newRev.GetSequence(), 0);
//ios support another approach to set properties::
//newRev.([@"testName"] = @"testCreateRevisions";
//newRev[@"tag"] = @1337;
newRev.SetUserProperties(properties);
NUnit.Framework.Assert.AreEqual(newRev.GetUserProperties(), properties);
SavedRevision rev1 = newRev.Save();
NUnit.Framework.Assert.IsNotNull("Save 1 failed", rev1);
NUnit.Framework.Assert.AreEqual(doc.GetCurrentRevision(), rev1);
NUnit.Framework.Assert.IsNotNull(rev1.GetId().StartsWith("1-"));
NUnit.Framework.Assert.AreEqual(1, rev1.GetSequence());
NUnit.Framework.Assert.IsNull(rev1.GetParentId());
NUnit.Framework.Assert.IsNull(rev1.GetParent());
newRev = rev1.CreateRevision();
newRevDocument = newRev.GetDocument();
NUnit.Framework.Assert.AreEqual(doc, newRevDocument);
NUnit.Framework.Assert.AreEqual(db, newRev.GetDatabase());
NUnit.Framework.Assert.AreEqual(rev1.GetId(), newRev.GetParentId());
NUnit.Framework.Assert.AreEqual(rev1, newRev.GetParent());
NUnit.Framework.Assert.AreEqual(rev1.GetProperties(), newRev.GetProperties());
NUnit.Framework.Assert.AreEqual(rev1.GetUserProperties(), newRev.GetUserProperties
());
NUnit.Framework.Assert.IsNotNull(!newRev.IsDeletion());
// we can't add/modify one property as on ios. need to add separate method?
// newRev[@"tag"] = @4567;
properties.Put("tag", 4567);
newRev.SetUserProperties(properties);
SavedRevision rev2 = newRev.Save();
NUnit.Framework.Assert.IsNotNull("Save 2 failed", rev2);
NUnit.Framework.Assert.AreEqual(doc.GetCurrentRevision(), rev2);
NUnit.Framework.Assert.IsNotNull(rev2.GetId().StartsWith("2-"));
NUnit.Framework.Assert.AreEqual(2, rev2.GetSequence());
NUnit.Framework.Assert.AreEqual(rev1.GetId(), rev2.GetParentId());
NUnit.Framework.Assert.AreEqual(rev1, rev2.GetParent());
NUnit.Framework.Assert.IsNotNull("Document revision ID is still " + doc.GetCurrentRevisionId
(), doc.GetCurrentRevisionId().StartsWith("2-"));
// Add a deletion/tombstone revision:
newRev = doc.CreateRevision();
NUnit.Framework.Assert.AreEqual(rev2.GetId(), newRev.GetParentId());
NUnit.Framework.Assert.AreEqual(rev2, newRev.GetParent());
newRev.SetIsDeletion(true);
SavedRevision rev3 = newRev.Save();
NUnit.Framework.Assert.IsNotNull("Save 3 failed", rev3);
NUnit.Framework.Assert.IsNotNull("Unexpected revID " + rev3.GetId(), rev3.GetId()
.StartsWith("3-"));
NUnit.Framework.Assert.AreEqual(3, rev3.GetSequence());
NUnit.Framework.Assert.IsTrue(rev3.IsDeletion());
NUnit.Framework.Assert.IsTrue(doc.IsDeleted());
NUnit.Framework.Assert.IsNull(doc.GetCurrentRevision());
IList<SavedRevision> leafRevs = new AList<SavedRevision>();
leafRevs.AddItem(rev3);
NUnit.Framework.Assert.AreEqual(doc.GetLeafRevisions(), leafRevs);
db.GetDocumentCount();
Document doc2 = db.GetDocument(doc.GetId());
NUnit.Framework.Assert.AreEqual(doc, doc2);
NUnit.Framework.Assert.IsNull(db.GetExistingDocument(doc.GetId()));
}
//API_SaveMultipleDocuments on IOS
//API_SaveMultipleUnsavedDocuments on IOS
//API_DeleteMultipleDocuments commented on IOS
/// <exception cref="System.Exception"></exception>
public virtual void TestDeleteDocument()
{
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("testName", "testDeleteDocument");
Database db = StartDatabase();
Document doc = CreateDocumentWithProperties(db, properties);
NUnit.Framework.Assert.IsTrue(!doc.IsDeleted());
NUnit.Framework.Assert.IsTrue(!doc.GetCurrentRevision().IsDeletion());
NUnit.Framework.Assert.IsTrue(doc.Delete());
NUnit.Framework.Assert.IsTrue(doc.IsDeleted());
NUnit.Framework.Assert.IsNull(doc.GetCurrentRevision());
}
/// <exception cref="System.Exception"></exception>
public virtual void TestPurgeDocument()
{
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("testName", "testPurgeDocument");
Database db = StartDatabase();
Document doc = CreateDocumentWithProperties(db, properties);
NUnit.Framework.Assert.IsNotNull(doc);
doc.Purge();
Document redoc = db.GetCachedDocument(doc.GetId());
NUnit.Framework.Assert.IsNull(redoc);
}
/// <exception cref="System.Exception"></exception>
public virtual void TestDeleteDocumentViaTombstoneRevision()
{
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("testName", "testDeleteDocument");
Database db = StartDatabase();
Document doc = CreateDocumentWithProperties(db, properties);
NUnit.Framework.Assert.IsTrue(!doc.IsDeleted());
NUnit.Framework.Assert.IsTrue(!doc.GetCurrentRevision().IsDeletion());
IDictionary<string, object> props = new Dictionary<string, object>(doc.GetProperties
());
props.Put("_deleted", true);
SavedRevision deletedRevision = doc.PutProperties(props);
NUnit.Framework.Assert.IsTrue(doc.IsDeleted());
NUnit.Framework.Assert.IsTrue(deletedRevision.IsDeletion());
NUnit.Framework.Assert.IsNull(doc.GetCurrentRevision());
}
/// <exception cref="System.Exception"></exception>
public virtual void TestAllDocuments()
{
Database db = StartDatabase();
int kNDocs = 5;
CreateDocuments(db, kNDocs);
// clear the cache so all documents/revisions will be re-fetched:
db.ClearDocumentCache();
Log.I(Tag, "----- all documents -----");
Query query = db.CreateAllDocumentsQuery();
//query.prefetch = YES;
Log.I(Tag, "Getting all documents: " + query);
QueryEnumerator rows = query.Run();
NUnit.Framework.Assert.AreEqual(rows.GetCount(), kNDocs);
int n = 0;
for (IEnumerator<QueryRow> it = rows; it.HasNext(); )
{
QueryRow row = it.Next();
Log.I(Tag, " --> " + row);
Document doc = row.GetDocument();
NUnit.Framework.Assert.IsNotNull("Couldn't get doc from query", doc);
NUnit.Framework.Assert.IsNotNull("QueryRow should have preloaded revision contents"
, doc.GetCurrentRevision().ArePropertiesAvailable());
Log.I(Tag, " Properties =" + doc.GetProperties());
NUnit.Framework.Assert.IsNotNull("Couldn't get doc properties", doc.GetProperties
());
NUnit.Framework.Assert.AreEqual(doc.GetProperty("testName"), "testDatabase");
n++;
}
NUnit.Framework.Assert.AreEqual(n, kNDocs);
}
/// <exception cref="System.Exception"></exception>
public virtual void TestLocalDocs()
{
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("foo", "bar");
Database db = StartDatabase();
IDictionary<string, object> props = db.GetExistingLocalDocument("dock");
NUnit.Framework.Assert.IsNull(props);
NUnit.Framework.Assert.IsNotNull("Couldn't put new local doc", db.PutLocalDocument
("dock", properties));
props = db.GetExistingLocalDocument("dock");
NUnit.Framework.Assert.AreEqual(props.Get("foo"), "bar");
IDictionary<string, object> newProperties = new Dictionary<string, object>();
newProperties.Put("FOOO", "BARRR");
NUnit.Framework.Assert.IsNotNull("Couldn't update local doc", db.PutLocalDocument
("dock", newProperties));
props = db.GetExistingLocalDocument("dock");
NUnit.Framework.Assert.IsNull(props.Get("foo"));
NUnit.Framework.Assert.AreEqual(props.Get("FOOO"), "BARRR");
NUnit.Framework.Assert.IsNotNull("Couldn't delete local doc", db.DeleteLocalDocument
("dock"));
props = db.GetExistingLocalDocument("dock");
NUnit.Framework.Assert.IsNull(props);
NUnit.Framework.Assert.IsNotNull("Second delete should have failed", !db.DeleteLocalDocument
("dock"));
}
//TODO issue: deleteLocalDocument should return error.code( see ios)
// HISTORY
/// <exception cref="System.Exception"></exception>
public virtual void TestHistory()
{
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("testName", "test06_History");
properties.Put("tag", 1);
Database db = StartDatabase();
Document doc = CreateDocumentWithProperties(db, properties);
string rev1ID = doc.GetCurrentRevisionId();
Log.I(Tag, "1st revision: " + rev1ID);
NUnit.Framework.Assert.IsNotNull("1st revision looks wrong: " + rev1ID, rev1ID.StartsWith
("1-"));
NUnit.Framework.Assert.AreEqual(doc.GetUserProperties(), properties);
properties = new Dictionary<string, object>();
properties.PutAll(doc.GetProperties());
properties.Put("tag", 2);
NUnit.Framework.Assert.IsNotNull(!properties.Equals(doc.GetProperties()));
NUnit.Framework.Assert.IsNotNull(doc.PutProperties(properties));
string rev2ID = doc.GetCurrentRevisionId();
Log.I(Tag, "rev2ID" + rev2ID);
NUnit.Framework.Assert.IsNotNull("2nd revision looks wrong:" + rev2ID, rev2ID.StartsWith
("2-"));
IList<SavedRevision> revisions = doc.GetRevisionHistory();
Log.I(Tag, "Revisions = " + revisions);
NUnit.Framework.Assert.AreEqual(revisions.Count, 2);
SavedRevision rev1 = revisions[0];
NUnit.Framework.Assert.AreEqual(rev1.GetId(), rev1ID);
IDictionary<string, object> gotProperties = rev1.GetProperties();
NUnit.Framework.Assert.AreEqual(1, gotProperties.Get("tag"));
SavedRevision rev2 = revisions[1];
NUnit.Framework.Assert.AreEqual(rev2.GetId(), rev2ID);
NUnit.Framework.Assert.AreEqual(rev2, doc.GetCurrentRevision());
gotProperties = rev2.GetProperties();
NUnit.Framework.Assert.AreEqual(2, gotProperties.Get("tag"));
IList<SavedRevision> tmp = new AList<SavedRevision>();
tmp.AddItem(rev2);
NUnit.Framework.Assert.AreEqual(doc.GetConflictingRevisions(), tmp);
NUnit.Framework.Assert.AreEqual(doc.GetLeafRevisions(), tmp);
}
/// <exception cref="System.Exception"></exception>
public virtual void TestHistoryAfterDocDeletion()
{
IDictionary<string, object> properties = new Dictionary<string, object>();
string docId = "testHistoryAfterDocDeletion";
properties.Put("tag", 1);
Database db = StartDatabase();
Document doc = db.GetDocument(docId);
NUnit.Framework.Assert.AreEqual(docId, doc.GetId());
doc.PutProperties(properties);
string revID = doc.GetCurrentRevisionId();
for (int i = 2; i < 6; i++)
{
properties.Put("tag", i);
properties.Put("_rev", revID);
doc.PutProperties(properties);
revID = doc.GetCurrentRevisionId();
Log.I(Tag, i + " revision: " + revID);
NUnit.Framework.Assert.IsTrue("revision is not correct:" + revID + ", should be with prefix "
+ i + "-", revID.StartsWith(i.ToString() + "-"));
NUnit.Framework.Assert.AreEqual("Doc Id is not correct ", docId, doc.GetId());
}
// now delete the doc and clear it from the cache so we
// make sure we are reading a fresh copy
doc.Delete();
database.ClearDocumentCache();
// get doc from db with same ID as before, and the current rev should be null since the
// last update was a deletion
Document docPostDelete = db.GetDocument(docId);
NUnit.Framework.Assert.IsNull(docPostDelete.GetCurrentRevision());
// save a new revision
properties = new Dictionary<string, object>();
properties.Put("tag", 6);
UnsavedRevision newRevision = docPostDelete.CreateRevision();
newRevision.SetProperties(properties);
SavedRevision newSavedRevision = newRevision.Save();
// make sure the current revision of doc matches the rev we just saved
NUnit.Framework.Assert.AreEqual(newSavedRevision, docPostDelete.GetCurrentRevision
());
// make sure the rev id is 7-
NUnit.Framework.Assert.IsTrue(docPostDelete.GetCurrentRevisionId().StartsWith("7-"
));
}
/// <exception cref="System.Exception"></exception>
public virtual void TestConflict()
{
IDictionary<string, object> prop = new Dictionary<string, object>();
prop.Put("foo", "bar");
Database db = StartDatabase();
Document doc = CreateDocumentWithProperties(db, prop);
SavedRevision rev1 = doc.GetCurrentRevision();
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.PutAll(doc.GetProperties());
properties.Put("tag", 2);
SavedRevision rev2a = doc.PutProperties(properties);
properties = new Dictionary<string, object>();
properties.PutAll(rev1.GetProperties());
properties.Put("tag", 3);
UnsavedRevision newRev = rev1.CreateRevision();
newRev.SetProperties(properties);
bool allowConflict = true;
SavedRevision rev2b = newRev.Save(allowConflict);
NUnit.Framework.Assert.IsNotNull("Failed to create a a conflict", rev2b);
IList<SavedRevision> confRevs = new AList<SavedRevision>();
confRevs.AddItem(rev2b);
confRevs.AddItem(rev2a);
NUnit.Framework.Assert.AreEqual(doc.GetConflictingRevisions(), confRevs);
NUnit.Framework.Assert.AreEqual(doc.GetLeafRevisions(), confRevs);
SavedRevision defaultRev;
SavedRevision otherRev;
if (Sharpen.Runtime.CompareOrdinal(rev2a.GetId(), rev2b.GetId()) > 0)
{
defaultRev = rev2a;
otherRev = rev2b;
}
else
{
defaultRev = rev2b;
otherRev = rev2a;
}
NUnit.Framework.Assert.AreEqual(doc.GetCurrentRevision(), defaultRev);
Query query = db.CreateAllDocumentsQuery();
query.SetAllDocsMode(Query.AllDocsMode.ShowConflicts);
QueryEnumerator rows = query.Run();
NUnit.Framework.Assert.AreEqual(rows.GetCount(), 1);
QueryRow row = rows.GetRow(0);
IList<SavedRevision> revs = row.GetConflictingRevisions();
NUnit.Framework.Assert.AreEqual(revs.Count, 2);
NUnit.Framework.Assert.AreEqual(revs[0], defaultRev);
NUnit.Framework.Assert.AreEqual(revs[1], otherRev);
}
//ATTACHMENTS
/// <exception cref="System.Exception"></exception>
/// <exception cref="System.IO.IOException"></exception>
public virtual void TestAttachments()
{
string attachmentName = "index.html";
string content = "This is a test attachment!";
Document doc = CreateDocWithAttachment(database, attachmentName, content);
UnsavedRevision newRev = doc.GetCurrentRevision().CreateRevision();
newRev.RemoveAttachment(attachmentName);
SavedRevision rev4 = newRev.Save();
NUnit.Framework.Assert.IsNotNull(rev4);
NUnit.Framework.Assert.AreEqual(0, rev4.GetAttachmentNames().Count);
}
/// <summary>https://github.com/couchbase/couchbase-lite-java-core/issues/132</summary>
/// <exception cref="System.Exception"></exception>
/// <exception cref="System.IO.IOException"></exception>
public virtual void TestUpdateDocWithAttachments()
{
string attachmentName = "index.html";
string content = "This is a test attachment!";
Document doc = CreateDocWithAttachment(database, attachmentName, content);
SavedRevision latestRevision = doc.GetCurrentRevision();
IDictionary<string, object> propertiesUpdated = new Dictionary<string, object>();
propertiesUpdated.Put("propertiesUpdated", "testUpdateDocWithAttachments");
UnsavedRevision newUnsavedRevision = latestRevision.CreateRevision();
newUnsavedRevision.SetUserProperties(propertiesUpdated);
SavedRevision newSavedRevision = newUnsavedRevision.Save();
NUnit.Framework.Assert.IsNotNull(newSavedRevision);
NUnit.Framework.Assert.AreEqual(1, newSavedRevision.GetAttachmentNames().Count);
Attachment fetched = doc.GetCurrentRevision().GetAttachment(attachmentName);
InputStream @is = fetched.GetContent();
byte[] attachmentBytes = TextUtils.Read(@is);
NUnit.Framework.Assert.AreEqual(content, Sharpen.Runtime.GetStringForBytes(attachmentBytes
));
NUnit.Framework.Assert.IsNotNull(fetched);
}
//CHANGE TRACKING
/// <exception cref="System.Exception"></exception>
public virtual void TestChangeTracking()
{
CountDownLatch doneSignal = new CountDownLatch(1);
Database db = StartDatabase();
db.AddChangeListener(new _ChangeListener_607(doneSignal));
CreateDocumentsAsync(db, 5);
// We expect that the changes reported by the server won't be notified, because those revisions
// are already cached in memory.
bool success = doneSignal.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(success);
NUnit.Framework.Assert.AreEqual(5, db.GetLastSequenceNumber());
}
private sealed class _ChangeListener_607 : Database.ChangeListener
{
public _ChangeListener_607(CountDownLatch doneSignal)
{
this.doneSignal = doneSignal;
}
public void Changed(Database.ChangeEvent @event)
{
doneSignal.CountDown();
}
private readonly CountDownLatch doneSignal;
}
//VIEWS
/// <exception cref="System.Exception"></exception>
public virtual void TestCreateView()
{
Database db = StartDatabase();
View view = db.GetView("vu");
NUnit.Framework.Assert.IsNotNull(view);
NUnit.Framework.Assert.AreEqual(db, view.GetDatabase());
NUnit.Framework.Assert.AreEqual("vu", view.GetName());
NUnit.Framework.Assert.IsNull(view.GetMap());
NUnit.Framework.Assert.IsNull(view.GetReduce());
view.SetMap(new _Mapper_635(), "1");
NUnit.Framework.Assert.IsNotNull(view.GetMap() != null);
int kNDocs = 50;
CreateDocuments(db, kNDocs);
Query query = view.CreateQuery();
NUnit.Framework.Assert.AreEqual(db, query.GetDatabase());
query.SetStartKey(23);
query.SetEndKey(33);
QueryEnumerator rows = query.Run();
NUnit.Framework.Assert.IsNotNull(rows);
NUnit.Framework.Assert.AreEqual(11, rows.GetCount());
int expectedKey = 23;
for (IEnumerator<QueryRow> it = rows; it.HasNext(); )
{
QueryRow row = it.Next();
NUnit.Framework.Assert.AreEqual(expectedKey, row.GetKey());
NUnit.Framework.Assert.AreEqual(expectedKey + 1, row.GetSequenceNumber());
++expectedKey;
}
}
private sealed class _Mapper_635 : Mapper
{
public _Mapper_635()
{
}
public void Map(IDictionary<string, object> document, Emitter emitter)
{
emitter.Emit(document.Get("sequence"), null);
}
}
//API_RunSlowView commented on IOS
/// <exception cref="System.Exception"></exception>
public virtual void TestValidation()
{
Database db = StartDatabase();
db.SetValidation("uncool", new _Validator_671());
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("groovy", "right on");
properties.Put("foo", "bar");
Document doc = db.CreateDocument();
NUnit.Framework.Assert.IsNotNull(doc.PutProperties(properties));
properties = new Dictionary<string, object>();
properties.Put("foo", "bar");
doc = db.CreateDocument();
try
{
NUnit.Framework.Assert.IsNull(doc.PutProperties(properties));
}
catch (CouchbaseLiteException e)
{
//TODO
NUnit.Framework.Assert.AreEqual(e.GetCBLStatus().GetCode(), Status.Forbidden);
}
}
private sealed class _Validator_671 : Validator
{
public _Validator_671()
{
}
public void Validate(Revision newRevision, ValidationContext context)
{
{
if (newRevision.GetProperty("groovy") == null)
{
context.Reject("uncool");
}
}
}
}
// assertEquals(e.getLocalizedMessage(), "forbidden: uncool"); //TODO: Not hooked up yet
/// <exception cref="System.Exception"></exception>
public virtual void TestViewWithLinkedDocs()
{
Database db = StartDatabase();
int kNDocs = 50;
Document[] docs = new Document[50];
string lastDocID = string.Empty;
for (int i = 0; i < kNDocs; i++)
{
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("sequence", i);
properties.Put("prev", lastDocID);
Document doc = CreateDocumentWithProperties(db, properties);
docs[i] = doc;
lastDocID = doc.GetId();
}
Query query = db.SlowQuery(new _Mapper_719());
query.SetStartKey(23);
query.SetEndKey(33);
query.SetPrefetch(true);
QueryEnumerator rows = query.Run();
NUnit.Framework.Assert.IsNotNull(rows);
NUnit.Framework.Assert.AreEqual(rows.GetCount(), 11);
int rowNumber = 23;
for (IEnumerator<QueryRow> it = rows; it.HasNext(); )
{
QueryRow row = it.Next();
NUnit.Framework.Assert.AreEqual(row.GetKey(), rowNumber);
Document prevDoc = docs[rowNumber];
NUnit.Framework.Assert.AreEqual(row.GetDocumentId(), prevDoc.GetId());
NUnit.Framework.Assert.AreEqual(row.GetDocument(), prevDoc);
++rowNumber;
}
}
private sealed class _Mapper_719 : Mapper
{
public _Mapper_719()
{
}
public void Map(IDictionary<string, object> document, Emitter emitter)
{
emitter.Emit(document.Get("sequence"), new object[] { "_id", document.Get("prev")
});
}
}
/// <exception cref="System.Exception"></exception>
public virtual void TestLiveQueryRun()
{
RunLiveQuery("run");
}
/// <exception cref="System.Exception"></exception>
public virtual void TestLiveQueryStart()
{
RunLiveQuery("start");
}
/// <exception cref="System.Exception"></exception>
public virtual void TestLiveQueryStartWaitForRows()
{
RunLiveQuery("startWaitForRows");
}
/// <summary>https://github.com/couchbase/couchbase-lite-java-core/issues/84</summary>
/// <exception cref="System.Exception"></exception>
public virtual void TestLiveQueryStop()
{
int kNDocs = 100;
CountDownLatch doneSignal = new CountDownLatch(1);
Database db = StartDatabase();
// run a live query
View view = db.GetView("vu");
view.SetMap(new _Mapper_774(), "1");
LiveQuery query = view.CreateQuery().ToLiveQuery();
AtomicInteger atomicInteger = new AtomicInteger(0);
// install a change listener which decrements countdown latch when it sees a new
// key from the list of expected keys
LiveQuery.ChangeListener changeListener = new _ChangeListener_786(atomicInteger,
kNDocs, doneSignal);
query.AddChangeListener(changeListener);
// create the docs that will cause the above change listener to decrement countdown latch
Log.D(Database.Tag, "testLiveQueryStop: createDocumentsAsync()");
CreateDocumentsAsync(db, kNDocs);
Log.D(Database.Tag, "testLiveQueryStop: calling query.start()");
query.Start();
// wait until the livequery is called back with kNDocs docs
Log.D(Database.Tag, "testLiveQueryStop: waiting for doneSignal");
bool success = doneSignal.Await(45, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(success);
Log.D(Database.Tag, "testLiveQueryStop: waiting for query.stop()");
query.Stop();
// after stopping the query, we should not get any more livequery callbacks, even
// if we add more docs to the database and pause (to give time for potential callbacks)
int numTimesCallbackCalled = atomicInteger.Get();
Log.D(Database.Tag, "testLiveQueryStop: numTimesCallbackCalled is: " + numTimesCallbackCalled
+ ". Now adding docs");
for (int i = 0; i < 10; i++)
{
CreateDocuments(db, 1);
Log.D(Database.Tag, "testLiveQueryStop: add a document. atomicInteger.get(): " +
atomicInteger.Get());
NUnit.Framework.Assert.AreEqual(numTimesCallbackCalled, atomicInteger.Get());
Sharpen.Thread.Sleep(200);
}
NUnit.Framework.Assert.AreEqual(numTimesCallbackCalled, atomicInteger.Get());
}
private sealed class _Mapper_774 : Mapper
{
public _Mapper_774()
{
}
public void Map(IDictionary<string, object> document, Emitter emitter)
{
emitter.Emit(document.Get("sequence"), null);
}
}
private sealed class _ChangeListener_786 : LiveQuery.ChangeListener
{
public _ChangeListener_786(AtomicInteger atomicInteger, int kNDocs, CountDownLatch
doneSignal)
{
this.atomicInteger = atomicInteger;
this.kNDocs = kNDocs;
this.doneSignal = doneSignal;
}
public void Changed(LiveQuery.ChangeEvent @event)
{
Log.D(LiteTestCase.Tag, "changed called, atomicInteger.incrementAndGet");
atomicInteger.IncrementAndGet();
NUnit.Framework.Assert.IsNull(@event.GetError());
if (@event.GetRows().GetCount() == kNDocs)
{
doneSignal.CountDown();
}
}
private readonly AtomicInteger atomicInteger;
private readonly int kNDocs;
private readonly CountDownLatch doneSignal;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestLiveQueryRestart()
{
}
// kick something off that will s
/// <exception cref="System.Exception"></exception>
public virtual void RunLiveQuery(string methodNameToCall)
{
Database db = StartDatabase();
CountDownLatch doneSignal = new CountDownLatch(11);
// 11 corresponds to startKey=23; endKey=33
// run a live query
View view = db.GetView("vu");
view.SetMap(new _Mapper_845(), "1");
LiveQuery query = view.CreateQuery().ToLiveQuery();
query.SetStartKey(23);
query.SetEndKey(33);
Log.I(Tag, "Created " + query);
// these are the keys that we expect to see in the livequery change listener callback
ICollection<int> expectedKeys = new HashSet<int>();
for (int i = 23; i < 34; i++)
{
expectedKeys.AddItem(i);
}
// install a change listener which decrements countdown latch when it sees a new
// key from the list of expected keys
LiveQuery.ChangeListener changeListener = new _ChangeListener_864(expectedKeys, doneSignal
);
query.AddChangeListener(changeListener);
// create the docs that will cause the above change listener to decrement countdown latch
int kNDocs = 50;
CreateDocumentsAsync(db, kNDocs);
if (methodNameToCall.Equals("start"))
{
// start the livequery running asynchronously
query.Start();
}
else
{
if (methodNameToCall.Equals("startWaitForRows"))
{
query.Start();
query.WaitForRows();
}
else
{
NUnit.Framework.Assert.IsNull(query.GetRows());
query.Run();
// this will block until the query completes
NUnit.Framework.Assert.IsNotNull(query.GetRows());
}
}
// wait for the doneSignal to be finished
bool success = doneSignal.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue("Done signal timed out, live query never ran", success
);
// stop the livequery since we are done with it
query.RemoveChangeListener(changeListener);
query.Stop();
}
private sealed class _Mapper_845 : Mapper
{
public _Mapper_845()
{
}
public void Map(IDictionary<string, object> document, Emitter emitter)
{
emitter.Emit(document.Get("sequence"), null);
}
}
private sealed class _ChangeListener_864 : LiveQuery.ChangeListener
{
public _ChangeListener_864(ICollection<int> expectedKeys, CountDownLatch doneSignal
)
{
this.expectedKeys = expectedKeys;
this.doneSignal = doneSignal;
}
public void Changed(LiveQuery.ChangeEvent @event)
{
QueryEnumerator rows = @event.GetRows();
for (IEnumerator<QueryRow> it = rows; it.HasNext(); )
{
QueryRow row = it.Next();
if (expectedKeys.Contains(row.GetKey()))
{
expectedKeys.Remove(row.GetKey());
doneSignal.CountDown();
}
}
}
private readonly ICollection<int> expectedKeys;
private readonly CountDownLatch doneSignal;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestAsyncViewQuery()
{
CountDownLatch doneSignal = new CountDownLatch(1);
Database db = StartDatabase();
View view = db.GetView("vu");
view.SetMap(new _Mapper_911(), "1");
int kNDocs = 50;
CreateDocuments(db, kNDocs);
Query query = view.CreateQuery();
query.SetStartKey(23);
query.SetEndKey(33);
query.RunAsync(new _QueryCompleteListener_925(db, doneSignal));
Log.I(Tag, "Waiting for async query to finish...");
bool success = doneSignal.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue("Done signal timed out, async query never ran", success
);
}
private sealed class _Mapper_911 : Mapper
{
public _Mapper_911()
{
}
public void Map(IDictionary<string, object> document, Emitter emitter)
{
emitter.Emit(document.Get("sequence"), null);
}
}
private sealed class _QueryCompleteListener_925 : Query.QueryCompleteListener
{
public _QueryCompleteListener_925(Database db, CountDownLatch doneSignal)
{
this.db = db;
this.doneSignal = doneSignal;
}
public void Completed(QueryEnumerator rows, Exception error)
{
Log.I(LiteTestCase.Tag, "Async query finished!");
NUnit.Framework.Assert.IsNotNull(rows);
NUnit.Framework.Assert.IsNull(error);
NUnit.Framework.Assert.AreEqual(rows.GetCount(), 11);
int expectedKey = 23;
for (IEnumerator<QueryRow> it = rows; it.HasNext(); )
{
QueryRow row = it.Next();
NUnit.Framework.Assert.AreEqual(row.GetDocument().GetDatabase(), db);
NUnit.Framework.Assert.AreEqual(row.GetKey(), expectedKey);
++expectedKey;
}
doneSignal.CountDown();
}
private readonly Database db;
private readonly CountDownLatch doneSignal;
}
/// <summary>
/// Make sure that a database's map/reduce functions are shared with the shadow database instance
/// running in the background server.
/// </summary>
/// <remarks>
/// Make sure that a database's map/reduce functions are shared with the shadow database instance
/// running in the background server.
/// </remarks>
/// <exception cref="System.Exception"></exception>
public virtual void TestSharedMapBlocks()
{
Manager mgr = new Manager(new LiteTestContext("API_SharedMapBlocks"), Manager.DefaultOptions
);
Database db = mgr.GetDatabase("db");
db.Open();
db.SetFilter("phil", new _ReplicationFilter_959());
db.SetValidation("val", new _Validator_966());
View view = db.GetView("view");
bool ok = view.SetMapReduce(new _Mapper_973(), new _Reducer_978(), "1");
NUnit.Framework.Assert.IsNotNull("Couldn't set map/reduce", ok);
Mapper map = view.GetMap();
Reducer reduce = view.GetReduce();
ReplicationFilter filter = db.GetFilter("phil");
Validator validation = db.GetValidation("val");
Future result = mgr.RunAsync("db", new _AsyncTask_993(filter, validation, map, reduce
));
result.Get();
// blocks until async task has run
db.Close();
mgr.Close();
}
private sealed class _ReplicationFilter_959 : ReplicationFilter
{
public _ReplicationFilter_959()
{
}
public bool Filter(SavedRevision revision, IDictionary<string, object> @params)
{
return true;
}
}
private sealed class _Validator_966 : Validator
{
public _Validator_966()
{
}
public void Validate(Revision newRevision, ValidationContext context)
{
}
}
private sealed class _Mapper_973 : Mapper
{
public _Mapper_973()
{
}
public void Map(IDictionary<string, object> document, Emitter emitter)
{
}
}
private sealed class _Reducer_978 : Reducer
{
public _Reducer_978()
{
}
public object Reduce(IList<object> keys, IList<object> values, bool rereduce)
{
return null;
}
}
private sealed class _AsyncTask_993 : AsyncTask
{
public _AsyncTask_993(ReplicationFilter filter, Validator validation, Mapper map,
Reducer reduce)
{
this.filter = filter;
this.validation = validation;
this.map = map;
this.reduce = reduce;
}
public void Run(Database database)
{
NUnit.Framework.Assert.IsNotNull(database);
View serverView = database.GetExistingView("view");
NUnit.Framework.Assert.IsNotNull(serverView);
NUnit.Framework.Assert.AreEqual(database.GetFilter("phil"), filter);
NUnit.Framework.Assert.AreEqual(database.GetValidation("val"), validation);
NUnit.Framework.Assert.AreEqual(serverView.GetMap(), map);
NUnit.Framework.Assert.AreEqual(serverView.GetReduce(), reduce);
}
private readonly ReplicationFilter filter;
private readonly Validator validation;
private readonly Mapper map;
private readonly Reducer reduce;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestChangeUUID()
{
Manager mgr = new Manager(new LiteTestContext("ChangeUUID"), Manager.DefaultOptions
);
Database db = mgr.GetDatabase("db");
db.Open();
string pub = db.PublicUUID();
string priv = db.PrivateUUID();
NUnit.Framework.Assert.IsTrue(pub.Length > 10);
NUnit.Framework.Assert.IsTrue(priv.Length > 10);
NUnit.Framework.Assert.IsTrue("replaceUUIDs failed", db.ReplaceUUIDs());
NUnit.Framework.Assert.IsFalse(pub.Equals(db.PublicUUID()));
NUnit.Framework.Assert.IsFalse(priv.Equals(db.PrivateUUID()));
mgr.Close();
}
/// <summary>https://github.com/couchbase/couchbase-lite-android/issues/220</summary>
/// <exception cref="System.Exception"></exception>
public virtual void TestMultiDocumentUpdate()
{
int numberOfDocuments = 10;
int numberOfUpdates = 10;
Document[] docs = new Document[numberOfDocuments];
for (int j = 0; j < numberOfDocuments; j++)
{
IDictionary<string, object> prop = new Dictionary<string, object>();
prop.Put("foo", "bar");
prop.Put("toogle", true);
Document document = CreateDocumentWithProperties(database, prop);
docs[j] = document;
}
AtomicInteger numDocsUpdated = new AtomicInteger(0);
AtomicInteger numExceptions = new AtomicInteger(0);
for (int j_1 = 0; j_1 < numberOfDocuments; j_1++)
{
Document doc = docs[j_1];
for (int k = 0; k < numberOfUpdates; k++)
{
IDictionary<string, object> contents = new Hashtable(doc.GetProperties());
bool wasChecked = (bool)contents.Get("toogle");
//toggle value of check property
contents.Put("toogle", !wasChecked);
try
{
doc.PutProperties(contents);
numDocsUpdated.IncrementAndGet();
}
catch (CouchbaseLiteException cblex)
{
Log.E(Tag, "Document update failed", cblex);
numExceptions.IncrementAndGet();
}
}
}
NUnit.Framework.Assert.AreEqual(numberOfDocuments * numberOfUpdates, numDocsUpdated
.Get());
NUnit.Framework.Assert.AreEqual(0, numExceptions.Get());
}
/// <summary>https://github.com/couchbase/couchbase-lite-android/issues/220</summary>
/// <exception cref="System.Exception"></exception>
public virtual void FailingTestMultiDocumentUpdateInTransaction()
{
int numberOfDocuments = 10;
int numberOfUpdates = 10;
Document[] docs = new Document[numberOfDocuments];
database.RunInTransaction(new _TransactionalTask_1086(this, numberOfDocuments, docs
));
AtomicInteger numDocsUpdated = new AtomicInteger(0);
AtomicInteger numExceptions = new AtomicInteger(0);
database.RunInTransaction(new _TransactionalTask_1104(this, numberOfDocuments, docs
, numberOfUpdates, numDocsUpdated, numExceptions));
//toggle value of check property
NUnit.Framework.Assert.AreEqual(numberOfDocuments * numberOfUpdates, numDocsUpdated
.Get());
NUnit.Framework.Assert.AreEqual(0, numExceptions.Get());
}
private sealed class _TransactionalTask_1086 : TransactionalTask
{
public _TransactionalTask_1086(ApiTest _enclosing, int numberOfDocuments, Document
[] docs)
{
this._enclosing = _enclosing;
this.numberOfDocuments = numberOfDocuments;
this.docs = docs;
}
public bool Run()
{
for (int j = 0; j < numberOfDocuments; j++)
{
IDictionary<string, object> prop = new Dictionary<string, object>();
prop.Put("foo", "bar");
prop.Put("toogle", true);
Document document = LiteTestCase.CreateDocumentWithProperties(this._enclosing.database
, prop);
docs[j] = document;
}
return true;
}
private readonly ApiTest _enclosing;
private readonly int numberOfDocuments;
private readonly Document[] docs;
}
private sealed class _TransactionalTask_1104 : TransactionalTask
{
public _TransactionalTask_1104(ApiTest _enclosing, int numberOfDocuments, Document
[] docs, int numberOfUpdates, AtomicInteger numDocsUpdated, AtomicInteger numExceptions
)
{
this._enclosing = _enclosing;
this.numberOfDocuments = numberOfDocuments;
this.docs = docs;
this.numberOfUpdates = numberOfUpdates;
this.numDocsUpdated = numDocsUpdated;
this.numExceptions = numExceptions;
}
public bool Run()
{
for (int j = 0; j < numberOfDocuments; j++)
{
Document doc = docs[j];
SavedRevision lastSavedRevision = null;
for (int k = 0; k < numberOfUpdates; k++)
{
if (lastSavedRevision != null)
{
NUnit.Framework.Assert.AreEqual(lastSavedRevision.GetId(), doc.GetCurrentRevisionId
());
}
IDictionary<string, object> contents = new Hashtable(doc.GetProperties());
Document docLatest = this._enclosing.database.GetDocument(doc.GetId());
bool wasChecked = (bool)contents.Get("toogle");
contents.Put("toogle", !wasChecked);
try
{
lastSavedRevision = doc.PutProperties(contents);
numDocsUpdated.IncrementAndGet();
}
catch (CouchbaseLiteException cblex)
{
Log.E(LiteTestCase.Tag, "Document update failed", cblex);
numExceptions.IncrementAndGet();
}
}
}
return true;
}
private readonly ApiTest _enclosing;
private readonly int numberOfDocuments;
private readonly Document[] docs;
private readonly int numberOfUpdates;
private readonly AtomicInteger numDocsUpdated;
private readonly AtomicInteger numExceptions;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftLeftLogicalInt641()
{
var test = new ImmUnaryOpTest__ShiftLeftLogicalInt641();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 ImmUnaryOpTest__ShiftLeftLogicalInt641
{
private struct TestStruct
{
public Vector256<Int64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalInt641 testClass)
{
var result = Avx2.ShiftLeftLogical(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static Int64[] _data = new Int64[Op1ElementCount];
private static Vector256<Int64> _clsVar;
private Vector256<Int64> _fld;
private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable;
static ImmUnaryOpTest__ShiftLeftLogicalInt641()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
}
public ImmUnaryOpTest__ShiftLeftLogicalInt641()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftLeftLogical(
Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftLeftLogical(
Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftLeftLogical(
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftLeftLogical(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftLeftLogicalInt641();
var result = Avx2.ShiftLeftLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftLeftLogical(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftLeftLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(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(Vector256<Int64> firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((long)(firstOp[0] << 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((long)(firstOp[i] << 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical)}<Int64>(Vector256<Int64><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public partial class NetworkClient : ServiceClient<NetworkClient>, INetworkClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The subscription credentials which uniquely identify the Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IApplicationGatewaysOperations.
/// </summary>
public virtual IApplicationGatewaysOperations ApplicationGateways { get; private set; }
/// <summary>
/// Gets the IExpressRouteCircuitAuthorizationsOperations.
/// </summary>
public virtual IExpressRouteCircuitAuthorizationsOperations ExpressRouteCircuitAuthorizations { get; private set; }
/// <summary>
/// Gets the IExpressRouteCircuitPeeringsOperations.
/// </summary>
public virtual IExpressRouteCircuitPeeringsOperations ExpressRouteCircuitPeerings { get; private set; }
/// <summary>
/// Gets the IExpressRouteCircuitsOperations.
/// </summary>
public virtual IExpressRouteCircuitsOperations ExpressRouteCircuits { get; private set; }
/// <summary>
/// Gets the IExpressRouteServiceProvidersOperations.
/// </summary>
public virtual IExpressRouteServiceProvidersOperations ExpressRouteServiceProviders { get; private set; }
/// <summary>
/// Gets the ILoadBalancersOperations.
/// </summary>
public virtual ILoadBalancersOperations LoadBalancers { get; private set; }
/// <summary>
/// Gets the INetworkInterfacesOperations.
/// </summary>
public virtual INetworkInterfacesOperations NetworkInterfaces { get; private set; }
/// <summary>
/// Gets the INetworkSecurityGroupsOperations.
/// </summary>
public virtual INetworkSecurityGroupsOperations NetworkSecurityGroups { get; private set; }
/// <summary>
/// Gets the ISecurityRulesOperations.
/// </summary>
public virtual ISecurityRulesOperations SecurityRules { get; private set; }
/// <summary>
/// Gets the INetworkWatchersOperations.
/// </summary>
public virtual INetworkWatchersOperations NetworkWatchers { get; private set; }
/// <summary>
/// Gets the IPacketCapturesOperations.
/// </summary>
public virtual IPacketCapturesOperations PacketCaptures { get; private set; }
/// <summary>
/// Gets the IPublicIPAddressesOperations.
/// </summary>
public virtual IPublicIPAddressesOperations PublicIPAddresses { get; private set; }
/// <summary>
/// Gets the IRouteFiltersOperations.
/// </summary>
public virtual IRouteFiltersOperations RouteFilters { get; private set; }
/// <summary>
/// Gets the IRouteFilterRulesOperations.
/// </summary>
public virtual IRouteFilterRulesOperations RouteFilterRules { get; private set; }
/// <summary>
/// Gets the IRouteTablesOperations.
/// </summary>
public virtual IRouteTablesOperations RouteTables { get; private set; }
/// <summary>
/// Gets the IRoutesOperations.
/// </summary>
public virtual IRoutesOperations Routes { get; private set; }
/// <summary>
/// Gets the IBgpServiceCommunitiesOperations.
/// </summary>
public virtual IBgpServiceCommunitiesOperations BgpServiceCommunities { get; private set; }
/// <summary>
/// Gets the IUsagesOperations.
/// </summary>
public virtual IUsagesOperations Usages { get; private set; }
/// <summary>
/// Gets the IVirtualNetworksOperations.
/// </summary>
public virtual IVirtualNetworksOperations VirtualNetworks { get; private set; }
/// <summary>
/// Gets the ISubnetsOperations.
/// </summary>
public virtual ISubnetsOperations Subnets { get; private set; }
/// <summary>
/// Gets the IVirtualNetworkPeeringsOperations.
/// </summary>
public virtual IVirtualNetworkPeeringsOperations VirtualNetworkPeerings { get; private set; }
/// <summary>
/// Gets the IVirtualNetworkGatewaysOperations.
/// </summary>
public virtual IVirtualNetworkGatewaysOperations VirtualNetworkGateways { get; private set; }
/// <summary>
/// Gets the IVirtualNetworkGatewayConnectionsOperations.
/// </summary>
public virtual IVirtualNetworkGatewayConnectionsOperations VirtualNetworkGatewayConnections { get; private set; }
/// <summary>
/// Gets the ILocalNetworkGatewaysOperations.
/// </summary>
public virtual ILocalNetworkGatewaysOperations LocalNetworkGateways { get; private set; }
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected NetworkClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected NetworkClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected NetworkClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected NetworkClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public NetworkClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public NetworkClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public NetworkClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the NetworkClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public NetworkClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
ApplicationGateways = new ApplicationGatewaysOperations(this);
ExpressRouteCircuitAuthorizations = new ExpressRouteCircuitAuthorizationsOperations(this);
ExpressRouteCircuitPeerings = new ExpressRouteCircuitPeeringsOperations(this);
ExpressRouteCircuits = new ExpressRouteCircuitsOperations(this);
ExpressRouteServiceProviders = new ExpressRouteServiceProvidersOperations(this);
LoadBalancers = new LoadBalancersOperations(this);
NetworkInterfaces = new NetworkInterfacesOperations(this);
NetworkSecurityGroups = new NetworkSecurityGroupsOperations(this);
SecurityRules = new SecurityRulesOperations(this);
NetworkWatchers = new NetworkWatchersOperations(this);
PacketCaptures = new PacketCapturesOperations(this);
PublicIPAddresses = new PublicIPAddressesOperations(this);
RouteFilters = new RouteFiltersOperations(this);
RouteFilterRules = new RouteFilterRulesOperations(this);
RouteTables = new RouteTablesOperations(this);
Routes = new RoutesOperations(this);
BgpServiceCommunities = new BgpServiceCommunitiesOperations(this);
Usages = new UsagesOperations(this);
VirtualNetworks = new VirtualNetworksOperations(this);
Subnets = new SubnetsOperations(this);
VirtualNetworkPeerings = new VirtualNetworkPeeringsOperations(this);
VirtualNetworkGateways = new VirtualNetworkGatewaysOperations(this);
VirtualNetworkGatewayConnections = new VirtualNetworkGatewayConnectionsOperations(this);
LocalNetworkGateways = new LocalNetworkGatewaysOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
/// <summary>
/// Checks whether a domain name in the cloudapp.net zone is available for use.
/// </summary>
/// <param name='location'>
/// The location of the domain name.
/// </param>
/// <param name='domainNameLabel'>
/// The domain name to be verified. It must conform to the following regular
/// expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DnsNameAvailabilityResult>> CheckDnsNameAvailabilityWithHttpMessagesAsync(string location, string domainNameLabel = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("domainNameLabel", domainNameLabel);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CheckDnsNameAvailability", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/CheckDnsNameAvailability").ToString();
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId));
List<string> _queryParameters = new List<string>();
if (domainNameLabel != null)
{
_queryParameters.Add(string.Format("domainNameLabel={0}", System.Uri.EscapeDataString(domainNameLabel)));
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DnsNameAvailabilityResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DnsNameAvailabilityResult>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="ColorAnimation.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Utility;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// Animates the value of a Color property using linear interpolation
/// between two values. The values are determined by the combination of
/// From, To, or By values that are set on the animation.
/// </summary>
public partial class ColorAnimation :
ColorAnimationBase
{
#region Data
/// <summary>
/// This is used if the user has specified From, To, and/or By values.
/// </summary>
private Color[] _keyValues;
private AnimationType _animationType;
private bool _isAnimationFunctionValid;
#endregion
#region Constructors
/// <summary>
/// Static ctor for ColorAnimation establishes
/// dependency properties, using as much shared data as possible.
/// </summary>
static ColorAnimation()
{
Type typeofProp = typeof(Color?);
Type typeofThis = typeof(ColorAnimation);
PropertyChangedCallback propCallback = new PropertyChangedCallback(AnimationFunction_Changed);
ValidateValueCallback validateCallback = new ValidateValueCallback(ValidateFromToOrByValue);
FromProperty = DependencyProperty.Register(
"From",
typeofProp,
typeofThis,
new PropertyMetadata((Color?)null, propCallback),
validateCallback);
ToProperty = DependencyProperty.Register(
"To",
typeofProp,
typeofThis,
new PropertyMetadata((Color?)null, propCallback),
validateCallback);
ByProperty = DependencyProperty.Register(
"By",
typeofProp,
typeofThis,
new PropertyMetadata((Color?)null, propCallback),
validateCallback);
EasingFunctionProperty = DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeofThis);
}
/// <summary>
/// Creates a new ColorAnimation with all properties set to
/// their default values.
/// </summary>
public ColorAnimation()
: base()
{
}
/// <summary>
/// Creates a new ColorAnimation that will animate a
/// Color property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public ColorAnimation(Color toValue, Duration duration)
: this()
{
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new ColorAnimation that will animate a
/// Color property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public ColorAnimation(Color toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
/// <summary>
/// Creates a new ColorAnimation that will animate a
/// Color property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public ColorAnimation(Color fromValue, Color toValue, Duration duration)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new ColorAnimation that will animate a
/// Color property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public ColorAnimation(Color fromValue, Color toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this ColorAnimation
/// </summary>
/// <returns>The copy</returns>
public new ColorAnimation Clone()
{
return (ColorAnimation)base.Clone();
}
//
// Note that we don't override the Clone virtuals (CloneCore, CloneCurrentValueCore,
// GetAsFrozenCore, and GetCurrentValueAsFrozenCore) even though this class has state
// not stored in a DP.
//
// We don't need to clone _animationType and _keyValues because they are the the cached
// results of animation function validation, which can be recomputed. The other remaining
// field, isAnimationFunctionValid, defaults to false, which causes this recomputation to happen.
//
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new ColorAnimation();
}
#endregion
#region Methods
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected override Color GetCurrentValueCore(Color defaultOriginValue, Color defaultDestinationValue, AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (!_isAnimationFunctionValid)
{
ValidateAnimationFunction();
}
double progress = animationClock.CurrentProgress.Value;
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
progress = easingFunction.Ease(progress);
}
Color from = new Color();
Color to = new Color();
Color accumulated = new Color();
Color foundation = new Color();
// need to validate the default origin and destination values if
// the animation uses them as the from, to, or foundation values
bool validateOrigin = false;
bool validateDestination = false;
switch(_animationType)
{
case AnimationType.Automatic:
from = defaultOriginValue;
to = defaultDestinationValue;
validateOrigin = true;
validateDestination = true;
break;
case AnimationType.From:
from = _keyValues[0];
to = defaultDestinationValue;
validateDestination = true;
break;
case AnimationType.To:
from = defaultOriginValue;
to = _keyValues[0];
validateOrigin = true;
break;
case AnimationType.By:
// According to the SMIL specification, a By animation is
// always additive. But we don't force this so that a
// user can re-use a By animation and have it replace the
// animations that precede it in the list without having
// to manually set the From value to the base value.
to = _keyValues[0];
foundation = defaultOriginValue;
validateOrigin = true;
break;
case AnimationType.FromTo:
from = _keyValues[0];
to = _keyValues[1];
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
case AnimationType.FromBy:
from = _keyValues[0];
to = AnimatedTypeHelpers.AddColor(_keyValues[0], _keyValues[1]);
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
default:
Debug.Fail("Unknown animation type.");
break;
}
if (validateOrigin
&& !AnimatedTypeHelpers.IsValidAnimationValueColor(defaultOriginValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"origin",
defaultOriginValue.ToString(CultureInfo.InvariantCulture)));
}
if (validateDestination
&& !AnimatedTypeHelpers.IsValidAnimationValueColor(defaultDestinationValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"destination",
defaultDestinationValue.ToString(CultureInfo.InvariantCulture)));
}
if (IsCumulative)
{
double currentRepeat = (double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
Color accumulator = AnimatedTypeHelpers.SubtractColor(to, from);
accumulated = AnimatedTypeHelpers.ScaleColor(accumulator, currentRepeat);
}
}
// return foundation + accumulated + from + ((to - from) * progress)
return AnimatedTypeHelpers.AddColor(
foundation,
AnimatedTypeHelpers.AddColor(
accumulated,
AnimatedTypeHelpers.InterpolateColor(from, to, progress)));
}
private void ValidateAnimationFunction()
{
_animationType = AnimationType.Automatic;
_keyValues = null;
if (From.HasValue)
{
if (To.HasValue)
{
_animationType = AnimationType.FromTo;
_keyValues = new Color[2];
_keyValues[0] = From.Value;
_keyValues[1] = To.Value;
}
else if (By.HasValue)
{
_animationType = AnimationType.FromBy;
_keyValues = new Color[2];
_keyValues[0] = From.Value;
_keyValues[1] = By.Value;
}
else
{
_animationType = AnimationType.From;
_keyValues = new Color[1];
_keyValues[0] = From.Value;
}
}
else if (To.HasValue)
{
_animationType = AnimationType.To;
_keyValues = new Color[1];
_keyValues[0] = To.Value;
}
else if (By.HasValue)
{
_animationType = AnimationType.By;
_keyValues = new Color[1];
_keyValues[0] = By.Value;
}
_isAnimationFunctionValid = true;
}
#endregion
#region Properties
private static void AnimationFunction_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ColorAnimation a = (ColorAnimation)d;
a._isAnimationFunctionValid = false;
a.PropertyChanged(e.Property);
}
private static bool ValidateFromToOrByValue(object value)
{
Color? typedValue = (Color?)value;
if (typedValue.HasValue)
{
return AnimatedTypeHelpers.IsValidAnimationValueColor(typedValue.Value);
}
else
{
return true;
}
}
/// <summary>
/// FromProperty
/// </summary>
public static readonly DependencyProperty FromProperty;
/// <summary>
/// From
/// </summary>
public Color? From
{
get
{
return (Color?)GetValue(FromProperty);
}
set
{
SetValueInternal(FromProperty, value);
}
}
/// <summary>
/// ToProperty
/// </summary>
public static readonly DependencyProperty ToProperty;
/// <summary>
/// To
/// </summary>
public Color? To
{
get
{
return (Color?)GetValue(ToProperty);
}
set
{
SetValueInternal(ToProperty, value);
}
}
/// <summary>
/// ByProperty
/// </summary>
public static readonly DependencyProperty ByProperty;
/// <summary>
/// By
/// </summary>
public Color? By
{
get
{
return (Color?)GetValue(ByProperty);
}
set
{
SetValueInternal(ByProperty, value);
}
}
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty;
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
/// <summary>
/// If this property is set to true the animation will add its value to
/// the base value instead of replacing it entirely.
/// </summary>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// It this property is set to true, the animation will accumulate its
/// value over repeats. For instance if you have a From value of 0.0 and
/// a To value of 1.0, the animation return values from 1.0 to 2.0 over
/// the second reteat cycle, and 2.0 to 3.0 over the third, etc.
/// </summary>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#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 BetMania.Services.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;
}
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
namespace ZXing.OneD
{
/// <summary>
/// <p>Decodes Codabar barcodes.</p>
///
/// <author>Bas Vijfwinkel</author>
/// </summary>
internal sealed class CodaBarReader : OneDReader
{
// These values are critical for determining how permissive the decoding
// will be. All stripe sizes must be within the window these define, as
// compared to the average stripe size.
private static readonly int MAX_ACCEPTABLE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 2.0f);
private static readonly int PADDING = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 1.5f);
private const String ALPHABET_STRING = "0123456789-$:/.+ABCD";
internal static readonly char[] ALPHABET = ALPHABET_STRING.ToCharArray();
/**
* These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of
* each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow.
*/
internal static int[] CHARACTER_ENCODINGS = {
0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9
0x00c, 0x018, 0x045, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD
};
// minimal number of characters that should be present (inclusing start and stop characters)
// under normal circumstances this should be set to 3, but can be set higher
// as a last-ditch attempt to reduce false positives.
private const int MIN_CHARACTER_LENGTH = 3;
// official start and end patterns
private static readonly char[] STARTEND_ENCODING = { 'A', 'B', 'C', 'D' };
// some codabar generator allow the codabar string to be closed by every
// character. This will cause lots of false positives!
// some industries use a checksum standard but this is not part of the original codabar standard
// for more information see : http://www.mecsw.com/specs/codabar.html
// Keep some instance variables to avoid reallocations
private readonly StringBuilder decodeRowResult;
private int[] counters;
private int counterLength;
public CodaBarReader()
{
decodeRowResult = new StringBuilder(20);
counters = new int[80];
counterLength = 0;
}
public override Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints)
{
for (var index = 0; index < counters.Length; index++)
counters[index] = 0;
if (!setCounters(row))
return null;
int startOffset = findStartPattern();
if (startOffset < 0)
return null;
int nextStart = startOffset;
decodeRowResult.Length = 0;
do
{
int charOffset = toNarrowWidePattern(nextStart);
if (charOffset == -1)
{
return null;
}
// Hack: We store the position in the alphabet table into a
// StringBuilder, so that we can access the decoded patterns in
// validatePattern. We'll translate to the actual characters later.
decodeRowResult.Append((char) charOffset);
nextStart += 8;
// Stop as soon as we see the end character.
if (decodeRowResult.Length > 1 &&
arrayContains(STARTEND_ENCODING, ALPHABET[charOffset]))
{
break;
}
} while (nextStart < counterLength); // no fixed end pattern so keep on reading while data is available
// Look for whitespace after pattern:
int trailingWhitespace = counters[nextStart - 1];
int lastPatternSize = 0;
for (int i = -8; i < -1; i++)
{
lastPatternSize += counters[nextStart + i];
}
// We need to see whitespace equal to 50% of the last pattern size,
// otherwise this is probably a false positive. The exception is if we are
// at the end of the row. (I.e. the barcode barely fits.)
if (nextStart < counterLength && trailingWhitespace < lastPatternSize/2)
{
return null;
}
if (!validatePattern(startOffset))
return null;
// Translate character table offsets to actual characters.
for (int i = 0; i < decodeRowResult.Length; i++)
{
decodeRowResult[i] = ALPHABET[decodeRowResult[i]];
}
// Ensure a valid start and end character
char startchar = decodeRowResult[0];
if (!arrayContains(STARTEND_ENCODING, startchar))
{
return null;
}
char endchar = decodeRowResult[decodeRowResult.Length - 1];
if (!arrayContains(STARTEND_ENCODING, endchar))
{
return null;
}
// remove stop/start characters character and check if a long enough string is contained
if (decodeRowResult.Length <= MIN_CHARACTER_LENGTH)
{
// Almost surely a false positive ( start + stop + at least 1 character)
return null;
}
if (!SupportClass.GetValue(hints, DecodeHintType.RETURN_CODABAR_START_END, false))
{
decodeRowResult.Remove(decodeRowResult.Length - 1, 1);
decodeRowResult.Remove(0, 1);
}
int runningCount = 0;
for (int i = 0; i < startOffset; i++)
{
runningCount += counters[i];
}
float left = runningCount;
for (int i = startOffset; i < nextStart - 1; i++)
{
runningCount += counters[i];
}
float right = runningCount;
var resultPointCallback = SupportClass.GetValue(hints, DecodeHintType.NEED_RESULT_POINT_CALLBACK, (ResultPointCallback) null);
if (resultPointCallback != null)
{
resultPointCallback(new ResultPoint(left, rowNumber));
resultPointCallback(new ResultPoint(right, rowNumber));
}
return new Result(
decodeRowResult.ToString(),
null,
new[]
{
new ResultPoint(left, rowNumber),
new ResultPoint(right, rowNumber)
},
BarcodeFormat.CODABAR);
}
private bool validatePattern(int start)
{
// First, sum up the total size of our four categories of stripe sizes;
int[] sizes = { 0, 0, 0, 0 };
int[] counts = { 0, 0, 0, 0 };
int end = decodeRowResult.Length - 1;
// We break out of this loop in the middle, in order to handle
// inter-character spaces properly.
int pos = start;
for (int i = 0; true; i++)
{
int pattern = CHARACTER_ENCODINGS[decodeRowResult[i]];
for (int j = 6; j >= 0; j--)
{
// Even j = bars, while odd j = spaces. Categories 2 and 3 are for
// long stripes, while 0 and 1 are for short stripes.
int category = (j & 1) + (pattern & 1) * 2;
sizes[category] += counters[pos + j];
counts[category]++;
pattern >>= 1;
}
if (i >= end)
{
break;
}
// We ignore the inter-character space - it could be of any size.
pos += 8;
}
// Calculate our allowable size thresholds using fixed-point math.
int[] maxes = new int[4];
int[] mins = new int[4];
// Define the threshold of acceptability to be the midpoint between the
// average small stripe and the average large stripe. No stripe lengths
// should be on the "wrong" side of that line.
for (int i = 0; i < 2; i++)
{
mins[i] = 0; // Accept arbitrarily small "short" stripes.
mins[i + 2] = ((sizes[i] << INTEGER_MATH_SHIFT) / counts[i] +
(sizes[i + 2] << INTEGER_MATH_SHIFT) / counts[i + 2]) >> 1;
maxes[i] = mins[i + 2];
maxes[i + 2] = (sizes[i + 2] * MAX_ACCEPTABLE + PADDING) / counts[i + 2];
}
// Now verify that all of the stripes are within the thresholds.
pos = start;
for (int i = 0; true; i++)
{
int pattern = CHARACTER_ENCODINGS[decodeRowResult[i]];
for (int j = 6; j >= 0; j--)
{
// Even j = bars, while odd j = spaces. Categories 2 and 3 are for
// long stripes, while 0 and 1 are for short stripes.
int category = (j & 1) + (pattern & 1) * 2;
int size = counters[pos + j] << INTEGER_MATH_SHIFT;
if (size < mins[category] || size > maxes[category])
{
return false;
}
pattern >>= 1;
}
if (i >= end)
{
break;
}
pos += 8;
}
return true;
}
/// <summary>
/// Records the size of all runs of white and black pixels, starting with white.
/// This is just like recordPattern, except it records all the counters, and
/// uses our builtin "counters" member for storage.
/// </summary>
/// <param name="row">row to count from</param>
private bool setCounters(BitArray row)
{
counterLength = 0;
// Start from the first white bit.
int i = row.getNextUnset(0);
int end = row.Size;
if (i >= end)
{
return false;
}
bool isWhite = true;
int count = 0;
while (i < end)
{
if (row[i] ^ isWhite)
{
// that is, exactly one is true
count++;
}
else
{
counterAppend(count);
count = 1;
isWhite = !isWhite;
}
i++;
}
counterAppend(count);
return true;
}
private void counterAppend(int e)
{
counters[counterLength] = e;
counterLength++;
if (counterLength >= counters.Length)
{
int[] temp = new int[counterLength * 2];
Array.Copy(counters, 0, temp, 0, counterLength);
counters = temp;
}
}
private int findStartPattern()
{
for (int i = 1; i < counterLength; i += 2)
{
int charOffset = toNarrowWidePattern(i);
if (charOffset != -1 && arrayContains(STARTEND_ENCODING, ALPHABET[charOffset]))
{
// Look for whitespace before start pattern, >= 50% of width of start pattern
// We make an exception if the whitespace is the first element.
int patternSize = 0;
for (int j = i; j < i + 7; j++)
{
patternSize += counters[j];
}
if (i == 1 || counters[i - 1] >= patternSize / 2)
{
return i;
}
}
}
return -1;
}
internal static bool arrayContains(char[] array, char key)
{
if (array != null)
{
foreach (char c in array)
{
if (c == key)
{
return true;
}
}
}
return false;
}
// Assumes that counters[position] is a bar.
private int toNarrowWidePattern(int position)
{
int end = position + 7;
if (end >= counterLength)
{
return -1;
}
int[] theCounters = counters;
int maxBar = 0;
int minBar = Int32.MaxValue;
for (int j = position; j < end; j += 2)
{
int currentCounter = theCounters[j];
if (currentCounter < minBar)
{
minBar = currentCounter;
}
if (currentCounter > maxBar)
{
maxBar = currentCounter;
}
}
int thresholdBar = (minBar + maxBar) / 2;
int maxSpace = 0;
int minSpace = Int32.MaxValue;
for (int j = position + 1; j < end; j += 2)
{
int currentCounter = theCounters[j];
if (currentCounter < minSpace)
{
minSpace = currentCounter;
}
if (currentCounter > maxSpace)
{
maxSpace = currentCounter;
}
}
int thresholdSpace = (minSpace + maxSpace) / 2;
int bitmask = 1 << 7;
int pattern = 0;
for (int i = 0; i < 7; i++)
{
int threshold = (i & 1) == 0 ? thresholdBar : thresholdSpace;
bitmask >>= 1;
if (theCounters[position + i] > threshold)
{
pattern |= bitmask;
}
}
for (int i = 0; i < CHARACTER_ENCODINGS.Length; i++)
{
if (CHARACTER_ENCODINGS[i] == pattern)
{
return i;
}
}
return -1;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmResourcesInfo.
/// </summary>
public partial class frmProfProjectTypes: System.Web.UI.Page
{
/*SqlConnection epsDbConn=new SqlConnection("Server=cp2693-a\\eps1;database=eps1;"+
"uid=tauheed;pwd=tauheed;");*/
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
loadForm();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
}
#endregion
private void loadForm()
{
if (Session["CPPTypes"].ToString() == "frmProfiles")
{
lblContent1.Text="Select project types for profile '"
+ Session["ProfilesName"].ToString()
+ "'. You may identify project types not included in this list by clicking"
+ " on the 'Add Project Types' button.";
lblContent3.Text="Use the 'Remove' button to remove Project Types"
+ " from this list.";
btnAddAll.Visible=true;
DataGrid1.Columns[2].Visible=false;
DataGrid1.Columns[3].Visible=false;
DataGrid1.Columns[4].Visible=false;
DataGrid1.Columns[5].Visible=false;
}
else if (Session["CPPTypes"].ToString() == "frmMainStaff")
{
lblContent1.Text="Select the kind of task you wish to work with.";
lblContent3.Text="";
btnAddAll.Visible=false;
DataGrid1.Columns[2].Visible=true;
DataGrid1.Columns[3].Visible=false;
DataGrid1.Columns[4].Visible=false;
}
if (!IsPostBack)
{
loadData();
}
}
private void loadData()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="wms_RetrieveProfProjTypes";
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=Session["ProfilesId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"ST");
Session["ds"] = ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
}
protected void btnOK_Click(object sender, System.EventArgs e)
{
//updateGrid();
Exit();
}
/*private void updateGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox) (i.Cells[2].FindControl("cbxSel"));
if ((cb.Checked == true) & (cb.Enabled==true))
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_AddProjectTypesPSEP";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@ProjectTypesId", SqlDbType.Int);
cmd.Parameters ["@ProjectTypesId"].Value=i.Cells[0].Text;
cmd.Parameters.Add("@ProfilesId", SqlDbType.Int);
cmd.Parameters ["@ProfilesId"].Value=Session["ProfilesId"].ToString();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}*/
protected void btnAddAll_Click(object sender, System.EventArgs e)
{
Session["CProjectTypes"]="frmProfProjectTypes";
Response.Redirect (strURL + "frmProjectTypes.aspx?");
}
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == "Update")
{
Session["CUpdProjectTypes"]="frmProfProjectTypes";
Response.Redirect (strURL + "frmUpdProjectType.aspx?"
+ "&btnAction=" + "Update"
+ "&Id=" + e.Item.Cells[8].Text
+ "&Name=" + e.Item.Cells[1].Text
+ "&Nameshort=" + e.Item.Cells[2].Text
+ "&Seq=" + e.Item.Cells[3].Text
+ "&Vis=" + e.Item.Cells[4].Text
);
}
if (e.CommandName == "Procs")
{
Session["CPSEPPT"]="frmProfProjectTypes";
Session["ProjTypesId"]=e.Item.Cells[8].Text;
Session["Nameshort"]=e.Item.Cells[2].Text;
Response.Redirect (strURL + "frmPSEPProjectTypes.aspx?");
}
else if (e.CommandName == "Remove")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_DeleteProfProjectTypes";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value=Int32.Parse (e.Item.Cells[0].Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
}
private void Exit()
{
Response.Redirect (strURL + Session["CPPTypes"].ToString() + ".aspx?");
}
protected void btnCancel_Click(object sender, System.EventArgs e)
{
Exit();
}
/*private void refreshGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox)(i.Cells[2].FindControl("cbxSel"));
Button btu = (Button)(i.Cells[3].FindControl("btnUpdate"));
Button bt = (Button)(i.Cells[4].FindControl("btnDelete"));
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.Text;
cmd.CommandText="Select Id from ProfileProjectTypes"
+ " Where ProjectTypesId = " + i.Cells[0].Text
+ " and ProfilesId = " + Session["ProfilesId"].ToString();
cmd.Connection.Open();
if (cmd.ExecuteScalar() != null)
{
cb.Checked = true;
cb.Enabled = false;
bt.Visible=false;
i.Cells[4].Text = "In Use";
lblContent2.Text="Note that project types with check marks already"
+ " present (in shaded boxes) have already been identified for this profile.";
}
cmd.CommandText="Select OrgId from ProjectTypes"
+ " Where Id = " + i.Cells[0].Text;
//+ " and OrgId = " + Session["OrgId"].ToString();
if (cmd.ExecuteScalar().ToString() != Session["OrgId"].ToString())
{
bt.Visible=false;
btu.Visible=false;
i.Cells[4].Text = " Externally Created ";
}
if (bt.Visible)
{
lblContent3.Visible=true;
}
cmd.Connection.Close();
}
}*/
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
#if ES_BUILD_STANDALONE
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
namespace Microsoft.Diagnostics.Tracing.Internal
#else
namespace System.Diagnostics.Tracing.Internal
#endif
{
#if ES_BUILD_AGAINST_DOTNET_V35
using Microsoft.Internal;
#endif
using Microsoft.Reflection;
using System.Reflection;
internal static class Environment
{
public static readonly string NewLine = System.Environment.NewLine;
public static int TickCount
{ get { return System.Environment.TickCount; } }
public static string GetResourceString(string key, params object[] args)
{
string fmt = rm.GetString(key);
if (fmt != null)
return string.Format(fmt, args);
string sargs = string.Empty;
foreach(var arg in args)
{
if (sargs != string.Empty)
sargs += ", ";
sargs += arg.ToString();
}
return key + " (" + sargs + ")";
}
public static string GetRuntimeResourceString(string key, params object[] args)
{
return GetResourceString(key, args);
}
private static System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly());
}
#if ES_BUILD_STANDALONE
internal static class BitOperations
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint RotateLeft(uint value, int offset)
=> (value << offset) | (value >> (32 - offset));
public static int PopCount(uint value)
{
const uint c1 = 0x_55555555u;
const uint c2 = 0x_33333333u;
const uint c3 = 0x_0F0F0F0Fu;
const uint c4 = 0x_01010101u;
value = value - ((value >> 1) & c1);
value = (value & c2) + ((value >> 2) & c2);
value = (((value + (value >> 4)) & c3) * c4) >> 24;
return (int)value;
}
public static int TrailingZeroCount(uint value)
{
if (value == 0)
return 32;
int count = 0;
while ((value & 1) == 0)
{
value >>= 1;
count++;
}
return count;
}
}
#endif
}
#if ES_BUILD_AGAINST_DOTNET_V35
namespace Microsoft.Internal
{
using System.Text;
internal static class Tuple
{
public static Tuple<T1> Create<T1>(T1 item1)
{
return new Tuple<T1>(item1);
}
public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
{
return new Tuple<T1, T2>(item1, item2);
}
}
[Serializable]
internal class Tuple<T1>
{
private readonly T1 m_Item1;
public T1 Item1 { get { return m_Item1; } }
public Tuple(T1 item1)
{
m_Item1 = item1;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
sb.Append(m_Item1);
sb.Append(")");
return sb.ToString();
}
int Size
{
get
{
return 1;
}
}
}
[Serializable]
public class Tuple<T1, T2>
{
private readonly T1 m_Item1;
private readonly T2 m_Item2;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public Tuple(T1 item1, T2 item2)
{
m_Item1 = item1;
m_Item2 = item2;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(")");
return sb.ToString();
}
int Size
{
get
{
return 2;
}
}
}
}
#endif
namespace Microsoft.Reflection
{
using System.Reflection;
#if ES_BUILD_PCL
[Flags]
public enum BindingFlags
{
DeclaredOnly = 0x02, // Only look at the members declared on the Type
Instance = 0x04, // Include Instance members in search
Static = 0x08, // Include Static members in search
Public = 0x10, // Include Public members in search
NonPublic = 0x20, // Include Non-Public members in search
}
public enum TypeCode {
Empty = 0, // Null reference
Object = 1, // Instance that isn't a value
DBNull = 2, // Database null value
Boolean = 3, // Boolean
Char = 4, // Unicode character
SByte = 5, // Signed 8-bit integer
Byte = 6, // Unsigned 8-bit integer
Int16 = 7, // Signed 16-bit integer
UInt16 = 8, // Unsigned 16-bit integer
Int32 = 9, // Signed 32-bit integer
UInt32 = 10, // Unsigned 32-bit integer
Int64 = 11, // Signed 64-bit integer
UInt64 = 12, // Unsigned 64-bit integer
Single = 13, // IEEE 32-bit float
Double = 14, // IEEE 64-bit double
Decimal = 15, // Decimal
DateTime = 16, // DateTime
String = 18, // Unicode character string
}
#endif
static class ReflectionExtensions
{
#if (!ES_BUILD_PCL && !ES_BUILD_PN)
//
// Type extension methods
//
public static bool IsEnum(this Type type) { return type.IsEnum; }
public static bool IsAbstract(this Type type) { return type.IsAbstract; }
public static bool IsSealed(this Type type) { return type.IsSealed; }
public static bool IsValueType(this Type type) { return type.IsValueType; }
public static bool IsGenericType(this Type type) { return type.IsGenericType; }
public static Type BaseType(this Type type) { return type.BaseType; }
public static Assembly Assembly(this Type type) { return type.Assembly; }
public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); }
public static bool ReflectionOnly(this Assembly assm) { return assm.ReflectionOnly; }
#else // ES_BUILD_PCL
//
// Type extension methods
//
public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; }
public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; }
public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; }
public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; }
public static bool IsGenericType(this Type type) { return type.IsConstructedGenericType; }
public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; }
public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; }
public static IEnumerable<PropertyInfo> GetProperties(this Type type)
{
#if ES_BUILD_PN
return type.GetProperties();
#else
return type.GetRuntimeProperties();
#endif
}
public static MethodInfo GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; }
public static Type[] GetGenericArguments(this Type type) { return type.GenericTypeArguments; }
public static MethodInfo[] GetMethods(this Type type, BindingFlags flags)
{
// Minimal implementation to cover only the cases we need
System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0);
System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic)) == 0);
Func<MethodInfo, bool> visFilter;
Func<MethodInfo, bool> instFilter;
switch (flags & (BindingFlags.Public | BindingFlags.NonPublic))
{
case 0: visFilter = mi => false; break;
case BindingFlags.Public: visFilter = mi => mi.IsPublic; break;
case BindingFlags.NonPublic: visFilter = mi => !mi.IsPublic; break;
default: visFilter = mi => true; break;
}
switch (flags & (BindingFlags.Instance | BindingFlags.Static))
{
case 0: instFilter = mi => false; break;
case BindingFlags.Instance: instFilter = mi => !mi.IsStatic; break;
case BindingFlags.Static: instFilter = mi => mi.IsStatic; break;
default: instFilter = mi => true; break;
}
List<MethodInfo> methodInfos = new List<MethodInfo>();
foreach (var declaredMethod in type.GetTypeInfo().DeclaredMethods)
{
if (visFilter(declaredMethod) && instFilter(declaredMethod))
methodInfos.Add(declaredMethod);
}
return methodInfos.ToArray();
}
public static FieldInfo[] GetFields(this Type type, BindingFlags flags)
{
// Minimal implementation to cover only the cases we need
System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0);
System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) == 0);
Func<FieldInfo, bool> visFilter;
Func<FieldInfo, bool> instFilter;
switch (flags & (BindingFlags.Public | BindingFlags.NonPublic))
{
case 0: visFilter = fi => false; break;
case BindingFlags.Public: visFilter = fi => fi.IsPublic; break;
case BindingFlags.NonPublic: visFilter = fi => !fi.IsPublic; break;
default: visFilter = fi => true; break;
}
switch (flags & (BindingFlags.Instance | BindingFlags.Static))
{
case 0: instFilter = fi => false; break;
case BindingFlags.Instance: instFilter = fi => !fi.IsStatic; break;
case BindingFlags.Static: instFilter = fi => fi.IsStatic; break;
default: instFilter = fi => true; break;
}
List<FieldInfo> fieldInfos = new List<FieldInfo>();
foreach (var declaredField in type.GetTypeInfo().DeclaredFields)
{
if (visFilter(declaredField) && instFilter(declaredField))
fieldInfos.Add(declaredField);
}
return fieldInfos.ToArray();
}
public static Type GetNestedType(this Type type, string nestedTypeName)
{
TypeInfo ti = null;
foreach(var nt in type.GetTypeInfo().DeclaredNestedTypes)
{
if (nt.Name == nestedTypeName)
{
ti = nt;
break;
}
}
return ti == null ? null : ti.AsType();
}
public static TypeCode GetTypeCode(this Type type)
{
if (type == typeof(bool)) return TypeCode.Boolean;
else if (type == typeof(byte)) return TypeCode.Byte;
else if (type == typeof(char)) return TypeCode.Char;
else if (type == typeof(ushort)) return TypeCode.UInt16;
else if (type == typeof(uint)) return TypeCode.UInt32;
else if (type == typeof(ulong)) return TypeCode.UInt64;
else if (type == typeof(sbyte)) return TypeCode.SByte;
else if (type == typeof(short)) return TypeCode.Int16;
else if (type == typeof(int)) return TypeCode.Int32;
else if (type == typeof(long)) return TypeCode.Int64;
else if (type == typeof(string)) return TypeCode.String;
else if (type == typeof(float)) return TypeCode.Single;
else if (type == typeof(double)) return TypeCode.Double;
else if (type == typeof(DateTime)) return TypeCode.DateTime;
else if (type == (typeof(decimal))) return TypeCode.Decimal;
else return TypeCode.Object;
}
//
// FieldInfo extension methods
//
public static object GetRawConstantValue(this FieldInfo fi)
{ return fi.GetValue(null); }
//
// Assembly extension methods
//
public static bool ReflectionOnly(this Assembly assm)
{
// In PCL we can't load in reflection-only context
return false;
}
#endif
}
}
#if ES_BUILD_STANDALONE
internal static partial class Interop
{
[SuppressUnmanagedCodeSecurityAttribute()]
internal static partial class Kernel32
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
internal static extern int GetCurrentThreadId();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
internal static extern uint GetCurrentProcessId();
}
internal static uint GetCurrentProcessId() => Kernel32.GetCurrentProcessId();
}
#endif
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.Live;
using Microsoft.Live.Web.Samples.AuthWithMSAccount.Models;
namespace Microsoft.Live.Web.Samples.AuthWithMSAccount.Controllers
{
public class AccountController : Controller
{
[Flags]
private enum AccountDataContent
{
Basic = 1,
Contacts = 2,
}
private const string ClientId = "%YourAppClientId%"; // Your app client Id
private const int ClientSecretKey = 0; // Your app secret key (index)
private const string ClientSecret = "%YourAppSecret%"; // Your app secret
private const string ClientDomain = "%YourAppDomain%"; // Your app site domain, e.g. www.foo.com
private LiveAuthClient liveAuthClient;
//
// GET: /Home/
public async Task<ActionResult> Index()
{
if (ClientId.Contains('%') || ClientSecret.Contains('%') || ClientDomain.Contains('%'))
{
throw new ArgumentException("Update the ClientId, ClientSecret, and ClientDomain with your app client Id, client secret and domain values that you get from https://account.live.com/developers/applications.");
}
try
{
LiveLoginResult loginStatus = await this.AuthClient.InitializeWebSessionAsync(this.HttpContext, this.CurrentPath);
switch (loginStatus.Status)
{
case LiveConnectSessionStatus.Expired:
string reAuthUrl = this.GetLoginUrl(new string[] { "wl.signin" }, this.CurrentPath);
this.Response.Redirect(reAuthUrl);
return null;
case LiveConnectSessionStatus.Connected:
return await GetAccountDataView(AccountDataContent.Basic);
}
}
catch (LiveAuthException ex)
{
// Log errors
}
return this.GetLoggedOutView();
}
public ActionResult Logout()
{
this.AuthClient.ClearSession(this.HttpContext);
return this.GetLoggedOutView();
}
public async Task<ActionResult> AuthHandler()
{
string redirectPath;
try
{
LiveLoginResult result = await this.AuthClient.ExchangeAuthCodeAsync(this.HttpContext, this.CurrentPath);
redirectPath = result.State;
}
catch (LiveAuthException ex)
{
redirectPath = ex.State;
}
this.Response.Redirect(redirectPath);
return null;
}
public async Task<ActionResult> ShowContacts()
{
try
{
var scopes = new string[] { "wl.signin", "wl.basic" };
LiveLoginResult loginStatus = await this.AuthClient.InitializeWebSessionAsync(
this.HttpContext,
this.CurrentPath,
scopes);
switch (loginStatus.Status)
{
case LiveConnectSessionStatus.Expired:
{
string reAuthUrl = this.GetLoginUrl(scopes, this.CurrentPath);
this.Response.Redirect(reAuthUrl);
return null;
}
case LiveConnectSessionStatus.Connected:
{
return await this.GetAccountDataView(AccountDataContent.Basic | AccountDataContent.Contacts);
}
default:
{
string authorizeUrl = this.GetLoginUrl(
scopes,
ShowContactsUrl);
this.Response.Redirect(authorizeUrl);
return null;
}
}
}
catch (LiveAuthException ex)
{
// Log errors
}
return this.GetLoggedOutView();
}
public ActionResult AjaxClient()
{
return View("AjaxClient", this.JSClientModel);
}
public async Task<ActionResult> AjaxCallback()
{
try
{
LiveLoginResult loginStatus = await this.AuthClient.InitializeWebSessionAsync(this.HttpContext, this.CurrentPath);
if (loginStatus.Status == LiveConnectSessionStatus.Expired)
{
string reAuthUrl = this.AuthClient.GetLoginUrl(new string[] { "wl.signin" }, this.CurrentPath);
this.Response.Redirect(reAuthUrl);
return null;
}
}
catch (LiveAuthException)
{
}
return View("AjaxCallback", this.JSClientModel);
}
private JSClientModel JSClientModel
{
get
{
var model = new JSClientModel()
{
JSPath = this.WLJSPath,
ClientId = ClientId,
Scope = "wl.signin wl.basic wl.skydrive",
RedirectUri = this.AjaxCallbackPath
};
return model;
}
}
private string WLJSPath
{
get
{
return "https://js.live.net/v5.0/wl.js";
}
}
private string AuthHandlerPath
{
get
{
return this.SiteRootPath + "account/authhandler";
}
}
private string AjaxClientPath
{
get
{
return this.SiteRootPath + "account/ajaxclient";
}
}
private string AjaxCallbackPath
{
get
{
return this.SiteRootPath + "account/ajaxcallback";
}
}
private string ShowContactsUrl
{
get
{
return this.SiteRootPath + "account/showcontacts";
}
}
private string SiteRootPath
{
get
{
string localhost = "localhost";
Uri currentUri = this.Request.Url;
string currentUrl = currentUri.GetLeftPart(UriPartial.Authority);
if (currentUri.Host == localhost)
{
currentUrl = currentUri.GetLeftPart(UriPartial.Authority).Replace(localhost, ClientDomain);
}
if (!currentUrl.EndsWith("/"))
{
currentUrl += "/";
}
return currentUrl;
}
}
private string CurrentPath
{
get
{
return this.SiteRootPath + this.Request.Path.TrimStart('/');
}
}
private LiveAuthClient AuthClient
{
get
{
if (this.liveAuthClient == null)
{
IDictionary<int, string> secretMap = new Dictionary<int, string>();
secretMap.Add(ClientSecretKey, ClientSecret);
this.liveAuthClient = new LiveAuthClient(ClientId, secretMap, null);
}
return this.liveAuthClient;
}
}
private static async Task<LiveOperationResult> QueryUserData(LiveConnectClient client, string path)
{
try
{
return await client.GetAsync(path);
}
catch
{
}
return null;
}
private async Task<ActionResult> GetAccountDataView(AccountDataContent content)
{
string errorText = null;
string logoutUrl = this.AuthClient.GetLogoutUrl(this.SiteRootPath + "account/logout");
var accountData = new AccountDataModel()
{
LogoutURL = logoutUrl,
ShowContactsURL = ShowContactsUrl,
HomeURL = this.SiteRootPath
};
LiveConnectClient client = new LiveConnectClient(this.AuthClient.Session);
LiveOperationResult meResult = await QueryUserData(client, "me");
if (meResult != null)
{
dynamic meInfo = meResult.Result;
accountData.Name = meInfo.name;
accountData.ProfileImage = await GetProfileImageData(client);
}
else
{
errorText = "There was an error while retrieving the user's information. Please try again later.";
}
if (errorText == null && (content & AccountDataContent.Contacts) == AccountDataContent.Contacts)
{
LiveOperationResult contactsResult = await QueryUserData(client, "me/contacts");
if (contactsResult != null)
{
dynamic contacts = contactsResult.Result;
accountData.Contacts = contacts.data;
}
else
{
errorText = "There was an error while retrieving the user's contacts data. Please try again later.";
}
}
accountData.Error = errorText;
return View("AccountData", accountData);
}
private ActionResult GetLoggedOutView()
{
return View("LoggedOut", new LoggedOutModel()
{
LoginURL = this.GetLoginUrl(new string[] { "wl.signin" }, this.SiteRootPath),
AjaxClientURL = this.AjaxClientPath
});
}
private string GetLoginUrl(IEnumerable<string> scopes, string callbackUrl)
{
var options = new Dictionary<string, string>();
options["state"] = callbackUrl;
string loginUrl = this.AuthClient.GetLoginUrl(scopes, this.AuthHandlerPath, options);
return loginUrl;
}
private static async Task<byte[]> GetProfileImageData(LiveConnectClient client)
{
byte[] imgData = null;
try
{
LiveDownloadOperationResult meImgResult = await client.DownloadAsync("me/picture");
imgData = new byte[meImgResult.Stream.Length];
await meImgResult.Stream.ReadAsync(imgData, 0, imgData.Length);
}
catch
{
// Failed to download image data.
}
return imgData;
}
}
}
| |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Input;
namespace ColorPickerSampleApplication
{
public partial class SampleViewer : Window
{
public SampleViewer()
{
InitializeComponent();
}
#region Dependency Property Fields
public static readonly DependencyProperty SelectedShapeProperty =
DependencyProperty.Register
("SelectedShape", typeof(Shape), typeof(SampleViewer),
new PropertyMetadata(null, selectedShape_Changed));
public static readonly DependencyProperty DrawingModeProperty =
DependencyProperty.Register
("DrawingMode", typeof(DrawingMode), typeof(SampleViewer),
new PropertyMetadata(DrawingMode.Select));
public static readonly DependencyProperty FillColorProperty =
DependencyProperty.Register
("FillColor", typeof(Color), typeof(SampleViewer),
new PropertyMetadata(Colors.LightGray));
public static readonly DependencyProperty StrokeColorProperty =
DependencyProperty.Register
("StrokeColor", typeof(Color), typeof(SampleViewer),
new PropertyMetadata(Colors.Black));
public static readonly DependencyProperty StrokeThicknessProperty =
DependencyProperty.Register
("StrokeThickness", typeof(double), typeof(SampleViewer),
new PropertyMetadata(1.0, strokeThickness_Changed));
#endregion
#region Public Properties
public DrawingMode DrawingMode
{
get
{
return (DrawingMode)GetValue(DrawingModeProperty);
}
set
{
SetValue(DrawingModeProperty, value);
}
}
public Color FillColor
{
get
{
return (Color)GetValue(FillColorProperty);
}
set
{
SetValue(FillColorProperty, value);
}
}
public Color StrokeColor
{
get
{
return (Color)GetValue(StrokeColorProperty);
}
set
{
SetValue(StrokeColorProperty, value);
}
}
public double StrokeThickness
{
get
{
return (double)GetValue(StrokeThicknessProperty);
}
set
{
SetValue(StrokeThicknessProperty, value);
}
}
#endregion
private static void selectedShape_Changed(object sender,
DependencyPropertyChangedEventArgs e)
{
SampleViewer sViewer = (SampleViewer)sender;
sViewer.OnSelectedShapeChanged((Shape)e.OldValue, (Shape)e.NewValue);
}
protected void OnSelectedShapeChanged(Shape oldShape, Shape newShape)
{
if (newShape != null)
{
FillColor = ((SolidColorBrush)newShape.Fill).Color;
StrokeColor = ((SolidColorBrush)newShape.Stroke).Color;
StrokeThickness = newShape.StrokeThickness;
}
}
private static void strokeThickness_Changed(object sender,
DependencyPropertyChangedEventArgs e)
{
SampleViewer sViewer = (SampleViewer)sender;
sViewer.OnStrokeThicknessChanged((double)e.OldValue, (double)e.NewValue);
}
protected void OnStrokeThicknessChanged(double oldThickness, double newThickness)
{
Shape currentShape = (Shape)GetValue(SelectedShapeProperty);
if (currentShape != null)
{
currentShape.StrokeThickness = newThickness;
}
}
private void OnDrawingCanvasMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Point clickPoint = e.GetPosition(DrawingCanvas);
if (DrawingMode == DrawingMode.Select)
{
if (e.OriginalSource is Shape)
{
Shape s = (Shape)e.OriginalSource;
SetValue(SelectedShapeProperty, s);
shapeClickPoint = e.GetPosition(s);
}
else
SetValue(SelectedShapeProperty, null);
}
else if (DrawingMode == DrawingMode.DrawRectangle && e.LeftButton == MouseButtonState.Pressed)
{
newRectangle = new Rectangle();
newRectangle.Stroke = new SolidColorBrush(StrokeColor);
newRectangle.StrokeThickness = StrokeThickness;
newRectangle.Fill = new SolidColorBrush(FillColor);
Canvas.SetLeft(newRectangle, clickPoint.X);
Canvas.SetTop(newRectangle, clickPoint.Y);
DrawingCanvas.Children.Add(newRectangle);
SetValue(SelectedShapeProperty, newRectangle);
}
else if (DrawingMode == DrawingMode.DrawEllipse && e.LeftButton == MouseButtonState.Pressed)
{
newEllipse = new Ellipse();
newEllipse.Stroke = new SolidColorBrush(StrokeColor);
newEllipse.StrokeThickness = StrokeThickness;
newEllipse.Fill = new SolidColorBrush(FillColor);
Canvas.SetLeft(newEllipse, clickPoint.X);
Canvas.SetTop(newEllipse, clickPoint.Y);
DrawingCanvas.Children.Add(newEllipse);
SetValue(SelectedShapeProperty, newEllipse);
}
else if (DrawingMode == DrawingMode.DrawLine && e.LeftButton == MouseButtonState.Pressed)
{
newLine = new Line();
newLine.Stroke = new SolidColorBrush(StrokeColor);
newLine.Fill = new SolidColorBrush(FillColor);;
newLine.X1 = clickPoint.X;
newLine.Y1 = clickPoint.Y;
newLine.StrokeThickness = StrokeThickness;
DrawingCanvas.Children.Add(newLine);
SetValue(SelectedShapeProperty, newLine);
}
}
private void OnDrawingCanvasMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (DrawingMode == DrawingMode.DrawRectangle)
{
newRectangle = null;
}
else if (DrawingMode == DrawingMode.DrawEllipse)
{
newEllipse = null;
}
else if (DrawingMode == DrawingMode.DrawLine)
{
newLine = null;
}
}
private void OnDrawingCanvasMouseMove(object sender, MouseEventArgs e)
{
Point dropPoint = e.GetPosition(DrawingCanvas);
if (DrawingMode == DrawingMode.Select)
{
Shape s = (Shape)GetValue(SelectedShapeProperty);
if (s != null && e.LeftButton == MouseButtonState.Pressed)
{
Canvas.SetLeft(s, dropPoint.X - shapeClickPoint.X);
Canvas.SetTop(s, dropPoint.Y - shapeClickPoint.Y);
}
}
else if (DrawingMode == DrawingMode.DrawRectangle)
{
if (newRectangle != null)
{
if (dropPoint.X > Canvas.GetLeft(newRectangle))
newRectangle.Width = dropPoint.X - Canvas.GetLeft(newRectangle);
if (dropPoint.Y > Canvas.GetTop(newRectangle))
newRectangle.Height = dropPoint.Y - Canvas.GetTop(newRectangle);
}
}
else if (DrawingMode == DrawingMode.DrawEllipse)
{
if (newEllipse != null)
{
if (dropPoint.X > Canvas.GetLeft(newEllipse))
newEllipse.Width = dropPoint.X - Canvas.GetLeft(newEllipse);
if (dropPoint.Y > Canvas.GetTop(newEllipse))
newEllipse.Height = dropPoint.Y - Canvas.GetTop(newEllipse);
}
}
else if (DrawingMode == DrawingMode.DrawLine)
{
if (newLine != null)
{
newLine.X2 = dropPoint.X;
newLine.Y2 = dropPoint.Y;
}
}
}
private void OnDrawingCanvasKeyDown(object sender, KeyEventArgs e)
{
Shape s = (Shape)GetValue(SelectedShapeProperty);
if (e.Key == Key.Delete && s!= null)
{
DrawingCanvas.Children.Remove(s);
SetValue(SelectedShapeProperty, null);
}
}
private void SetStroke(object sender, RoutedEventArgs e)
{
Shape selectedShape = (Shape)GetValue(SelectedShapeProperty);
Microsoft.Samples.CustomControls.ColorPickerDialog cPicker
= new Microsoft.Samples.CustomControls.ColorPickerDialog();
cPicker.StartingColor = StrokeColor;
cPicker.Owner = this;
bool? dialogResult = cPicker.ShowDialog();
if (dialogResult != null && (bool)dialogResult == true)
{
if (selectedShape != null)
selectedShape.Stroke = new SolidColorBrush(cPicker.SelectedColor);
StrokeColor = cPicker.SelectedColor;
}
}
private void SetFill(object sender, RoutedEventArgs e)
{
Shape selectedShape = (Shape)GetValue(SelectedShapeProperty);
Microsoft.Samples.CustomControls.ColorPickerDialog cPicker
= new Microsoft.Samples.CustomControls.ColorPickerDialog();
cPicker.StartingColor = FillColor;
cPicker.Owner = this;
bool? dialogResult = cPicker.ShowDialog();
if (dialogResult != null && (bool)dialogResult == true)
{
if (selectedShape != null)
selectedShape.Fill = new SolidColorBrush(cPicker.SelectedColor);
FillColor = cPicker.SelectedColor;
}
}
private void drawingModeChanged(object sender, EventArgs e)
{
RadioButton r = (RadioButton)sender;
SetValue(DrawingModeProperty, Enum.Parse(typeof(DrawingMode), r.Name));
}
private void exitMenuItemClicked(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
#region Private Fields
private Point shapeClickPoint;
private Rectangle newRectangle;
private Line newLine;
private Ellipse newEllipse;
#endregion
}
public enum DrawingMode
{
Select=0, DrawLine=1, DrawRectangle=2, DrawEllipse=3
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
public static class ReaderWriterLockSlimTests
{
[Fact]
public static void Ctor()
{
ReaderWriterLockSlim rwls;
using (rwls = new ReaderWriterLockSlim())
{
Assert.Equal(LockRecursionPolicy.NoRecursion, rwls.RecursionPolicy);
}
using (rwls = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion))
{
Assert.Equal(LockRecursionPolicy.NoRecursion, rwls.RecursionPolicy);
}
using (rwls = new ReaderWriterLockSlim((LockRecursionPolicy)12345))
{
Assert.Equal(LockRecursionPolicy.NoRecursion, rwls.RecursionPolicy);
}
using (rwls = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion))
{
Assert.Equal(LockRecursionPolicy.SupportsRecursion, rwls.RecursionPolicy);
}
}
[Fact]
public static void Dispose()
{
ReaderWriterLockSlim rwls;
rwls = new ReaderWriterLockSlim();
rwls.Dispose();
Assert.Throws<ObjectDisposedException>(() => rwls.TryEnterReadLock(0));
Assert.Throws<ObjectDisposedException>(() => rwls.TryEnterUpgradeableReadLock(0));
Assert.Throws<ObjectDisposedException>(() => rwls.TryEnterWriteLock(0));
rwls.Dispose();
for (int i = 0; i < 3; i++)
{
rwls = new ReaderWriterLockSlim();
switch (i)
{
case 0: rwls.EnterReadLock(); break;
case 1: rwls.EnterUpgradeableReadLock(); break;
case 2: rwls.EnterWriteLock(); break;
}
Assert.Throws<SynchronizationLockException>(() => rwls.Dispose());
}
}
[Fact]
public static void EnterExit()
{
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Assert.False(rwls.IsReadLockHeld);
rwls.EnterReadLock();
Assert.True(rwls.IsReadLockHeld);
rwls.ExitReadLock();
Assert.False(rwls.IsReadLockHeld);
Assert.False(rwls.IsUpgradeableReadLockHeld);
rwls.EnterUpgradeableReadLock();
Assert.True(rwls.IsUpgradeableReadLockHeld);
rwls.ExitUpgradeableReadLock();
Assert.False(rwls.IsUpgradeableReadLockHeld);
Assert.False(rwls.IsWriteLockHeld);
rwls.EnterWriteLock();
Assert.True(rwls.IsWriteLockHeld);
rwls.ExitWriteLock();
Assert.False(rwls.IsWriteLockHeld);
Assert.False(rwls.IsUpgradeableReadLockHeld);
rwls.EnterUpgradeableReadLock();
Assert.False(rwls.IsWriteLockHeld);
Assert.True(rwls.IsUpgradeableReadLockHeld);
rwls.EnterWriteLock();
Assert.True(rwls.IsWriteLockHeld);
rwls.ExitWriteLock();
Assert.False(rwls.IsWriteLockHeld);
Assert.True(rwls.IsUpgradeableReadLockHeld);
rwls.ExitUpgradeableReadLock();
Assert.False(rwls.IsUpgradeableReadLockHeld);
Assert.True(rwls.TryEnterReadLock(0));
rwls.ExitReadLock();
Assert.True(rwls.TryEnterReadLock(Timeout.InfiniteTimeSpan));
rwls.ExitReadLock();
Assert.True(rwls.TryEnterUpgradeableReadLock(0));
rwls.ExitUpgradeableReadLock();
Assert.True(rwls.TryEnterUpgradeableReadLock(Timeout.InfiniteTimeSpan));
rwls.ExitUpgradeableReadLock();
Assert.True(rwls.TryEnterWriteLock(0));
rwls.ExitWriteLock();
Assert.True(rwls.TryEnterWriteLock(Timeout.InfiniteTimeSpan));
rwls.ExitWriteLock();
}
}
[Fact]
public static void DeadlockAvoidance()
{
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
rwls.EnterReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterReadLock());
Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock());
Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock());
rwls.ExitReadLock();
rwls.EnterUpgradeableReadLock();
rwls.EnterReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterReadLock());
rwls.ExitReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock());
rwls.EnterWriteLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock());
rwls.ExitWriteLock();
rwls.ExitUpgradeableReadLock();
rwls.EnterWriteLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterReadLock());
Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock());
Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock());
rwls.ExitWriteLock();
}
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion))
{
rwls.EnterReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock());
rwls.EnterReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock());
rwls.ExitReadLock();
rwls.ExitReadLock();
rwls.EnterUpgradeableReadLock();
rwls.EnterReadLock();
rwls.EnterUpgradeableReadLock();
rwls.ExitUpgradeableReadLock();
rwls.EnterReadLock();
rwls.ExitReadLock();
rwls.ExitReadLock();
rwls.EnterWriteLock();
rwls.EnterWriteLock();
rwls.ExitWriteLock();
rwls.ExitWriteLock();
rwls.ExitUpgradeableReadLock();
rwls.EnterWriteLock();
rwls.EnterReadLock();
rwls.ExitReadLock();
rwls.EnterUpgradeableReadLock();
rwls.ExitUpgradeableReadLock();
rwls.EnterWriteLock();
rwls.ExitWriteLock();
rwls.ExitWriteLock();
}
}
[Theory]
[InlineData(LockRecursionPolicy.NoRecursion)]
[InlineData(LockRecursionPolicy.SupportsRecursion)]
public static void InvalidExits(LockRecursionPolicy policy)
{
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim(policy))
{
Assert.Throws<SynchronizationLockException>(() => rwls.ExitReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitUpgradeableReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock());
rwls.EnterReadLock();
Assert.Throws<SynchronizationLockException>(() => rwls.ExitUpgradeableReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock());
rwls.ExitReadLock();
rwls.EnterUpgradeableReadLock();
Assert.Throws<SynchronizationLockException>(() => rwls.ExitReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock());
rwls.ExitUpgradeableReadLock();
rwls.EnterWriteLock();
Assert.Throws<SynchronizationLockException>(() => rwls.ExitReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitUpgradeableReadLock());
rwls.ExitWriteLock();
using (Barrier barrier = new Barrier(2))
{
Task t = Task.Factory.StartNew(() =>
{
rwls.EnterWriteLock();
barrier.SignalAndWait();
barrier.SignalAndWait();
rwls.ExitWriteLock();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
barrier.SignalAndWait();
Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock());
barrier.SignalAndWait();
t.GetAwaiter().GetResult();
}
}
}
[Fact]
public static void InvalidTimeouts()
{
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterReadLock(-2));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterUpgradeableReadLock(-3));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterWriteLock(-4));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterReadLock(TimeSpan.MaxValue));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterUpgradeableReadLock(TimeSpan.MinValue));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterWriteLock(TimeSpan.FromMilliseconds(-2)));
}
}
[Fact]
public static void WritersAreMutuallyExclusiveFromReaders()
{
using (Barrier barrier = new Barrier(2))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Task.WaitAll(
Task.Run(() =>
{
rwls.EnterWriteLock();
barrier.SignalAndWait();
Assert.True(rwls.IsWriteLockHeld);
barrier.SignalAndWait();
rwls.ExitWriteLock();
}),
Task.Run(() =>
{
barrier.SignalAndWait();
Assert.False(rwls.TryEnterReadLock(0));
Assert.False(rwls.IsReadLockHeld);
barrier.SignalAndWait();
}));
}
}
[Fact]
public static void WritersAreMutuallyExclusiveFromWriters()
{
using (Barrier barrier = new Barrier(2))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Task.WaitAll(
Task.Run(() =>
{
rwls.EnterWriteLock();
barrier.SignalAndWait();
Assert.True(rwls.IsWriteLockHeld);
barrier.SignalAndWait();
rwls.ExitWriteLock();
}),
Task.Run(() =>
{
barrier.SignalAndWait();
Assert.False(rwls.TryEnterWriteLock(0));
Assert.False(rwls.IsReadLockHeld);
barrier.SignalAndWait();
}));
}
}
[Fact]
public static void ReadersMayBeConcurrent()
{
using (Barrier barrier = new Barrier(2))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Assert.Equal(0, rwls.CurrentReadCount);
Task.WaitAll(
Task.Run(() =>
{
rwls.EnterReadLock();
barrier.SignalAndWait(); // 1
Assert.True(rwls.IsReadLockHeld);
barrier.SignalAndWait(); // 2
Assert.Equal(2, rwls.CurrentReadCount);
barrier.SignalAndWait(); // 3
barrier.SignalAndWait(); // 4
rwls.ExitReadLock();
}),
Task.Run(() =>
{
barrier.SignalAndWait(); // 1
rwls.EnterReadLock();
barrier.SignalAndWait(); // 2
Assert.True(rwls.IsReadLockHeld);
Assert.Equal(0, rwls.WaitingReadCount);
barrier.SignalAndWait(); // 3
rwls.ExitReadLock();
barrier.SignalAndWait(); // 4
}));
Assert.Equal(0, rwls.CurrentReadCount);
}
}
[Fact]
public static void WriterToWriterChain()
{
using (AutoResetEvent are = new AutoResetEvent(false))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
rwls.EnterWriteLock();
Task t = Task.Factory.StartNew(() =>
{
Assert.False(rwls.TryEnterWriteLock(10));
Task.Run(() => are.Set()); // ideally this won't fire until we've called EnterWriteLock, but it's a benign race in that the test will succeed either way
rwls.EnterWriteLock();
rwls.ExitWriteLock();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
are.WaitOne();
rwls.ExitWriteLock();
t.GetAwaiter().GetResult();
}
}
[Fact]
public static void WriterToReaderChain()
{
using (AutoResetEvent are = new AutoResetEvent(false))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
rwls.EnterWriteLock();
Task t = Task.Factory.StartNew(() =>
{
Assert.False(rwls.TryEnterReadLock(TimeSpan.FromMilliseconds(10)));
Task.Run(() => are.Set()); // ideally this won't fire until we've called EnterReadLock, but it's a benign race in that the test will succeed either way
rwls.EnterReadLock();
rwls.ExitReadLock();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
are.WaitOne();
rwls.ExitWriteLock();
t.GetAwaiter().GetResult();
}
}
[Fact]
public static void WriterToUpgradeableReaderChain()
{
using (AutoResetEvent are = new AutoResetEvent(false))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
rwls.EnterWriteLock();
Task t = Task.Factory.StartNew(() =>
{
Assert.False(rwls.TryEnterUpgradeableReadLock(TimeSpan.FromMilliseconds(10)));
Task.Run(() => are.Set()); // ideally this won't fire until we've called EnterReadLock, but it's a benign race in that the test will succeed either way
rwls.EnterUpgradeableReadLock();
rwls.ExitUpgradeableReadLock();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
are.WaitOne();
rwls.ExitWriteLock();
t.GetAwaiter().GetResult();
}
}
}
}
| |
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Diagnostics;
using Lucene.Net.Util;
using System.Collections.Generic;
using Console = Lucene.Net.Util.SystemConsole;
namespace Lucene.Net.Analysis
{
/*
* 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 AttributeSource = Lucene.Net.Util.AttributeSource;
//using RollingBuffer = Lucene.Net.Util.RollingBuffer;
// TODO: cut SynFilter over to this
// TODO: somehow add "nuke this input token" capability...
/// <summary>
/// LUCENENET specific abstraction so we can reference <see cref="LookaheadTokenFilter.Position"/> without
/// specifying a generic closing type.
/// </summary>
public abstract class LookaheadTokenFilter : TokenFilter
{
internal LookaheadTokenFilter(TokenStream input) // Not for end users to use directly
: base(input)
{ }
public abstract override bool IncrementToken();
/// <summary>
/// Holds all state for a single position; subclass this
/// to record other state at each position.
/// </summary>
// LUCENENET NOTE: This class was originally marked protected, but was made public because of
// inconsistent accessibility issues with using it as a generic constraint.
public class Position : RollingBuffer.IResettable
{
// Buffered input tokens at this position:
public IList<AttributeSource.State> InputTokens { get; private set; } = new List<AttributeSource.State>();
// Next buffered token to be returned to consumer:
public int NextRead { get; set; }
// Any token leaving from this position should have this startOffset:
public int StartOffset { get; set; } = -1;
// Any token arriving to this position should have this endOffset:
public int EndOffset { get; set; } = -1;
public void Reset()
{
InputTokens.Clear();
NextRead = 0;
StartOffset = -1;
EndOffset = -1;
}
public virtual void Add(AttributeSource.State state)
{
InputTokens.Add(state);
}
public virtual AttributeSource.State NextState()
{
if (Debugging.AssertsEnabled) Debugging.Assert(NextRead < InputTokens.Count);
return InputTokens[NextRead++];
}
}
}
/// <summary>
/// An abstract <see cref="TokenFilter"/> to make it easier to build graph
/// token filters requiring some lookahead. This class handles
/// the details of buffering up tokens, recording them by
/// position, restoring them, providing access to them, etc.
/// </summary>
public abstract class LookaheadTokenFilter<T> : LookaheadTokenFilter
where T : LookaheadTokenFilter.Position
{
protected readonly static bool DEBUG =
#if VERBOSE_TEST_LOGGING
true
#else
false
#endif
;
protected readonly IPositionIncrementAttribute m_posIncAtt;
protected readonly IPositionLengthAttribute m_posLenAtt;
protected readonly IOffsetAttribute m_offsetAtt;
// Position of last read input token:
protected int m_inputPos;
// Position of next possible output token to return:
protected int m_outputPos;
// True if we hit end from our input:
protected bool m_end;
private bool tokenPending;
private bool insertPending;
// LUCENENET specific - moved Position class to a non-generic class named LookaheadTokenFilter so we can refer to
// it without referring to the generic closing type.
protected internal LookaheadTokenFilter(TokenStream input)
: base(input)
{
m_positions = new RollingBufferAnonymousClass(this);
m_posIncAtt = AddAttribute<IPositionIncrementAttribute>();
m_posLenAtt = AddAttribute<IPositionLengthAttribute>();
m_offsetAtt = AddAttribute<IOffsetAttribute>();
}
/// <summary>
/// Call this only from within <see cref="AfterPosition()"/>, to insert a new
/// token. After calling this you should set any
/// necessary token you need.
/// </summary>
protected virtual void InsertToken()
{
if (tokenPending)
{
m_positions.Get(m_inputPos).Add(CaptureState());
tokenPending = false;
}
if (Debugging.AssertsEnabled) Debugging.Assert(!insertPending);
insertPending = true;
}
/// <summary>
/// This is called when all input tokens leaving a given
/// position have been returned. Override this and
/// call insertToken and then set whichever token's
/// attributes you want, if you want to inject
/// a token starting from this position.
/// </summary>
protected virtual void AfterPosition()
{
}
protected abstract T NewPosition();
protected readonly RollingBuffer<T> m_positions;
private class RollingBufferAnonymousClass : RollingBuffer<T>
{
private readonly LookaheadTokenFilter<T> outerInstance;
public RollingBufferAnonymousClass(LookaheadTokenFilter<T> outerInstance)
: base(outerInstance.NewPosition)
{
this.outerInstance = outerInstance;
}
protected override T NewInstance()
{
return outerInstance.NewPosition();
}
}
/// <summary>
/// Returns true if there is a new token. </summary>
protected virtual bool PeekToken()
{
if (DEBUG)
{
Console.WriteLine("LTF.peekToken inputPos=" + m_inputPos + " outputPos=" + m_outputPos + " tokenPending=" + tokenPending);
}
if (Debugging.AssertsEnabled) Debugging.Assert(!m_end);
if (Debugging.AssertsEnabled) Debugging.Assert(m_inputPos == -1 || m_outputPos <= m_inputPos);
if (tokenPending)
{
m_positions.Get(m_inputPos).Add(CaptureState());
tokenPending = false;
}
bool gotToken = m_input.IncrementToken();
if (DEBUG)
{
Console.WriteLine(" input.incrToken() returned " + gotToken);
}
if (gotToken)
{
m_inputPos += m_posIncAtt.PositionIncrement;
if (Debugging.AssertsEnabled) Debugging.Assert(m_inputPos >= 0);
if (DEBUG)
{
Console.WriteLine(" now inputPos=" + m_inputPos);
}
Position startPosData = m_positions.Get(m_inputPos);
Position endPosData = m_positions.Get(m_inputPos + m_posLenAtt.PositionLength);
int startOffset = m_offsetAtt.StartOffset;
if (startPosData.StartOffset == -1)
{
startPosData.StartOffset = startOffset;
}
else
{
// Make sure our input isn't messing up offsets:
if (Debugging.AssertsEnabled) Debugging.Assert(startPosData.StartOffset == startOffset, "prev startOffset={0} vs new startOffset={1} inputPos={2}", startPosData.StartOffset, startOffset, m_inputPos);
}
int endOffset = m_offsetAtt.EndOffset;
if (endPosData.EndOffset == -1)
{
endPosData.EndOffset = endOffset;
}
else
{
// Make sure our input isn't messing up offsets:
if (Debugging.AssertsEnabled) Debugging.Assert(endPosData.EndOffset == endOffset, "prev endOffset={0} vs new endOffset={1} inputPos={2}", endPosData.EndOffset, endOffset, m_inputPos);
}
tokenPending = true;
}
else
{
m_end = true;
}
return gotToken;
}
/// <summary>
/// Call this when you are done looking ahead; it will set
/// the next token to return. Return the boolean back to
/// the caller.
/// </summary>
protected virtual bool NextToken()
{
//System.out.println(" nextToken: tokenPending=" + tokenPending);
if (DEBUG)
{
Console.WriteLine("LTF.nextToken inputPos=" + m_inputPos + " outputPos=" + m_outputPos + " tokenPending=" + tokenPending);
}
Position posData = m_positions.Get(m_outputPos);
// While loop here in case we have to
// skip over a hole from the input:
while (true)
{
//System.out.println(" check buffer @ outputPos=" +
//outputPos + " inputPos=" + inputPos + " nextRead=" +
//posData.nextRead + " vs size=" +
//posData.inputTokens.size());
// See if we have a previously buffered token to
// return at the current position:
if (posData.NextRead < posData.InputTokens.Count)
{
if (DEBUG)
{
Console.WriteLine(" return previously buffered token");
}
// this position has buffered tokens to serve up:
if (tokenPending)
{
m_positions.Get(m_inputPos).Add(CaptureState());
tokenPending = false;
}
RestoreState(m_positions.Get(m_outputPos).NextState());
//System.out.println(" return!");
return true;
}
if (m_inputPos == -1 || m_outputPos == m_inputPos)
{
// No more buffered tokens:
// We may still get input tokens at this position
//System.out.println(" break buffer");
if (tokenPending)
{
// Fast path: just return token we had just incr'd,
// without having captured/restored its state:
if (DEBUG)
{
Console.WriteLine(" pass-through: return pending token");
}
tokenPending = false;
return true;
}
else if (m_end || !PeekToken())
{
if (DEBUG)
{
Console.WriteLine(" END");
}
AfterPosition();
if (insertPending)
{
// Subclass inserted a token at this same
// position:
if (DEBUG)
{
Console.WriteLine(" return inserted token");
}
if (Debugging.AssertsEnabled) Debugging.Assert(InsertedTokenConsistent());
insertPending = false;
return true;
}
return false;
}
}
else
{
if (posData.StartOffset != -1)
{
// this position had at least one token leaving
if (DEBUG)
{
Console.WriteLine(" call afterPosition");
}
AfterPosition();
if (insertPending)
{
// Subclass inserted a token at this same
// position:
if (DEBUG)
{
Console.WriteLine(" return inserted token");
}
if (Debugging.AssertsEnabled) Debugging.Assert(InsertedTokenConsistent());
insertPending = false;
return true;
}
}
// Done with this position; move on:
m_outputPos++;
if (DEBUG)
{
Console.WriteLine(" next position: outputPos=" + m_outputPos);
}
m_positions.FreeBefore(m_outputPos);
posData = m_positions.Get(m_outputPos);
}
}
}
// If subclass inserted a token, make sure it had in fact
// looked ahead enough:
private bool InsertedTokenConsistent()
{
int posLen = m_posLenAtt.PositionLength;
Position endPosData = m_positions.Get(m_outputPos + posLen);
if (Debugging.AssertsEnabled) Debugging.Assert(endPosData.EndOffset != -1);
if (Debugging.AssertsEnabled) Debugging.Assert(m_offsetAtt.EndOffset == endPosData.EndOffset,"offsetAtt.endOffset={0} vs expected={1}", m_offsetAtt.EndOffset, endPosData.EndOffset);
return true;
}
// TODO: end()?
// TODO: close()?
public override void Reset()
{
base.Reset();
m_positions.Reset();
m_inputPos = -1;
m_outputPos = 0;
tokenPending = false;
m_end = false;
}
}
}
| |
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using Abp.Auditing;
using Abp.Authorization;
using Abp.Authorization.Roles;
using Abp.Authorization.Users;
using Abp.Configuration;
using Abp.DynamicEntityProperties;
using Abp.EntityFramework;
using Abp.Localization;
using Abp.Notifications;
using Abp.Organizations;
using Abp.EntityFramework.Extensions;
using Abp.Webhooks;
namespace Abp.Zero.EntityFramework
{
public abstract class AbpZeroCommonDbContext<TRole, TUser, TSelf> : AbpDbContext
where TRole : AbpRole<TUser>
where TUser : AbpUser<TUser>
where TSelf : AbpZeroCommonDbContext<TRole, TUser, TSelf>
{
/// <summary>
/// Roles.
/// </summary>
public virtual DbSet<TRole> Roles { get; set; }
/// <summary>
/// Users.
/// </summary>
public virtual DbSet<TUser> Users { get; set; }
/// <summary>
/// User logins.
/// </summary>
public virtual DbSet<UserLogin> UserLogins { get; set; }
/// <summary>
/// User login attempts.
/// </summary>
public virtual DbSet<UserLoginAttempt> UserLoginAttempts { get; set; }
/// <summary>
/// User roles.
/// </summary>
public virtual DbSet<UserRole> UserRoles { get; set; }
/// <summary>
/// User claims.
/// </summary>
public virtual DbSet<UserClaim> UserClaims { get; set; }
/// <summary>
/// User tokens.
/// </summary>
public virtual DbSet<UserToken> UserTokens { get; set; }
/// <summary>
/// Role claims.
/// </summary>
public virtual DbSet<RoleClaim> RoleClaims { get; set; }
/// <summary>
/// Permissions.
/// </summary>
public virtual DbSet<PermissionSetting> Permissions { get; set; }
/// <summary>
/// Role permissions.
/// </summary>
public virtual DbSet<RolePermissionSetting> RolePermissions { get; set; }
/// <summary>
/// User permissions.
/// </summary>
public virtual DbSet<UserPermissionSetting> UserPermissions { get; set; }
/// <summary>
/// Settings.
/// </summary>
public virtual DbSet<Setting> Settings { get; set; }
/// <summary>
/// Audit logs.
/// </summary>
public virtual DbSet<AuditLog> AuditLogs { get; set; }
/// <summary>
/// Languages.
/// </summary>
public virtual DbSet<ApplicationLanguage> Languages { get; set; }
/// <summary>
/// LanguageTexts.
/// </summary>
public virtual DbSet<ApplicationLanguageText> LanguageTexts { get; set; }
/// <summary>
/// OrganizationUnits.
/// </summary>
public virtual DbSet<OrganizationUnit> OrganizationUnits { get; set; }
/// <summary>
/// UserOrganizationUnits.
/// </summary>
public virtual DbSet<UserOrganizationUnit> UserOrganizationUnits { get; set; }
/// <summary>
/// OrganizationUnitRoles.
/// </summary>
public virtual DbSet<OrganizationUnitRole> OrganizationUnitRoles { get; set; }
/// <summary>
/// Tenant notifications.
/// </summary>
public virtual DbSet<TenantNotificationInfo> TenantNotifications { get; set; }
/// <summary>
/// User notifications.
/// </summary>
public virtual DbSet<UserNotificationInfo> UserNotifications { get; set; }
/// <summary>
/// Notification subscriptions.
/// </summary>
public virtual DbSet<NotificationSubscriptionInfo> NotificationSubscriptions { get; set; }
/// <summary>
/// Webhook information
/// </summary>
public virtual DbSet<WebhookEvent> WebhookEvents { get; set; }
/// <summary>
/// Web subscriptions
/// </summary>
public virtual DbSet<WebhookSubscriptionInfo> WebhookSubscriptions { get; set; }
/// <summary>
/// Webhook work items
/// </summary>
public virtual DbSet<WebhookSendAttempt> WebhookSendAttempts { get; set; }
/// <summary>
/// DynamicProperties
/// </summary>
public virtual DbSet<DynamicProperty> DynamicProperties { get; set; }
/// <summary>
/// DynamicProperty selectable values
/// </summary>
public virtual DbSet<DynamicPropertyValue> DynamicPropertyValues { get; set; }
/// <summary>
/// Entities dynamic properties. Which property that entity has
/// </summary>
public virtual DbSet<DynamicEntityProperty> DynamicEntityProperties { get; set; }
/// <summary>
/// Entities dynamic properties values
/// </summary>
public virtual DbSet<DynamicEntityPropertyValue> DynamicEntityPropertyValues { get; set; }
/// <summary>
/// Default constructor.
/// Do not directly instantiate this class. Instead, use dependency injection!
/// </summary>
protected AbpZeroCommonDbContext()
{
}
/// <summary>
/// Constructor with connection string parameter.
/// </summary>
/// <param name="nameOrConnectionString">Connection string or a name in connection strings in configuration file</param>
protected AbpZeroCommonDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
protected AbpZeroCommonDbContext(DbCompiledModel model)
: base(model)
{
}
/// <summary>
/// This constructor can be used for unit tests.
/// </summary>
protected AbpZeroCommonDbContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
protected AbpZeroCommonDbContext(string nameOrConnectionString, DbCompiledModel model)
: base(nameOrConnectionString, model)
{
}
protected AbpZeroCommonDbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext)
: base(objectContext, dbContextOwnsObjectContext)
{
}
/// <summary>
/// Constructor.
/// </summary>
protected AbpZeroCommonDbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection)
: base(existingConnection, model, contextOwnsConnection)
{
}
/// <summary>
///
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
#region TUser.Set_ConcurrencyStamp
modelBuilder.Entity<TUser>()
.Property(e => e.ConcurrencyStamp)
.IsConcurrencyToken();
#endregion
#region TUser.Set_ForeignKeys
modelBuilder.Entity<TUser>()
.HasOptional(p => p.DeleterUser)
.WithMany()
.HasForeignKey(p => p.DeleterUserId);
modelBuilder.Entity<TUser>()
.HasOptional(p => p.CreatorUser)
.WithMany()
.HasForeignKey(p => p.CreatorUserId);
modelBuilder.Entity<TUser>()
.HasOptional(p => p.LastModifierUser)
.WithMany()
.HasForeignKey(p => p.LastModifierUserId);
#endregion
#region TRole.Set_ConcurrencyStamp
modelBuilder.Entity<TRole>()
.Property(e => e.ConcurrencyStamp)
.IsConcurrencyToken();
#endregion
#region AuditLog.IX_TenantId_UserId
modelBuilder.Entity<AuditLog>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserId", 1);
modelBuilder.Entity<AuditLog>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_UserId", 2);
#endregion
#region AuditLog.IX_TenantId_ExecutionTime
modelBuilder.Entity<AuditLog>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_ExecutionTime", 1);
modelBuilder.Entity<AuditLog>()
.Property(e => e.ExecutionTime)
.CreateIndex("IX_TenantId_ExecutionTime", 2);
#endregion
#region AuditLog.IX_TenantId_ExecutionDuration
modelBuilder.Entity<AuditLog>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_ExecutionDuration", 1);
modelBuilder.Entity<AuditLog>()
.Property(e => e.ExecutionDuration)
.CreateIndex("IX_TenantId_ExecutionDuration", 2);
#endregion
#region ApplicationLanguage.IX_TenantId_Name
modelBuilder.Entity<ApplicationLanguage>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Name", 1);
modelBuilder.Entity<ApplicationLanguage>()
.Property(e => e.Name)
.CreateIndex("IX_TenantId_Name", 2);
#endregion
#region ApplicationLanguageText.IX_TenantId_Source_LanguageName_Key
modelBuilder.Entity<ApplicationLanguageText>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Source_LanguageName_Key", 1);
modelBuilder.Entity<ApplicationLanguageText>()
.Property(e => e.Source)
.CreateIndex("IX_TenantId_Source_LanguageName_Key", 2);
modelBuilder.Entity<ApplicationLanguageText>()
.Property(e => e.LanguageName)
.CreateIndex("IX_TenantId_Source_LanguageName_Key", 3);
modelBuilder.Entity<ApplicationLanguageText>()
.Property(e => e.Key)
.CreateIndex("IX_TenantId_Source_LanguageName_Key", 4);
#endregion
#region NotificationSubscriptionInfo.IX_NotificationName_EntityTypeName_EntityId_UserId
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.NotificationName)
.CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 1);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.EntityTypeName)
.CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 2);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.EntityId)
.CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 3);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.UserId)
.CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 4);
#endregion
#region NotificationSubscriptionInfo.IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 1);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.NotificationName)
.CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 2);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.EntityTypeName)
.CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 3);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.EntityId)
.CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 4);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 5);
#endregion
#region UserNotificationInfo.IX_UserId_State_CreationTime
modelBuilder.Entity<UserNotificationInfo>()
.Property(e => e.UserId)
.CreateIndex("IX_UserId_State_CreationTime", 1);
modelBuilder.Entity<UserNotificationInfo>()
.Property(e => e.State)
.CreateIndex("IX_UserId_State_CreationTime", 2);
modelBuilder.Entity<UserNotificationInfo>()
.Property(e => e.CreationTime)
.CreateIndex("IX_UserId_State_CreationTime", 3);
#endregion
#region OrganizationUnit.IX_TenantId_Code
modelBuilder.Entity<OrganizationUnit>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Code", 1);
modelBuilder.Entity<OrganizationUnit>()
.Property(e => e.Code)
.CreateIndex("IX_TenantId_Code", 2);
#endregion
#region PermissionSetting.IX_TenantId_Name
modelBuilder.Entity<PermissionSetting>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Name", 1);
modelBuilder.Entity<PermissionSetting>()
.Property(e => e.Name)
.CreateIndex("IX_TenantId_Name", 2);
#endregion
#region RoleClaim.IX_RoleId
modelBuilder.Entity<RoleClaim>()
.Property(e => e.RoleId)
.CreateIndex("IX_RoleId", 1);
#endregion
#region RoleClaim.IX_TenantId_ClaimType
modelBuilder.Entity<RoleClaim>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_ClaimType", 1);
modelBuilder.Entity<RoleClaim>()
.Property(e => e.ClaimType)
.CreateIndex("IX_TenantId_ClaimType", 2);
#endregion
#region Role.IX_TenantId_NormalizedName
modelBuilder.Entity<TRole>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_NormalizedName", 1);
modelBuilder.Entity<TRole>()
.Property(e => e.NormalizedName)
.CreateIndex("IX_TenantId_NormalizedName", 2);
#endregion
#region Setting.IX_TenantId_Name
modelBuilder.Entity<Setting>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Name", 1);
modelBuilder.Entity<Setting>()
.Property(e => e.Name)
.CreateIndex("IX_TenantId_Name", 2);
#endregion
#region TenantNotificationInfo.IX_TenantId
modelBuilder.Entity<TenantNotificationInfo>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Name", 1);
#endregion
#region UserClaim.IX_TenantId_ClaimType
modelBuilder.Entity<UserClaim>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_ClaimType", 1);
modelBuilder.Entity<UserClaim>()
.Property(e => e.ClaimType)
.CreateIndex("IX_TenantId_ClaimType", 2);
#endregion
#region UserLoginAttempt.IX_TenancyName_UserNameOrEmailAddress_Result
modelBuilder.Entity<UserLoginAttempt>()
.Property(e => e.TenancyName)
.CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 1);
modelBuilder.Entity<UserLoginAttempt>()
.Property(e => e.UserNameOrEmailAddress)
.CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 2);
modelBuilder.Entity<UserLoginAttempt>()
.Property(ula => ula.Result)
.CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 3);
#endregion
#region UserLoginAttempt.IX_UserId_TenantId
modelBuilder.Entity<UserLoginAttempt>()
.Property(e => e.UserId)
.CreateIndex("IX_UserId_TenantId", 1);
modelBuilder.Entity<UserLoginAttempt>()
.Property(e => e.TenantId)
.CreateIndex("IX_UserId_TenantId", 2);
#endregion
#region UserLogin.IX_TenantId_LoginProvider_ProviderKey
modelBuilder.Entity<UserLogin>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_LoginProvider_ProviderKey", 1);
modelBuilder.Entity<UserLogin>()
.Property(e => e.LoginProvider)
.CreateIndex("IX_TenantId_LoginProvider_ProviderKey", 2);
modelBuilder.Entity<UserLogin>()
.Property(e => e.ProviderKey)
.CreateIndex("IX_TenantId_LoginProvider_ProviderKey", 3);
#endregion
#region UserLogin.IX_TenantId_UserId
modelBuilder.Entity<UserLogin>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserId", 1);
modelBuilder.Entity<UserLogin>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_UserId", 2);
#endregion
#region UserOrganizationUnit.IX_TenantId_UserId
modelBuilder.Entity<UserOrganizationUnit>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserId", 1);
modelBuilder.Entity<UserOrganizationUnit>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_UserId", 2);
#endregion
#region UserOrganizationUnit.IX_TenantId_OrganizationUnitId
modelBuilder.Entity<UserOrganizationUnit>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_OrganizationUnitId", 1);
modelBuilder.Entity<UserOrganizationUnit>()
.Property(e => e.OrganizationUnitId)
.CreateIndex("IX_TenantId_OrganizationUnitId", 2);
#endregion
#region OrganizationUnitRole.IX_TenantId_RoleId
modelBuilder.Entity<OrganizationUnitRole>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_RoleId", 1);
modelBuilder.Entity<OrganizationUnitRole>()
.Property(e => e.RoleId)
.CreateIndex("IX_TenantId_RoleId", 2);
#endregion
#region OrganizationUnitRole.IX_TenantId_OrganizationUnitId
modelBuilder.Entity<OrganizationUnitRole>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_OrganizationUnitId", 1);
modelBuilder.Entity<OrganizationUnitRole>()
.Property(e => e.OrganizationUnitId)
.CreateIndex("IX_TenantId_OrganizationUnitId", 2);
#endregion
#region UserRole.IX_TenantId_UserId
modelBuilder.Entity<UserRole>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserId", 1);
modelBuilder.Entity<UserRole>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_UserId", 2);
modelBuilder.Entity<Setting>()
.HasIndex(e => new {e.TenantId, e.Name, e.UserId})
.IsUnique();
#endregion
#region UserRole.IX_TenantId_RoleId
modelBuilder.Entity<UserRole>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_RoleId", 1);
modelBuilder.Entity<UserRole>()
.Property(e => e.RoleId)
.CreateIndex("IX_TenantId_RoleId", 2);
#endregion
#region TUser.IX_TenantId_NormalizedUserName
modelBuilder.Entity<TUser>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_NormalizedUserName", 1);
modelBuilder.Entity<TUser>()
.Property(e => e.NormalizedUserName)
.CreateIndex("IX_TenantId_NormalizedUserName", 2);
#endregion
#region TUser.IX_TenantId_NormalizedEmailAddress
modelBuilder.Entity<TUser>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_NormalizedEmailAddress", 1);
modelBuilder.Entity<TUser>()
.Property(e => e.NormalizedEmailAddress)
.CreateIndex("IX_TenantId_NormalizedEmailAddress", 2);
#endregion
#region UserToken.IX_TenantId_UserId
modelBuilder.Entity<UserToken>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserId", 1);
modelBuilder.Entity<UserToken>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_UserId", 2);
#endregion
#region DynamicEntityProperties
modelBuilder.Entity<DynamicProperty>()
.HasIndex(e => new {e.PropertyName, e.TenantId})
.IsUnique();
modelBuilder.Entity<DynamicEntityProperty>()
.HasIndex(e => new {e.EntityFullName, e.DynamicPropertyId, e.TenantId})
.IsUnique();
#endregion
#region UserLogin.ProviderKey_TenantId
modelBuilder.Entity<UserLogin>()
.HasIndex(e => new {e.ProviderKey, e.TenantId})
.IsUnique();
#endregion
}
}
}
| |
using System;
using System.Threading;
using Microsoft.Extensions.Logging;
using Orleans.Threading;
namespace Orleans.Runtime
{
internal abstract class AsynchAgent : IHealthCheckable, IDisposable
{
public enum FaultBehavior
{
CrashOnFault, // Crash the process if the agent faults
RestartOnFault, // Restart the agent if it faults
IgnoreFault // Allow the agent to stop if it faults, but take no other action (other than logging)
}
private readonly ExecutorFaultHandler executorFaultHandler;
protected readonly ExecutorService executorService;
protected ThreadPoolExecutor executor;
protected CancellationTokenSource Cts;
protected object Lockable;
protected ILogger Log;
protected ILoggerFactory loggerFactory;
protected readonly string type;
protected FaultBehavior OnFault;
protected bool disposed;
public ThreadState State { get; protected set; }
internal string Name { get; private set; }
protected AsynchAgent(string nameSuffix, ExecutorService executorService, ILoggerFactory loggerFactory)
{
Cts = new CancellationTokenSource();
var thisType = GetType();
type = thisType.Namespace + "." + thisType.Name;
if (type.StartsWith("Orleans.", StringComparison.Ordinal))
{
type = type.Substring(8);
}
if (!string.IsNullOrEmpty(nameSuffix))
{
Name = type + "/" + nameSuffix;
}
else
{
Name = type;
}
Lockable = new object();
State = ThreadState.Unstarted;
OnFault = FaultBehavior.IgnoreFault;
this.loggerFactory = loggerFactory;
this.Log = loggerFactory.CreateLogger(Name);
this.executorService = executorService;
this.executorFaultHandler = new ExecutorFaultHandler(this);
}
protected AsynchAgent(ExecutorService executorService, ILoggerFactory loggerFactory)
: this(null, executorService, loggerFactory)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
try
{
if (State != ThreadState.Stopped)
{
Stop();
}
}
catch (Exception exc)
{
// ignore. Just make sure DomainUnload handler does not throw.
Log.Debug("Ignoring error during Stop: {0}", exc);
}
}
public virtual void Start()
{
ThrowIfDisposed();
lock (Lockable)
{
if (State == ThreadState.Running)
{
return;
}
if (State == ThreadState.Stopped)
{
Cts = new CancellationTokenSource();
}
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
LogStatus(Log, "Starting AsyncAgent {0} on managed thread {1}", Name, Thread.CurrentThread.ManagedThreadId);
EnsureExecutorInitialized();
OnStart();
State = ThreadState.Running;
}
if (Log.IsEnabled(LogLevel.Debug)) Log.Debug("Started asynch agent " + this.Name);
}
public virtual void OnStart() { }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public virtual void Stop()
{
try
{
ThrowIfDisposed();
lock (Lockable)
{
if (State == ThreadState.Running)
{
State = ThreadState.StopRequested;
Cts.Cancel();
executor = null;
State = ThreadState.Stopped;
}
}
AppDomain.CurrentDomain.DomainUnload -= CurrentDomain_DomainUnload;
}
catch (Exception exc)
{
// ignore. Just make sure stop does not throw.
Log.Debug("Ignoring error during Stop: {0}", exc);
}
Log.Debug("Stopped agent");
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing || disposed) return;
if (Cts != null)
{
Cts.Dispose();
Cts = null;
}
disposed = true;
}
public override string ToString()
{
return Name;
}
public bool CheckHealth(DateTime lastCheckTime)
{
return executor.CheckHealth(lastCheckTime);
}
internal static bool IsStarting { get; set; }
protected virtual ThreadPoolExecutorOptions.Builder ExecutorOptionsBuilder =>
new ThreadPoolExecutorOptions.Builder(Name, GetType(), Cts, loggerFactory).WithExceptionFilters(executorFaultHandler);
private sealed class ExecutorFaultHandler : ExecutionExceptionFilter
{
private readonly AsynchAgent agent;
public ExecutorFaultHandler(AsynchAgent agent)
{
this.agent = agent;
}
public override bool ExceptionHandler(Exception ex, Threading.ExecutionContext context)
{
if(!agent.HandleFault(ex, context))
{
context.CancellationTokenSource.Cancel();
}
return true;
}
}
/// <summary>
/// Handles fault
/// </summary>
/// <param name="ex"></param>
/// <param name="context"></param>
/// <returns>false agent has been stopped</returns>
protected bool HandleFault(Exception ex, Threading.ExecutionContext context)
{
State = ThreadState.Stopped;
if (ex is ThreadAbortException)
{
return false;
}
LogExecutorError(ex);
if (OnFault == FaultBehavior.RestartOnFault && !Cts.IsCancellationRequested)
{
try
{
Start();
}
catch (Exception exc)
{
Log.Error(ErrorCode.Runtime_Error_100027, "Unable to restart AsynchAgent", exc);
State = ThreadState.Stopped;
}
}
return State != ThreadState.Stopped;
}
private void EnsureExecutorInitialized()
{
if (executor == null)
{
executor = executorService.GetExecutor(ExecutorOptionsBuilder.Options);
}
}
private void LogExecutorError(Exception exc)
{
var logMessagePrefix = $"Asynch agent {Name} encountered unexpected exception";
switch (OnFault)
{
case FaultBehavior.CrashOnFault:
var logMessage = $"{logMessagePrefix} The process will be terminated.";
Console.WriteLine(logMessage, exc);
Log.Error(ErrorCode.Runtime_Error_100023, logMessage, exc);
Log.Fail(ErrorCode.Runtime_Error_100024, logMessage);
break;
case FaultBehavior.IgnoreFault:
Log.Error(ErrorCode.Runtime_Error_100025, $"{logMessagePrefix} The executor will exit.", exc);
break;
case FaultBehavior.RestartOnFault:
Log.Error(ErrorCode.Runtime_Error_100026, $"{logMessagePrefix} The Stage will be restarted.", exc);
break;
default:
throw new NotImplementedException();
}
}
private static void LogStatus(ILogger log, string msg, params object[] args)
{
if (IsStarting)
{
// Reduce log noise during silo startup
if (log.IsEnabled(LogLevel.Debug)) log.Debug(msg, args);
}
else
{
// Changes in agent threads during all operations aside for initial creation are usually important diag events.
log.Info(msg, args);
}
}
private void ThrowIfDisposed()
{
if (disposed)
{
throw new ObjectDisposedException("Cannot access disposed AsynchAgent");
}
}
}
}
| |
namespace android.view
{
[global::MonoJavaBridge.JavaClass()]
public partial class ScaleGestureDetector : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ScaleGestureDetector()
{
InitJNI();
}
protected ScaleGestureDetector(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.ScaleGestureDetector.OnScaleGestureListener_))]
public interface OnScaleGestureListener : global::MonoJavaBridge.IJavaObject
{
bool onScale(android.view.ScaleGestureDetector arg0);
bool onScaleBegin(android.view.ScaleGestureDetector arg0);
void onScaleEnd(android.view.ScaleGestureDetector arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.ScaleGestureDetector.OnScaleGestureListener))]
public sealed partial class OnScaleGestureListener_ : java.lang.Object, OnScaleGestureListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnScaleGestureListener_()
{
InitJNI();
}
internal OnScaleGestureListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onScale8980;
bool android.view.ScaleGestureDetector.OnScaleGestureListener.onScale(android.view.ScaleGestureDetector arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.OnScaleGestureListener_._onScale8980, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.OnScaleGestureListener_.staticClass, global::android.view.ScaleGestureDetector.OnScaleGestureListener_._onScale8980, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onScaleBegin8981;
bool android.view.ScaleGestureDetector.OnScaleGestureListener.onScaleBegin(android.view.ScaleGestureDetector arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.OnScaleGestureListener_._onScaleBegin8981, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.OnScaleGestureListener_.staticClass, global::android.view.ScaleGestureDetector.OnScaleGestureListener_._onScaleBegin8981, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onScaleEnd8982;
void android.view.ScaleGestureDetector.OnScaleGestureListener.onScaleEnd(android.view.ScaleGestureDetector arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.OnScaleGestureListener_._onScaleEnd8982, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.OnScaleGestureListener_.staticClass, global::android.view.ScaleGestureDetector.OnScaleGestureListener_._onScaleEnd8982, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.ScaleGestureDetector.OnScaleGestureListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ScaleGestureDetector$OnScaleGestureListener"));
global::android.view.ScaleGestureDetector.OnScaleGestureListener_._onScale8980 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.OnScaleGestureListener_.staticClass, "onScale", "(Landroid/view/ScaleGestureDetector;)Z");
global::android.view.ScaleGestureDetector.OnScaleGestureListener_._onScaleBegin8981 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.OnScaleGestureListener_.staticClass, "onScaleBegin", "(Landroid/view/ScaleGestureDetector;)Z");
global::android.view.ScaleGestureDetector.OnScaleGestureListener_._onScaleEnd8982 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.OnScaleGestureListener_.staticClass, "onScaleEnd", "(Landroid/view/ScaleGestureDetector;)V");
}
}
[global::MonoJavaBridge.JavaClass()]
public partial class SimpleOnScaleGestureListener : java.lang.Object, OnScaleGestureListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static SimpleOnScaleGestureListener()
{
InitJNI();
}
protected SimpleOnScaleGestureListener(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onScale8983;
public virtual bool onScale(android.view.ScaleGestureDetector arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener._onScale8983, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener.staticClass, global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener._onScale8983, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onScaleBegin8984;
public virtual bool onScaleBegin(android.view.ScaleGestureDetector arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener._onScaleBegin8984, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener.staticClass, global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener._onScaleBegin8984, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onScaleEnd8985;
public virtual void onScaleEnd(android.view.ScaleGestureDetector arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener._onScaleEnd8985, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener.staticClass, global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener._onScaleEnd8985, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _SimpleOnScaleGestureListener8986;
public SimpleOnScaleGestureListener() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.ScaleGestureDetector.SimpleOnScaleGestureListener.staticClass, global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener._SimpleOnScaleGestureListener8986);
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ScaleGestureDetector$SimpleOnScaleGestureListener"));
global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener._onScale8983 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener.staticClass, "onScale", "(Landroid/view/ScaleGestureDetector;)Z");
global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener._onScaleBegin8984 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener.staticClass, "onScaleBegin", "(Landroid/view/ScaleGestureDetector;)Z");
global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener._onScaleEnd8985 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener.staticClass, "onScaleEnd", "(Landroid/view/ScaleGestureDetector;)V");
global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener._SimpleOnScaleGestureListener8986 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.SimpleOnScaleGestureListener.staticClass, "<init>", "()V");
}
}
internal static global::MonoJavaBridge.MethodId _getEventTime8987;
public virtual long getEventTime()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.view.ScaleGestureDetector._getEventTime8987);
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.staticClass, global::android.view.ScaleGestureDetector._getEventTime8987);
}
internal static global::MonoJavaBridge.MethodId _onTouchEvent8988;
public virtual bool onTouchEvent(android.view.MotionEvent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.ScaleGestureDetector._onTouchEvent8988, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.staticClass, global::android.view.ScaleGestureDetector._onTouchEvent8988, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isInProgress8989;
public virtual bool isInProgress()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.ScaleGestureDetector._isInProgress8989);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.staticClass, global::android.view.ScaleGestureDetector._isInProgress8989);
}
internal static global::MonoJavaBridge.MethodId _getFocusX8990;
public virtual float getFocusX()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.view.ScaleGestureDetector._getFocusX8990);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.staticClass, global::android.view.ScaleGestureDetector._getFocusX8990);
}
internal static global::MonoJavaBridge.MethodId _getFocusY8991;
public virtual float getFocusY()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.view.ScaleGestureDetector._getFocusY8991);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.staticClass, global::android.view.ScaleGestureDetector._getFocusY8991);
}
internal static global::MonoJavaBridge.MethodId _getCurrentSpan8992;
public virtual float getCurrentSpan()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.view.ScaleGestureDetector._getCurrentSpan8992);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.staticClass, global::android.view.ScaleGestureDetector._getCurrentSpan8992);
}
internal static global::MonoJavaBridge.MethodId _getPreviousSpan8993;
public virtual float getPreviousSpan()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.view.ScaleGestureDetector._getPreviousSpan8993);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.staticClass, global::android.view.ScaleGestureDetector._getPreviousSpan8993);
}
internal static global::MonoJavaBridge.MethodId _getScaleFactor8994;
public virtual float getScaleFactor()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.view.ScaleGestureDetector._getScaleFactor8994);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.staticClass, global::android.view.ScaleGestureDetector._getScaleFactor8994);
}
internal static global::MonoJavaBridge.MethodId _getTimeDelta8995;
public virtual long getTimeDelta()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.view.ScaleGestureDetector._getTimeDelta8995);
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.view.ScaleGestureDetector.staticClass, global::android.view.ScaleGestureDetector._getTimeDelta8995);
}
internal static global::MonoJavaBridge.MethodId _ScaleGestureDetector8996;
public ScaleGestureDetector(android.content.Context arg0, android.view.ScaleGestureDetector.OnScaleGestureListener arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.ScaleGestureDetector.staticClass, global::android.view.ScaleGestureDetector._ScaleGestureDetector8996, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.ScaleGestureDetector.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ScaleGestureDetector"));
global::android.view.ScaleGestureDetector._getEventTime8987 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.staticClass, "getEventTime", "()J");
global::android.view.ScaleGestureDetector._onTouchEvent8988 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z");
global::android.view.ScaleGestureDetector._isInProgress8989 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.staticClass, "isInProgress", "()Z");
global::android.view.ScaleGestureDetector._getFocusX8990 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.staticClass, "getFocusX", "()F");
global::android.view.ScaleGestureDetector._getFocusY8991 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.staticClass, "getFocusY", "()F");
global::android.view.ScaleGestureDetector._getCurrentSpan8992 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.staticClass, "getCurrentSpan", "()F");
global::android.view.ScaleGestureDetector._getPreviousSpan8993 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.staticClass, "getPreviousSpan", "()F");
global::android.view.ScaleGestureDetector._getScaleFactor8994 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.staticClass, "getScaleFactor", "()F");
global::android.view.ScaleGestureDetector._getTimeDelta8995 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.staticClass, "getTimeDelta", "()J");
global::android.view.ScaleGestureDetector._ScaleGestureDetector8996 = @__env.GetMethodIDNoThrow(global::android.view.ScaleGestureDetector.staticClass, "<init>", "(Landroid/content/Context;Landroid/view/ScaleGestureDetector$OnScaleGestureListener;)V");
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmBarcodeLoad
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmBarcodeLoad() : base()
{
FormClosed += frmBarcodeLoad_FormClosed;
Load += frmBarcodeLoad_Load;
KeyPress += frmBarcodeLoad_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.RadioButton _Option1_11;
public System.Windows.Forms.RadioButton _Option1_10;
public System.Windows.Forms.RadioButton _Option1_9;
public System.Windows.Forms.RadioButton _Option1_8;
public System.Windows.Forms.RadioButton _Option1_7;
public System.Windows.Forms.RadioButton _Option1_6;
public System.Windows.Forms.RadioButton _Option1_5;
public System.Windows.Forms.RadioButton _Option1_4;
public System.Windows.Forms.RadioButton _Option1_3;
public System.Windows.Forms.RadioButton _Option1_2;
public System.Windows.Forms.RadioButton _Option1_1;
public System.Windows.Forms.RadioButton _Option1_0;
public System.Windows.Forms.GroupBox Frame1;
public System.Windows.Forms.CheckBox _chkFields_0;
public System.Windows.Forms.CheckBox _chkFields_1;
public System.Windows.Forms.CheckBox _chkFields_2;
public System.Windows.Forms.CheckBox _chkFields_3;
public System.Windows.Forms.CheckBox _chkFields_4;
public System.Windows.Forms.CheckBox _chkFields_5;
private System.Windows.Forms.TextBox withEventsField_txtpos;
public System.Windows.Forms.TextBox txtpos {
get { return withEventsField_txtpos; }
set {
if (withEventsField_txtpos != null) {
withEventsField_txtpos.Leave -= txtpos_Leave;
}
withEventsField_txtpos = value;
if (withEventsField_txtpos != null) {
withEventsField_txtpos.Leave += txtpos_Leave;
}
}
}
private System.Windows.Forms.ComboBox withEventsField_cmbfont;
public System.Windows.Forms.ComboBox cmbfont {
get { return withEventsField_cmbfont; }
set {
if (withEventsField_cmbfont != null) {
withEventsField_cmbfont.Leave -= cmbfont_Leave;
}
withEventsField_cmbfont = value;
if (withEventsField_cmbfont != null) {
withEventsField_cmbfont.Leave += cmbfont_Leave;
}
}
}
public System.Windows.Forms.RadioButton _Option2_2;
public System.Windows.Forms.RadioButton _Option2_1;
public System.Windows.Forms.RadioButton _Option2_0;
public System.Windows.Forms.Label Label6;
public System.Windows.Forms.Label Label5;
public System.Windows.Forms.GroupBox frmDeposits;
private System.Windows.Forms.HScrollBar withEventsField_HSLeft;
public System.Windows.Forms.HScrollBar HSLeft {
get { return withEventsField_HSLeft; }
set {
if (withEventsField_HSLeft != null) {
withEventsField_HSLeft.Scroll -= HSLeft_Scroll;
}
withEventsField_HSLeft = value;
if (withEventsField_HSLeft != null) {
withEventsField_HSLeft.Scroll += HSLeft_Scroll;
}
}
}
private System.Windows.Forms.HScrollBar withEventsField_HSTop;
public System.Windows.Forms.HScrollBar HSTop {
get { return withEventsField_HSTop; }
set {
if (withEventsField_HSTop != null) {
withEventsField_HSTop.Scroll -= HSTop_Scroll;
}
withEventsField_HSTop = value;
if (withEventsField_HSTop != null) {
withEventsField_HSTop.Scroll += HSTop_Scroll;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdundo;
public System.Windows.Forms.Button cmdundo {
get { return withEventsField_cmdundo; }
set {
if (withEventsField_cmdundo != null) {
withEventsField_cmdundo.Click -= cmdUndo_Click;
}
withEventsField_cmdundo = value;
if (withEventsField_cmdundo != null) {
withEventsField_cmdundo.Click += cmdUndo_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdnormal;
public System.Windows.Forms.Button cmdnormal {
get { return withEventsField_cmdnormal; }
set {
if (withEventsField_cmdnormal != null) {
withEventsField_cmdnormal.Click -= cmdnormal_Click;
}
withEventsField_cmdnormal = value;
if (withEventsField_cmdnormal != null) {
withEventsField_cmdnormal.Click += cmdnormal_Click;
}
}
}
public System.Windows.Forms.ComboBox cmbpos;
private System.Windows.Forms.Button withEventsField_cmdadd;
public System.Windows.Forms.Button cmdadd {
get { return withEventsField_cmdadd; }
set {
if (withEventsField_cmdadd != null) {
withEventsField_cmdadd.Click -= cmdAdd_Click;
}
withEventsField_cmdadd = value;
if (withEventsField_cmdadd != null) {
withEventsField_cmdadd.Click += cmdAdd_Click;
}
}
}
public System.Windows.Forms.OpenFileDialog cmdDlgOpen;
public System.Windows.Forms.SaveFileDialog cmdDlgSave;
public System.Windows.Forms.FontDialog cmdDlgFont;
public System.Windows.Forms.ColorDialog cmdDlgColor;
public System.Windows.Forms.PrintDialog cmdDlgPrint;
private System.Windows.Forms.Button withEventsField_cmdSave;
public System.Windows.Forms.Button cmdSave {
get { return withEventsField_cmdSave; }
set {
if (withEventsField_cmdSave != null) {
withEventsField_cmdSave.Click -= cmdSave_Click;
}
withEventsField_cmdSave = value;
if (withEventsField_cmdSave != null) {
withEventsField_cmdSave.Click += cmdSave_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
private System.Windows.Forms.HScrollBar withEventsField_HSHeight;
public System.Windows.Forms.HScrollBar HSHeight {
get { return withEventsField_HSHeight; }
set {
if (withEventsField_HSHeight != null) {
withEventsField_HSHeight.Scroll -= HSHeight_Scroll;
}
withEventsField_HSHeight = value;
if (withEventsField_HSHeight != null) {
withEventsField_HSHeight.Scroll += HSHeight_Scroll;
}
}
}
private System.Windows.Forms.HScrollBar withEventsField_HSselect;
public System.Windows.Forms.HScrollBar HSselect {
get { return withEventsField_HSselect; }
set {
if (withEventsField_HSselect != null) {
withEventsField_HSselect.Scroll -= HSselect_Scroll;
}
withEventsField_HSselect = value;
if (withEventsField_HSselect != null) {
withEventsField_HSselect.Scroll += HSselect_Scroll;
}
}
}
public System.Windows.Forms.PictureBox _picSelect_0;
public System.Windows.Forms.Panel picInner;
public System.Windows.Forms.Panel picOuter;
private System.Windows.Forms.HScrollBar withEventsField_HSWidth;
public System.Windows.Forms.HScrollBar HSWidth {
get { return withEventsField_HSWidth; }
set {
if (withEventsField_HSWidth != null) {
withEventsField_HSWidth.Scroll -= HSWidth_Scroll;
}
withEventsField_HSWidth = value;
if (withEventsField_HSWidth != null) {
withEventsField_HSWidth.Scroll += HSWidth_Scroll;
}
}
}
public System.Windows.Forms.Label _lbl_7;
public System.Windows.Forms.Label lblLeft;
public System.Windows.Forms.Label _lbl_6;
public System.Windows.Forms.Label _lbl_5;
public System.Windows.Forms.Label lblTop;
public System.Windows.Forms.Label _lbl_4;
public System.Windows.Forms.Label Label8;
public System.Windows.Forms.Label lblLineNo;
public System.Windows.Forms.Label Label7;
public System.Windows.Forms.Label Label1;
public System.Windows.Forms.Label lblWidth;
public System.Windows.Forms.Label _lbl_0;
public System.Windows.Forms.Label _lbl_1;
public System.Windows.Forms.Label _lbl_2;
public System.Windows.Forms.Label _lbl_3;
public System.Windows.Forms.Label lblHeight;
public System.Windows.Forms.Label lbldesign;
//Public WithEvents Option1 As Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray
//Public WithEvents Option2 As Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray
//Public WithEvents chkFields As Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents picSelect As Microsoft.VisualBasic.Compatibility.VB6.PictureBoxArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmBarcodeLoad));
this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.Frame1 = new System.Windows.Forms.GroupBox();
this._Option1_11 = new System.Windows.Forms.RadioButton();
this._Option1_10 = new System.Windows.Forms.RadioButton();
this._Option1_9 = new System.Windows.Forms.RadioButton();
this._Option1_8 = new System.Windows.Forms.RadioButton();
this._Option1_7 = new System.Windows.Forms.RadioButton();
this._Option1_6 = new System.Windows.Forms.RadioButton();
this._Option1_5 = new System.Windows.Forms.RadioButton();
this._Option1_4 = new System.Windows.Forms.RadioButton();
this._Option1_3 = new System.Windows.Forms.RadioButton();
this._Option1_2 = new System.Windows.Forms.RadioButton();
this._Option1_1 = new System.Windows.Forms.RadioButton();
this._Option1_0 = new System.Windows.Forms.RadioButton();
this.frmDeposits = new System.Windows.Forms.GroupBox();
this._chkFields_4 = new System.Windows.Forms.CheckBox();
this._chkFields_0 = new System.Windows.Forms.CheckBox();
this.txtpos = new System.Windows.Forms.TextBox();
this.cmbfont = new System.Windows.Forms.ComboBox();
this._Option2_2 = new System.Windows.Forms.RadioButton();
this._Option2_1 = new System.Windows.Forms.RadioButton();
this._Option2_0 = new System.Windows.Forms.RadioButton();
this.Label6 = new System.Windows.Forms.Label();
this.Label5 = new System.Windows.Forms.Label();
this._chkFields_1 = new System.Windows.Forms.CheckBox();
this._chkFields_2 = new System.Windows.Forms.CheckBox();
this._chkFields_3 = new System.Windows.Forms.CheckBox();
this._chkFields_5 = new System.Windows.Forms.CheckBox();
this.HSLeft = new System.Windows.Forms.HScrollBar();
this.HSTop = new System.Windows.Forms.HScrollBar();
this.cmdundo = new System.Windows.Forms.Button();
this.cmdnormal = new System.Windows.Forms.Button();
this.cmbpos = new System.Windows.Forms.ComboBox();
this.cmdadd = new System.Windows.Forms.Button();
this.cmdDlgOpen = new System.Windows.Forms.OpenFileDialog();
this.cmdDlgSave = new System.Windows.Forms.SaveFileDialog();
this.cmdDlgFont = new System.Windows.Forms.FontDialog();
this.cmdDlgColor = new System.Windows.Forms.ColorDialog();
this.cmdDlgPrint = new System.Windows.Forms.PrintDialog();
this.cmdSave = new System.Windows.Forms.Button();
this.cmdExit = new System.Windows.Forms.Button();
this.HSHeight = new System.Windows.Forms.HScrollBar();
this.HSselect = new System.Windows.Forms.HScrollBar();
this.picOuter = new System.Windows.Forms.Panel();
this.picInner = new System.Windows.Forms.Panel();
this._picSelect_0 = new System.Windows.Forms.PictureBox();
this.HSWidth = new System.Windows.Forms.HScrollBar();
this._lbl_7 = new System.Windows.Forms.Label();
this.lblLeft = new System.Windows.Forms.Label();
this._lbl_6 = new System.Windows.Forms.Label();
this._lbl_5 = new System.Windows.Forms.Label();
this.lblTop = new System.Windows.Forms.Label();
this._lbl_4 = new System.Windows.Forms.Label();
this.Label8 = new System.Windows.Forms.Label();
this.lblLineNo = new System.Windows.Forms.Label();
this.Label7 = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
this.lblWidth = new System.Windows.Forms.Label();
this._lbl_0 = new System.Windows.Forms.Label();
this._lbl_1 = new System.Windows.Forms.Label();
this._lbl_2 = new System.Windows.Forms.Label();
this._lbl_3 = new System.Windows.Forms.Label();
this.lblHeight = new System.Windows.Forms.Label();
this.lbldesign = new System.Windows.Forms.Label();
this.Frame1.SuspendLayout();
this.frmDeposits.SuspendLayout();
this.picOuter.SuspendLayout();
this.picInner.SuspendLayout();
((System.ComponentModel.ISupportInitialize)this._picSelect_0).BeginInit();
this.SuspendLayout();
//
//Frame1
//
this.Frame1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.Frame1.Controls.Add(this._Option1_11);
this.Frame1.Controls.Add(this._Option1_10);
this.Frame1.Controls.Add(this._Option1_9);
this.Frame1.Controls.Add(this._Option1_8);
this.Frame1.Controls.Add(this._Option1_7);
this.Frame1.Controls.Add(this._Option1_6);
this.Frame1.Controls.Add(this._Option1_5);
this.Frame1.Controls.Add(this._Option1_4);
this.Frame1.Controls.Add(this._Option1_3);
this.Frame1.Controls.Add(this._Option1_2);
this.Frame1.Controls.Add(this._Option1_1);
this.Frame1.Controls.Add(this._Option1_0);
this.Frame1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Frame1.Location = new System.Drawing.Point(568, 24);
this.Frame1.Name = "Frame1";
this.Frame1.Padding = new System.Windows.Forms.Padding(0);
this.Frame1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Frame1.Size = new System.Drawing.Size(142, 300);
this.Frame1.TabIndex = 41;
this.Frame1.TabStop = false;
this.Frame1.Text = "Select Field to Format";
//
//_Option1_11
//
this._Option1_11.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option1_11.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option1_11.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_11.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_11.Location = new System.Drawing.Point(8, 280);
this._Option1_11.Name = "_Option1_11";
this._Option1_11.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_11.Size = new System.Drawing.Size(129, 17);
this._Option1_11.TabIndex = 53;
this._Option1_11.TabStop = true;
this._Option1_11.Text = "&Price for 24:";
this._Option1_11.UseVisualStyleBackColor = false;
//
//_Option1_10
//
this._Option1_10.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option1_10.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option1_10.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_10.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_10.Location = new System.Drawing.Point(8, 256);
this._Option1_10.Name = "_Option1_10";
this._Option1_10.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_10.Size = new System.Drawing.Size(129, 17);
this._Option1_10.TabIndex = 52;
this._Option1_10.TabStop = true;
this._Option1_10.Text = "&Price for 12:";
this._Option1_10.UseVisualStyleBackColor = false;
//
//_Option1_9
//
this._Option1_9.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option1_9.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option1_9.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_9.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_9.Location = new System.Drawing.Point(8, 232);
this._Option1_9.Name = "_Option1_9";
this._Option1_9.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_9.Size = new System.Drawing.Size(129, 17);
this._Option1_9.TabIndex = 51;
this._Option1_9.TabStop = true;
this._Option1_9.Text = "&Price for 6:";
this._Option1_9.UseVisualStyleBackColor = false;
//
//_Option1_8
//
this._Option1_8.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option1_8.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option1_8.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_8.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_8.Location = new System.Drawing.Point(8, 184);
this._Option1_8.Name = "_Option1_8";
this._Option1_8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_8.Size = new System.Drawing.Size(129, 17);
this._Option1_8.TabIndex = 50;
this._Option1_8.TabStop = true;
this._Option1_8.Text = "Blan&k";
this._Option1_8.UseVisualStyleBackColor = false;
//
//_Option1_7
//
this._Option1_7.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option1_7.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option1_7.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_7.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_7.Location = new System.Drawing.Point(8, 160);
this._Option1_7.Name = "_Option1_7";
this._Option1_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_7.Size = new System.Drawing.Size(129, 17);
this._Option1_7.TabIndex = 49;
this._Option1_7.TabStop = true;
this._Option1_7.Text = "Bar&code:";
this._Option1_7.UseVisualStyleBackColor = false;
//
//_Option1_6
//
this._Option1_6.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option1_6.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option1_6.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_6.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_6.Location = new System.Drawing.Point(8, 136);
this._Option1_6.Name = "_Option1_6";
this._Option1_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_6.Size = new System.Drawing.Size(129, 17);
this._Option1_6.TabIndex = 48;
this._Option1_6.TabStop = true;
this._Option1_6.Text = "&Line:";
this._Option1_6.UseVisualStyleBackColor = false;
//
//_Option1_5
//
this._Option1_5.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option1_5.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option1_5.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_5.Location = new System.Drawing.Point(8, 112);
this._Option1_5.Name = "_Option1_5";
this._Option1_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_5.Size = new System.Drawing.Size(129, 17);
this._Option1_5.TabIndex = 47;
this._Option1_5.TabStop = true;
this._Option1_5.Text = "&Group:";
this._Option1_5.UseVisualStyleBackColor = false;
//
//_Option1_4
//
this._Option1_4.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option1_4.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option1_4.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_4.Location = new System.Drawing.Point(8, 208);
this._Option1_4.Name = "_Option1_4";
this._Option1_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_4.Size = new System.Drawing.Size(129, 17);
this._Option1_4.TabIndex = 46;
this._Option1_4.TabStop = true;
this._Option1_4.Text = "&Price for 1:";
this._Option1_4.UseVisualStyleBackColor = false;
//
//_Option1_3
//
this._Option1_3.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option1_3.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option1_3.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_3.Location = new System.Drawing.Point(8, 88);
this._Option1_3.Name = "_Option1_3";
this._Option1_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_3.Size = new System.Drawing.Size(129, 17);
this._Option1_3.TabIndex = 45;
this._Option1_3.TabStop = true;
this._Option1_3.Text = "&Telephone:";
this._Option1_3.UseVisualStyleBackColor = false;
//
//_Option1_2
//
this._Option1_2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option1_2.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option1_2.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_2.Location = new System.Drawing.Point(8, 64);
this._Option1_2.Name = "_Option1_2";
this._Option1_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_2.Size = new System.Drawing.Size(129, 17);
this._Option1_2.TabIndex = 44;
this._Option1_2.TabStop = true;
this._Option1_2.Text = "Barcode &No:";
this._Option1_2.UseVisualStyleBackColor = false;
//
//_Option1_1
//
this._Option1_1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option1_1.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option1_1.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_1.Location = new System.Drawing.Point(8, 40);
this._Option1_1.Name = "_Option1_1";
this._Option1_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_1.Size = new System.Drawing.Size(129, 17);
this._Option1_1.TabIndex = 43;
this._Option1_1.TabStop = true;
this._Option1_1.Text = "Stock &Item Name:";
this._Option1_1.UseVisualStyleBackColor = false;
//
//_Option1_0
//
this._Option1_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option1_0.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option1_0.Cursor = System.Windows.Forms.Cursors.Default;
this._Option1_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._Option1_0.Location = new System.Drawing.Point(8, 16);
this._Option1_0.Name = "_Option1_0";
this._Option1_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option1_0.Size = new System.Drawing.Size(129, 17);
this._Option1_0.TabIndex = 42;
this._Option1_0.TabStop = true;
this._Option1_0.Text = "Company Na&me:";
this._Option1_0.UseVisualStyleBackColor = false;
//
//frmDeposits
//
this.frmDeposits.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.frmDeposits.Controls.Add(this._chkFields_4);
this.frmDeposits.Controls.Add(this._chkFields_0);
this.frmDeposits.Controls.Add(this.txtpos);
this.frmDeposits.Controls.Add(this.cmbfont);
this.frmDeposits.Controls.Add(this._Option2_2);
this.frmDeposits.Controls.Add(this._Option2_1);
this.frmDeposits.Controls.Add(this._Option2_0);
this.frmDeposits.Controls.Add(this.Label6);
this.frmDeposits.Controls.Add(this.Label5);
this.frmDeposits.ForeColor = System.Drawing.SystemColors.ControlText;
this.frmDeposits.Location = new System.Drawing.Point(568, 328);
this.frmDeposits.Name = "frmDeposits";
this.frmDeposits.Padding = new System.Windows.Forms.Padding(0);
this.frmDeposits.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.frmDeposits.Size = new System.Drawing.Size(142, 185);
this.frmDeposits.TabIndex = 31;
this.frmDeposits.TabStop = false;
this.frmDeposits.Text = "Font";
//
//_chkFields_4
//
this._chkFields_4.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._chkFields_4.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._chkFields_4.Cursor = System.Windows.Forms.Cursors.Default;
this._chkFields_4.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._chkFields_4.ForeColor = System.Drawing.SystemColors.WindowText;
this._chkFields_4.Location = new System.Drawing.Point(8, 160);
this._chkFields_4.Name = "_chkFields_4";
this._chkFields_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._chkFields_4.Size = new System.Drawing.Size(129, 19);
this._chkFields_4.TabIndex = 40;
this._chkFields_4.Text = "Add/Remo&ve:";
this._chkFields_4.UseVisualStyleBackColor = false;
//
//_chkFields_0
//
this._chkFields_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._chkFields_0.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._chkFields_0.Cursor = System.Windows.Forms.Cursors.Default;
this._chkFields_0.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._chkFields_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._chkFields_0.Location = new System.Drawing.Point(8, 64);
this._chkFields_0.Name = "_chkFields_0";
this._chkFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._chkFields_0.Size = new System.Drawing.Size(129, 19);
this._chkFields_0.TabIndex = 39;
this._chkFields_0.Tag = "Company_Name";
this._chkFields_0.Text = "B&old:";
this._chkFields_0.UseVisualStyleBackColor = false;
//
//txtpos
//
this.txtpos.AcceptsReturn = true;
this.txtpos.BackColor = System.Drawing.SystemColors.Window;
this.txtpos.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtpos.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtpos.Location = new System.Drawing.Point(72, 48);
this.txtpos.MaxLength = 0;
this.txtpos.Name = "txtpos";
this.txtpos.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtpos.Size = new System.Drawing.Size(65, 19);
this.txtpos.TabIndex = 37;
this.txtpos.Text = "1";
//
//cmbfont
//
this.cmbfont.BackColor = System.Drawing.SystemColors.Window;
this.cmbfont.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbfont.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbfont.Items.AddRange(new object[] {
"8",
"10",
"12"
});
this.cmbfont.Location = new System.Drawing.Point(72, 24);
this.cmbfont.Name = "cmbfont";
this.cmbfont.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbfont.Size = new System.Drawing.Size(65, 21);
this.cmbfont.TabIndex = 35;
this.cmbfont.Text = "8";
//
//_Option2_2
//
this._Option2_2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option2_2.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option2_2.Cursor = System.Windows.Forms.Cursors.Default;
this._Option2_2.ForeColor = System.Drawing.SystemColors.WindowText;
this._Option2_2.Location = new System.Drawing.Point(8, 136);
this._Option2_2.Name = "_Option2_2";
this._Option2_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option2_2.Size = new System.Drawing.Size(129, 17);
this._Option2_2.TabIndex = 34;
this._Option2_2.TabStop = true;
this._Option2_2.Text = "Align &Right:";
this._Option2_2.UseVisualStyleBackColor = false;
//
//_Option2_1
//
this._Option2_1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option2_1.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option2_1.Cursor = System.Windows.Forms.Cursors.Default;
this._Option2_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._Option2_1.Location = new System.Drawing.Point(8, 112);
this._Option2_1.Name = "_Option2_1";
this._Option2_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option2_1.Size = new System.Drawing.Size(129, 17);
this._Option2_1.TabIndex = 33;
this._Option2_1.TabStop = true;
this._Option2_1.Text = "Align &Center:";
this._Option2_1.UseVisualStyleBackColor = false;
//
//_Option2_0
//
this._Option2_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Option2_0.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._Option2_0.Cursor = System.Windows.Forms.Cursors.Default;
this._Option2_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._Option2_0.Location = new System.Drawing.Point(8, 88);
this._Option2_0.Name = "_Option2_0";
this._Option2_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Option2_0.Size = new System.Drawing.Size(129, 17);
this._Option2_0.TabIndex = 32;
this._Option2_0.TabStop = true;
this._Option2_0.Text = "Align Le&ft:";
this._Option2_0.UseVisualStyleBackColor = false;
//
//Label6
//
this.Label6.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.Label6.Cursor = System.Windows.Forms.Cursors.Default;
this.Label6.ForeColor = System.Drawing.SystemColors.WindowText;
this.Label6.Location = new System.Drawing.Point(8, 48);
this.Label6.Name = "Label6";
this.Label6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label6.Size = new System.Drawing.Size(65, 17);
this.Label6.TabIndex = 38;
this.Label6.Text = "Ro&w Position:";
//
//Label5
//
this.Label5.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.Label5.Cursor = System.Windows.Forms.Cursors.Default;
this.Label5.ForeColor = System.Drawing.SystemColors.WindowText;
this.Label5.Location = new System.Drawing.Point(8, 24);
this.Label5.Name = "Label5";
this.Label5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label5.Size = new System.Drawing.Size(65, 17);
this.Label5.TabIndex = 36;
this.Label5.Text = "Font Si&ze:";
//
//_chkFields_1
//
this._chkFields_1.Location = new System.Drawing.Point(0, 0);
this._chkFields_1.Name = "_chkFields_1";
this._chkFields_1.Size = new System.Drawing.Size(104, 24);
this._chkFields_1.TabIndex = 0;
//
//_chkFields_2
//
this._chkFields_2.Location = new System.Drawing.Point(0, 0);
this._chkFields_2.Name = "_chkFields_2";
this._chkFields_2.Size = new System.Drawing.Size(104, 24);
this._chkFields_2.TabIndex = 0;
//
//_chkFields_3
//
this._chkFields_3.Location = new System.Drawing.Point(0, 0);
this._chkFields_3.Name = "_chkFields_3";
this._chkFields_3.Size = new System.Drawing.Size(104, 24);
this._chkFields_3.TabIndex = 0;
//
//_chkFields_5
//
this._chkFields_5.Location = new System.Drawing.Point(0, 0);
this._chkFields_5.Name = "_chkFields_5";
this._chkFields_5.Size = new System.Drawing.Size(104, 24);
this._chkFields_5.TabIndex = 0;
//
//HSLeft
//
this.HSLeft.Cursor = System.Windows.Forms.Cursors.Default;
this.HSLeft.LargeChange = 5;
this.HSLeft.Location = new System.Drawing.Point(416, 48);
this.HSLeft.Maximum = 104;
this.HSLeft.Name = "HSLeft";
this.HSLeft.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HSLeft.Size = new System.Drawing.Size(112, 19);
this.HSLeft.TabIndex = 27;
this.HSLeft.TabStop = true;
//
//HSTop
//
this.HSTop.Cursor = System.Windows.Forms.Cursors.Default;
this.HSTop.LargeChange = 5;
this.HSTop.Location = new System.Drawing.Point(280, 48);
this.HSTop.Maximum = 26;
this.HSTop.Name = "HSTop";
this.HSTop.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HSTop.Size = new System.Drawing.Size(112, 19);
this.HSTop.TabIndex = 26;
this.HSTop.TabStop = true;
//
//cmdundo
//
this.cmdundo.BackColor = System.Drawing.SystemColors.Control;
this.cmdundo.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdundo.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdundo.Location = new System.Drawing.Point(136, 464);
this.cmdundo.Name = "cmdundo";
this.cmdundo.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdundo.Size = new System.Drawing.Size(88, 49);
this.cmdundo.TabIndex = 5;
this.cmdundo.Text = "&Undo";
this.cmdundo.UseVisualStyleBackColor = false;
//
//cmdnormal
//
this.cmdnormal.BackColor = System.Drawing.SystemColors.Control;
this.cmdnormal.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdnormal.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdnormal.Location = new System.Drawing.Point(384, 560);
this.cmdnormal.Name = "cmdnormal";
this.cmdnormal.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdnormal.Size = new System.Drawing.Size(88, 41);
this.cmdnormal.TabIndex = 20;
this.cmdnormal.Text = "Back To &Default";
this.cmdnormal.UseVisualStyleBackColor = false;
//
//cmbpos
//
this.cmbpos.BackColor = System.Drawing.SystemColors.Window;
this.cmbpos.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbpos.DropDownStyle = System.Windows.Forms.ComboBoxStyle.Simple;
this.cmbpos.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbpos.Items.AddRange(new object[] {
"Second Row",
"Third Row",
"Fourth Row",
"Fifth Row",
"Sixth Row",
"Seventh Row",
"Eight Row"
});
this.cmbpos.Location = new System.Drawing.Point(248, 560);
this.cmbpos.Name = "cmbpos";
this.cmbpos.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbpos.Size = new System.Drawing.Size(65, 21);
this.cmbpos.TabIndex = 18;
this.cmbpos.Text = "First Row";
//
//cmdadd
//
this.cmdadd.BackColor = System.Drawing.SystemColors.Control;
this.cmdadd.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdadd.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdadd.Location = new System.Drawing.Point(368, 464);
this.cmdadd.Name = "cmdadd";
this.cmdadd.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdadd.Size = new System.Drawing.Size(88, 49);
this.cmdadd.TabIndex = 1;
this.cmdadd.Text = "&Save Design";
this.cmdadd.UseVisualStyleBackColor = false;
//
//cmdSave
//
this.cmdSave.BackColor = System.Drawing.SystemColors.Control;
this.cmdSave.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdSave.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdSave.Location = new System.Drawing.Point(472, 464);
this.cmdSave.Name = "cmdSave";
this.cmdSave.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdSave.Size = new System.Drawing.Size(88, 49);
this.cmdSave.TabIndex = 0;
this.cmdSave.Text = "&Apply Changes";
this.cmdSave.UseVisualStyleBackColor = false;
//
//cmdExit
//
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Location = new System.Drawing.Point(32, 464);
this.cmdExit.Name = "cmdExit";
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Size = new System.Drawing.Size(88, 49);
this.cmdExit.TabIndex = 2;
this.cmdExit.Text = "&Back";
this.cmdExit.UseVisualStyleBackColor = false;
//
//HSHeight
//
this.HSHeight.Cursor = System.Windows.Forms.Cursors.Default;
this.HSHeight.LargeChange = 5;
this.HSHeight.Location = new System.Drawing.Point(144, 48);
this.HSHeight.Maximum = 82;
this.HSHeight.Minimum = 10;
this.HSHeight.Name = "HSHeight";
this.HSHeight.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HSHeight.Size = new System.Drawing.Size(112, 19);
this.HSHeight.TabIndex = 4;
this.HSHeight.TabStop = true;
this.HSHeight.Value = 30;
//
//HSselect
//
this.HSselect.Cursor = System.Windows.Forms.Cursors.Default;
this.HSselect.LargeChange = 500;
this.HSselect.Location = new System.Drawing.Point(32, 384);
this.HSselect.Maximum = 33266;
this.HSselect.Name = "HSselect";
this.HSselect.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HSselect.Size = new System.Drawing.Size(531, 22);
this.HSselect.SmallChange = 100;
this.HSselect.TabIndex = 16;
this.HSselect.TabStop = true;
//
//picOuter
//
this.picOuter.BackColor = System.Drawing.SystemColors.Control;
this.picOuter.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picOuter.Controls.Add(this.picInner);
this.picOuter.Cursor = System.Windows.Forms.Cursors.Default;
this.picOuter.ForeColor = System.Drawing.SystemColors.ControlText;
this.picOuter.Location = new System.Drawing.Point(32, 88);
this.picOuter.Name = "picOuter";
this.picOuter.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picOuter.Size = new System.Drawing.Size(531, 297);
this.picOuter.TabIndex = 14;
this.picOuter.TabStop = true;
//
//picInner
//
this.picInner.BackColor = System.Drawing.SystemColors.Control;
this.picInner.Controls.Add(this._picSelect_0);
this.picInner.Cursor = System.Windows.Forms.Cursors.Default;
this.picInner.ForeColor = System.Drawing.SystemColors.WindowText;
this.picInner.Location = new System.Drawing.Point(0, 0);
this.picInner.Name = "picInner";
this.picInner.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picInner.Size = new System.Drawing.Size(533, 204);
this.picInner.TabIndex = 6;
this.picInner.TabStop = true;
//
//_picSelect_0
//
this._picSelect_0.BackColor = System.Drawing.SystemColors.Window;
this._picSelect_0.Cursor = System.Windows.Forms.Cursors.Default;
this._picSelect_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._picSelect_0.Location = new System.Drawing.Point(0, 0);
this._picSelect_0.Name = "_picSelect_0";
this._picSelect_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._picSelect_0.Size = new System.Drawing.Size(118, 142);
this._picSelect_0.TabIndex = 15;
//
//HSWidth
//
this.HSWidth.Cursor = System.Windows.Forms.Cursors.Default;
this.HSWidth.LargeChange = 5;
this.HSWidth.Location = new System.Drawing.Point(16, 48);
this.HSWidth.Maximum = 204;
this.HSWidth.Minimum = 10;
this.HSWidth.Name = "HSWidth";
this.HSWidth.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HSWidth.Size = new System.Drawing.Size(104, 19);
this.HSWidth.TabIndex = 3;
this.HSWidth.TabStop = true;
this.HSWidth.Value = 40;
//
//_lbl_7
//
this._lbl_7.AutoSize = true;
this._lbl_7.BackColor = System.Drawing.Color.Transparent;
this._lbl_7.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_7.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_7.Location = new System.Drawing.Point(512, 32);
this._lbl_7.Name = "_lbl_7";
this._lbl_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_7.Size = new System.Drawing.Size(23, 13);
this._lbl_7.TabIndex = 30;
this._lbl_7.Text = "mm";
//
//lblLeft
//
this.lblLeft.AutoSize = true;
this.lblLeft.BackColor = System.Drawing.Color.Transparent;
this.lblLeft.Cursor = System.Windows.Forms.Cursors.Default;
this.lblLeft.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblLeft.Location = new System.Drawing.Point(480, 32);
this.lblLeft.Name = "lblLeft";
this.lblLeft.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblLeft.Size = new System.Drawing.Size(13, 13);
this.lblLeft.TabIndex = 29;
this.lblLeft.Text = "0";
this.lblLeft.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lbl_6
//
this._lbl_6.AutoSize = true;
this._lbl_6.BackColor = System.Drawing.Color.Transparent;
this._lbl_6.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_6.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_6.Location = new System.Drawing.Point(416, 32);
this._lbl_6.Name = "_lbl_6";
this._lbl_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_6.Size = new System.Drawing.Size(60, 13);
this._lbl_6.TabIndex = 28;
this._lbl_6.Text = "Left Margin";
//
//_lbl_5
//
this._lbl_5.AutoSize = true;
this._lbl_5.BackColor = System.Drawing.Color.Transparent;
this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_5.Location = new System.Drawing.Point(376, 32);
this._lbl_5.Name = "_lbl_5";
this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_5.Size = new System.Drawing.Size(23, 13);
this._lbl_5.TabIndex = 25;
this._lbl_5.Text = "mm";
//
//lblTop
//
this.lblTop.AutoSize = true;
this.lblTop.BackColor = System.Drawing.Color.Transparent;
this.lblTop.Cursor = System.Windows.Forms.Cursors.Default;
this.lblTop.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblTop.Location = new System.Drawing.Point(344, 32);
this.lblTop.Name = "lblTop";
this.lblTop.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblTop.Size = new System.Drawing.Size(13, 13);
this.lblTop.TabIndex = 24;
this.lblTop.Text = "0";
this.lblTop.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lbl_4
//
this._lbl_4.AutoSize = true;
this._lbl_4.BackColor = System.Drawing.Color.Transparent;
this._lbl_4.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_4.Location = new System.Drawing.Point(280, 32);
this._lbl_4.Name = "_lbl_4";
this._lbl_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_4.Size = new System.Drawing.Size(61, 13);
this._lbl_4.TabIndex = 23;
this._lbl_4.Text = "Top Margin";
//
//Label8
//
this.Label8.BackColor = System.Drawing.SystemColors.Control;
this.Label8.Cursor = System.Windows.Forms.Cursors.Default;
this.Label8.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label8.Location = new System.Drawing.Point(16, 72);
this.Label8.Name = "Label8";
this.Label8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label8.Size = new System.Drawing.Size(425, 17);
this.Label8.TabIndex = 22;
this.Label8.Text = "The Numbers from (1 to 23) on the left side is the row position where your field " + "will appear.";
//
//lblLineNo
//
this.lblLineNo.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.lblLineNo.Cursor = System.Windows.Forms.Cursors.Default;
this.lblLineNo.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblLineNo.Location = new System.Drawing.Point(16, 88);
this.lblLineNo.Name = "lblLineNo";
this.lblLineNo.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblLineNo.Size = new System.Drawing.Size(17, 297);
this.lblLineNo.TabIndex = 21;
this.lblLineNo.Text = "1- 2- 3- 4- 5- 6- 7- 8- 9- 10- 11- 12- 13- 14- 15- 16- 17- 18- 19- 20- 21- 22- 2" + "3-";
//
//Label7
//
this.Label7.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this.Label7.Cursor = System.Windows.Forms.Cursors.Default;
this.Label7.ForeColor = System.Drawing.SystemColors.WindowText;
this.Label7.Location = new System.Drawing.Point(544, 1);
this.Label7.Name = "Label7";
this.Label7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label7.Size = new System.Drawing.Size(169, 17);
this.Label7.TabIndex = 19;
//
//Label1
//
this.Label1.AutoSize = true;
this.Label1.BackColor = System.Drawing.Color.Transparent;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Location = new System.Drawing.Point(32, 3);
this.Label1.Name = "Label1";
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.Size = new System.Drawing.Size(74, 13);
this.Label1.TabIndex = 17;
this.Label1.Text = "Design Name:";
//
//lblWidth
//
this.lblWidth.AutoSize = true;
this.lblWidth.BackColor = System.Drawing.Color.Transparent;
this.lblWidth.Cursor = System.Windows.Forms.Cursors.Default;
this.lblWidth.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblWidth.Location = new System.Drawing.Point(80, 32);
this.lblWidth.Name = "lblWidth";
this.lblWidth.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblWidth.Size = new System.Drawing.Size(19, 13);
this.lblWidth.TabIndex = 13;
this.lblWidth.Text = "50";
this.lblWidth.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_lbl_0
//
this._lbl_0.AutoSize = true;
this._lbl_0.BackColor = System.Drawing.Color.Transparent;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_0.Location = new System.Drawing.Point(104, 32);
this._lbl_0.Name = "_lbl_0";
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.Size = new System.Drawing.Size(23, 13);
this._lbl_0.TabIndex = 12;
this._lbl_0.Text = "mm";
//
//_lbl_1
//
this._lbl_1.AutoSize = true;
this._lbl_1.BackColor = System.Drawing.Color.Transparent;
this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_1.Location = new System.Drawing.Point(16, 32);
this._lbl_1.Name = "_lbl_1";
this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_1.Size = new System.Drawing.Size(64, 13);
this._lbl_1.TabIndex = 11;
this._lbl_1.Text = "Label Width";
//
//_lbl_2
//
this._lbl_2.AutoSize = true;
this._lbl_2.BackColor = System.Drawing.Color.Transparent;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Location = new System.Drawing.Point(144, 32);
this._lbl_2.Name = "_lbl_2";
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.Size = new System.Drawing.Size(67, 13);
this._lbl_2.TabIndex = 10;
this._lbl_2.Text = "Label Height";
//
//_lbl_3
//
this._lbl_3.AutoSize = true;
this._lbl_3.BackColor = System.Drawing.Color.Transparent;
this._lbl_3.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_3.Location = new System.Drawing.Point(240, 32);
this._lbl_3.Name = "_lbl_3";
this._lbl_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_3.Size = new System.Drawing.Size(23, 13);
this._lbl_3.TabIndex = 9;
this._lbl_3.Text = "mm";
//
//lblHeight
//
this.lblHeight.AutoSize = true;
this.lblHeight.BackColor = System.Drawing.Color.Transparent;
this.lblHeight.Cursor = System.Windows.Forms.Cursors.Default;
this.lblHeight.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblHeight.Location = new System.Drawing.Point(216, 32);
this.lblHeight.Name = "lblHeight";
this.lblHeight.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblHeight.Size = new System.Drawing.Size(13, 13);
this.lblHeight.TabIndex = 8;
this.lblHeight.Text = "0";
this.lblHeight.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//lbldesign
//
this.lbldesign.AutoSize = true;
this.lbldesign.BackColor = System.Drawing.Color.Transparent;
this.lbldesign.Cursor = System.Windows.Forms.Cursors.Default;
this.lbldesign.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbldesign.Location = new System.Drawing.Point(144, 3);
this.lbldesign.Name = "lbldesign";
this.lbldesign.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbldesign.Size = new System.Drawing.Size(39, 13);
this.lbldesign.TabIndex = 7;
this.lbldesign.Text = "Label1";
//
//frmBarcodeLoad
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(726, 519);
this.ControlBox = false;
this.Controls.Add(this.Frame1);
this.Controls.Add(this.frmDeposits);
this.Controls.Add(this.HSLeft);
this.Controls.Add(this.HSTop);
this.Controls.Add(this.cmdundo);
this.Controls.Add(this.cmdnormal);
this.Controls.Add(this.cmbpos);
this.Controls.Add(this.cmdadd);
this.Controls.Add(this.cmdSave);
this.Controls.Add(this.cmdExit);
this.Controls.Add(this.HSHeight);
this.Controls.Add(this.HSselect);
this.Controls.Add(this.picOuter);
this.Controls.Add(this.HSWidth);
this.Controls.Add(this._lbl_7);
this.Controls.Add(this.lblLeft);
this.Controls.Add(this._lbl_6);
this.Controls.Add(this._lbl_5);
this.Controls.Add(this.lblTop);
this.Controls.Add(this._lbl_4);
this.Controls.Add(this.Label8);
this.Controls.Add(this.lblLineNo);
this.Controls.Add(this.Label7);
this.Controls.Add(this.Label1);
this.Controls.Add(this.lblWidth);
this.Controls.Add(this._lbl_0);
this.Controls.Add(this._lbl_1);
this.Controls.Add(this._lbl_2);
this.Controls.Add(this._lbl_3);
this.Controls.Add(this.lblHeight);
this.Controls.Add(this.lbldesign);
this.Cursor = System.Windows.Forms.Cursors.Default;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon");
this.KeyPreview = true;
this.Location = new System.Drawing.Point(3, 29);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmBarcodeLoad";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Barcode Designing";
this.Frame1.ResumeLayout(false);
this.frmDeposits.ResumeLayout(false);
this.picOuter.ResumeLayout(false);
this.picInner.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)this._picSelect_0).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
namespace InControl
{
using System;
using System.IO;
using UnityEngine;
#if NETFX_CORE
using Windows.Storage;
using Windows.Storage.Streams;
using System.Threading.Tasks;
#endif
public static class Utility
{
public const float Epsilon = 1.0e-7f;
private static Vector2[] circleVertexList = {
new Vector2( +0.0000f, +1.0000f ),
new Vector2( +0.2588f, +0.9659f ),
new Vector2( +0.5000f, +0.8660f ),
new Vector2( +0.7071f, +0.7071f ),
new Vector2( +0.8660f, +0.5000f ),
new Vector2( +0.9659f, +0.2588f ),
new Vector2( +1.0000f, +0.0000f ),
new Vector2( +0.9659f, -0.2588f ),
new Vector2( +0.8660f, -0.5000f ),
new Vector2( +0.7071f, -0.7071f ),
new Vector2( +0.5000f, -0.8660f ),
new Vector2( +0.2588f, -0.9659f ),
new Vector2( +0.0000f, -1.0000f ),
new Vector2( -0.2588f, -0.9659f ),
new Vector2( -0.5000f, -0.8660f ),
new Vector2( -0.7071f, -0.7071f ),
new Vector2( -0.8660f, -0.5000f ),
new Vector2( -0.9659f, -0.2588f ),
new Vector2( -1.0000f, -0.0000f ),
new Vector2( -0.9659f, +0.2588f ),
new Vector2( -0.8660f, +0.5000f ),
new Vector2( -0.7071f, +0.7071f ),
new Vector2( -0.5000f, +0.8660f ),
new Vector2( -0.2588f, +0.9659f ),
new Vector2( +0.0000f, +1.0000f )
};
public static void DrawCircleGizmo( Vector2 center, float radius )
{
var p = (circleVertexList[0] * radius) + center;
var c = circleVertexList.Length;
for (var i = 1; i < c; i++)
{
Gizmos.DrawLine( p, p = (circleVertexList[i] * radius) + center );
}
}
public static void DrawCircleGizmo( Vector2 center, float radius, Color color )
{
Gizmos.color = color;
DrawCircleGizmo( center, radius );
}
public static void DrawOvalGizmo( Vector2 center, Vector2 size )
{
var r = size / 2.0f;
var p = Vector2.Scale( circleVertexList[0], r ) + center;
var c = circleVertexList.Length;
for (var i = 1; i < c; i++)
{
Gizmos.DrawLine( p, p = Vector2.Scale( circleVertexList[i], r ) + center );
}
}
public static void DrawOvalGizmo( Vector2 center, Vector2 size, Color color )
{
Gizmos.color = color;
DrawOvalGizmo( center, size );
}
public static void DrawRectGizmo( Rect rect )
{
var p0 = new Vector3( rect.xMin, rect.yMin );
var p1 = new Vector3( rect.xMax, rect.yMin );
var p2 = new Vector3( rect.xMax, rect.yMax );
var p3 = new Vector3( rect.xMin, rect.yMax );
Gizmos.DrawLine( p0, p1 );
Gizmos.DrawLine( p1, p2 );
Gizmos.DrawLine( p2, p3 );
Gizmos.DrawLine( p3, p0 );
}
public static void DrawRectGizmo( Rect rect, Color color )
{
Gizmos.color = color;
DrawRectGizmo( rect );
}
public static void DrawRectGizmo( Vector2 center, Vector2 size )
{
var hw = size.x / 2.0f;
var hh = size.y / 2.0f;
var p0 = new Vector3( center.x - hw, center.y - hh );
var p1 = new Vector3( center.x + hw, center.y - hh );
var p2 = new Vector3( center.x + hw, center.y + hh );
var p3 = new Vector3( center.x - hw, center.y + hh );
Gizmos.DrawLine( p0, p1 );
Gizmos.DrawLine( p1, p2 );
Gizmos.DrawLine( p2, p3 );
Gizmos.DrawLine( p3, p0 );
}
public static void DrawRectGizmo( Vector2 center, Vector2 size, Color color )
{
Gizmos.color = color;
DrawRectGizmo( center, size );
}
public static bool GameObjectIsCulledOnCurrentCamera( GameObject gameObject )
{
return (Camera.current.cullingMask & (1 << gameObject.layer)) == 0;
}
public static Color MoveColorTowards( Color color0, Color color1, float maxDelta )
{
var r = Mathf.MoveTowards( color0.r, color1.r, maxDelta );
var g = Mathf.MoveTowards( color0.g, color1.g, maxDelta );
var b = Mathf.MoveTowards( color0.b, color1.b, maxDelta );
var a = Mathf.MoveTowards( color0.a, color1.a, maxDelta );
return new Color( r, g, b, a );
}
public static float ApplyDeadZone( float value, float lowerDeadZone, float upperDeadZone )
{
if (value < 0.0f)
{
if (value > -lowerDeadZone)
{
return 0.0f;
}
if (value < -upperDeadZone)
{
return -1.0f;
}
return (value + lowerDeadZone) / (upperDeadZone - lowerDeadZone);
}
else
{
if (value < lowerDeadZone)
{
return 0.0f;
}
if (value > upperDeadZone)
{
return 1.0f;
}
return (value - lowerDeadZone) / (upperDeadZone - lowerDeadZone);
}
}
// This is useful for DPad calculations where the control will snap to 8 directions
// as some DPads on analogs provide slight noise preventing accurate calculations.
public static Vector2 ApplySeparateDeadZone( float x, float y, float lowerDeadZone, float upperDeadZone )
{
return new Vector2(
ApplyDeadZone( x, lowerDeadZone, upperDeadZone ),
ApplyDeadZone( y, lowerDeadZone, upperDeadZone )
).normalized;
}
public static Vector2 ApplyCircularDeadZone( Vector2 v, float lowerDeadZone, float upperDeadZone )
{
var magnitude = v.magnitude;
if (magnitude < lowerDeadZone)
{
return Vector2.zero;
}
if (magnitude > upperDeadZone)
{
return v.normalized;
}
return v.normalized * ((magnitude - lowerDeadZone) / (upperDeadZone - lowerDeadZone));
}
public static Vector2 ApplyCircularDeadZone( float x, float y, float lowerDeadZone, float upperDeadZone )
{
return ApplyCircularDeadZone( new Vector2( x, y ), lowerDeadZone, upperDeadZone );
}
public static float ApplySmoothing( float thisValue, float lastValue, float deltaTime, float sensitivity )
{
// 1.0f and above is instant (no smoothing).
if (Utility.Approximately( sensitivity, 1.0f ))
{
return thisValue;
}
// Apply sensitivity (how quickly the value adapts to changes).
var maxDelta = deltaTime * sensitivity * 100.0f;
// Snap to zero when changing direction quickly.
if (IsNotZero( thisValue ) && Mathf.Sign( lastValue ) != Mathf.Sign( thisValue ))
{
lastValue = 0.0f;
}
return Mathf.MoveTowards( lastValue, thisValue, maxDelta );
}
// float ApplySmoothing( float lastValue, float thisValue, float deltaTime, float sensitivity )
// {
// sensitivity = Mathf.Clamp( sensitivity, 0.001f, 1.0f );
//
// if (Mathf.Approximately( sensitivity, 1.0f ))
// {
// return thisValue;
// }
//
// return Mathf.Lerp( lastValue, thisValue, deltaTime * sensitivity * 100.0f );
// }
public static float ApplySnapping( float value, float threshold )
{
if (value < -threshold)
{
return -1.0f;
}
if (value > threshold)
{
return 1.0f;
}
return 0.0f;
}
// TODO: This meaningless distinction should probably be removed entirely.
internal static bool TargetIsButton( InputControlType target )
{
return (target >= InputControlType.Action1 && target <= InputControlType.Action12) ||
(target >= InputControlType.Button0 && target <= InputControlType.Button19);
}
internal static bool TargetIsStandard( InputControlType target )
{
return (target >= InputControlType.LeftStickUp && target <= InputControlType.Action12) ||
(target >= InputControlType.Command && target <= InputControlType.DPadY);
}
internal static bool TargetIsAlias( InputControlType target )
{
return target >= InputControlType.Command && target <= InputControlType.DPadY;
}
#if NETFX_CORE
public static async Task<string> Async_ReadFromFile( string path )
{
string name = Path.GetFileName( path );
string folderPath = Path.GetDirectoryName( path );
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync( folderPath );
StorageFile file = await folder.GetFileAsync( name );
return await FileIO.ReadTextAsync( file );
}
public static async Task Async_WriteToFile( string path, string data )
{
string name = Path.GetFileName( path );
string folderPath = Path.GetDirectoryName( path );
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync( folderPath );
StorageFile file = await folder.CreateFileAsync( name, CreationCollisionOption.ReplaceExisting );
await FileIO.WriteTextAsync( file, data );
}
#endif
public static string ReadFromFile( string path )
{
#if NETFX_CORE
return Async_ReadFromFile( path ).Result;
#else
var streamReader = new StreamReader( path );
var data = streamReader.ReadToEnd();
streamReader.Close();
return data;
#endif
}
public static void WriteToFile( string path, string data )
{
#if NETFX_CORE
Async_WriteToFile( path, data ).Wait();
#else
var streamWriter = new StreamWriter( path );
streamWriter.Write( data );
streamWriter.Flush();
streamWriter.Close();
#endif
}
public static float Abs( float value )
{
return value < 0.0f ? -value : value;
}
public static bool Approximately( float v1, float v2 )
{
var delta = v1 - v2;
return (delta >= -Epsilon) && (delta <= Epsilon);
}
public static bool Approximately( Vector2 v1, Vector2 v2 )
{
return Approximately( v1.x, v2.x ) && Approximately( v1.y, v2.y );
}
public static bool IsNotZero( float value )
{
return (value < -Epsilon) || (value > Epsilon);
}
public static bool IsZero( float value )
{
return (value >= -Epsilon) && (value <= Epsilon);
}
public static bool AbsoluteIsOverThreshold( float value, float threshold )
{
return (value < -threshold) || (value > threshold);
}
public static float NormalizeAngle( float angle )
{
while (angle < 0.0f)
{
angle += 360.0f;
}
while (angle > 360.0f)
{
angle -= 360.0f;
}
return angle;
}
public static float VectorToAngle( Vector2 vector )
{
if (Utility.IsZero( vector.x ) && Utility.IsZero( vector.y ))
{
return 0.0f;
}
return Utility.NormalizeAngle( Mathf.Atan2( vector.x, vector.y ) * Mathf.Rad2Deg );
}
public static float Min( float v0, float v1 )
{
return (v0 >= v1) ? v1 : v0;
}
public static float Max( float v0, float v1 )
{
return (v0 <= v1) ? v1 : v0;
}
public static float Min( float v0, float v1, float v2, float v3 )
{
var r0 = (v0 >= v1) ? v1 : v0;
var r1 = (v2 >= v3) ? v3 : v2;
return (r0 >= r1) ? r1 : r0;
}
public static float Max( float v0, float v1, float v2, float v3 )
{
var r0 = (v0 <= v1) ? v1 : v0;
var r1 = (v2 <= v3) ? v3 : v2;
return (r0 <= r1) ? r1 : r0;
}
internal static float ValueFromSides( float negativeSide, float positiveSide )
{
var nsv = Utility.Abs( negativeSide );
var psv = Utility.Abs( positiveSide );
if (Utility.Approximately( nsv, psv ))
{
return 0.0f;
}
return nsv > psv ? -nsv : psv;
}
internal static float ValueFromSides( float negativeSide, float positiveSide, bool invertSides )
{
if (invertSides)
{
return ValueFromSides( positiveSide, negativeSide );
}
else
{
return ValueFromSides( negativeSide, positiveSide );
}
}
public static void ArrayResize<T>( ref T[] array, int capacity )
{
if (array == null || capacity > array.Length)
{
Array.Resize( ref array, NextPowerOfTwo( capacity ) );
}
}
public static void ArrayExpand<T>( ref T[] array, int capacity )
{
if (array == null || capacity > array.Length)
{
array = new T[NextPowerOfTwo( capacity )];
}
}
public static int NextPowerOfTwo( int value )
{
if (value > 0)
{
value--;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
value |= value >> 16;
value++;
return value;
}
return 0;
}
internal static bool Is32Bit
{
get
{
return IntPtr.Size == 4;
}
}
internal static bool Is64Bit
{
get
{
return IntPtr.Size == 8;
}
}
#if !NETFX_CORE && !UNITY_WEBPLAYER && !UNITY_EDITOR_OSX && (UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN)
public static string HKLM_GetString( string path, string key )
{
try
{
var rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( path );
if (rk == null)
{
return "";
}
return (string) rk.GetValue( key );
}
catch
{
return null;
}
}
public static string GetWindowsVersion()
{
var product = HKLM_GetString( @"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName" );
if (product != null)
{
var version = HKLM_GetString( @"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CSDVersion" );
var bitSize = Is32Bit ? "32Bit" : "64Bit";
var buildNumber = GetSystemBuildNumber();
return product + (version != null ? " " + version : "") + " " + bitSize + " Build " + buildNumber;
}
return SystemInfo.operatingSystem;
}
public static int GetSystemBuildNumber()
{
return Environment.OSVersion.Version.Build;
}
#else
public static int GetSystemBuildNumber()
{
return 0;
}
#endif
internal static void LoadScene( string sceneName )
{
#if UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2
Application.LoadLevel( sceneName );
#else
UnityEngine.SceneManagement.SceneManager.LoadScene( sceneName );
#endif
}
internal static string PluginFileExtension()
{
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
return ".bundle";
#elif UNITY_EDITOR_LINUX || UNITY_STANDALONE_LINUX
return ".dylib";
#else
return ".dll";
#endif
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.