context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/*
*
* Tiger Tree Hash Optimized - by Gil Schmidt.
*
* - this code was writtin based on:
* "Tree Hash EXchange format (THEX)"
* http://www.open-content.net/specs/draft-jchapweske-thex-02.html
*
* - the tiger hash class was converted from visual basic code called TigerNet:
* http://www.hotpixel.net/software.html
*
* - Base32 class was taken from:
* http://msdn.microsoft.com/msdnmag/issues/04/07/CustomPreferences/default.aspx
* didn't want to waste my time on writing a Base32 class.
*
* - after making the first working TTH class i noticed that it was very slow,i decided
* to improve the code by fixed size ('Block_Size') blocks and compress them into 1 hash
* string. (save memory and makes the cpu works a little less in a smaller arrays).
*
* - increase 'Block_Size' for better performance but it will cost you by memory.
*
* - fixed code for 0 byte file (thanks Flow84).
*
* if you use this code please add my name and email to the references!
* [ contact me at Gil_Smdt@hotmali.com ]
*
*/
using System;
using System.Text;
using System.IO;
using System.Collections;
namespace TTH
{
public class ThexOptimized
{
const int ZERO_BYTE_FILE = 0; //file with no data.
const int Block_Size = 64; //64k
const int Leaf_Size = 1024; //1k - don't change this.
private int Leaf_Count; //number of leafs.
private byte[][] HashValues; //array for hash values.
private FileStream FilePtr; //dest file stream pointer.
public byte[] GetTTH(string Filename)
{
byte[] TTH = null;
try
{
if (!File.Exists(Filename))
{
System.Diagnostics.Debug.WriteLine("file doesn't exists " + Filename);
return null;
}
//open the file.
FilePtr = new FileStream(Filename,FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
//if the file is 0 byte long.
if (FilePtr.Length == ZERO_BYTE_FILE)
{
Tiger TG = new Tiger();
TTH = TG.ComputeHash(new byte[] { 0 });
}
//the file is smaller then a single leaf.
else if (FilePtr.Length <= Leaf_Size * Block_Size)
TTH = CompressSmallBlock();
//normal file.
else
{
Leaf_Count = (int)(FilePtr.Length / Leaf_Size);
if (FilePtr.Length % Leaf_Size > 0) Leaf_Count++;
GetLeafHash(); //get leafs hash from file.
System.Diagnostics.Debug.WriteLine("===> [ Moving to internal hash. ]");
TTH = CompressHashBlock(HashValues, Leaf_Count); //get root TTH from hash array.
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("error while trying to get TTH for file: " +
Filename + ". (" + e.Message + ")");
TTH = null;
}
if (FilePtr != null) FilePtr.Close();
return TTH;
}
private void GetLeafHash() //gets the leafs from the file and hashes them.
{
int i;
int Blocks_Count = (int) Leaf_Count / (Block_Size * 2);
if (Leaf_Count % (Block_Size * 2) > 0) Blocks_Count++;
HashValues = new byte[Blocks_Count][];
byte[][] HashBlock = new byte[(int)Block_Size][];
for (i = 0; i < (int) Leaf_Count / (Block_Size * 2); i++) //loops threw the blocks.
{
for (int LeafIndex = 0; LeafIndex < (int) Block_Size; LeafIndex++) //creates new block.
HashBlock[LeafIndex] = GetNextLeafHash(); //extracts two leafs to a hash.
HashValues[i] = CompressHashBlock(HashBlock,Block_Size); //compresses the block to hash.
}
if (i < Blocks_Count) HashValues[i] = CompressSmallBlock(); //this block wasn't big enough.
Leaf_Count = Blocks_Count;
}
private byte[] GetNextLeafHash() //reads 2 leafs from the file and returns their combined hash.
{
byte[] LeafA = new byte[Leaf_Size];
byte[] LeafB = new byte[Leaf_Size];
int DataSize = FilePtr.Read(LeafA,0,Leaf_Size);
//check if leaf is too small.
if (DataSize < Leaf_Size || FilePtr.Position == FilePtr.Length) return (LeafHash(ByteExtract(LeafA, DataSize)));
DataSize = FilePtr.Read(LeafB,0,Leaf_Size);
if (DataSize < Leaf_Size)
LeafB = ByteExtract(LeafB,DataSize);
LeafA = LeafHash(LeafA);
LeafB = LeafHash(LeafB);
return InternalHash(LeafA,LeafB); //returns combined hash.
}
private byte[] CompressHashBlock(byte[][] HashBlock,int HashCount) //compresses hash blocks to hash.
{
if (HashBlock.Length == 0) return null;
while (HashCount > 1) //until there's only 1 hash.
{
int TempBlockSize = (int) HashCount / 2;
if (HashCount % 2 > 0) TempBlockSize++;
byte[][] TempBlock = new byte[TempBlockSize][];
int HashIndex = 0;
for (int i = 0; i < (int) HashCount / 2; i++) //makes hash from pairs.
{
TempBlock[i] = InternalHash(HashBlock[HashIndex],HashBlock[HashIndex+1]);
HashIndex += 2;
}
//this one doesn't have a pair :(
if (HashCount % 2 > 0) TempBlock[TempBlockSize - 1] = HashBlock[HashCount - 1];
HashBlock = TempBlock;
HashCount = TempBlockSize;
}
return HashBlock[0];
}
private byte[] CompressSmallBlock() //compress a small block to hash.
{
long DataSize = (long) (FilePtr.Length - FilePtr.Position);
int LeafCount = (int) DataSize / (Leaf_Size * 2);
if (DataSize % (Leaf_Size * 2) > 0) LeafCount++;
byte[][] SmallBlock = new byte[LeafCount][];
//extracts leafs from file.
for (int i = 0; i < (int) DataSize / (Leaf_Size * 2); i++)
SmallBlock[i] = GetNextLeafHash();
if (DataSize % (Leaf_Size * 2) > 0) SmallBlock[LeafCount - 1] = GetNextLeafHash();
return CompressHashBlock(SmallBlock,LeafCount); //gets hash from the small block.
}
private byte[] InternalHash(byte[] LeafA,byte[] LeafB) //internal hash.
{
byte[] Data = new byte[LeafA.Length + LeafB.Length + 1];
Data[0] = 0x01; //internal hash mark.
//combines two leafs.
LeafA.CopyTo(Data,1);
LeafB.CopyTo(Data,LeafA.Length + 1);
//gets tiger hash value for combined leaf hash.
Tiger TG = new Tiger();
TG.Initialize();
return TG.ComputeHash(Data);
}
private byte[] LeafHash(byte[] Raw_Data) //leaf hash.
{
byte[] Data = new byte[Raw_Data.Length + 1];
Data[0] = 0x00; //leaf hash mark.
Raw_Data.CopyTo(Data,1);
//gets tiger hash value for leafs blocks.
Tiger TG = new Tiger();
TG.Initialize();
return TG.ComputeHash(Data);
}
private byte[] ByteExtract(byte[] Raw_Data,int Data_Length) //if we use the extra 0x00 in Raw_Data we will get wrong hash.
{
byte[] Data = new byte[Data_Length];
for (int i = 0; i < Data_Length; i++)
Data[i] = Raw_Data[i];
return Data;
}
}
}
| |
/*
* Deed API
*
* Land Registry Deed API
*
* OpenAPI spec version: 2.3.1
*
* 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;
namespace IO.Swagger.Model
{
/// <summary>
/// Unique deed, consisting of property, borrower and charge information as well as clauses for the deed.
/// </summary>
[DataContract]
public partial class OperativeDeedDeed : IEquatable<OperativeDeedDeed>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="OperativeDeedDeed" /> class.
/// </summary>
/// <param name="TitleNumber">Unique Land Registry identifier for the registered estate..</param>
/// <param name="MdRef">Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345).</param>
/// <param name="Borrowers">Borrowers.</param>
/// <param name="ChargeClause">ChargeClause.</param>
/// <param name="AdditionalProvisions">AdditionalProvisions.</param>
/// <param name="Lender">Lender.</param>
/// <param name="EffectiveClause">Text to display the make effective clause.</param>
/// <param name="PropertyAddress">The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA.</param>
/// <param name="Reference">A conveyancer reference. Can be displayed on the deed if the mortgage document template permits..</param>
/// <param name="DateOfMortgageOffer">Date that the mortgage offer was made. Can be displayed on the deed if the mortgage document template permits..</param>
/// <param name="MiscellaneousInformation">Values unsuited to other keys. Can be displayed on the deed if the mortgage document template permits..</param>
/// <param name="DeedStatus">Current state of the deed.</param>
/// <param name="EffectiveDate">An effective date is shown if the deed is made effective.</param>
public OperativeDeedDeed(string TitleNumber = default(string), string MdRef = default(string), OpBorrowers Borrowers = default(OpBorrowers), ChargeClause ChargeClause = default(ChargeClause), AdditionalProvisions AdditionalProvisions = default(AdditionalProvisions), Lender Lender = default(Lender), string EffectiveClause = default(string), string PropertyAddress = default(string), string Reference = default(string), string DateOfMortgageOffer = default(string), string MiscellaneousInformation = default(string), string DeedStatus = default(string), string EffectiveDate = default(string))
{
this.TitleNumber = TitleNumber;
this.MdRef = MdRef;
this.Borrowers = Borrowers;
this.ChargeClause = ChargeClause;
this.AdditionalProvisions = AdditionalProvisions;
this.Lender = Lender;
this.EffectiveClause = EffectiveClause;
this.PropertyAddress = PropertyAddress;
this.Reference = Reference;
this.DateOfMortgageOffer = DateOfMortgageOffer;
this.MiscellaneousInformation = MiscellaneousInformation;
this.DeedStatus = DeedStatus;
this.EffectiveDate = EffectiveDate;
}
/// <summary>
/// Unique Land Registry identifier for the registered estate.
/// </summary>
/// <value>Unique Land Registry identifier for the registered estate.</value>
[DataMember(Name="title_number", EmitDefaultValue=false)]
public string TitleNumber { get; set; }
/// <summary>
/// Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345)
/// </summary>
/// <value>Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345)</value>
[DataMember(Name="md_ref", EmitDefaultValue=false)]
public string MdRef { get; set; }
/// <summary>
/// Gets or Sets Borrowers
/// </summary>
[DataMember(Name="borrowers", EmitDefaultValue=false)]
public OpBorrowers Borrowers { get; set; }
/// <summary>
/// Gets or Sets ChargeClause
/// </summary>
[DataMember(Name="charge_clause", EmitDefaultValue=false)]
public ChargeClause ChargeClause { get; set; }
/// <summary>
/// Gets or Sets AdditionalProvisions
/// </summary>
[DataMember(Name="additional_provisions", EmitDefaultValue=false)]
public AdditionalProvisions AdditionalProvisions { get; set; }
/// <summary>
/// Gets or Sets Lender
/// </summary>
[DataMember(Name="lender", EmitDefaultValue=false)]
public Lender Lender { get; set; }
/// <summary>
/// Text to display the make effective clause
/// </summary>
/// <value>Text to display the make effective clause</value>
[DataMember(Name="effective_clause", EmitDefaultValue=false)]
public string EffectiveClause { get; set; }
/// <summary>
/// The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA
/// </summary>
/// <value>The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA</value>
[DataMember(Name="property_address", EmitDefaultValue=false)]
public string PropertyAddress { get; set; }
/// <summary>
/// A conveyancer reference. Can be displayed on the deed if the mortgage document template permits.
/// </summary>
/// <value>A conveyancer reference. Can be displayed on the deed if the mortgage document template permits.</value>
[DataMember(Name="reference", EmitDefaultValue=false)]
public string Reference { get; set; }
/// <summary>
/// Date that the mortgage offer was made. Can be displayed on the deed if the mortgage document template permits.
/// </summary>
/// <value>Date that the mortgage offer was made. Can be displayed on the deed if the mortgage document template permits.</value>
[DataMember(Name="date_of_mortgage_offer", EmitDefaultValue=false)]
public string DateOfMortgageOffer { get; set; }
/// <summary>
/// Values unsuited to other keys. Can be displayed on the deed if the mortgage document template permits.
/// </summary>
/// <value>Values unsuited to other keys. Can be displayed on the deed if the mortgage document template permits.</value>
[DataMember(Name="miscellaneous_information", EmitDefaultValue=false)]
public string MiscellaneousInformation { get; set; }
/// <summary>
/// Current state of the deed
/// </summary>
/// <value>Current state of the deed</value>
[DataMember(Name="deed_status", EmitDefaultValue=false)]
public string DeedStatus { get; set; }
/// <summary>
/// An effective date is shown if the deed is made effective
/// </summary>
/// <value>An effective date is shown if the deed is made effective</value>
[DataMember(Name="effective_date", EmitDefaultValue=false)]
public string EffectiveDate { 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 OperativeDeedDeed {\n");
sb.Append(" TitleNumber: ").Append(TitleNumber).Append("\n");
sb.Append(" MdRef: ").Append(MdRef).Append("\n");
sb.Append(" Borrowers: ").Append(Borrowers).Append("\n");
sb.Append(" ChargeClause: ").Append(ChargeClause).Append("\n");
sb.Append(" AdditionalProvisions: ").Append(AdditionalProvisions).Append("\n");
sb.Append(" Lender: ").Append(Lender).Append("\n");
sb.Append(" EffectiveClause: ").Append(EffectiveClause).Append("\n");
sb.Append(" PropertyAddress: ").Append(PropertyAddress).Append("\n");
sb.Append(" Reference: ").Append(Reference).Append("\n");
sb.Append(" DateOfMortgageOffer: ").Append(DateOfMortgageOffer).Append("\n");
sb.Append(" MiscellaneousInformation: ").Append(MiscellaneousInformation).Append("\n");
sb.Append(" DeedStatus: ").Append(DeedStatus).Append("\n");
sb.Append(" EffectiveDate: ").Append(EffectiveDate).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 string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as OperativeDeedDeed);
}
/// <summary>
/// Returns true if OperativeDeedDeed instances are equal
/// </summary>
/// <param name="other">Instance of OperativeDeedDeed to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OperativeDeedDeed other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.TitleNumber == other.TitleNumber ||
this.TitleNumber != null &&
this.TitleNumber.Equals(other.TitleNumber)
) &&
(
this.MdRef == other.MdRef ||
this.MdRef != null &&
this.MdRef.Equals(other.MdRef)
) &&
(
this.Borrowers == other.Borrowers ||
this.Borrowers != null &&
this.Borrowers.Equals(other.Borrowers)
) &&
(
this.ChargeClause == other.ChargeClause ||
this.ChargeClause != null &&
this.ChargeClause.Equals(other.ChargeClause)
) &&
(
this.AdditionalProvisions == other.AdditionalProvisions ||
this.AdditionalProvisions != null &&
this.AdditionalProvisions.Equals(other.AdditionalProvisions)
) &&
(
this.Lender == other.Lender ||
this.Lender != null &&
this.Lender.Equals(other.Lender)
) &&
(
this.EffectiveClause == other.EffectiveClause ||
this.EffectiveClause != null &&
this.EffectiveClause.Equals(other.EffectiveClause)
) &&
(
this.PropertyAddress == other.PropertyAddress ||
this.PropertyAddress != null &&
this.PropertyAddress.Equals(other.PropertyAddress)
) &&
(
this.Reference == other.Reference ||
this.Reference != null &&
this.Reference.Equals(other.Reference)
) &&
(
this.DateOfMortgageOffer == other.DateOfMortgageOffer ||
this.DateOfMortgageOffer != null &&
this.DateOfMortgageOffer.Equals(other.DateOfMortgageOffer)
) &&
(
this.MiscellaneousInformation == other.MiscellaneousInformation ||
this.MiscellaneousInformation != null &&
this.MiscellaneousInformation.Equals(other.MiscellaneousInformation)
) &&
(
this.DeedStatus == other.DeedStatus ||
this.DeedStatus != null &&
this.DeedStatus.Equals(other.DeedStatus)
) &&
(
this.EffectiveDate == other.EffectiveDate ||
this.EffectiveDate != null &&
this.EffectiveDate.Equals(other.EffectiveDate)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.TitleNumber != null)
hash = hash * 59 + this.TitleNumber.GetHashCode();
if (this.MdRef != null)
hash = hash * 59 + this.MdRef.GetHashCode();
if (this.Borrowers != null)
hash = hash * 59 + this.Borrowers.GetHashCode();
if (this.ChargeClause != null)
hash = hash * 59 + this.ChargeClause.GetHashCode();
if (this.AdditionalProvisions != null)
hash = hash * 59 + this.AdditionalProvisions.GetHashCode();
if (this.Lender != null)
hash = hash * 59 + this.Lender.GetHashCode();
if (this.EffectiveClause != null)
hash = hash * 59 + this.EffectiveClause.GetHashCode();
if (this.PropertyAddress != null)
hash = hash * 59 + this.PropertyAddress.GetHashCode();
if (this.Reference != null)
hash = hash * 59 + this.Reference.GetHashCode();
if (this.DateOfMortgageOffer != null)
hash = hash * 59 + this.DateOfMortgageOffer.GetHashCode();
if (this.MiscellaneousInformation != null)
hash = hash * 59 + this.MiscellaneousInformation.GetHashCode();
if (this.DeedStatus != null)
hash = hash * 59 + this.DeedStatus.GetHashCode();
if (this.EffectiveDate != null)
hash = hash * 59 + this.EffectiveDate.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// Reference (string) maxLength
if(this.Reference != null && this.Reference.Length > 50)
{
yield return new ValidationResult("Invalid value for Reference, length must be less than 50.", new [] { "Reference" });
}
// Reference (string) pattern
Regex regexReference = new Regex(@"^(?!\\s*$).+", RegexOptions.CultureInvariant);
if (false == regexReference.Match(this.Reference).Success)
{
yield return new ValidationResult("Invalid value for Reference, must match a pattern of /^(?!\\s*$).+/.", new [] { "Reference" });
}
// DateOfMortgageOffer (string) maxLength
if(this.DateOfMortgageOffer != null && this.DateOfMortgageOffer.Length > 50)
{
yield return new ValidationResult("Invalid value for DateOfMortgageOffer, length must be less than 50.", new [] { "DateOfMortgageOffer" });
}
// DateOfMortgageOffer (string) pattern
Regex regexDateOfMortgageOffer = new Regex(@"^(?!\\s*$).+", RegexOptions.CultureInvariant);
if (false == regexDateOfMortgageOffer.Match(this.DateOfMortgageOffer).Success)
{
yield return new ValidationResult("Invalid value for DateOfMortgageOffer, must match a pattern of /^(?!\\s*$).+/.", new [] { "DateOfMortgageOffer" });
}
// MiscellaneousInformation (string) maxLength
if(this.MiscellaneousInformation != null && this.MiscellaneousInformation.Length > 250)
{
yield return new ValidationResult("Invalid value for MiscellaneousInformation, length must be less than 250.", new [] { "MiscellaneousInformation" });
}
// MiscellaneousInformation (string) pattern
Regex regexMiscellaneousInformation = new Regex(@"^(?!\\s*$).+", RegexOptions.CultureInvariant);
if (false == regexMiscellaneousInformation.Match(this.MiscellaneousInformation).Success)
{
yield return new ValidationResult("Invalid value for MiscellaneousInformation, must match a pattern of /^(?!\\s*$).+/.", new [] { "MiscellaneousInformation" });
}
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions;
using Avalonia.Markup.Xaml.XamlIl.Runtime;
using Avalonia.Platform;
using XamlX.Transform;
using XamlX.TypeSystem;
using XamlX.IL;
using XamlX.Emit;
#if RUNTIME_XAML_CECIL
using TypeAttributes = Mono.Cecil.TypeAttributes;
using Mono.Cecil;
using XamlX.Ast;
using XamlX.IL.Cecil;
#endif
namespace Avalonia.Markup.Xaml.XamlIl
{
static class AvaloniaXamlIlRuntimeCompiler
{
#if !RUNTIME_XAML_CECIL
private static SreTypeSystem _sreTypeSystem;
private static Type _ignoresAccessChecksFromAttribute;
private static ModuleBuilder _sreBuilder;
private static IXamlType _sreContextType;
private static XamlLanguageTypeMappings _sreMappings;
private static XamlLanguageEmitMappings<IXamlILEmitter, XamlILNodeEmitResult> _sreEmitMappings;
private static XamlXmlnsMappings _sreXmlns;
private static AssemblyBuilder _sreAsm;
private static bool _sreCanSave;
public static void DumpRuntimeCompilationResults()
{
if (_sreBuilder == null)
return;
var saveMethod = _sreAsm.GetType().GetMethods()
.FirstOrDefault(m => m.Name == "Save" && m.GetParameters().Length == 1);
if (saveMethod == null)
return;
try
{
_sreBuilder.CreateGlobalFunctions();
saveMethod.Invoke(_sreAsm, new Object[] {"XamlIlLoader.ildump"});
}
catch
{
//Ignore
}
}
static void InitializeSre()
{
if (_sreTypeSystem == null)
_sreTypeSystem = new SreTypeSystem();
if (_sreBuilder == null)
{
_sreCanSave = !(RuntimeInformation.FrameworkDescription.StartsWith(".NET Core"));
var name = new AssemblyName(Guid.NewGuid().ToString("N"));
if (_sreCanSave)
{
var define = AppDomain.CurrentDomain.GetType().GetMethods()
.FirstOrDefault(m => m.Name == "DefineDynamicAssembly"
&& m.GetParameters().Length == 3 &&
m.GetParameters()[2].ParameterType == typeof(string));
if (define != null)
_sreAsm = (AssemblyBuilder)define.Invoke(AppDomain.CurrentDomain, new object[]
{
name, (AssemblyBuilderAccess)3,
Path.GetDirectoryName(typeof(AvaloniaXamlIlRuntimeCompiler).Assembly.GetModules()[0]
.FullyQualifiedName)
});
else
_sreCanSave = false;
}
if(_sreAsm == null)
_sreAsm = AssemblyBuilder.DefineDynamicAssembly(name,
AssemblyBuilderAccess.RunAndCollect);
_sreBuilder = _sreAsm.DefineDynamicModule("XamlIlLoader.ildump");
}
if (_sreMappings == null)
(_sreMappings, _sreEmitMappings) = AvaloniaXamlIlLanguage.Configure(_sreTypeSystem);
if (_sreXmlns == null)
_sreXmlns = XamlXmlnsMappings.Resolve(_sreTypeSystem, _sreMappings);
if (_sreContextType == null)
_sreContextType = XamlILContextDefinition.GenerateContextClass(
_sreTypeSystem.CreateTypeBuilder(
_sreBuilder.DefineType("XamlIlContext")), _sreTypeSystem, _sreMappings,
_sreEmitMappings);
if (_ignoresAccessChecksFromAttribute == null)
_ignoresAccessChecksFromAttribute = EmitIgnoresAccessCheckAttributeDefinition(_sreBuilder);
}
static Type EmitIgnoresAccessCheckAttributeDefinition(ModuleBuilder builder)
{
var tb = builder.DefineType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute",
TypeAttributes.Class | TypeAttributes.Public, typeof(Attribute));
var field = tb.DefineField("_name", typeof(string), FieldAttributes.Private);
var propGet = tb.DefineMethod("get_AssemblyName", MethodAttributes.Public, typeof(string),
Array.Empty<Type>());
var propGetIl = propGet.GetILGenerator();
propGetIl.Emit(OpCodes.Ldarg_0);
propGetIl.Emit(OpCodes.Ldfld, field);
propGetIl.Emit(OpCodes.Ret);
var prop = tb.DefineProperty("AssemblyName", PropertyAttributes.None, typeof(string), Array.Empty<Type>());
prop.SetGetMethod(propGet);
var ctor = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard,
new[] { typeof(string) });
var ctorIl = ctor.GetILGenerator();
ctorIl.Emit(OpCodes.Ldarg_0);
ctorIl.Emit(OpCodes.Ldarg_1);
ctorIl.Emit(OpCodes.Stfld, field);
ctorIl.Emit(OpCodes.Ldarg_0);
ctorIl.Emit(OpCodes.Call, typeof(Attribute)
.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.First(x => x.GetParameters().Length == 0));
ctorIl.Emit(OpCodes.Ret);
tb.SetCustomAttribute(new CustomAttributeBuilder(
typeof(AttributeUsageAttribute).GetConstructor(new[] { typeof(AttributeTargets) }),
new object[] { AttributeTargets.Assembly },
new[] { typeof(AttributeUsageAttribute).GetProperty("AllowMultiple") },
new object[] { true }));
return tb.CreateTypeInfo();
}
static void EmitIgnoresAccessCheckToAttribute(AssemblyName assemblyName)
{
var name = assemblyName.Name;
if(string.IsNullOrWhiteSpace(name))
return;
var key = assemblyName.GetPublicKey();
if (key != null && key.Length != 0)
name += ", PublicKey=" + BitConverter.ToString(key).Replace("-", "").ToUpperInvariant();
_sreAsm.SetCustomAttribute(new CustomAttributeBuilder(
_ignoresAccessChecksFromAttribute.GetConstructors()[0],
new object[] { name }));
}
static object LoadSre(string xaml, Assembly localAssembly, object rootInstance, Uri uri, bool isDesignMode)
{
var success = false;
try
{
var rv = LoadSreCore(xaml, localAssembly, rootInstance, uri, isDesignMode);
success = true;
return rv;
}
finally
{
if(!success && _sreCanSave)
DumpRuntimeCompilationResults();
}
}
static object LoadSreCore(string xaml, Assembly localAssembly, object rootInstance, Uri uri, bool isDesignMode)
{
InitializeSre();
if (localAssembly?.GetName() != null)
EmitIgnoresAccessCheckToAttribute(localAssembly.GetName());
var asm = localAssembly == null ? null : _sreTypeSystem.GetAssembly(localAssembly);
var tb = _sreBuilder.DefineType("Builder_" + Guid.NewGuid().ToString("N") + "_" + uri);
var clrPropertyBuilder = tb.DefineNestedType("ClrProperties_" + Guid.NewGuid().ToString("N"));
var indexerClosureType = _sreBuilder.DefineType("IndexerClosure_" + Guid.NewGuid().ToString("N"));
var compiler = new AvaloniaXamlIlCompiler(new AvaloniaXamlIlCompilerConfiguration(_sreTypeSystem, asm,
_sreMappings, _sreXmlns, AvaloniaXamlIlLanguage.CustomValueConverter,
new XamlIlClrPropertyInfoEmitter(_sreTypeSystem.CreateTypeBuilder(clrPropertyBuilder)),
new XamlIlPropertyInfoAccessorFactoryEmitter(_sreTypeSystem.CreateTypeBuilder(indexerClosureType))),
_sreEmitMappings,
_sreContextType) { EnableIlVerification = true };
IXamlType overrideType = null;
if (rootInstance != null)
{
overrideType = _sreTypeSystem.GetType(rootInstance.GetType());
}
compiler.IsDesignMode = isDesignMode;
compiler.ParseAndCompile(xaml, uri?.ToString(), null, _sreTypeSystem.CreateTypeBuilder(tb), overrideType);
var created = tb.CreateTypeInfo();
clrPropertyBuilder.CreateTypeInfo();
return LoadOrPopulate(created, rootInstance);
}
#endif
static object LoadOrPopulate(Type created, object rootInstance)
{
var isp = Expression.Parameter(typeof(IServiceProvider));
var epar = Expression.Parameter(typeof(object));
var populate = created.GetMethod(AvaloniaXamlIlCompiler.PopulateName);
isp = Expression.Parameter(typeof(IServiceProvider));
var populateCb = Expression.Lambda<Action<IServiceProvider, object>>(
Expression.Call(populate, isp, Expression.Convert(epar, populate.GetParameters()[1].ParameterType)),
isp, epar).Compile();
if (rootInstance == null)
{
var targetType = populate.GetParameters()[1].ParameterType;
var overrideField = targetType.GetField("!XamlIlPopulateOverride",
BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
if (overrideField != null)
{
overrideField.SetValue(null,
new Action<object>(
target => { populateCb(XamlIlRuntimeHelpers.CreateRootServiceProviderV2(), target); }));
try
{
return Activator.CreateInstance(targetType);
}
finally
{
overrideField.SetValue(null, null);
}
}
var createCb = Expression.Lambda<Func<IServiceProvider, object>>(
Expression.Convert(Expression.Call(
created.GetMethod(AvaloniaXamlIlCompiler.BuildName), isp), typeof(object)), isp).Compile();
return createCb(XamlIlRuntimeHelpers.CreateRootServiceProviderV2());
}
else
{
populateCb(XamlIlRuntimeHelpers.CreateRootServiceProviderV2(), rootInstance);
return rootInstance;
}
}
public static object Load(Stream stream, Assembly localAssembly, object rootInstance, Uri uri,
bool isDesignMode)
{
string xaml;
using (var sr = new StreamReader(stream))
xaml = sr.ReadToEnd();
#if RUNTIME_XAML_CECIL
return LoadCecil(xaml, localAssembly, rootInstance, uri);
#else
return LoadSre(xaml, localAssembly, rootInstance, uri, isDesignMode);
#endif
}
#if RUNTIME_XAML_CECIL
private static Dictionary<string, (Action<IServiceProvider, object> populate, Func<IServiceProvider, object>
build)>
s_CecilCache =
new Dictionary<string, (Action<IServiceProvider, object> populate, Func<IServiceProvider, object> build)
>();
private static string _cecilEmitDir;
private static CecilTypeSystem _cecilTypeSystem;
private static XamlIlLanguageTypeMappings _cecilMappings;
private static XamlLanguageEmitMappings<IXamlILEmitter, XamlILNodeEmitResult> _cecilEmitMappings;
private static XamlIlXmlnsMappings _cecilXmlns;
private static bool _cecilInitialized;
static void InitializeCecil()
{
if(_cecilInitialized)
return;
var path = Assembly.GetEntryAssembly().GetModules()[0].FullyQualifiedName;
_cecilEmitDir = Path.Combine(Path.GetDirectoryName(path), "emit");
Directory.CreateDirectory(_cecilEmitDir);
var refs = new[] {path}.Concat(File.ReadAllLines(path + ".refs"));
_cecilTypeSystem = new CecilTypeSystem(refs);
(_cecilMappings, _cecilEmitMappings) = AvaloniaXamlIlLanguage.Configure(_cecilTypeSystem);
_cecilXmlns = XamlIlXmlnsMappings.Resolve(_cecilTypeSystem, _cecilMappings);
_cecilInitialized = true;
}
private static Dictionary<string, Type> _cecilGeneratedCache = new Dictionary<string, Type>();
static object LoadCecil(string xaml, Assembly localAssembly, object rootInstance, Uri uri)
{
if (uri == null)
throw new InvalidOperationException("Please, go away");
InitializeCecil();
IXamlType overrideType = null;
if (rootInstance != null)
{
overrideType = _cecilTypeSystem.GetType(rootInstance.GetType().FullName);
}
var safeUri = uri.ToString()
.Replace(":", "_")
.Replace("/", "_")
.Replace("?", "_")
.Replace("=", "_")
.Replace(".", "_");
if (_cecilGeneratedCache.TryGetValue(safeUri, out var cached))
return LoadOrPopulate(cached, rootInstance);
var asm = _cecilTypeSystem.CreateAndRegisterAssembly(safeUri, new Version(1, 0),
ModuleKind.Dll);
var def = new TypeDefinition("XamlIlLoader", safeUri,
TypeAttributes.Class | TypeAttributes.Public, asm.MainModule.TypeSystem.Object);
var contextDef = new TypeDefinition("XamlIlLoader", safeUri + "_XamlIlContext",
TypeAttributes.Class | TypeAttributes.Public, asm.MainModule.TypeSystem.Object);
asm.MainModule.Types.Add(def);
asm.MainModule.Types.Add(contextDef);
var tb = _cecilTypeSystem.CreateTypeBuilder(def);
var compiler = new AvaloniaXamlIlCompiler(new XamlIlTransformerConfiguration(_cecilTypeSystem,
localAssembly == null ? null : _cecilTypeSystem.FindAssembly(localAssembly.GetName().Name),
_cecilMappings, XamlIlXmlnsMappings.Resolve(_cecilTypeSystem, _cecilMappings),
AvaloniaXamlIlLanguage.CustomValueConverter),
_cecilEmitMappings,
_cecilTypeSystem.CreateTypeBuilder(contextDef));
compiler.ParseAndCompile(xaml, uri.ToString(), tb, overrideType);
var asmPath = Path.Combine(_cecilEmitDir, safeUri + ".dll");
using(var f = File.Create(asmPath))
asm.Write(f);
var loaded = Assembly.LoadFile(asmPath)
.GetTypes().First(x => x.Name == safeUri);
_cecilGeneratedCache[safeUri] = loaded;
return LoadOrPopulate(loaded, rootInstance);
}
#endif
}
}
| |
/*
* Copyright (c) 2006-2016, openmetaverse.co
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.InteropServices;
using System.Globalization;
namespace OpenMetaverse
{
/// <summary>
/// A three-dimensional vector with doubleing-point values
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector3d : IComparable<Vector3d>, IEquatable<Vector3d>
{
/// <summary>X value</summary>
public double X;
/// <summary>Y value</summary>
public double Y;
/// <summary>Z value</summary>
public double Z;
#region Constructors
public Vector3d(double x, double y, double z)
{
X = x;
Y = y;
Z = z;
}
public Vector3d(double value)
{
X = value;
Y = value;
Z = value;
}
/// <summary>
/// Constructor, builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing three eight-byte doubles</param>
/// <param name="pos">Beginning position in the byte array</param>
public Vector3d(byte[] byteArray, int pos)
{
X = Y = Z = 0d;
FromBytes(byteArray, pos);
}
public Vector3d(Vector3 vector)
{
X = vector.X;
Y = vector.Y;
Z = vector.Z;
}
public Vector3d(Vector3d vector)
{
X = vector.X;
Y = vector.Y;
Z = vector.Z;
}
#endregion Constructors
#region Public Methods
public double Length()
{
return Math.Sqrt(DistanceSquared(this, Zero));
}
public double LengthSquared()
{
return DistanceSquared(this, Zero);
}
public void Normalize()
{
this = Normalize(this);
}
/// <summary>
/// Test if this vector is equal to another vector, within a given
/// tolerance range
/// </summary>
/// <param name="vec">Vector to test against</param>
/// <param name="tolerance">The acceptable magnitude of difference
/// between the two vectors</param>
/// <returns>True if the magnitude of difference between the two vectors
/// is less than the given tolerance, otherwise false</returns>
public bool ApproxEquals(Vector3d vec, double tolerance)
{
Vector3d diff = this - vec;
return (diff.LengthSquared() <= tolerance * tolerance);
}
/// <summary>
/// IComparable.CompareTo implementation
/// </summary>
public int CompareTo(Vector3d vector)
{
return this.Length().CompareTo(vector.Length());
}
/// <summary>
/// Test if this vector is composed of all finite numbers
/// </summary>
public bool IsFinite()
{
return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z));
}
/// <summary>
/// Builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing a 24 byte vector</param>
/// <param name="pos">Beginning position in the byte array</param>
public void FromBytes(byte[] byteArray, int pos)
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[24];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 24);
Array.Reverse(conversionBuffer, 0, 8);
Array.Reverse(conversionBuffer, 8, 8);
Array.Reverse(conversionBuffer, 16, 8);
X = BitConverter.ToDouble(conversionBuffer, 0);
Y = BitConverter.ToDouble(conversionBuffer, 8);
Z = BitConverter.ToDouble(conversionBuffer, 16);
}
else
{
// Little endian architecture
X = BitConverter.ToDouble(byteArray, pos);
Y = BitConverter.ToDouble(byteArray, pos + 8);
Z = BitConverter.ToDouble(byteArray, pos + 16);
}
}
/// <summary>
/// Returns the raw bytes for this vector
/// </summary>
/// <returns>A 24 byte array containing X, Y, and Z</returns>
public byte[] GetBytes()
{
byte[] byteArray = new byte[24];
ToBytes(byteArray, 0);
return byteArray;
}
/// <summary>
/// Writes the raw bytes for this vector to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 24 bytes before the end of the array</param>
public void ToBytes(byte[] dest, int pos)
{
Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 8);
Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 8, 8);
Buffer.BlockCopy(BitConverter.GetBytes(Z), 0, dest, pos + 16, 8);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(dest, pos + 0, 8);
Array.Reverse(dest, pos + 8, 8);
Array.Reverse(dest, pos + 16, 8);
}
}
#endregion Public Methods
#region Static Methods
public static Vector3d Add(Vector3d value1, Vector3d value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
public static Vector3d Clamp(Vector3d value1, Vector3d min, Vector3d max)
{
return new Vector3d(
Utils.Clamp(value1.X, min.X, max.X),
Utils.Clamp(value1.Y, min.Y, max.Y),
Utils.Clamp(value1.Z, min.Z, max.Z));
}
public static Vector3d Cross(Vector3d value1, Vector3d value2)
{
return new Vector3d(
value1.Y * value2.Z - value2.Y * value1.Z,
value1.Z * value2.X - value2.Z * value1.X,
value1.X * value2.Y - value2.X * value1.Y);
}
public static double Distance(Vector3d value1, Vector3d value2)
{
return Math.Sqrt(DistanceSquared(value1, value2));
}
public static double DistanceSquared(Vector3d value1, Vector3d value2)
{
return
(value1.X - value2.X) * (value1.X - value2.X) +
(value1.Y - value2.Y) * (value1.Y - value2.Y) +
(value1.Z - value2.Z) * (value1.Z - value2.Z);
}
public static Vector3d Divide(Vector3d value1, Vector3d value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
public static Vector3d Divide(Vector3d value1, double value2)
{
double factor = 1d / value2;
value1.X *= factor;
value1.Y *= factor;
value1.Z *= factor;
return value1;
}
public static double Dot(Vector3d value1, Vector3d value2)
{
return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z;
}
public static Vector3d Lerp(Vector3d value1, Vector3d value2, double amount)
{
return new Vector3d(
Utils.Lerp(value1.X, value2.X, amount),
Utils.Lerp(value1.Y, value2.Y, amount),
Utils.Lerp(value1.Z, value2.Z, amount));
}
public static Vector3d Max(Vector3d value1, Vector3d value2)
{
return new Vector3d(
Math.Max(value1.X, value2.X),
Math.Max(value1.Y, value2.Y),
Math.Max(value1.Z, value2.Z));
}
public static Vector3d Min(Vector3d value1, Vector3d value2)
{
return new Vector3d(
Math.Min(value1.X, value2.X),
Math.Min(value1.Y, value2.Y),
Math.Min(value1.Z, value2.Z));
}
public static Vector3d Multiply(Vector3d value1, Vector3d value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
public static Vector3d Multiply(Vector3d value1, double scaleFactor)
{
value1.X *= scaleFactor;
value1.Y *= scaleFactor;
value1.Z *= scaleFactor;
return value1;
}
public static Vector3d Negate(Vector3d value)
{
value.X = -value.X;
value.Y = -value.Y;
value.Z = -value.Z;
return value;
}
public static Vector3d Normalize(Vector3d value)
{
double factor = Distance(value, Zero);
if (factor > Double.Epsilon)
{
factor = 1d / factor;
value.X *= factor;
value.Y *= factor;
value.Z *= factor;
}
else
{
value.X = 0d;
value.Y = 0d;
value.Z = 0d;
}
return value;
}
/// <summary>
/// Parse a vector from a string
/// </summary>
/// <param name="val">A string representation of a 3D vector, enclosed
/// in arrow brackets and separated by commas</param>
public static Vector3d Parse(string val)
{
char[] splitChar = { ',' };
string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar);
return new Vector3d(
Double.Parse(split[0].Trim(), Utils.EnUsCulture),
Double.Parse(split[1].Trim(), Utils.EnUsCulture),
Double.Parse(split[2].Trim(), Utils.EnUsCulture));
}
public static bool TryParse(string val, out Vector3d result)
{
try
{
result = Parse(val);
return true;
}
catch (Exception)
{
result = Vector3d.Zero;
return false;
}
}
/// <summary>
/// Interpolates between two vectors using a cubic equation
/// </summary>
public static Vector3d SmoothStep(Vector3d value1, Vector3d value2, double amount)
{
return new Vector3d(
Utils.SmoothStep(value1.X, value2.X, amount),
Utils.SmoothStep(value1.Y, value2.Y, amount),
Utils.SmoothStep(value1.Z, value2.Z, amount));
}
public static Vector3d Subtract(Vector3d value1, Vector3d value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
#endregion Static Methods
#region Overrides
public override bool Equals(object obj)
{
return (obj is Vector3d) ? this == (Vector3d)obj : false;
}
public bool Equals(Vector3d other)
{
return this == other;
}
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode();
}
/// <summary>
/// Get a formatted string representation of the vector
/// </summary>
/// <returns>A string representation of the vector</returns>
public override string ToString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z);
}
/// <summary>
/// Get a string representation of the vector elements with up to three
/// decimal digits and separated by spaces only
/// </summary>
/// <returns>Raw string representation of the vector</returns>
public string ToRawString()
{
CultureInfo enUs = new CultureInfo("en-us");
enUs.NumberFormat.NumberDecimalDigits = 3;
return String.Format(enUs, "{0} {1} {2}", X, Y, Z);
}
#endregion Overrides
#region Operators
public static bool operator ==(Vector3d value1, Vector3d value2)
{
return value1.X == value2.X
&& value1.Y == value2.Y
&& value1.Z == value2.Z;
}
public static bool operator !=(Vector3d value1, Vector3d value2)
{
return !(value1 == value2);
}
public static Vector3d operator +(Vector3d value1, Vector3d value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
public static Vector3d operator -(Vector3d value)
{
value.X = -value.X;
value.Y = -value.Y;
value.Z = -value.Z;
return value;
}
public static Vector3d operator -(Vector3d value1, Vector3d value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
public static Vector3d operator *(Vector3d value1, Vector3d value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
public static Vector3d operator *(Vector3d value, double scaleFactor)
{
value.X *= scaleFactor;
value.Y *= scaleFactor;
value.Z *= scaleFactor;
return value;
}
public static Vector3d operator /(Vector3d value1, Vector3d value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
public static Vector3d operator /(Vector3d value, double divider)
{
double factor = 1d / divider;
value.X *= factor;
value.Y *= factor;
value.Z *= factor;
return value;
}
/// <summary>
/// Cross product between two vectors
/// </summary>
public static Vector3d operator %(Vector3d value1, Vector3d value2)
{
return Cross(value1, value2);
}
/// <summary>
/// Implicit casting for Vector3 > Vector3d
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator Vector3d(Vector3 value)
{
return new Vector3d(value);
}
#endregion Operators
/// <summary>A vector with a value of 0,0,0</summary>
public readonly static Vector3d Zero = new Vector3d();
/// <summary>A vector with a value of 1,1,1</summary>
public readonly static Vector3d One = new Vector3d();
/// <summary>A unit vector facing forward (X axis), value of 1,0,0</summary>
public readonly static Vector3d UnitX = new Vector3d(1d, 0d, 0d);
/// <summary>A unit vector facing left (Y axis), value of 0,1,0</summary>
public readonly static Vector3d UnitY = new Vector3d(0d, 1d, 0d);
/// <summary>A unit vector facing up (Z axis), value of 0,0,1</summary>
public readonly static Vector3d UnitZ = new Vector3d(0d, 0d, 1d);
}
}
| |
using Shouldly;
namespace Tests.Caliburn.RoutedUIMessaging.Triggers
{
using System.Windows;
using System.Windows.Input;
using Fakes;
using Fakes.UI;
using global::Caliburn.Core;
using global::Caliburn.PresentationFramework.RoutedMessaging;
using global::Caliburn.PresentationFramework.RoutedMessaging.Triggers;
using global::Caliburn.PresentationFramework.RoutedMessaging.Triggers.Support;
using Xunit;
using NSubstitute;
public class The_gesture_message_trigger : TestBase
{
IInteractionNode node;
FakeElement element;
FakeMessage message;
protected override void given_the_context_of()
{
node = Mock<IInteractionNode>();
element = new FakeElement();
message = new FakeMessage {AvailabilityEffect = Mock<IAvailabilityEffect>()};
}
[Fact]
public void can_attach_itself_to_an_element_using_a_mouse_gesture()
{
var trigger = new GestureMessageTrigger
{
Modifiers = ModifierKeys.Control,
MouseAction = MouseAction.LeftDoubleClick,
Message = message
};
node.UIElement.Returns(element);
trigger.Attach(node);
trigger.Node.ShouldBe(node);
message.InvalidatedHandler.ShouldNotBeNull();
message.InitializeCalledWith.ShouldBe(node);
var binding = element.InputBindings[0];
var gesture = binding.Gesture as MouseGesture;
binding.Command.ShouldBe(new GestureMessageTrigger.GestureCommand(binding.Gesture));
gesture.MouseAction.ShouldBe(MouseAction.LeftDoubleClick);
gesture.Modifiers.ShouldBe(ModifierKeys.Control);
}
[Fact]
public void can_attach_itself_to_an_element_using_a_key_gesture()
{
var trigger = new GestureMessageTrigger
{
Modifiers = ModifierKeys.Alt,
Key = Key.S,
Message = message
};
node.UIElement.Returns(element);
trigger.Attach(node);
trigger.Node.ShouldBe(node);
message.InvalidatedHandler.ShouldNotBeNull();
message.InitializeCalledWith.ShouldBe(node);
var binding = element.InputBindings[0];
var gesture = binding.Gesture as UnrestrictedKeyGesture;
binding.Command.ShouldBe(new GestureMessageTrigger.GestureCommand(binding.Gesture));
gesture.Key.ShouldBe(Key.S);
gesture.Modifiers.ShouldBe(ModifierKeys.Alt);
}
[Fact]
public void throws_exception_if_attempt_to_attach_to_non_UIElement()
{
Assert.Throws<CaliburnException>(() =>{
var trigger = new GestureMessageTrigger {
Modifiers = ModifierKeys.Alt,
Key = Key.S,
Message = message
};
node.UIElement.Returns(new DependencyObject());
trigger.Attach(node);
});
var uiElement = node.Received(2).UIElement;
uiElement.ShouldBeNull();
}
[Fact]
public void can_trigger_message_processing()
{
var trigger = new GestureMessageTrigger
{
Modifiers = ModifierKeys.Alt,
Key = Key.S,
Message = message
};
object parameter = new object();
node.UIElement.Returns(element);
trigger.Attach(node);
element.InputBindings[0].Command.Execute(parameter);
node.Received().ProcessMessage(Arg.Is<IRoutedMessage>(x => x == message),
Arg.Is<object>(x => x == parameter));
}
[Fact]
public void can_update_availability()
{
var trigger = new GestureMessageTrigger
{
Modifiers = ModifierKeys.Alt,
Key = Key.S,
Message = message
};
node.UIElement.Returns(element);
node.UIElement.Returns(element);
trigger.Attach(node);
trigger.UpdateAvailabilty(false);
message.AvailabilityEffect.Received().ApplyTo(element, false);
}
[StaFact]
public void represents_availability_consistently_through_ICommand_for_disable_availability_when_not_available()
{
message = new FakeMessage {AvailabilityEffect = AvailabilityEffect.Disable};
var trigger = new GestureMessageTrigger
{
Modifiers = ModifierKeys.Alt,
Key = Key.S,
Message = message
};
node.UIElement.Returns(element);
node.UIElement.Returns(element);
trigger.Attach(node);
trigger.UpdateAvailabilty(false);
element.IsEnabled.ShouldBeFalse();
}
[Fact]
public void represents_availability_consistently_through_ICommand_for_disable_availability_when_available()
{
message = new FakeMessage {AvailabilityEffect = AvailabilityEffect.Disable};
var trigger = new GestureMessageTrigger
{
Modifiers = ModifierKeys.Alt,
Key = Key.S,
Message = message
};
node.UIElement.Returns(element);
node.UIElement.Returns(element);
trigger.Attach(node);
trigger.UpdateAvailabilty(true);
element.IsEnabled.ShouldBeTrue();
}
[Fact]
public void
represents_availability_consistently_through_ICommand_for_non_disable_availability_when_not_available()
{
message = new FakeMessage {AvailabilityEffect = AvailabilityEffect.Hide};
var trigger = new GestureMessageTrigger
{
Modifiers = ModifierKeys.Alt,
Key = Key.S,
Message = message
};
node.UIElement.Returns(element);
node.UIElement.Returns(element);
trigger.Attach(node);
trigger.UpdateAvailabilty(false);
element.IsEnabled.ShouldBeTrue();
}
[Fact]
public void represents_availability_consistently_through_ICommand_for_non_disable_availability_when_available()
{
message = new FakeMessage {AvailabilityEffect = AvailabilityEffect.Hide};
var trigger = new GestureMessageTrigger
{
Modifiers = ModifierKeys.Alt,
Key = Key.S,
Message = message
};
node.UIElement.Returns(element);
node.UIElement.Returns(element);
trigger.Attach(node);
trigger.UpdateAvailabilty(true);
element.IsEnabled.ShouldBeTrue();
}
}
}
| |
// 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.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.TypeInfos.NativeFormat;
using System.Reflection.Runtime.Assemblies;
using System.Reflection.Runtime.FieldInfos;
using System.Reflection.Runtime.FieldInfos.NativeFormat;
using System.Reflection.Runtime.MethodInfos;
using System.Reflection.Runtime.BindingFlagSupport;
using System.Reflection.Runtime.Modules;
using Internal.Runtime.Augments;
using Internal.Reflection.Augments;
using Internal.Reflection.Core.Execution;
using Internal.Metadata.NativeFormat;
namespace System.Reflection.Runtime.General
{
internal sealed class ReflectionCoreCallbacksImplementation : ReflectionCoreCallbacks
{
internal ReflectionCoreCallbacksImplementation()
{
}
public sealed override Assembly Load(AssemblyName refName)
{
if (refName == null)
throw new ArgumentNullException("assemblyRef");
return RuntimeAssembly.GetRuntimeAssembly(refName.ToRuntimeAssemblyName());
}
public sealed override Assembly Load(byte[] rawAssembly, byte[] pdbSymbolStore)
{
if (rawAssembly == null)
throw new ArgumentNullException(nameof(rawAssembly));
return RuntimeAssembly.GetRuntimeAssemblyFromByteArray(rawAssembly, pdbSymbolStore);
}
//
// This overload of GetMethodForHandle only accepts handles for methods declared on non-generic types (the method, however,
// can be an instance of a generic method.) To resolve handles for methods declared on generic types, you must pass
// the declaring type explicitly using the two-argument overload of GetMethodFromHandle.
//
// This is a vestige from desktop generic sharing that got itself enshrined in the code generated by the C# compiler for Linq Expressions.
//
public sealed override MethodBase GetMethodFromHandle(RuntimeMethodHandle runtimeMethodHandle)
{
ExecutionEnvironment executionEnvironment = ReflectionCoreExecution.ExecutionEnvironment;
QMethodDefinition methodHandle;
RuntimeTypeHandle declaringTypeHandle;
RuntimeTypeHandle[] genericMethodTypeArgumentHandles;
if (!executionEnvironment.TryGetMethodFromHandle(runtimeMethodHandle, out declaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles))
throw new ArgumentException(SR.Argument_InvalidHandle);
MethodBase methodBase = ReflectionCoreExecution.ExecutionDomain.GetMethod(declaringTypeHandle, methodHandle, genericMethodTypeArgumentHandles);
if (methodBase.DeclaringType.IsConstructedGenericType) // For compat with desktop, insist that the caller pass us the declaring type to resolve members of generic types.
throw new ArgumentException(SR.Format(SR.Argument_MethodDeclaringTypeGeneric, methodBase));
return methodBase;
}
//
// This overload of GetMethodHandle can handle all method handles.
//
public sealed override MethodBase GetMethodFromHandle(RuntimeMethodHandle runtimeMethodHandle, RuntimeTypeHandle declaringTypeHandle)
{
ExecutionEnvironment executionEnvironment = ReflectionCoreExecution.ExecutionEnvironment;
QMethodDefinition methodHandle;
RuntimeTypeHandle[] genericMethodTypeArgumentHandles;
if (!executionEnvironment.TryGetMethodFromHandleAndType(runtimeMethodHandle, declaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles))
{
// This may be a method declared on a non-generic type: this api accepts that too so try the other table.
RuntimeTypeHandle actualDeclaringTypeHandle;
if (!executionEnvironment.TryGetMethodFromHandle(runtimeMethodHandle, out actualDeclaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles))
throw new ArgumentException(SR.Argument_InvalidHandle);
if (!actualDeclaringTypeHandle.Equals(declaringTypeHandle))
throw new ArgumentException(SR.Format(SR.Argument_ResolveMethodHandle,
declaringTypeHandle.GetTypeForRuntimeTypeHandle(),
actualDeclaringTypeHandle.GetTypeForRuntimeTypeHandle()));
}
MethodBase methodBase = ReflectionCoreExecution.ExecutionDomain.GetMethod(declaringTypeHandle, methodHandle, genericMethodTypeArgumentHandles);
return methodBase;
}
//
// This overload of GetFieldForHandle only accepts handles for fields declared on non-generic types. To resolve handles for fields
// declared on generic types, you must pass the declaring type explicitly using the two-argument overload of GetFieldFromHandle.
//
// This is a vestige from desktop generic sharing that got itself enshrined in the code generated by the C# compiler for Linq Expressions.
//
public sealed override FieldInfo GetFieldFromHandle(RuntimeFieldHandle runtimeFieldHandle)
{
ExecutionEnvironment executionEnvironment = ReflectionCoreExecution.ExecutionEnvironment;
FieldHandle fieldHandle;
RuntimeTypeHandle declaringTypeHandle;
if (!executionEnvironment.TryGetFieldFromHandle(runtimeFieldHandle, out declaringTypeHandle, out fieldHandle))
throw new ArgumentException(SR.Argument_InvalidHandle);
FieldInfo fieldInfo = GetFieldInfo(declaringTypeHandle, fieldHandle);
if (fieldInfo.DeclaringType.IsConstructedGenericType) // For compat with desktop, insist that the caller pass us the declaring type to resolve members of generic types.
throw new ArgumentException(SR.Format(SR.Argument_FieldDeclaringTypeGeneric, fieldInfo));
return fieldInfo;
}
//
// This overload of GetFieldHandle can handle all field handles.
//
public sealed override FieldInfo GetFieldFromHandle(RuntimeFieldHandle runtimeFieldHandle, RuntimeTypeHandle declaringTypeHandle)
{
ExecutionEnvironment executionEnvironment = ReflectionCoreExecution.ExecutionEnvironment;
FieldHandle fieldHandle;
if (!executionEnvironment.TryGetFieldFromHandleAndType(runtimeFieldHandle, declaringTypeHandle, out fieldHandle))
{
// This may be a field declared on a non-generic type: this api accepts that too so try the other table.
RuntimeTypeHandle actualDeclaringTypeHandle;
if (!executionEnvironment.TryGetFieldFromHandle(runtimeFieldHandle, out actualDeclaringTypeHandle, out fieldHandle))
throw new ArgumentException(SR.Argument_InvalidHandle);
if (!actualDeclaringTypeHandle.Equals(declaringTypeHandle))
throw new ArgumentException(SR.Format(SR.Argument_ResolveFieldHandle,
declaringTypeHandle.GetTypeForRuntimeTypeHandle(),
actualDeclaringTypeHandle.GetTypeForRuntimeTypeHandle()));
}
FieldInfo fieldInfo = GetFieldInfo(declaringTypeHandle, fieldHandle);
return fieldInfo;
}
public sealed override EventInfo GetImplicitlyOverriddenBaseClassEvent(EventInfo e)
{
return e.GetImplicitlyOverriddenBaseClassMember();
}
public sealed override MethodInfo GetImplicitlyOverriddenBaseClassMethod(MethodInfo m)
{
return m.GetImplicitlyOverriddenBaseClassMember();
}
public sealed override PropertyInfo GetImplicitlyOverriddenBaseClassProperty(PropertyInfo p)
{
return p.GetImplicitlyOverriddenBaseClassMember();
}
private FieldInfo GetFieldInfo(RuntimeTypeHandle declaringTypeHandle, FieldHandle fieldHandle)
{
RuntimeTypeInfo contextTypeInfo = declaringTypeHandle.GetTypeForRuntimeTypeHandle();
NativeFormatRuntimeNamedTypeInfo definingTypeInfo = contextTypeInfo.AnchoringTypeDefinitionForDeclaredMembers.CastToNativeFormatRuntimeNamedTypeInfo();
MetadataReader reader = definingTypeInfo.Reader;
// RuntimeFieldHandles always yield FieldInfo's whose ReflectedType equals the DeclaringType.
RuntimeTypeInfo reflectedType = contextTypeInfo;
return NativeFormatRuntimeFieldInfo.GetRuntimeFieldInfo(fieldHandle, definingTypeInfo, contextTypeInfo, reflectedType);
}
[DebuggerHidden]
[DebuggerStepThrough]
public sealed override object ActivatorCreateInstance(Type type, bool nonPublic)
{
return ActivatorImplementation.CreateInstance(type, nonPublic);
}
[DebuggerHidden]
[DebuggerStepThrough]
public sealed override object ActivatorCreateInstance(Type type, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
{
return ActivatorImplementation.CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes);
}
// V2 api: Creates open or closed delegates to static or instance methods - relaxed signature checking allowed.
public sealed override Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method, bool throwOnBindFailure)
{
return CreateDelegateWorker(type, firstArgument, method, throwOnBindFailure, allowClosed: true);
}
// V1 api: Creates open delegates to static or instance methods - relaxed signature checking allowed.
public sealed override Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure)
{
// This API existed in v1/v1.1 and only expected to create open
// instance delegates, so we forbid closed delegates for backward compatibility.
// But we'll allow relaxed signature checking and open static delegates because
// there's no ambiguity there (the caller would have to explicitly
// pass us a static method or a method with a non-exact signature
// and the only change in behavior from v1.1 there is that we won't
// fail the call).
return CreateDelegateWorker(type, null, method, throwOnBindFailure, allowClosed: false);
}
private static Delegate CreateDelegateWorker(Type type, object firstArgument, MethodInfo method, bool throwOnBindFailure, bool allowClosed)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeTypeInfo runtimeDelegateType = type as RuntimeTypeInfo;
if (runtimeDelegateType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
RuntimeMethodInfo runtimeMethodInfo = method as RuntimeMethodInfo;
if (runtimeMethodInfo == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!runtimeDelegateType.IsDelegate)
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
Delegate result = runtimeMethodInfo.CreateDelegateNoThrowOnBindFailure(runtimeDelegateType, firstArgument, allowClosed);
if (result == null)
{
if (throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return null;
}
return result;
}
// V1 api: Creates closed delegates to instance methods only, relaxed signature checking disallowed.
public sealed override Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (target == null)
throw new ArgumentNullException(nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeTypeInfo runtimeDelegateType = type as RuntimeTypeInfo;
if (runtimeDelegateType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (!runtimeDelegateType.IsDelegate)
throw new ArgumentException(SR.Arg_MustBeDelegate);
RuntimeTypeInfo runtimeContainingType = target.GetType().CastToRuntimeTypeInfo();
RuntimeMethodInfo runtimeMethodInfo = LookupMethodForCreateDelegate(runtimeDelegateType, runtimeContainingType, method, isStatic: false, ignoreCase: ignoreCase);
if (runtimeMethodInfo == null)
{
if (throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return null;
}
return runtimeMethodInfo.CreateDelegateWithoutSignatureValidation(type, target, isStatic: false, isOpen: false);
}
// V1 api: Creates open delegates to static methods only, relaxed signature checking disallowed.
public sealed override Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (target == null)
throw new ArgumentNullException(nameof(target));
if (target.ContainsGenericParameters)
throw new ArgumentException(SR.Arg_UnboundGenParam);
if (method == null)
throw new ArgumentNullException(nameof(method));
RuntimeTypeInfo runtimeDelegateType = type as RuntimeTypeInfo;
if (runtimeDelegateType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
RuntimeTypeInfo runtimeContainingType = target as RuntimeTypeInfo;
if (runtimeContainingType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target));
if (!runtimeDelegateType.IsDelegate)
throw new ArgumentException(SR.Arg_MustBeDelegate);
RuntimeMethodInfo runtimeMethodInfo = LookupMethodForCreateDelegate(runtimeDelegateType, runtimeContainingType, method, isStatic: true, ignoreCase: ignoreCase);
if (runtimeMethodInfo == null)
{
if (throwOnBindFailure)
throw new ArgumentException(SR.Arg_DlgtTargMeth);
return null;
}
return runtimeMethodInfo.CreateDelegateWithoutSignatureValidation(type, target: null, isStatic: true, isOpen: true);
}
//
// Helper for the V1/V1.1 Delegate.CreateDelegate() api. These apis take method names rather than MethodInfo and only expect to create open static delegates
// or closed instance delegates. For backward compatibility, they don't allow relaxed signature matching (which could make the choice of target method ambiguous.)
//
private static RuntimeMethodInfo LookupMethodForCreateDelegate(RuntimeTypeInfo runtimeDelegateType, RuntimeTypeInfo containingType, string method, bool isStatic, bool ignoreCase)
{
Debug.Assert(runtimeDelegateType.IsDelegate);
BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.ExactBinding;
if (isStatic)
{
bindingFlags |= BindingFlags.Static | BindingFlags.FlattenHierarchy;
}
else
{
bindingFlags |= BindingFlags.Instance;
}
if (ignoreCase)
{
bindingFlags |= BindingFlags.IgnoreCase;
}
RuntimeMethodInfo invokeMethod = runtimeDelegateType.GetInvokeMethod();
ParameterInfo[] parameters = invokeMethod.GetParametersNoCopy();
int numParameters = parameters.Length;
Type[] parameterTypes = new Type[numParameters];
for (int i = 0; i < numParameters; i++)
{
parameterTypes[i] = parameters[i].ParameterType;
}
MethodInfo methodInfo = containingType.GetMethod(method, bindingFlags, null, parameterTypes, null);
if (methodInfo == null)
return null;
if (!methodInfo.ReturnType.Equals(invokeMethod.ReturnType))
return null;
return (RuntimeMethodInfo)methodInfo; // This cast is safe since we already verified that containingType is runtime implemented.
}
public sealed override Type GetTypeFromCLSID(Guid clsid, string server, bool throwOnError)
{
// Note: "throwOnError" is a vacuous parameter. Any errors due to the CLSID not being registered or the server not being found will happen
// on the Activator.CreateInstance() call. GetTypeFromCLSID() merely wraps the data in a Type object without any validation.
return RuntimeCLSIDTypeInfo.GetRuntimeCLSIDTypeInfo(clsid, server);
}
public sealed override IntPtr GetFunctionPointer(RuntimeMethodHandle runtimeMethodHandle, RuntimeTypeHandle declaringTypeHandle)
{
MethodBase method = GetMethodFromHandle(runtimeMethodHandle, declaringTypeHandle);
switch (method)
{
case RuntimeMethodInfo methodInfo:
return methodInfo.LdFtnResult;
case RuntimeConstructorInfo constructorInfo:
return constructorInfo.LdFtnResult;
default:
throw new PlatformNotSupportedException();
}
}
public sealed override void RunModuleConstructor(Module module)
{
RuntimeAssembly assembly = (RuntimeAssembly)module.Assembly;
assembly.RunModuleConstructor();
}
public sealed override void MakeTypedReference(object target, FieldInfo[] flds, out Type type, out int offset)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
if (flds == null)
throw new ArgumentNullException(nameof(flds));
if (flds.Length == 0)
throw new ArgumentException(SR.Arg_ArrayZeroError);
offset = 0;
Type targetType = target.GetType();
for (int i = 0; i < flds.Length; i++)
{
RuntimeFieldInfo field = flds[i] as RuntimeFieldInfo;
if (field == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo);
if (field.IsInitOnly || field.IsStatic)
throw new ArgumentException(SR.Argument_TypedReferenceInvalidField);
// For proper handling of Nullable<T> don't change to something like 'IsAssignableFrom'
// Currently we can't make a TypedReference to fields of Nullable<T>, which is fine.
Type declaringType = field.DeclaringType;
if (targetType != declaringType && !targetType.IsSubclassOf(declaringType))
throw new MissingMemberException(SR.MissingMemberTypeRef); // MissingMemberException is a strange exception to throw, but it is the compatible exception.
Type fieldType = field.FieldType;
if (fieldType.IsPrimitive)
throw new ArgumentException(SR.Arg_TypeRefPrimitve); // This check exists for compatibility (why such an ad-hoc restriction?)
if (i < (flds.Length - 1) && !fieldType.IsValueType)
throw new MissingMemberException(SR.MissingMemberNestErr); // MissingMemberException is a strange exception to throw, but it is the compatible exception.
targetType = fieldType;
offset = checked(offset + field.Offset);
}
type = targetType;
}
public sealed override Assembly[] GetLoadedAssemblies() => RuntimeAssembly.GetLoadedAssemblies();
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using NUnit.Framework.Constraints;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace NUnit.Framework
{
/// <summary>
/// Delegate used by tests that execute code and
/// capture any thrown exception.
/// </summary>
public delegate void TestDelegate();
#if ASYNC
/// <summary>
/// Delegate used by tests that execute async code and
/// capture any thrown exception.
/// </summary>
public delegate System.Threading.Tasks.Task AsyncTestDelegate();
#endif
/// <summary>
/// The Assert class contains a collection of static methods that
/// implement the most common assertions used in NUnit.
/// </summary>
public partial class Assert
{
#region Constructor
/// <summary>
/// We don't actually want any instances of this object, but some people
/// like to inherit from it to add other static methods. Hence, the
/// protected constructor disallows any instances of this object.
/// </summary>
protected Assert() { }
#endregion
#region Equals and ReferenceEquals
/// <summary>
/// DO NOT USE! Use Assert.AreEqual(...) instead.
/// The Equals method throws an InvalidOperationException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new bool Equals(object a, object b)
{
throw new InvalidOperationException("Assert.Equals should not be used for Assertions, use Assert.AreEqual(...) instead.");
}
/// <summary>
/// DO NOT USE!
/// The ReferenceEquals method throws an InvalidOperationException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new void ReferenceEquals(object a, object b)
{
throw new InvalidOperationException("Assert.ReferenceEquals should not be used for Assertions, use Assert.AreSame(...) instead.");
}
#endregion
#region Pass
/// <summary>
/// Throws a <see cref="SuccessException"/> with the message and arguments
/// that are passed in. This allows a test to be cut short, with a result
/// of success returned to NUnit.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Pass(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
// If we are in a multiple assert block, this is an error
if (TestExecutionContext.CurrentContext.MultipleAssertLevel > 0)
throw new Exception("Assert.Pass may not be used in a multiple assertion block.");
throw new SuccessException(message);
}
/// <summary>
/// Throws a <see cref="SuccessException"/> with the message and arguments
/// that are passed in. This allows a test to be cut short, with a result
/// of success returned to NUnit.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
static public void Pass(string message)
{
Assert.Pass(message, null);
}
/// <summary>
/// Throws a <see cref="SuccessException"/> with the message and arguments
/// that are passed in. This allows a test to be cut short, with a result
/// of success returned to NUnit.
/// </summary>
static public void Pass()
{
Assert.Pass(string.Empty, null);
}
#endregion
#region Fail
/// <summary>
/// Throws an <see cref="AssertionException"/> with the message and arguments
/// that are passed in. This is used by the other Assert functions.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Fail(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
ReportFailure(message);
}
/// <summary>
/// Throws an <see cref="AssertionException"/> with the message that is
/// passed in. This is used by the other Assert functions.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
static public void Fail(string message)
{
Assert.Fail(message, null);
}
/// <summary>
/// Throws an <see cref="AssertionException"/>.
/// This is used by the other Assert functions.
/// </summary>
static public void Fail()
{
Assert.Fail(string.Empty, null);
}
#endregion
#region Warn
/// <summary>
/// Issues a warning using the message and arguments provided.
/// </summary>
/// <param name="message">The message to display.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Warn(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
IssueWarning(message);
}
/// <summary>
/// Issues a warning using the message provided.
/// </summary>
/// <param name="message">The message to display.</param>
static public void Warn(string message)
{
IssueWarning(message);
}
#endregion
#region Ignore
/// <summary>
/// Throws an <see cref="IgnoreException"/> with the message and arguments
/// that are passed in. This causes the test to be reported as ignored.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Ignore(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
// If we are in a multiple assert block, this is an error
if (TestExecutionContext.CurrentContext.MultipleAssertLevel > 0)
throw new Exception("Assert.Ignore may not be used in a multiple assertion block.");
throw new IgnoreException(message);
}
/// <summary>
/// Throws an <see cref="IgnoreException"/> with the message that is
/// passed in. This causes the test to be reported as ignored.
/// </summary>
/// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param>
static public void Ignore(string message)
{
Assert.Ignore(message, null);
}
/// <summary>
/// Throws an <see cref="IgnoreException"/>.
/// This causes the test to be reported as ignored.
/// </summary>
static public void Ignore()
{
Assert.Ignore(string.Empty, null);
}
#endregion
#region InConclusive
/// <summary>
/// Throws an <see cref="InconclusiveException"/> with the message and arguments
/// that are passed in. This causes the test to be reported as inconclusive.
/// </summary>
/// <param name="message">The message to initialize the <see cref="InconclusiveException"/> with.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Inconclusive(string message, params object[] args)
{
if (message == null) message = string.Empty;
else if (args != null && args.Length > 0)
message = string.Format(message, args);
// If we are in a multiple assert block, this is an error
if (TestExecutionContext.CurrentContext.MultipleAssertLevel > 0)
throw new Exception("Assert.Inconclusive may not be used in a multiple assertion block.");
throw new InconclusiveException(message);
}
/// <summary>
/// Throws an <see cref="InconclusiveException"/> with the message that is
/// passed in. This causes the test to be reported as inconclusive.
/// </summary>
/// <param name="message">The message to initialize the <see cref="InconclusiveException"/> with.</param>
static public void Inconclusive(string message)
{
Assert.Inconclusive(message, null);
}
/// <summary>
/// Throws an <see cref="InconclusiveException"/>.
/// This causes the test to be reported as Inconclusive.
/// </summary>
static public void Inconclusive()
{
Assert.Inconclusive(string.Empty, null);
}
#endregion
#region Contains
/// <summary>
/// Asserts that an object is contained in a collection.
/// </summary>
/// <param name="expected">The expected object</param>
/// <param name="actual">The collection to be examined</param>
/// <param name="message">The message to display in case of failure</param>
/// <param name="args">Array of objects to be used in formatting the message</param>
public static void Contains(object expected, ICollection actual, string message, params object[] args)
{
Assert.That(actual, new CollectionContainsConstraint(expected) ,message, args);
}
/// <summary>
/// Asserts that an object is contained in a collection.
/// </summary>
/// <param name="expected">The expected object</param>
/// <param name="actual">The collection to be examined</param>
public static void Contains(object expected, ICollection actual)
{
Assert.That(actual, new CollectionContainsConstraint(expected) ,null, null);
}
#endregion
#region Multiple
/// <summary>
/// Wraps code containing a series of assertions, which should all
/// be executed, even if they fail. Failed results are saved and
/// reported at the end of the code block.
/// </summary>
/// <param name="testDelegate">A TestDelegate to be executed in Multiple Assertion mode.</param>
public static void Multiple(TestDelegate testDelegate)
{
TestExecutionContext context = TestExecutionContext.CurrentContext;
Guard.OperationValid(context != null, "Assert.Multiple called outside of a valid TestExecutionContext");
context.MultipleAssertLevel++;
try
{
testDelegate();
}
finally
{
context.MultipleAssertLevel--;
}
if (context.MultipleAssertLevel == 0 && context.CurrentResult.PendingFailures > 0)
throw new MultipleAssertException();
}
#endregion
#region Helper Methods
private static void ReportFailure(ConstraintResult result, string message)
{
ReportFailure(result, message, null);
}
private static void ReportFailure(ConstraintResult result, string message, params object[] args)
{
MessageWriter writer = new TextMessageWriter(message, args);
result.WriteMessageTo(writer);
ReportFailure(writer.ToString());
}
private static void ReportFailure(string message)
{
// Failure is recorded in <assertion> element in all cases
TestExecutionContext.CurrentContext.CurrentResult.RecordAssertion(
AssertionStatus.Failed, message, GetStackTrace());
// If we are outside any multiple assert block, then throw
if (TestExecutionContext.CurrentContext.MultipleAssertLevel == 0)
throw new AssertionException(message);
}
private static void IssueWarning(string message)
{
var result = TestExecutionContext.CurrentContext.CurrentResult;
result.RecordAssertion(AssertionStatus.Warning, message, GetStackTrace());
}
// System.Environment.StackTrace puts extra entries on top of the stack, at least in some environments
private static StackFilter SystemEnvironmentFilter = new StackFilter(@" System\.Environment\.");
private static string GetStackTrace()
{
string stackTrace = null;
#if PORTABLE && !NETSTANDARD1_6
// TODO: This isn't actually working! Since we catch it right here,
// the stack trace only has one entry.
try
{
// Throw to get stack trace for recording the assertion
throw new Exception();
}
catch (Exception ex)
{
stackTrace = ex.StackTrace;
}
#else
stackTrace = SystemEnvironmentFilter.Filter(Environment.StackTrace);
#endif
return StackFilter.DefaultFilter.Filter(stackTrace);
}
private static void IncrementAssertCount()
{
TestExecutionContext.CurrentContext.IncrementAssertCount();
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Screens.Ranking;
using osu.Game.Storyboards;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneStoryboardWithOutro : PlayerTestScene
{
protected override bool HasCustomSteps => true;
protected new OutroPlayer Player => (OutroPlayer)base.Player;
private double currentStoryboardDuration;
private bool showResults = true;
private event Func<HealthProcessor, JudgementResult, bool> currentFailConditions;
[SetUpSteps]
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("enable storyboard", () => LocalConfig.SetValue(OsuSetting.ShowStoryboard, true));
AddStep("set dim level to 0", () => LocalConfig.SetValue<double>(OsuSetting.DimLevel, 0));
AddStep("reset fail conditions", () => currentFailConditions = (_, __) => false);
AddStep("set storyboard duration to 2s", () => currentStoryboardDuration = 2000);
AddStep("set ShowResults = true", () => showResults = true);
}
[Test]
public void TestStoryboardSkipOutro()
{
CreateTest(null);
AddUntilStep("completion set by processor", () => Player.ScoreProcessor.HasCompleted.Value);
AddStep("skip outro", () => InputManager.Key(osuTK.Input.Key.Space));
AddUntilStep("wait for score shown", () => Player.IsScoreShown);
AddUntilStep("time less than storyboard duration", () => Player.GameplayClockContainer.GameplayClock.CurrentTime < currentStoryboardDuration);
}
[Test]
public void TestStoryboardNoSkipOutro()
{
CreateTest(null);
AddUntilStep("storyboard ends", () => Player.GameplayClockContainer.GameplayClock.CurrentTime >= currentStoryboardDuration);
AddUntilStep("wait for score shown", () => Player.IsScoreShown);
}
[Test]
public void TestStoryboardExitDuringOutroStillExits()
{
CreateTest(null);
AddUntilStep("completion set by processor", () => Player.ScoreProcessor.HasCompleted.Value);
AddStep("exit via pause", () => Player.ExitViaPause());
AddAssert("player exited", () => !Player.IsCurrentScreen() && Player.GetChildScreen() == null);
}
[TestCase(false)]
[TestCase(true)]
public void TestStoryboardToggle(bool enabledAtBeginning)
{
CreateTest(null);
AddStep($"{(enabledAtBeginning ? "enable" : "disable")} storyboard", () => LocalConfig.SetValue(OsuSetting.ShowStoryboard, enabledAtBeginning));
AddStep("toggle storyboard", () => LocalConfig.SetValue(OsuSetting.ShowStoryboard, !enabledAtBeginning));
AddUntilStep("wait for score shown", () => Player.IsScoreShown);
}
[Test]
public void TestOutroEndsDuringFailAnimation()
{
CreateTest(() =>
{
AddStep("fail on first judgement", () => currentFailConditions = (_, __) => true);
// Fail occurs at 164ms with the provided beatmap.
// Fail animation runs for 2.5s realtime but the gameplay time change is *variable* due to the frequency transform being applied, so we need a bit of lenience.
AddStep("set storyboard duration to 0.6s", () => currentStoryboardDuration = 600);
});
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("storyboard ends", () => Player.GameplayClockContainer.GameplayClock.CurrentTime >= currentStoryboardDuration);
AddUntilStep("wait for fail overlay", () => Player.FailOverlay.State.Value == Visibility.Visible);
}
[Test]
public void TestShowResultsFalse()
{
CreateTest(() =>
{
AddStep("set ShowResults = false", () => showResults = false);
});
AddUntilStep("storyboard ends", () => Player.GameplayClockContainer.GameplayClock.CurrentTime >= currentStoryboardDuration);
AddWaitStep("wait", 10);
AddAssert("no score shown", () => !Player.IsScoreShown);
}
[Test]
public void TestStoryboardEndsBeforeCompletion()
{
CreateTest(() => AddStep("set storyboard duration to .1s", () => currentStoryboardDuration = 100));
AddUntilStep("storyboard ends", () => Player.GameplayClockContainer.GameplayClock.CurrentTime >= currentStoryboardDuration);
AddUntilStep("completion set by processor", () => Player.ScoreProcessor.HasCompleted.Value);
AddUntilStep("wait for score shown", () => Player.IsScoreShown);
}
[Test]
public void TestStoryboardRewind()
{
SkipOverlay.FadeContainer fadeContainer() => Player.ChildrenOfType<SkipOverlay.FadeContainer>().First();
CreateTest(null);
AddUntilStep("completion set by processor", () => Player.ScoreProcessor.HasCompleted.Value);
AddUntilStep("skip overlay content becomes visible", () => fadeContainer().State == Visibility.Visible);
AddStep("rewind", () => Player.GameplayClockContainer.Seek(-1000));
AddUntilStep("skip overlay content not visible", () => fadeContainer().State == Visibility.Hidden);
AddUntilStep("skip overlay content becomes visible", () => fadeContainer().State == Visibility.Visible);
AddUntilStep("storyboard ends", () => Player.GameplayClockContainer.GameplayClock.CurrentTime >= currentStoryboardDuration);
}
[Test]
public void TestPerformExitNoOutro()
{
CreateTest(null);
AddStep("disable storyboard", () => LocalConfig.SetValue(OsuSetting.ShowStoryboard, false));
AddUntilStep("completion set by processor", () => Player.ScoreProcessor.HasCompleted.Value);
AddStep("exit via pause", () => Player.ExitViaPause());
AddAssert("player exited", () => Stack.CurrentScreen == null);
}
protected override bool AllowFail => true;
protected override Ruleset CreatePlayerRuleset() => new OsuRuleset();
protected override TestPlayer CreatePlayer(Ruleset ruleset) => new OutroPlayer(currentFailConditions, showResults);
protected override IBeatmap CreateBeatmap(RulesetInfo ruleset)
{
var beatmap = new Beatmap();
beatmap.HitObjects.Add(new HitCircle());
return beatmap;
}
protected override WorkingBeatmap CreateWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null)
{
return base.CreateWorkingBeatmap(beatmap, createStoryboard(currentStoryboardDuration));
}
private Storyboard createStoryboard(double duration)
{
var storyboard = new Storyboard();
var sprite = new StoryboardSprite("unknown", Anchor.TopLeft, Vector2.Zero);
sprite.TimelineGroup.Alpha.Add(Easing.None, 0, duration, 1, 0);
storyboard.GetLayer("Background").Add(sprite);
return storyboard;
}
protected class OutroPlayer : TestPlayer
{
public void ExitViaPause() => PerformExit(true);
public new FailOverlay FailOverlay => base.FailOverlay;
public bool IsScoreShown => !this.IsCurrentScreen() && this.GetChildScreen() is ResultsScreen;
private event Func<HealthProcessor, JudgementResult, bool> failConditions;
public OutroPlayer(Func<HealthProcessor, JudgementResult, bool> failConditions, bool showResults = true)
: base(false, showResults)
{
this.failConditions = failConditions;
}
protected override void LoadComplete()
{
base.LoadComplete();
HealthProcessor.FailConditions += failConditions;
}
protected override Task ImportScore(Score score)
{
return Task.CompletedTask;
}
}
}
}
| |
namespace FakeItEasy.Specs
{
using System;
using System.Diagnostics.CodeAnalysis;
using FakeItEasy.Configuration;
using FakeItEasy.Tests.TestHelpers;
using FluentAssertions;
using Xbehave;
using Xunit;
public static class ConfigurationSpecs
{
public interface IFoo
{
void Bar();
int Baz();
string Bas();
IFoo Bafoo();
IFoo Bafoo(out int i);
IFoo Wrap(IFoo wrappee);
}
[SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "It's just used for testing.")]
public interface IInterface
{
}
[Scenario]
[InlineData(typeof(IInterface))]
[InlineData(typeof(AbstractClass))]
[InlineData(typeof(ClassWithProtectedConstructor))]
[InlineData(typeof(ClassWithInternalConstructorVisibleToDynamicProxy))]
[InlineData(typeof(InternalClassVisibleToDynamicProxy))]
public static void ConfigureToString(Type typeOfFake, object fake, string? stringResult)
{
"Given a fake"
.x(() => fake = Sdk.Create.Fake(typeOfFake));
"And I configure the fake's ToString method"
.x(() => A.CallTo(() => fake.ToString()).Returns("I configured " + typeOfFake + ".ToString()"));
"When I call the method"
.x(() => stringResult = fake.ToString());
"Then it returns the configured value"
.x(() => stringResult.Should().Be("I configured " + typeOfFake + ".ToString()"));
}
[Scenario]
public static void CallbackOnVoid(
IFoo fake,
bool wasCalled)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure a method to invoke an action when a void method is called"
.x(() => A.CallTo(() => fake.Bar()).Invokes(x => wasCalled = true));
"When I call the method"
.x(() => fake.Bar());
"Then it invokes the action"
.x(() => wasCalled.Should().BeTrue());
}
[Scenario]
public static void CallbackOnStringReturningMethod(
IFoo fake,
bool wasCalled,
string result)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure a method to invoke an action when a string-returning method is called"
.x(() => A.CallTo(() => fake.Bas()).Invokes(x => wasCalled = true));
"When I call the method"
.x(() => result = fake.Bas());
"Then it invokes the action"
.x(() => wasCalled.Should().BeTrue());
"And a default value is returned"
.x(() => result.Should().BeEmpty());
}
[Scenario]
public static void MultipleCallbacks(
IFoo fake,
bool firstWasCalled,
bool secondWasCalled,
int returnValue)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure a method to invoke two actions and return a value"
.x(() =>
A.CallTo(() => fake.Baz())
.Invokes(x => firstWasCalled = true)
.Invokes(x => secondWasCalled = true)
.Returns(10));
"When I call the method"
.x(() => returnValue = fake.Baz());
"Then it calls the first callback"
.x(() => firstWasCalled.Should().BeTrue());
"And it calls the first callback"
.x(() => secondWasCalled.Should().BeTrue());
"And it returns the configured value"
.x(() => returnValue.Should().Be(10));
}
[Scenario]
public static void CallBaseMethod(
BaseClass fake,
int returnValue,
bool callbackWasInvoked)
{
"Given a fake"
.x(() => fake = A.Fake<BaseClass>());
"And I configure a method to invoke an action and call the base method"
.x(() =>
A.CallTo(() => fake.ReturnSomething())
.Invokes(x => callbackWasInvoked = true)
.CallsBaseMethod());
"When I call the method"
.x(() => returnValue = fake.ReturnSomething());
"Then it calls the base method"
.x(() => fake.WasCalled.Should().BeTrue());
"And it returns the value from base method"
.x(() => returnValue.Should().Be(10));
"And it invokes the callback"
.x(() => callbackWasInvoked.Should().BeTrue());
}
[Scenario]
public static void MultipleReturns(
IFoo fake,
IReturnValueArgumentValidationConfiguration<int> configuration,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure the return value for the method"
.x(() =>
{
configuration = A.CallTo(() => fake.Baz());
configuration.Returns(42);
});
"When I use the same configuration object to set the return value again"
.x(() => exception = Record.Exception(() => configuration.Returns(0)));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void ReturnThenThrow(
IFoo fake,
IReturnValueArgumentValidationConfiguration<int> configuration,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure the return value for the method"
.x(() =>
{
configuration = A.CallTo(() => fake.Baz());
configuration.Returns(42);
});
"When I use the same configuration object to have the method throw an exception"
.x(() => exception = Record.Exception(() => configuration.Throws<Exception>()));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void ReturnThenCallsBaseMethod(
IFoo fake,
IReturnValueArgumentValidationConfiguration<int> configuration,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure the return value for the method"
.x(() =>
{
configuration = A.CallTo(() => fake.Baz());
configuration.Returns(42);
});
"When I use the same configuration object to have the method call the base method"
.x(() => exception = Record.Exception(() => configuration.CallsBaseMethod()));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void MultipleThrows(
IFoo fake,
IReturnValueArgumentValidationConfiguration<int> configuration,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure the return method to throw an exception"
.x(() =>
{
configuration = A.CallTo(() => fake.Baz());
configuration.Throws<ArgumentNullException>();
});
"When I use the same configuration object to have the method throw an exception again"
.x(() => exception = Record.Exception(() => configuration.Throws<ArgumentException>()));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void CallToObjectOnNonFake(
BaseClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new BaseClass());
"When I start to configure the object"
.x(() => exception = Record.Exception(() => A.CallTo(notAFake)));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+BaseClass' of type FakeItEasy.Specs.ConfigurationSpecs+BaseClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToNonVirtualVoidOnNonFake(
BaseClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new BaseClass());
"When I start to configure a non-virtual void method on the object"
.x(() => exception = Record.Exception(() => A.CallTo(() => notAFake.DoSomethingNonVirtual())));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+BaseClass' of type FakeItEasy.Specs.ConfigurationSpecs+BaseClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToNonVirtualVoidOnFake(
BaseClass fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<BaseClass>());
"When I start to configure a non-virtual void method on the fake"
.x(() => exception = Record.Exception(() => A.CallTo(() => fake.DoSomethingNonVirtual())));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."));
}
[Scenario]
public static void CallToSealedVoidOnNonFake(
DerivedClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new DerivedClass());
"When I start to configure a sealed void method on the object"
.x(() => exception = Record.Exception(() => A.CallTo(() => notAFake.DoSomething())));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+DerivedClass' of type FakeItEasy.Specs.ConfigurationSpecs+DerivedClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToSealedVoidOnFake(
DerivedClass fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<DerivedClass>());
"When I start to configure a sealed void method on the fake"
.x(() => exception = Record.Exception(() => A.CallTo(() => fake.DoSomething())));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."));
}
[Scenario]
public static void CallToNonVirtualNonVoidOnNonFake(
BaseClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new BaseClass());
"When I start to configure a non-virtual non-void method on the object"
.x(() => exception = Record.Exception(() => A.CallTo(() => notAFake.ReturnSomethingNonVirtual())));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+BaseClass' of type FakeItEasy.Specs.ConfigurationSpecs+BaseClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToNonVirtualNonVoidOnFake(
BaseClass fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<BaseClass>());
"When I start to configure a non-virtual non-void method on the fake"
.x(() => exception = Record.Exception(() => A.CallTo(() => fake.ReturnSomethingNonVirtual())));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."));
}
[Scenario]
public static void CallToSealedNonVoidOnNonFake(
DerivedClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new DerivedClass());
"When I start to configure a sealed non-void method on the object"
.x(() => exception = Record.Exception(() => A.CallTo(() => notAFake.ReturnSomething())));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+DerivedClass' of type FakeItEasy.Specs.ConfigurationSpecs+DerivedClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToSealedNonVoidOnFake(
DerivedClass fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<DerivedClass>());
"When I start to configure a sealed non-void method on the fake"
.x(() => exception = Record.Exception(() => A.CallTo(() => fake.ReturnSomething())));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."));
}
[Scenario]
public static void CallToSetNonVirtualOnNonFake(
BaseClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new BaseClass());
"When I start to configure a non-virtual property setter on the object"
.x(() => exception = Record.Exception(() => A.CallToSet(() => notAFake.SomeNonVirtualProperty)));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+BaseClass' of type FakeItEasy.Specs.ConfigurationSpecs+BaseClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToSetNonVirtualOnFake(
BaseClass fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<BaseClass>());
"When I start to configure a non-virtual property setter on the fake"
.x(() => exception = Record.Exception(() => A.CallToSet(() => fake.SomeNonVirtualProperty)));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."));
}
[Scenario]
public static void CallToSetSealedOnNonFake(
DerivedClass notAFake,
Exception exception)
{
"Given an object that is not a fake"
.x(() => notAFake = new DerivedClass());
"When I start to configure a sealed property setter on the object"
.x(() => exception = Record.Exception(() => A.CallToSet(() => notAFake.SomeProperty)));
"Then it throws an argument exception"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
.And.Message.Should().Contain("Object 'FakeItEasy.Specs.ConfigurationSpecs+DerivedClass' of type FakeItEasy.Specs.ConfigurationSpecs+DerivedClass is not recognized as a fake object."));
}
[Scenario]
public static void CallToSetSealedOnFake(
DerivedClass fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<DerivedClass>());
"When I start to configure a sealed property setter on the fake"
.x(() => exception = Record.Exception(() => A.CallToSet(() => fake.SomeProperty)));
"Then it throws a fake configuration exception"
.x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
.And.Message.Should().Contain("Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted."));
}
[Scenario]
public static void DoesNothingAfterStrictVoidDoesNotThrow(
IFoo fake,
Exception exception)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure a void method to do nothing"
.x(() => A.CallTo(() => fake.Bar()).DoesNothing());
"When I call the method"
.x(() => exception = Record.Exception(() => fake.Bar()));
"Then it does not throw an exception"
.x(() => exception.Should().BeNull());
}
[Scenario]
public static void DoesNothingAfterStrictValueTypeKeepsDefaultReturnValue(
IFoo fake,
int result)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure all methods to do nothing"
.x(() => A.CallTo(fake).DoesNothing());
"When I call a value type method"
.x(() => result = fake.Baz());
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Baz()));
}
[Scenario]
public static void DoesNothingAfterStrictNonFakeableReferenceTypeKeepsDefaultReturnValue(
IFoo fake,
string result)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure all methods to do nothing"
.x(() => A.CallTo(fake).DoesNothing());
"When I call a non-fakeable reference type method"
.x(() => result = fake.Bas());
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Bas()));
}
[Scenario]
public static void DoesNothingAfterStrictFakeableReferenceTypeKeepsDefaultReturnValue(
IFoo fake,
IFoo result)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure all methods to do nothing"
.x(() => A.CallTo(fake).DoesNothing());
"When I call a fakeable reference type method"
.x(() => result = fake.Bafoo());
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Bafoo()));
}
[Scenario]
public static void ThrowsAndDoesNothingAppliedToSameACallTo(
IFoo fake,
IVoidArgumentValidationConfiguration callToBar,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I identify a method to configure"
.x(() => callToBar = A.CallTo(() => fake.Bar()));
"And I configure the method to throw an exception"
.x(() => callToBar.Throws<Exception>());
"When I configure the method to do nothing"
.x(() => exception = Record.Exception(() => callToBar.DoesNothing()));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void DoesNothingAndThrowsAppliedToSameACallTo(
IFoo fake,
IVoidArgumentValidationConfiguration callToBar,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I identify a method to configure"
.x(() => callToBar = A.CallTo(() => fake.Bar()));
"And I configure the method to do nothing"
.x(() => callToBar.DoesNothing());
"When I configure the method to throw an exception"
.x(() => exception = Record.Exception(() => callToBar.Throws<Exception>()));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void CallsBaseMethodAndDoesNothing(BaseClass fake)
{
"Given a fake"
.x(() => fake = A.Fake<BaseClass>());
"And I configure a method to call the base method"
.x(() => A.CallTo(() => fake.DoSomething()).CallsBaseMethod());
"And I configure the method to do nothing"
.x(() => A.CallTo(() => fake.DoSomething()).DoesNothing());
"When I call the method"
.x(() => fake.DoSomething());
"Then it does nothing"
.x(() => fake.WasCalled.Should().BeFalse());
}
[Scenario]
public static void CallsBaseMethodAndDoesNothingAppliedToSameACallTo(
BaseClass fake,
IVoidArgumentValidationConfiguration callToDoSomething,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<BaseClass>());
"And I identify a method to configure"
.x(() => callToDoSomething = A.CallTo(() => fake.DoSomething()));
"And I configure the method to call the base method"
.x(() => callToDoSomething.CallsBaseMethod());
"And I configure the method to do nothing"
.x(() => exception = Record.Exception(() => callToDoSomething.DoesNothing()));
"Then it throws an invalid operation exception"
.x(() => exception.Should().BeAnExceptionOfType<InvalidOperationException>());
}
[Scenario]
public static void InvokesAfterStrictVoidDoesNotThrow(
IFoo fake,
Exception exception)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure a void method to invoke an action"
.x(() => A.CallTo(() => fake.Bar()).Invokes(() => { }));
"When I call the method"
.x(() => exception = Record.Exception(() => fake.Bar()));
"Then it does not throw an exception"
.x(() => exception.Should().BeNull());
}
[Scenario]
public static void InvokesAfterStrictValueTypeKeepsDefaultReturnValue(
IFoo fake,
int result)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure a value type method to invoke an action"
.x(() => A.CallTo(() => fake.Baz()).Invokes(() => { }));
"When I call the method"
.x(() => result = fake.Baz());
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Baz()));
}
[Scenario]
public static void InvokesAfterStrictNonFakeableReferenceTypeKeepsDefaultReturnValue(
IFoo fake,
string result)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure all methods to invoke an action"
.x(() => A.CallTo(fake).Invokes(() => { }));
"When I call a non-fakeable reference type method"
.x(() => result = fake.Bas());
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Bas()));
}
[Scenario]
public static void InvokesAfterStrictFakeableableReferenceTypeKeepsDefaultReturnValue(
IFoo fake,
IFoo result)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(options => options.Strict()));
"And I configure all methods to invoke an action"
.x(() => A.CallTo(fake).Invokes(() => { }));
"When I call a fakeable reference type method"
.x(() => result = fake.Bafoo());
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Bafoo()));
}
[Scenario]
public static void AssignsOutAndRefParametersForAllMethodsKeepsDefaultReturnValue(
IFoo fake,
IFoo result,
int i)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"And I configure all methods to assign out and ref parameters"
.x(() => A.CallTo(fake).AssignsOutAndRefParameters(0));
"When I call a reference type method"
.x(() => result = fake.Bafoo(out i));
"Then it returns the same value as an unconfigured fake"
.x(() => result.Should().Be(A.Fake<IFoo>().Bafoo(out i)));
}
[Scenario]
public static void UnusedVoidCallSpec(
IFoo fake,
Exception exception)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(o => o.Strict()));
"When I specify a call to a void method without configuring its behavior"
.x(() => A.CallTo(() => fake.Bar()));
"And I make a call to that method"
.x(() => exception = Record.Exception(() => fake.Bar()));
"Then it throws an expectation exception"
.x(() => exception.Should().BeAnExceptionOfType<ExpectationException>());
}
[Scenario]
public static void UnusedNonVoidCallSpec(
IFoo fake,
Exception exception)
{
"Given a strict fake"
.x(() => fake = A.Fake<IFoo>(o => o.Strict()));
"When I specify a call to a void method without configuring its behavior"
.x(() => A.CallTo(() => fake.Baz()));
"And I make a call to that method"
.x(() => exception = Record.Exception(() => fake.Baz()));
"Then it throws an expectation exception"
.x(() => exception.Should().BeAnExceptionOfType<ExpectationException>());
}
[Scenario]
public static void NestedCallThatIncludesArrayConstruction(
IFoo fake,
Exception exception)
{
"Given a fake"
.x(() => fake = A.Fake<IFoo>());
"When I specify a call and create a non-object array in the call configuration"
.x(() => exception = Record.Exception(() => A.CallTo(() => fake.Wrap(Foo.BuildFromArray(new[] { 1, 2, 3 })))));
"Then it doesn't throw"
.x(() => exception.Should().BeNull());
}
public class BaseClass
{
public bool WasCalled { get; private set; }
public string SomeNonVirtualProperty { get; set; } = string.Empty;
public virtual string SomeProperty { get; set; } = string.Empty;
public virtual void DoSomething()
{
this.WasCalled = true;
}
public void DoSomethingNonVirtual()
{
}
public virtual int ReturnSomething()
{
this.WasCalled = true;
return 10;
}
public int ReturnSomethingNonVirtual()
{
return 11;
}
}
public class DerivedClass : BaseClass
{
public sealed override string SomeProperty { get; set; } = string.Empty;
public sealed override void DoSomething()
{
}
public sealed override int ReturnSomething()
{
return 10;
}
}
public class Foo : IFoo
{
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "integers", Justification = "Required for testing.")]
public static IFoo BuildFromArray(int[] integers)
{
return new Foo();
}
public void Bar()
{
throw new NotSupportedException();
}
public int Baz()
{
throw new NotSupportedException();
}
public string Bas()
{
throw new NotSupportedException();
}
public IFoo Bafoo()
{
throw new NotSupportedException();
}
public IFoo Bafoo(out int i)
{
throw new NotSupportedException();
}
public IFoo Wrap(IFoo wrappee)
{
throw new NotImplementedException();
}
}
public class FooFactory : DummyFactory<IFoo>
{
public static IFoo Instance { get; } = new Foo();
protected override IFoo Create()
{
return Instance;
}
}
}
}
| |
//
// (C) Copyright 2003-2010 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using Autodesk.Revit;
using Autodesk.Revit.Creation;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
namespace Revit.SDK.Samples.CreateAirHandler.CS
{
/// <summary>
/// Create one air handler and add connectors.
/// </summary>
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
[Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
public class Command : IExternalCommand
{
/// <summary>
/// The revit application
/// </summary>
private static Autodesk.Revit.ApplicationServices.Application m_application;
/// <summary>
/// The current document of the application
/// </summary>
private static Autodesk.Revit.DB.Document m_document;
/// <summary>
/// the factory to creaate extrusions and connectors
/// </summary>
private FamilyItemFactory f;
/// <summary>
/// the extrusion array
/// </summary>
private Extrusion[] extrusions;
/// <summary>
/// The list of all the elements to be combined in the air handler system
/// </summary>
private CombinableElementArray m_combineElements;
#region Data used to create extrusions and connectors
/// <summary>
/// Data to create extrusions and connectors
/// </summary>
private Autodesk.Revit.DB.XYZ [,] profileData = new Autodesk.Revit.DB.XYZ [5, 4]
{
// In Array 0 to 2, the data is the points that defines the edges of the profile
{
new Autodesk.Revit.DB.XYZ (-17.28, -0.53, 0.9),
new Autodesk.Revit.DB.XYZ (-17.28, 11, 0.9),
new Autodesk.Revit.DB.XYZ (-0.57, 11, 0.9),
new Autodesk.Revit.DB.XYZ (-0.57, -0.53, 0.9)
},
{
new Autodesk.Revit.DB.XYZ (-0.57, 7, 6.58),
new Autodesk.Revit.DB.XYZ (-0.57, 7, 3),
new Autodesk.Revit.DB.XYZ (-0.57, 3.6, 3),
new Autodesk.Revit.DB.XYZ (-0.57, 3.6, 6.58)
},
{
new Autodesk.Revit.DB.XYZ (-17.28, -0.073, 7.17),
new Autodesk.Revit.DB.XYZ (-17.28, 10.76, 7.17),
new Autodesk.Revit.DB.XYZ (-17.28, 10.76, 3.58),
new Autodesk.Revit.DB.XYZ (-17.28, -0.073, 3.58)
},
// In Array 3 and 4, the data is the normal and origin of the plane of the arc profile
{
new Autodesk.Revit.DB.XYZ (0, -1, 0),
new Autodesk.Revit.DB.XYZ (-9, 0.53, 7.17),
null,
null
},
{
new Autodesk.Revit.DB.XYZ (0, -1, 0),
new Autodesk.Revit.DB.XYZ (-8.24, 0.53, 0.67),
null,
null
}
};
/// <summary>
/// the normal and origin of the sketch plane
/// </summary>
private Autodesk.Revit.DB.XYZ [,] sketchPlaneData = new Autodesk.Revit.DB.XYZ [5, 2]
{
{new Autodesk.Revit.DB.XYZ (0, 0, 1), new Autodesk.Revit.DB.XYZ (0, 0, 0.9)},
{new Autodesk.Revit.DB.XYZ (1, 0, 0), new Autodesk.Revit.DB.XYZ (-0.57, 0, 0)},
{new Autodesk.Revit.DB.XYZ (-1, 0, 0), new Autodesk.Revit.DB.XYZ (-17.28, 0, 0)},
{new Autodesk.Revit.DB.XYZ (0, -1, 0), new Autodesk.Revit.DB.XYZ (0, 0.53, 0)},
{new Autodesk.Revit.DB.XYZ (0, -1, 0), new Autodesk.Revit.DB.XYZ (0, 0.53, 0)}
};
/// <summary>
/// the start and end offsets of the extrusion
/// </summary>
private double[,] extrusionOffsets = new double[5, 2]
{
{-0.9, 6.77},
{0, -0.18},
{0, -0.08},
{1, 1.15},
{1, 1.15}
};
/// <summary>
/// whether the extrusion is solid
/// </summary>
private bool[] isSolid = new bool[5] { true, false, false, true, true };
/// <summary>
/// the radius of the arc profile
/// </summary>
private double arcRadius = 0.17;
/// <summary>
/// the height and width of the connector
/// </summary>
private double[,] connectorDimensions = new double[2, 2]
{
{3.58, 3.4},
{3.59, 10.833}
};
/// <summary>
/// the flow of the connector
/// </summary>
private double flow = 547;
/// <summary>
/// Transaction of ExternalCommand
/// </summary>
private Transaction m_transaction;
#endregion
#region IExternalCommand Members
/// <summary>
/// Implement this method as an external command for Revit.
/// </summary>
/// <param name="commandData">An object that is passed to the external application
/// which contains data related to the command,
/// such as the application object and active view.</param>
/// <param name="message">A message that can be set by the external application
/// which will be displayed if a failure or cancellation is returned by
/// the external command.</param>
/// <param name="elements">A set of elements to which the external application
/// can add elements that are to be highlighted in case of failure or cancellation.</param>
/// <returns>Return the status of the external command.
/// A result of Succeeded means that the API external method functioned as expected.
/// Cancelled can be used to signify that the user cancelled the external operation
/// at some point. Failure should be returned if the application is unable to proceed with
/// the operation.</returns>
public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message,
ElementSet elements)
{
// set out default result to failure.
Autodesk.Revit.UI.Result retRes = Autodesk.Revit.UI.Result.Failed;
m_application = commandData.Application.Application;
m_document = commandData.Application.ActiveUIDocument.Document;
f = m_document.FamilyCreate;
extrusions = new Extrusion[5];
m_combineElements = new CombinableElementArray();
m_transaction = new Transaction(m_document, "External Tool");
m_transaction.Start();
if (m_document.OwnerFamily.FamilyCategory.Name != "Mechanical Equipment")
{
message = "Please make sure you opened a template of Mechanical Equipment.";
return retRes;
}
try
{
CreateExtrusions();
m_document.Regenerate();
CreateConnectors();
m_document.Regenerate();
m_document.CombineElements(m_combineElements);
m_document.Regenerate();
}
catch(Exception x)
{
m_transaction.RollBack();
message = x.Message;
return retRes;
}
m_transaction.Commit();
retRes = Autodesk.Revit.UI.Result.Succeeded;
return retRes;
}
#endregion
/// <summary>
/// get all planar faces of an extrusion
/// </summary>
/// <param name="extrusion">the extrusion to read</param>
/// <returns>a list of all planar faces of the extrusion</returns>
public List<PlanarFace> GetPlanarFaces(Extrusion extrusion)
{
// the option to get geometry elements
Options m_geoOptions = m_application.Create.NewGeometryOptions();
m_geoOptions.View = m_document.ActiveView;
m_geoOptions.ComputeReferences = true;
// get the planar faces
List<PlanarFace> m_planarFaces = new List<PlanarFace>();
Autodesk.Revit.DB.GeometryElement geoElement = extrusion.get_Geometry(m_geoOptions);
foreach (GeometryObject geoObject in geoElement.Objects)
{
Solid geoSolid = geoObject as Solid;
if (null == geoSolid)
{
continue;
}
foreach (Face geoFace in geoSolid.Faces)
{
if (geoFace is PlanarFace)
{
m_planarFaces.Add(geoFace as PlanarFace);
}
}
}
return m_planarFaces;
}
/// <summary>
/// create the extrusions of the air handler system
/// </summary>
private void CreateExtrusions()
{
Autodesk.Revit.Creation.Application app = m_application.Create;
CurveArray curves = null;
CurveArrArray profile = null;
Plane plane = null;
SketchPlane sketchPlane = null;
#region Create the cuboid extrusions
for (int i = 0; i <= 2; ++i)
{
// create the profile
curves = app.NewCurveArray();
curves.Append(app.NewLine(profileData[i, 0], profileData[i, 1], true));
curves.Append(app.NewLine(profileData[i, 1], profileData[i, 2], true));
curves.Append(app.NewLine(profileData[i, 2], profileData[i, 3], true));
curves.Append(app.NewLine(profileData[i, 3], profileData[i, 0], true));
profile = app.NewCurveArrArray();
profile.Append(curves);
// create the sketch plane
plane = app.NewPlane(sketchPlaneData[i, 0], sketchPlaneData[i, 1]);
sketchPlane = f.NewSketchPlane(plane);
// create the extrusion
extrusions[i] = f.NewExtrusion(isSolid[i], profile, sketchPlane,
extrusionOffsets[i, 1]);
extrusions[i].StartOffset = extrusionOffsets[i, 0];
m_combineElements.Append(extrusions[i]);
}
#endregion
#region Create the round extrusions
for (int i = 3; i <= 4; ++i)
{
// create the profile
profile = app.NewCurveArrArray();
curves = app.NewCurveArray();
plane = new Plane(profileData[i, 0], profileData[i, 1]);
curves.Append(app.NewArc(plane, arcRadius, 0, Math.PI * 2));
profile.Append(curves);
// create the sketch plane
plane = app.NewPlane(sketchPlaneData[i, 0], sketchPlaneData[i, 1]);
sketchPlane = f.NewSketchPlane(plane);
// create the extrusion
extrusions[i] = f.NewExtrusion(isSolid[i], profile, sketchPlane,
extrusionOffsets[i, 1]);
extrusions[i].StartOffset = extrusionOffsets[i, 0];
m_combineElements.Append(extrusions[i]);
}
#endregion
}
/// <summary>
/// create the connectors on the extrusions
/// </summary>
private void CreateConnectors()
{
List<PlanarFace> m_planarFaces = null;
Parameter param = null;
#region Create the Supply Air duct connector
// get the planar faces of extrusion1
m_planarFaces = GetPlanarFaces(extrusions[1]);
// create the Supply Air duct connector
DuctConnector connSupplyAir = f.NewDuctConnector(m_planarFaces[0].Reference,
DuctSystemType.SupplyAir);
param = connSupplyAir.get_Parameter(BuiltInParameter.CONNECTOR_HEIGHT);
param.Set(connectorDimensions[0, 0]);
param = connSupplyAir.get_Parameter(BuiltInParameter.CONNECTOR_WIDTH);
param.Set(connectorDimensions[0, 1]);
param = connSupplyAir.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_DIRECTION_PARAM);
param.Set(2);
param = connSupplyAir.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_CONFIGURATION_PARAM);
param.Set(1);
param = connSupplyAir.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_PARAM);
param.Set(flow);
#endregion
#region Create the Return Air duct connector
// get the planar faces of extrusion2
m_planarFaces = GetPlanarFaces(extrusions[2]);
// create the Return Air duct connector
DuctConnector connReturnAir = f.NewDuctConnector(m_planarFaces[0].Reference,
DuctSystemType.ReturnAir);
param = connReturnAir.get_Parameter(BuiltInParameter.CONNECTOR_HEIGHT);
param.Set(connectorDimensions[1, 0]);
param = connReturnAir.get_Parameter(BuiltInParameter.CONNECTOR_WIDTH);
param.Set(connectorDimensions[1, 1]);
param = connReturnAir.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_DIRECTION_PARAM);
param.Set(1);
param =
connReturnAir.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_CONFIGURATION_PARAM);
param.Set(1);
param = connReturnAir.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_PARAM);
param.Set(flow);
#endregion
#region Create the Supply Hydronic pipe connector
// get the planar faces of extrusion3
m_planarFaces = GetPlanarFaces(extrusions[3]);
// create the Hydronic Supply pipe connector
PipeConnector connSupplyHydronic = f.NewPipeConnector(m_planarFaces[0].Reference,
PipeSystemType.SupplyHydronic);
param = connSupplyHydronic.get_Parameter(BuiltInParameter.CONNECTOR_RADIUS);
param.Set(arcRadius);
param =
connSupplyHydronic.get_Parameter(BuiltInParameter.RBS_PIPE_FLOW_DIRECTION_PARAM);
param.Set(2);
#endregion
#region Create the Return Hydronic pipe connector
// get the planar faces of extrusion4
m_planarFaces = GetPlanarFaces(extrusions[4]);
// create the Hydronic Return pipe connector
PipeConnector connReturnHydronic = f.NewPipeConnector(m_planarFaces[0].Reference,
PipeSystemType.ReturnHydronic);
param = connReturnHydronic.get_Parameter(BuiltInParameter.CONNECTOR_RADIUS);
param.Set(arcRadius);
param =
connReturnHydronic.get_Parameter(BuiltInParameter.RBS_PIPE_FLOW_DIRECTION_PARAM);
param.Set(1);
#endregion
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting
{
using static ParameterValidationHelpers;
/// <summary>
/// Options for creating and running scripts.
/// </summary>
public sealed class ScriptOptions
{
public static ScriptOptions Default { get; } = new ScriptOptions(
filePath: "",
references: GetDefaultMetadataReferences(),
namespaces: ImmutableArray<string>.Empty,
metadataResolver: RuntimeMetadataReferenceResolver.Default,
sourceResolver: SourceFileResolver.Default);
private static ImmutableArray<MetadataReference> GetDefaultMetadataReferences()
{
if (GacFileResolver.IsAvailable)
{
return ImmutableArray<MetadataReference>.Empty;
}
// Provide similar surface to mscorlib (netstandard 2.0).
// These references are resolved lazily. Keep in sync with list in core csi.rsp.
var files = new[]
{
"System.Collections",
"System.Collections.Concurrent",
"System.Console",
"System.Diagnostics.Debug",
"System.Diagnostics.Process",
"System.Diagnostics.StackTrace",
"System.Globalization",
"System.IO",
"System.IO.FileSystem",
"System.IO.FileSystem.Primitives",
"System.Reflection",
"System.Reflection.Extensions",
"System.Reflection.Primitives",
"System.Runtime",
"System.Runtime.InteropServices",
"System.Text.Encoding",
"System.Text.Encoding.CodePages",
"System.Text.Encoding.Extensions",
"System.Text.RegularExpressions",
"System.Threading",
"System.Threading.Tasks",
"System.Threading.Tasks.Parallel",
"System.Threading.Thread",
};
return ImmutableArray.CreateRange(files.Select(CreateUnresolvedReference));
}
/// <summary>
/// An array of <see cref="MetadataReference"/>s to be added to the script.
/// </summary>
/// <remarks>
/// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>).
/// Unresolved references are resolved when the script is about to be executed
/// (<see cref="Script.RunAsync(object, CancellationToken)"/>.
/// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>.
/// </remarks>
public ImmutableArray<MetadataReference> MetadataReferences { get; private set; }
/// <summary>
/// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives.
/// </summary>
public MetadataReferenceResolver MetadataResolver { get; private set; }
/// <summary>
/// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive.
/// </summary>
public SourceReferenceResolver SourceResolver { get; private set; }
/// <summary>
/// The namespaces, static classes and aliases imported by the script.
/// </summary>
public ImmutableArray<string> Imports { get; private set; }
/// <summary>
/// The path to the script source if it originated from a file, empty otherwise.
/// </summary>
public string FilePath { get; private set; }
internal ScriptOptions(
string filePath,
ImmutableArray<MetadataReference> references,
ImmutableArray<string> namespaces,
MetadataReferenceResolver metadataResolver,
SourceReferenceResolver sourceResolver)
{
Debug.Assert(filePath != null);
Debug.Assert(!references.IsDefault);
Debug.Assert(!namespaces.IsDefault);
Debug.Assert(metadataResolver != null);
Debug.Assert(sourceResolver != null);
FilePath = filePath;
MetadataReferences = references;
Imports = namespaces;
MetadataResolver = metadataResolver;
SourceResolver = sourceResolver;
}
private ScriptOptions(ScriptOptions other)
: this(filePath: other.FilePath,
references: other.MetadataReferences,
namespaces: other.Imports,
metadataResolver: other.MetadataResolver,
sourceResolver: other.SourceResolver)
{
}
// a reference to an assembly should by default be equivalent to #r, which applies recursive global alias:
private static readonly MetadataReferenceProperties s_assemblyReferenceProperties =
MetadataReferenceProperties.Assembly.WithRecursiveAliases(true);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="FilePath"/> changed.
/// </summary>
public ScriptOptions WithFilePath(string filePath) =>
(FilePath == filePath) ? this : new ScriptOptions(this) { FilePath = filePath ?? "" };
private static MetadataReference CreateUnresolvedReference(string reference) =>
new UnresolvedMetadataReference(reference, s_assemblyReferenceProperties);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
private ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) =>
MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ToImmutableArrayChecked(references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params MetadataReference[] references) =>
WithReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ConcatChecked(MetadataReferences, references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params MetadataReference[] references) =>
AddReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions WithReferences(IEnumerable<Assembly> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions WithReferences(params Assembly[] references) =>
WithReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions AddReferences(IEnumerable<Assembly> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly));
private static MetadataReference CreateReferenceFromAssembly(Assembly assembly)
{
return MetadataReference.CreateFromAssemblyInternal(assembly, s_assemblyReferenceProperties);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions AddReferences(params Assembly[] references) =>
AddReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<string> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params string[] references) =>
WithReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<string> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params string[] references) =>
AddReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>.
/// </summary>
public ScriptOptions WithMetadataResolver(MetadataReferenceResolver resolver) =>
MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>.
/// </summary>
public ScriptOptions WithSourceResolver(SourceReferenceResolver resolver) =>
SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
private ScriptOptions WithImports(ImmutableArray<string> imports) =>
Imports.Equals(imports) ? this : new ScriptOptions(this) { Imports = CheckImmutableArray(imports, nameof(imports)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(IEnumerable<string> imports) =>
WithImports(ToImmutableArrayChecked(imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(params string[] imports) =>
WithImports((IEnumerable<string>)imports);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(IEnumerable<string> imports) =>
WithImports(ConcatChecked(Imports, imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(params string[] imports) =>
AddImports((IEnumerable<string>)imports);
}
}
| |
// 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.Reflection.Metadata.Tests;
using Xunit;
namespace System.Reflection.Metadata.Ecma335.Tests
{
public class ControlFlowBuilderTests
{
[Fact]
public void AddFinallyFaultFilterRegions()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var l1 = il.DefineLabel();
var l2 = il.DefineLabel();
var l3 = il.DefineLabel();
var l4 = il.DefineLabel();
var l5 = il.DefineLabel();
il.MarkLabel(l1);
Assert.Equal(0, il.Offset);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l2);
Assert.Equal(1, il.Offset);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l3);
Assert.Equal(3, il.Offset);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l4);
Assert.Equal(6, il.Offset);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l5);
Assert.Equal(10, il.Offset);
flow.AddFaultRegion(l1, l2, l3, l4);
flow.AddFinallyRegion(l1, l2, l3, l4);
flow.AddFilterRegion(l1, l2, l3, l4, l5);
var builder = new BlobBuilder();
builder.WriteByte(0xff);
flow.SerializeExceptionTable(builder);
AssertEx.Equal(new byte[]
{
0xFF, 0x00, 0x00, 0x00, // padding
0x01, // flag
(byte)(builder.Count - 4), // size
0x00, 0x00, // reserved
0x04, 0x00, // kind
0x00, 0x00, // try offset
0x01, // try length
0x03, 0x00, // handler offset
0x03, // handler length
0x00, 0x00, 0x00, 0x00, // catch type or filter offset
0x02, 0x00, // kind
0x00, 0x00, // try offset
0x01, // try length
0x03, 0x00, // handler offset
0x03, // handler length
0x00, 0x00, 0x00, 0x00, // catch type or filter offset
0x01, 0x00, // kind
0x00, 0x00, // try offset
0x01, // try length
0x03, 0x00, // handler offset
0x03, // handler length
0x0A, 0x00, 0x00, 0x00 // catch type or filter offset
}, builder.ToArray());
}
[Fact]
public void AddCatchRegions()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var l1 = il.DefineLabel();
var l2 = il.DefineLabel();
var l3 = il.DefineLabel();
var l4 = il.DefineLabel();
var l5 = il.DefineLabel();
il.MarkLabel(l1);
Assert.Equal(0, il.Offset);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l2);
Assert.Equal(1, il.Offset);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l3);
Assert.Equal(3, il.Offset);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l4);
Assert.Equal(6, il.Offset);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l5);
Assert.Equal(10, il.Offset);
flow.AddCatchRegion(l1, l2, l3, l4, MetadataTokens.TypeDefinitionHandle(1));
flow.AddCatchRegion(l1, l2, l3, l4, MetadataTokens.TypeSpecificationHandle(2));
flow.AddCatchRegion(l1, l2, l3, l4, MetadataTokens.TypeReferenceHandle(3));
var builder = new BlobBuilder();
flow.SerializeExceptionTable(builder);
AssertEx.Equal(new byte[]
{
0x01, // flag
(byte)builder.Count, // size
0x00, 0x00, // reserved
0x00, 0x00, // kind
0x00, 0x00, // try offset
0x01, // try length
0x03, 0x00, // handler offset
0x03, // handler length
0x01, 0x00, 0x00, 0x02, // catch type or filter offset
0x00, 0x00, // kind
0x00, 0x00, // try offset
0x01, // try length
0x03, 0x00, // handler offset
0x03, // handler length
0x02, 0x00, 0x00, 0x1B, // catch type or filter offset
0x00, 0x00, // kind
0x00, 0x00, // try offset
0x01, // try length
0x03, 0x00, // handler offset
0x03, // handler length
0x03, 0x00, 0x00, 0x01, // catch type or filter offset
}, builder.ToArray());
}
[Fact]
public void AddRegion_Errors1()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var ilx = new InstructionEncoder(code, new ControlFlowBuilder());
var l1 = il.DefineLabel();
var l2 = il.DefineLabel();
var l3 = il.DefineLabel();
var l4 = il.DefineLabel();
var l5 = il.DefineLabel();
ilx.DefineLabel();
ilx.DefineLabel();
ilx.DefineLabel();
ilx.DefineLabel();
ilx.DefineLabel();
ilx.DefineLabel();
var lx = ilx.DefineLabel();
il.MarkLabel(l1);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l2);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l3);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l4);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l5);
Assert.Throws<ArgumentException>(() => flow.AddCatchRegion(l1, l2, l3, l4, default(TypeDefinitionHandle)));
Assert.Throws<ArgumentException>(() => flow.AddCatchRegion(l1, l2, l3, l4, MetadataTokens.MethodDefinitionHandle(1)));
Assert.Throws<ArgumentNullException>(() => flow.AddCatchRegion(default(LabelHandle), l2, l3, l4, MetadataTokens.TypeReferenceHandle(1)));
Assert.Throws<ArgumentNullException>(() => flow.AddCatchRegion(l1, default(LabelHandle), l3, l4, MetadataTokens.TypeReferenceHandle(1)));
Assert.Throws<ArgumentNullException>(() => flow.AddCatchRegion(l1, l2, default(LabelHandle), l4, MetadataTokens.TypeReferenceHandle(1)));
Assert.Throws<ArgumentNullException>(() => flow.AddCatchRegion(l1, l2, l3, default(LabelHandle), MetadataTokens.TypeReferenceHandle(1)));
Assert.Throws<ArgumentException>(() => flow.AddCatchRegion(lx, l2, l3, l4, MetadataTokens.TypeReferenceHandle(1)));
Assert.Throws<ArgumentException>(() => flow.AddCatchRegion(l1, lx, l3, l4, MetadataTokens.TypeReferenceHandle(1)));
Assert.Throws<ArgumentException>(() => flow.AddCatchRegion(l1, l2, lx, l4, MetadataTokens.TypeReferenceHandle(1)));
Assert.Throws<ArgumentException>(() => flow.AddCatchRegion(l1, l2, l3, lx, MetadataTokens.TypeReferenceHandle(1)));
}
[Fact]
public void AddRegion_Errors2()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var l1 = il.DefineLabel();
var l2 = il.DefineLabel();
var l3 = il.DefineLabel();
var l4 = il.DefineLabel();
var l5 = il.DefineLabel();
il.MarkLabel(l1);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l2);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l3);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l4);
var streamBuilder = new BlobBuilder();
var encoder = new MethodBodyStreamEncoder(streamBuilder);
flow.AddFaultRegion(l2, l1, l3, l4);
Assert.Throws<InvalidOperationException>(() => encoder.AddMethodBody(il));
}
[Fact]
public void AddRegion_Errors3()
{
var code = new BlobBuilder();
var flow = new ControlFlowBuilder();
var il = new InstructionEncoder(code, flow);
var l1 = il.DefineLabel();
var l2 = il.DefineLabel();
var l3 = il.DefineLabel();
var l4 = il.DefineLabel();
var l5 = il.DefineLabel();
il.MarkLabel(l1);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l2);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l3);
il.OpCode(ILOpCode.Nop);
il.MarkLabel(l4);
var streamBuilder = new BlobBuilder();
var encoder = new MethodBodyStreamEncoder(streamBuilder);
flow.AddFaultRegion(l1, l2, l4, l3);
Assert.Throws<InvalidOperationException>(() => encoder.AddMethodBody(il));
}
}
}
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass()]
public partial class SlidingDrawer : android.view.ViewGroup
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static SlidingDrawer()
{
InitJNI();
}
protected SlidingDrawer(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.SlidingDrawer.OnDrawerCloseListener_))]
public interface OnDrawerCloseListener : global::MonoJavaBridge.IJavaObject
{
void onDrawerClosed();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.SlidingDrawer.OnDrawerCloseListener))]
public sealed partial class OnDrawerCloseListener_ : java.lang.Object, OnDrawerCloseListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnDrawerCloseListener_()
{
InitJNI();
}
internal OnDrawerCloseListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onDrawerClosed11960;
void android.widget.SlidingDrawer.OnDrawerCloseListener.onDrawerClosed()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.OnDrawerCloseListener_._onDrawerClosed11960);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.OnDrawerCloseListener_.staticClass, global::android.widget.SlidingDrawer.OnDrawerCloseListener_._onDrawerClosed11960);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.SlidingDrawer.OnDrawerCloseListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/SlidingDrawer$OnDrawerCloseListener"));
global::android.widget.SlidingDrawer.OnDrawerCloseListener_._onDrawerClosed11960 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.OnDrawerCloseListener_.staticClass, "onDrawerClosed", "()V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.SlidingDrawer.OnDrawerOpenListener_))]
public interface OnDrawerOpenListener : global::MonoJavaBridge.IJavaObject
{
void onDrawerOpened();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.SlidingDrawer.OnDrawerOpenListener))]
public sealed partial class OnDrawerOpenListener_ : java.lang.Object, OnDrawerOpenListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnDrawerOpenListener_()
{
InitJNI();
}
internal OnDrawerOpenListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onDrawerOpened11961;
void android.widget.SlidingDrawer.OnDrawerOpenListener.onDrawerOpened()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.OnDrawerOpenListener_._onDrawerOpened11961);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.OnDrawerOpenListener_.staticClass, global::android.widget.SlidingDrawer.OnDrawerOpenListener_._onDrawerOpened11961);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.SlidingDrawer.OnDrawerOpenListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/SlidingDrawer$OnDrawerOpenListener"));
global::android.widget.SlidingDrawer.OnDrawerOpenListener_._onDrawerOpened11961 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.OnDrawerOpenListener_.staticClass, "onDrawerOpened", "()V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.SlidingDrawer.OnDrawerScrollListener_))]
public interface OnDrawerScrollListener : global::MonoJavaBridge.IJavaObject
{
void onScrollStarted();
void onScrollEnded();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.SlidingDrawer.OnDrawerScrollListener))]
public sealed partial class OnDrawerScrollListener_ : java.lang.Object, OnDrawerScrollListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnDrawerScrollListener_()
{
InitJNI();
}
internal OnDrawerScrollListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onScrollStarted11962;
void android.widget.SlidingDrawer.OnDrawerScrollListener.onScrollStarted()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.OnDrawerScrollListener_._onScrollStarted11962);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.OnDrawerScrollListener_.staticClass, global::android.widget.SlidingDrawer.OnDrawerScrollListener_._onScrollStarted11962);
}
internal static global::MonoJavaBridge.MethodId _onScrollEnded11963;
void android.widget.SlidingDrawer.OnDrawerScrollListener.onScrollEnded()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.OnDrawerScrollListener_._onScrollEnded11963);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.OnDrawerScrollListener_.staticClass, global::android.widget.SlidingDrawer.OnDrawerScrollListener_._onScrollEnded11963);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.SlidingDrawer.OnDrawerScrollListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/SlidingDrawer$OnDrawerScrollListener"));
global::android.widget.SlidingDrawer.OnDrawerScrollListener_._onScrollStarted11962 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.OnDrawerScrollListener_.staticClass, "onScrollStarted", "()V");
global::android.widget.SlidingDrawer.OnDrawerScrollListener_._onScrollEnded11963 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.OnDrawerScrollListener_.staticClass, "onScrollEnded", "()V");
}
}
internal static global::MonoJavaBridge.MethodId _lock11964;
public virtual void @lock()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._lock11964);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._lock11964);
}
internal static global::MonoJavaBridge.MethodId _close11965;
public virtual void close()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._close11965);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._close11965);
}
internal static global::MonoJavaBridge.MethodId _getContent11966;
public virtual global::android.view.View getContent()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.SlidingDrawer._getContent11966)) as android.view.View;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._getContent11966)) as android.view.View;
}
internal static global::MonoJavaBridge.MethodId _open11967;
public virtual void open()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._open11967);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._open11967);
}
internal static global::MonoJavaBridge.MethodId _unlock11968;
public virtual void unlock()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._unlock11968);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._unlock11968);
}
internal static global::MonoJavaBridge.MethodId _toggle11969;
public virtual void toggle()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._toggle11969);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._toggle11969);
}
internal static global::MonoJavaBridge.MethodId _onTouchEvent11970;
public override bool onTouchEvent(android.view.MotionEvent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.SlidingDrawer._onTouchEvent11970, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._onTouchEvent11970, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _dispatchDraw11971;
protected override void dispatchDraw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._dispatchDraw11971, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._dispatchDraw11971, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onLayout11972;
protected override void onLayout(bool arg0, int arg1, int arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._onLayout11972, 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));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._onLayout11972, 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));
}
internal static global::MonoJavaBridge.MethodId _onFinishInflate11973;
protected override void onFinishInflate()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._onFinishInflate11973);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._onFinishInflate11973);
}
internal static global::MonoJavaBridge.MethodId _onMeasure11974;
protected override void onMeasure(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._onMeasure11974, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._onMeasure11974, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _onInterceptTouchEvent11975;
public override bool onInterceptTouchEvent(android.view.MotionEvent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.SlidingDrawer._onInterceptTouchEvent11975, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._onInterceptTouchEvent11975, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _animateToggle11976;
public virtual void animateToggle()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._animateToggle11976);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._animateToggle11976);
}
internal static global::MonoJavaBridge.MethodId _animateClose11977;
public virtual void animateClose()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._animateClose11977);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._animateClose11977);
}
internal static global::MonoJavaBridge.MethodId _animateOpen11978;
public virtual void animateOpen()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._animateOpen11978);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._animateOpen11978);
}
internal static global::MonoJavaBridge.MethodId _setOnDrawerOpenListener11979;
public virtual void setOnDrawerOpenListener(android.widget.SlidingDrawer.OnDrawerOpenListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._setOnDrawerOpenListener11979, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._setOnDrawerOpenListener11979, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setOnDrawerCloseListener11980;
public virtual void setOnDrawerCloseListener(android.widget.SlidingDrawer.OnDrawerCloseListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._setOnDrawerCloseListener11980, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._setOnDrawerCloseListener11980, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setOnDrawerScrollListener11981;
public virtual void setOnDrawerScrollListener(android.widget.SlidingDrawer.OnDrawerScrollListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer._setOnDrawerScrollListener11981, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._setOnDrawerScrollListener11981, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getHandle11982;
public virtual global::android.view.View getHandle()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.SlidingDrawer._getHandle11982)) as android.view.View;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._getHandle11982)) as android.view.View;
}
internal static global::MonoJavaBridge.MethodId _isOpened11983;
public virtual bool isOpened()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.SlidingDrawer._isOpened11983);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._isOpened11983);
}
internal static global::MonoJavaBridge.MethodId _isMoving11984;
public virtual bool isMoving()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.SlidingDrawer._isMoving11984);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._isMoving11984);
}
internal static global::MonoJavaBridge.MethodId _SlidingDrawer11985;
public SlidingDrawer(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._SlidingDrawer11985, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _SlidingDrawer11986;
public SlidingDrawer(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.SlidingDrawer.staticClass, global::android.widget.SlidingDrawer._SlidingDrawer11986, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
public static int ORIENTATION_HORIZONTAL
{
get
{
return 0;
}
}
public static int ORIENTATION_VERTICAL
{
get
{
return 1;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.SlidingDrawer.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/SlidingDrawer"));
global::android.widget.SlidingDrawer._lock11964 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "@lock", "()V");
global::android.widget.SlidingDrawer._close11965 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "close", "()V");
global::android.widget.SlidingDrawer._getContent11966 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "getContent", "()Landroid/view/View;");
global::android.widget.SlidingDrawer._open11967 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "open", "()V");
global::android.widget.SlidingDrawer._unlock11968 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "unlock", "()V");
global::android.widget.SlidingDrawer._toggle11969 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "toggle", "()V");
global::android.widget.SlidingDrawer._onTouchEvent11970 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z");
global::android.widget.SlidingDrawer._dispatchDraw11971 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "dispatchDraw", "(Landroid/graphics/Canvas;)V");
global::android.widget.SlidingDrawer._onLayout11972 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "onLayout", "(ZIIII)V");
global::android.widget.SlidingDrawer._onFinishInflate11973 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "onFinishInflate", "()V");
global::android.widget.SlidingDrawer._onMeasure11974 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "onMeasure", "(II)V");
global::android.widget.SlidingDrawer._onInterceptTouchEvent11975 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "onInterceptTouchEvent", "(Landroid/view/MotionEvent;)Z");
global::android.widget.SlidingDrawer._animateToggle11976 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "animateToggle", "()V");
global::android.widget.SlidingDrawer._animateClose11977 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "animateClose", "()V");
global::android.widget.SlidingDrawer._animateOpen11978 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "animateOpen", "()V");
global::android.widget.SlidingDrawer._setOnDrawerOpenListener11979 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "setOnDrawerOpenListener", "(Landroid/widget/SlidingDrawer$OnDrawerOpenListener;)V");
global::android.widget.SlidingDrawer._setOnDrawerCloseListener11980 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "setOnDrawerCloseListener", "(Landroid/widget/SlidingDrawer$OnDrawerCloseListener;)V");
global::android.widget.SlidingDrawer._setOnDrawerScrollListener11981 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "setOnDrawerScrollListener", "(Landroid/widget/SlidingDrawer$OnDrawerScrollListener;)V");
global::android.widget.SlidingDrawer._getHandle11982 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "getHandle", "()Landroid/view/View;");
global::android.widget.SlidingDrawer._isOpened11983 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "isOpened", "()Z");
global::android.widget.SlidingDrawer._isMoving11984 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "isMoving", "()Z");
global::android.widget.SlidingDrawer._SlidingDrawer11985 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::android.widget.SlidingDrawer._SlidingDrawer11986 = @__env.GetMethodIDNoThrow(global::android.widget.SlidingDrawer.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V");
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataColumnMapping.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
[
System.ComponentModel.TypeConverterAttribute(typeof(System.Data.Common.DataColumnMapping.DataColumnMappingConverter))
]
public sealed class DataColumnMapping : MarshalByRefObject, IColumnMapping, ICloneable {
private DataColumnMappingCollection parent;
private string _dataSetColumnName;
private string _sourceColumnName;
public DataColumnMapping() {
}
public DataColumnMapping(string sourceColumn, string dataSetColumn) {
SourceColumn = sourceColumn;
DataSetColumn = dataSetColumn;
}
[
DefaultValue(""),
ResCategoryAttribute(Res.DataCategory_Mapping),
ResDescriptionAttribute(Res.DataColumnMapping_DataSetColumn),
]
public string DataSetColumn {
get {
string dataSetColumnName = _dataSetColumnName;
return ((null != dataSetColumnName) ? dataSetColumnName : ADP.StrEmpty);
}
set {
_dataSetColumnName = value;
}
}
internal DataColumnMappingCollection Parent {
get {
return parent;
}
set {
parent = value;
}
}
[
DefaultValue(""),
ResCategoryAttribute(Res.DataCategory_Mapping),
ResDescriptionAttribute(Res.DataColumnMapping_SourceColumn),
]
public string SourceColumn {
get {
string sourceColumnName = _sourceColumnName;
return ((null != sourceColumnName) ? sourceColumnName : ADP.StrEmpty);
}
set {
if ((null != Parent) && (0 != ADP.SrcCompare(_sourceColumnName, value))) {
Parent.ValidateSourceColumn(-1, value);
}
_sourceColumnName = value;
}
}
object ICloneable.Clone() {
DataColumnMapping clone = new DataColumnMapping(); // MDAC 81448
clone._sourceColumnName = _sourceColumnName;
clone._dataSetColumnName = _dataSetColumnName;
return clone;
}
[ EditorBrowsableAttribute(EditorBrowsableState.Advanced) ] // MDAC 69508
public DataColumn GetDataColumnBySchemaAction(DataTable dataTable, Type dataType, MissingSchemaAction schemaAction) {
return GetDataColumnBySchemaAction(SourceColumn, DataSetColumn, dataTable, dataType, schemaAction);
}
[ EditorBrowsableAttribute(EditorBrowsableState.Advanced) ] // MDAC 69508
static public DataColumn GetDataColumnBySchemaAction(string sourceColumn, string dataSetColumn, DataTable dataTable, Type dataType, MissingSchemaAction schemaAction) {
if (null == dataTable) {
throw ADP.ArgumentNull("dataTable");
}
if (ADP.IsEmpty(dataSetColumn)) {
#if DEBUG
if (AdapterSwitches.DataSchema.TraceWarning) {
Debug.WriteLine("explicit filtering of SourceColumn \"" + sourceColumn + "\"");
}
#endif
return null;
}
DataColumnCollection columns = dataTable.Columns;
Debug.Assert(null != columns, "GetDataColumnBySchemaAction: unexpected null DataColumnCollection");
int index = columns.IndexOf(dataSetColumn);
if ((0 <= index) && (index < columns.Count)) {
DataColumn dataColumn = columns[index];
Debug.Assert(null != dataColumn, "GetDataColumnBySchemaAction: unexpected null dataColumn");
if (!ADP.IsEmpty(dataColumn.Expression)) {
#if DEBUG
if (AdapterSwitches.DataSchema.TraceError) {
Debug.WriteLine("schema mismatch on DataColumn \"" + dataSetColumn + "\" which is a computed column");
}
#endif
throw ADP.ColumnSchemaExpression(sourceColumn, dataSetColumn);
}
if ((null == dataType) || (dataType.IsArray == dataColumn.DataType.IsArray)) {
#if DEBUG
if (AdapterSwitches.DataSchema.TraceInfo) {
Debug.WriteLine("schema match on DataColumn \"" + dataSetColumn + "\"");
}
#endif
return dataColumn;
}
#if DEBUG
if (AdapterSwitches.DataSchema.TraceWarning) {
Debug.WriteLine("schema mismatch on DataColumn \"" + dataSetColumn + "\" " + dataType.Name + " != " + dataColumn.DataType.Name);
}
#endif
throw ADP.ColumnSchemaMismatch(sourceColumn, dataType, dataColumn);
}
return CreateDataColumnBySchemaAction(sourceColumn, dataSetColumn, dataTable, dataType, schemaAction);
}
static internal DataColumn CreateDataColumnBySchemaAction(string sourceColumn, string dataSetColumn, DataTable dataTable, Type dataType, MissingSchemaAction schemaAction) {
Debug.Assert(dataTable != null, "Should not call with a null DataTable");
if (ADP.IsEmpty(dataSetColumn)) {
return null;
}
switch (schemaAction) {
case MissingSchemaAction.Add:
case MissingSchemaAction.AddWithKey:
#if DEBUG
if (AdapterSwitches.DataSchema.TraceInfo) {
Debug.WriteLine("schema add of DataColumn \"" + dataSetColumn + "\" <" + Convert.ToString(dataType, CultureInfo.InvariantCulture) +">");
}
#endif
return new DataColumn(dataSetColumn, dataType);
case MissingSchemaAction.Ignore:
#if DEBUG
if (AdapterSwitches.DataSchema.TraceWarning) {
Debug.WriteLine("schema filter of DataColumn \"" + dataSetColumn + "\" <" + Convert.ToString(dataType, CultureInfo.InvariantCulture) +">");
}
#endif
return null;
case MissingSchemaAction.Error:
#if DEBUG
if (AdapterSwitches.DataSchema.TraceError) {
Debug.WriteLine("schema error on DataColumn \"" + dataSetColumn + "\" <" + Convert.ToString(dataType, CultureInfo.InvariantCulture) +">");
}
#endif
throw ADP.ColumnSchemaMissing(dataSetColumn, dataTable.TableName, sourceColumn);
}
throw ADP.InvalidMissingSchemaAction(schemaAction);
}
public override String ToString() {
return SourceColumn;
}
sealed internal class DataColumnMappingConverter : System.ComponentModel.ExpandableObjectConverter {
// converter classes should have public ctor
public DataColumnMappingConverter() {
}
override public bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (typeof(InstanceDescriptor) == destinationType) {
return true;
}
return base.CanConvertTo(context, destinationType);
}
override public object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (null == destinationType) {
throw ADP.ArgumentNull("destinationType");
}
if ((typeof(InstanceDescriptor) == destinationType) && (value is DataColumnMapping)) {
DataColumnMapping mapping = (DataColumnMapping)value;
object[] values = new object[] { mapping.SourceColumn, mapping.DataSetColumn };
Type[] types = new Type[] { typeof(string), typeof(string) };
ConstructorInfo ctor = typeof(DataColumnMapping).GetConstructor(types);
return new InstanceDescriptor(ctor, values);
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using NuGet.VisualStudio.Resources;
using MsBuildProject = Microsoft.Build.Evaluation.Project;
using MsBuildProjectItem = Microsoft.Build.Evaluation.ProjectItem;
using Project = EnvDTE.Project;
namespace NuGet.VisualStudio
{
public class VsProjectSystem : PhysicalFileSystem, IVsProjectSystem, IComparer<IPackageFile>
{
private const string BinDir = "bin";
private FrameworkName _targetFramework;
private readonly IFileSystem _baseFileSystem;
public VsProjectSystem(Project project, IFileSystemProvider fileSystemProvider)
: base(project.GetFullPath())
{
Project = project;
_baseFileSystem = fileSystemProvider.GetFileSystem(project.GetFullPath());
Debug.Assert(_baseFileSystem != null);
}
protected Project Project
{
get;
private set;
}
protected IFileSystem BaseFileSystem
{
get
{
return _baseFileSystem;
}
}
public virtual string ProjectName
{
get
{
return Project.Name;
}
}
public string UniqueName
{
get
{
return Project.GetUniqueName();
}
}
public FrameworkName TargetFramework
{
get
{
if (_targetFramework == null)
{
_targetFramework = Project.GetTargetFrameworkName() ?? VersionUtility.DefaultTargetFramework;
}
return _targetFramework;
}
}
public virtual bool IsBindingRedirectSupported
{
get
{
// Silverlight projects and Windows Phone projects do not support binding redirect.
// They both share the same identifier as "Silverlight"
return !"Silverlight".Equals(TargetFramework.Identifier, StringComparison.OrdinalIgnoreCase);
}
}
public override void AddFile(string path, Stream stream)
{
AddFileCore(path, () => base.AddFile(path, stream));
}
public override void AddFile(string path, Action<Stream> writeToStream)
{
AddFileCore(path, () => base.AddFile(path, writeToStream));
}
private void AddFileCore(string path, Action addFile)
{
bool fileExistsInProject = FileExistsInProject(path);
// If the file exists on disk but not in the project then skip it
if (base.FileExists(path) && !fileExistsInProject)
{
Logger.Log(MessageLevel.Warning, VsResources.Warning_FileAlreadyExists, path);
}
else
{
EnsureCheckedOutIfExists(path);
addFile();
if (!fileExistsInProject)
{
AddFileToProject(path);
}
}
}
public override Stream CreateFile(string path)
{
EnsureCheckedOutIfExists(path);
return base.CreateFile(path);
}
public override void DeleteDirectory(string path, bool recursive = false)
{
// Only delete this folder if it is empty and we didn't specify that we want to recurse
if (!recursive && (base.GetFiles(path, "*.*", recursive).Any() || base.GetDirectories(path).Any()))
{
Logger.Log(MessageLevel.Warning, VsResources.Warning_DirectoryNotEmpty, path);
return;
}
// Workaround for TFS update issue. If we're bound to TFS, do not try and delete directories.
if (!(_baseFileSystem is ISourceControlFileSystem) && Project.DeleteProjectItem(path))
{
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFolder, path);
}
}
public override void DeleteFile(string path)
{
if (Project.DeleteProjectItem(path))
{
string folderPath = Path.GetDirectoryName(path);
if (!String.IsNullOrEmpty(folderPath))
{
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFileFromFolder, Path.GetFileName(path), folderPath);
}
else
{
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFile, Path.GetFileName(path));
}
}
}
public void AddFrameworkReference(string name)
{
try
{
// Add a reference to the project
AddGacReference(name);
Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName);
}
catch (Exception e)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddGacReference, name), e);
}
}
protected virtual void AddGacReference(string name)
{
Project.Object.References.Add(name);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to catch all exceptions")]
public virtual void AddReference(string referencePath, Stream stream)
{
string name = Path.GetFileNameWithoutExtension(referencePath);
try
{
// Get the full path to the reference
string fullPath = PathUtility.GetAbsolutePath(Root, referencePath);
string assemblyPath = fullPath;
bool usedTempFile = false;
// There is a bug in Visual Studio whereby if the fullPath contains a comma,
// then calling Project.Object.References.Add() on it will throw a COM exception.
// To work around it, we copy the assembly into temp folder and add reference to the copied assembly
if (fullPath.Contains(","))
{
string tempFile = Path.Combine(Path.GetTempPath(), Path.GetFileName(fullPath));
File.Copy(fullPath, tempFile, true);
assemblyPath = tempFile;
usedTempFile = true;
}
// Add a reference to the project
dynamic reference = Project.Object.References.Add(assemblyPath);
// if we copied the assembly to temp folder earlier, delete it now since we no longer need it.
if (usedTempFile)
{
try
{
File.Delete(assemblyPath);
}
catch
{
// don't care if we fail to delete a temp file
}
}
TrySetCopyLocal(reference);
// This happens if the assembly appears in any of the search paths that VS uses to locate assembly references.
// Most commonly, it happens if this assembly is in the GAC or in the output path.
if (!reference.Path.Equals(fullPath, StringComparison.OrdinalIgnoreCase))
{
// Get the msbuild project for this project
MsBuildProject buildProject = Project.AsMSBuildProject();
if (buildProject != null)
{
// Get the assembly name of the reference we are trying to add
AssemblyName assemblyName = AssemblyName.GetAssemblyName(fullPath);
// Try to find the item for the assembly name
MsBuildProjectItem item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences()
where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2)
select assemblyReferenceNode.Item1).FirstOrDefault();
if (item != null)
{
// Add the <HintPath> metadata item as a relative path
item.SetMetadataValue("HintPath", referencePath);
// Save the project after we've modified it.
Project.Save();
}
}
}
Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName);
}
catch (Exception e)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddReference, name), e);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to catch all exceptions")]
public virtual void RemoveReference(string name)
{
try
{
// Get the reference name without extension
string referenceName = Path.GetFileNameWithoutExtension(name);
// Remove the reference from the project
// NOTE:- Project.Object.References.Item requires Reference.Identity
// which is, the Assembly name without path or extension
// But, we pass in the assembly file name. And, this works for
// almost all the assemblies since Assembly Name is the same as the assembly file name
// In case of F#, the input parameter is case-sensitive as well
// Hence, an override to THIS function is added to take care of that
var reference = Project.Object.References.Item(referenceName);
if (reference != null)
{
reference.Remove();
Logger.Log(MessageLevel.Debug, VsResources.Debug_RemoveReference, name, ProjectName);
}
}
catch (Exception e)
{
Logger.Log(MessageLevel.Warning, e.Message);
}
}
public virtual bool FileExistsInProject(string path)
{
return Project.ContainsFile(path);
}
protected virtual bool ExcludeFile(string path)
{
// Exclude files from the bin directory.
return Path.GetDirectoryName(path).Equals(BinDir, StringComparison.OrdinalIgnoreCase);
}
protected virtual void AddFileToProject(string path)
{
if (ExcludeFile(path))
{
return;
}
// Get the project items for the folder path
string folderPath = Path.GetDirectoryName(path);
string fullPath = GetFullPath(path);
ThreadHelper.Generic.Invoke(() =>
{
ProjectItems container = Project.GetProjectItems(folderPath, createIfNotExists: true);
// Add the file to project or folder
AddFileToContainer(fullPath, folderPath, container);
});
Logger.Log(MessageLevel.Debug, VsResources.Debug_AddedFileToProject, path, ProjectName);
}
protected virtual void AddFileToContainer(string fullPath, string folderPath, ProjectItems container)
{
container.AddFromFileCopy(fullPath);
}
public virtual string ResolvePath(string path)
{
return path;
}
public override IEnumerable<string> GetFiles(string path, string filter, bool recursive)
{
if (recursive)
{
throw new NotSupportedException();
}
else
{
// Get all physical files
return from p in Project.GetChildItems(path, filter, VsConstants.VsProjectItemKindPhysicalFile)
select p.Name;
}
}
public override IEnumerable<string> GetDirectories(string path)
{
// Get all physical folders
return from p in Project.GetChildItems(path, "*.*", VsConstants.VsProjectItemKindPhysicalFolder)
select p.Name;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We never want to fail when checking for existance")]
public virtual bool ReferenceExists(string name)
{
try
{
string referenceName = name;
if (Constants.AssemblyReferencesExtensions.Contains(Path.GetExtension(name), StringComparer.OrdinalIgnoreCase))
{
// Get the reference name without extension
referenceName = Path.GetFileNameWithoutExtension(name);
}
return Project.Object.References.Item(referenceName) != null;
}
catch
{
}
return false;
}
public virtual dynamic GetPropertyValue(string propertyName)
{
try
{
Property property = Project.Properties.Item(propertyName);
if (property != null)
{
return property.Value;
}
}
catch (ArgumentException)
{
// If the property doesn't exist this will throw an argument exception
}
return null;
}
public virtual void AddImport(string targetPath, ProjectImportLocation location)
{
if (String.IsNullOrEmpty(targetPath))
{
throw new ArgumentNullException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "targetPath");
}
string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath);
Project.AddImportStatement(relativeTargetPath, location);
Project.Save();
}
public virtual void RemoveImport(string targetPath)
{
if (String.IsNullOrEmpty(targetPath))
{
throw new ArgumentNullException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "targetPath");
}
string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath);
Project.RemoveImportStatement(relativeTargetPath);
Project.Save();
}
public virtual bool IsSupportedFile(string path)
{
string fileName = Path.GetFileName(path);
// exclude all file names with the pattern as "web.*.config",
// e.g. web.config, web.release.config, web.debug.config
return !(fileName.StartsWith("web.", StringComparison.OrdinalIgnoreCase) &&
fileName.EndsWith(".config", StringComparison.OrdinalIgnoreCase));
}
private void EnsureCheckedOutIfExists(string path)
{
Project.EnsureCheckedOutIfExists(this, path);
}
private static bool AssemblyNamesMatch(AssemblyName name1, AssemblyName name2)
{
return name1.Name.Equals(name2.Name, StringComparison.OrdinalIgnoreCase) &&
EqualsIfNotNull(name1.Version, name2.Version) &&
EqualsIfNotNull(name1.CultureInfo, name2.CultureInfo) &&
EqualsIfNotNull(name1.GetPublicKeyToken(), name2.GetPublicKeyToken(), Enumerable.SequenceEqual);
}
private static bool EqualsIfNotNull<T>(T obj1, T obj2)
{
return EqualsIfNotNull(obj1, obj2, (a, b) => a.Equals(b));
}
private static bool EqualsIfNotNull<T>(T obj1, T obj2, Func<T, T, bool> equals)
{
// If both objects are non null do the equals
if (obj1 != null && obj2 != null)
{
return equals(obj1, obj2);
}
// Otherwise consider them equal if either of the values are null
return true;
}
public int Compare(IPackageFile x, IPackageFile y)
{
// BUG 636: We sort files so that they are added in the correct order
// e.g aspx before aspx.cs
if (x.Path.Equals(y.Path, StringComparison.OrdinalIgnoreCase))
{
return 0;
}
// Add files that are prefixes of other files first
if (x.Path.StartsWith(y.Path, StringComparison.OrdinalIgnoreCase))
{
return -1;
}
if (y.Path.StartsWith(x.Path, StringComparison.OrdinalIgnoreCase))
{
return 1;
}
return y.Path.CompareTo(x.Path);
}
private static void TrySetCopyLocal(dynamic reference)
{
// Always set copy local to true for references that we add
try
{
reference.CopyLocal = true;
}
catch (NotSupportedException)
{
}
catch (NotImplementedException)
{
}
}
}
}
| |
// 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.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Security
{
internal class SslState
{
//
// The public Client and Server classes enforce the parameters rules before
// calling into this .ctor.
//
internal SslState(Stream innerStream)
{
}
internal void ValidateCreateContext(SslClientAuthenticationOptions sslClientAuthenticationOptions, RemoteCertValidationCallback remoteCallback, LocalCertSelectionCallback localCallback)
{
}
internal void ValidateCreateContext(SslAuthenticationOptions sslAuthenticationOptions)
{
}
internal SslApplicationProtocol NegotiatedApplicationProtocol
{
get
{
return default;
}
}
internal bool IsAuthenticated
{
get
{
return false;
}
}
internal bool IsMutuallyAuthenticated
{
get
{
return false;
}
}
internal bool RemoteCertRequired
{
get
{
return false;
}
}
internal bool IsServer
{
get
{
return false;
}
}
//
// This will return selected local cert for both client/server streams
//
internal X509Certificate LocalCertificate
{
get
{
return null;
}
}
internal ChannelBinding GetChannelBinding(ChannelBindingKind kind)
{
return null;
}
internal bool CheckCertRevocationStatus
{
get
{
return false;
}
}
internal CipherAlgorithmType CipherAlgorithm
{
get
{
return CipherAlgorithmType.Null;
}
}
internal int CipherStrength
{
get
{
return 0;
}
}
internal HashAlgorithmType HashAlgorithm
{
get
{
return HashAlgorithmType.None;
}
}
internal int HashStrength
{
get
{
return 0;
}
}
internal ExchangeAlgorithmType KeyExchangeAlgorithm
{
get
{
return ExchangeAlgorithmType.None;
}
}
internal int KeyExchangeStrength
{
get
{
return 0;
}
}
internal SslProtocols SslProtocol
{
get
{
return SslProtocols.None;
}
}
internal _SslStream SecureStream
{
get
{
return null;
}
}
public bool IsShutdown { get; internal set; }
internal void CheckThrow(bool authSucessCheck)
{
}
internal void Flush()
{
}
internal Task FlushAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
//
// This is to not depend on GC&SafeHandle class if the context is not needed anymore.
//
internal void Close()
{
}
//
// This method assumes that a SSPI context is already in a good shape.
// For example it is either a fresh context or already authenticated context that needs renegotiation.
//
internal void ProcessAuthentication(LazyAsyncResult lazyResult)
{
}
internal void EndProcessAuthentication(IAsyncResult result)
{
}
internal IAsyncResult BeginShutdown(AsyncCallback asyncCallback, object asyncState)
{
throw new NotImplementedException();
}
internal void EndShutdown(IAsyncResult asyncResult)
{
throw new NotImplementedException();
}
}
internal class _SslStream : Stream
{
public override bool CanRead
{
get
{
throw new NotImplementedException();
}
}
public override bool CanSeek
{
get
{
throw new NotImplementedException();
}
}
public override bool CanWrite
{
get
{
throw new NotImplementedException();
}
}
public override long Length
{
get
{
throw new NotImplementedException();
}
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override void Flush()
{
throw new NotImplementedException();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return Task.FromException(new NotImplementedException());
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public new ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
throw new NotImplementedException();
}
public override int EndRead(IAsyncResult asyncResult)
{
throw new NotImplementedException();
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
throw new NotImplementedException();
}
public override void EndWrite(IAsyncResult asyncResult)
{
throw new NotImplementedException();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Dynamic;
using System.Linq;
using System.Text;
namespace Massive.SQLite
{
public static class ObjectExtensions
{
/// <summary>
/// Extension method for adding in a bunch of parameters
/// </summary>
public static void AddParams(this DbCommand cmd, params object[] args)
{
foreach (var item in args)
{
AddParam(cmd, item);
}
}
/// <summary>
/// Extension for adding single parameter
/// </summary>
public static void AddParam(this DbCommand cmd, object item)
{
var p = cmd.CreateParameter();
p.ParameterName = string.Format("@{0}", cmd.Parameters.Count);
if (item == null)
{
p.Value = DBNull.Value;
}
else
{
if (item.GetType() == typeof(Guid))
{
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
}
else if (item.GetType() == typeof(ExpandoObject))
{
var d = (IDictionary<string, object>)item;
p.Value = d.Values.FirstOrDefault();
}
else
{
p.Value = item;
}
if (item.GetType() == typeof(string))
p.Size = ((string)item).Length > 4000 ? -1 : 4000;
}
cmd.Parameters.Add(p);
}
/// <summary>
/// Turns an IDataReader to a Dynamic list of things
/// </summary>
public static List<dynamic> ToExpandoList(this IDataReader rdr)
{
var result = new List<dynamic>();
while (rdr.Read())
{
result.Add(rdr.RecordToExpando());
}
return result;
}
public static dynamic RecordToExpando(this IDataReader rdr)
{
dynamic e = new ExpandoObject();
var d = e as IDictionary<string, object>;
object[] values = new object[rdr.FieldCount];
rdr.GetValues(values);
for(int i = 0; i < values.Length; i++)
{
var v = values[i];
d.Add(rdr.GetName(i), DBNull.Value.Equals(v) ? null : v);
}
return e;
}
/// <summary>
/// Turns the object into an ExpandoObject
/// </summary>
public static dynamic ToExpando(this object o)
{
if (o.GetType() == typeof(ExpandoObject)) return o; //shouldn't have to... but just in case
var result = new ExpandoObject();
var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection)))
{
var nv = (NameValueCollection)o;
nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i));
}
else
{
var props = o.GetType().GetProperties();
foreach (var item in props)
{
d.Add(item.Name, item.GetValue(o, null));
}
}
return result;
}
/// <summary>
/// Turns the object into a Dictionary
/// </summary>
public static IDictionary<string, object> ToDictionary(this object thingy)
{
return (IDictionary<string, object>)thingy.ToExpando();
}
}
/// <summary>
/// A class that wraps your database table in Dynamic Funtime
/// </summary>
public class DynamicModel : DynamicObject
{
DbProviderFactory _factory;
string ConnectionString;
public static DynamicModel Open(string connectionStringName)
{
dynamic dm = new DynamicModel(connectionStringName);
return dm;
}
public DynamicModel(string connectionStringName, string tableName = "", string primaryKeyField = "")
{
TableName = tableName == "" ? this.GetType().Name : tableName;
PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField;
var _providerName = "System.Data.SQLite";
_factory = DbProviderFactories.GetFactory(_providerName);
ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
_providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName;
}
/// <summary>
/// Creates a new Expando from a Form POST - white listed against the columns in the DB
/// </summary>
public dynamic CreateFrom(NameValueCollection coll)
{
dynamic result = new ExpandoObject();
var dc = (IDictionary<string, object>)result;
var schema = Schema;
//loop the collection, setting only what's in the Schema
foreach (var item in coll.Keys)
{
var exists = schema.Any(x => x.COLUMN_NAME.ToLower() == item.ToString().ToLower());
if (exists)
{
var key = item.ToString();
var val = coll[key];
if (!String.IsNullOrEmpty(val))
{
//what to do here? If it's empty... set it to NULL?
//if it's a string value - let it go through if it's NULLABLE?
//Empty? WTF?
dc.Add(key, val);
}
}
}
return result;
}
/// <summary>
/// Gets a default value for the column
/// </summary>
public dynamic DefaultValue(dynamic column)
{
dynamic result = null;
string def = column.COLUMN_DEFAULT;
if (String.IsNullOrEmpty(def))
{
result = null;
}
else if (def.ToUpper() == "CURRENT_TIME")
{
result = DateTime.UtcNow.ToString("HH:mm:ss");
}
else if (def.ToUpper() == "CURRENT_DATE")
{
result = DateTime.UtcNow.ToString("yyyy-MM-dd");
}
else if (def.ToUpper() == "CURRENT_TIMESTAMP")
{
result = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
}
return result;
}
/// <summary>
/// Creates an empty Expando set with defaults from the DB
/// </summary>
public dynamic Prototype
{
get
{
dynamic result = new ExpandoObject();
var schema = Schema;
foreach (dynamic column in schema)
{
var dc = (IDictionary<string, object>)result;
dc.Add(column.COLUMN_NAME, DefaultValue(column));
}
result._Table = this;
return result;
}
}
/// <summary>
/// List out all the schema bits for use with ... whatever
/// </summary>
IEnumerable<dynamic> _schema;
public IEnumerable<dynamic> Schema
{
get
{
if (_schema == null)
{
var rows = new List<dynamic>();
foreach (var row in Query("PRAGMA table_info('" + TableName + "')"))
{
rows.Add(new
{
COLUMN_NAME = (row as IDictionary<string, object>)["name"].ToString(),
DATA_TYPE = (row as IDictionary<string, object>)["type"].ToString(),
IS_NULLABLE = (row as IDictionary<string, object>)["notnull"].ToString() == "0" ? "NO" : "YES",
COLUMN_DEFAULT = (row as IDictionary<string, object>)["dflt_value"] ?? "",
});
}
_schema = rows;
}
return _schema;
}
}
/// <summary>
/// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert
/// </summary>
public virtual IEnumerable<dynamic> Query(string sql, params object[] args)
{
using (var conn = OpenConnection())
{
var rdr = CreateCommand(sql, conn, args).ExecuteReader();
while (rdr.Read())
{
yield return rdr.RecordToExpando(); ;
}
}
}
public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, params object[] args)
{
using (var rdr = CreateCommand(sql, connection, args).ExecuteReader())
{
while (rdr.Read())
{
yield return rdr.RecordToExpando(); ;
}
}
}
/// <summary>
/// Returns a single result
/// </summary>
public virtual object Scalar(string sql, params object[] args)
{
object result = null;
using (var conn = OpenConnection())
{
result = CreateCommand(sql, conn, args).ExecuteScalar();
}
return result;
}
/// <summary>
/// Creates a DBCommand that you can use for loving your database.
/// </summary>
DbCommand CreateCommand(string sql, DbConnection conn, params object[] args)
{
var result = _factory.CreateCommand();
result.Connection = conn;
result.CommandText = sql;
if (args.Length > 0)
result.AddParams(args);
return result;
}
/// <summary>
/// Returns and OpenConnection
/// </summary>
public virtual DbConnection OpenConnection()
{
var result = _factory.CreateConnection();
result.ConnectionString = ConnectionString;
result.Open();
return result;
}
/// <summary>
/// Builds a set of Insert and Update commands based on the passed-on objects.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual List<DbCommand> BuildCommands(params object[] things)
{
var commands = new List<DbCommand>();
foreach (var item in things)
{
if (HasPrimaryKey(item))
{
commands.Add(CreateUpdateCommand(item, GetPrimaryKey(item)));
}
else
{
commands.Add(CreateInsertCommand(item));
}
}
return commands;
}
/// <summary>
/// Executes a set of objects as Insert or Update commands based on their property settings, within a transaction.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual int Save(params object[] things)
{
var commands = BuildCommands(things);
return Execute(commands);
}
public virtual int Execute(DbCommand command)
{
return Execute(new DbCommand[] { command });
}
public virtual int Execute(string sql, params object[] args)
{
return Execute(CreateCommand(sql, null, args));
}
/// <summary>
/// Executes a series of DBCommands in a transaction
/// </summary>
public virtual int Execute(IEnumerable<DbCommand> commands)
{
var result = 0;
using (var conn = OpenConnection())
{
using (var tx = conn.BeginTransaction())
{
foreach (var cmd in commands)
{
cmd.Connection = conn;
cmd.Transaction = tx;
result += cmd.ExecuteNonQuery();
}
tx.Commit();
}
}
return result;
}
public virtual string PrimaryKeyField { get; set; }
/// <summary>
/// Conventionally introspects the object passed in for a field that
/// looks like a PK. If you've named your PrimaryKeyField, this becomes easy
/// </summary>
public virtual bool HasPrimaryKey(object o)
{
return o.ToDictionary().ContainsKey(PrimaryKeyField);
}
/// <summary>
/// If the object passed in has a property with the same name as your PrimaryKeyField
/// it is returned here.
/// </summary>
public virtual object GetPrimaryKey(object o)
{
object result = null;
o.ToDictionary().TryGetValue(PrimaryKeyField, out result);
return result;
}
public virtual string TableName { get; set; }
/// <summary>
/// Creates a command for use with transactions - internal stuff mostly, but here for you to play with
/// </summary>
public virtual DbCommand CreateInsertCommand(object o)
{
DbCommand result = null;
var expando = o.ToExpando();
var settings = (IDictionary<string, object>)expando;
var sbKeys = new StringBuilder();
var sbVals = new StringBuilder();
var stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})";
result = CreateCommand(stub, null);
int counter = 0;
foreach (var item in settings)
{
sbKeys.AppendFormat("{0},", item.Key);
sbVals.AppendFormat("@{0},", counter.ToString());
result.AddParam(item.Value);
counter++;
}
if (counter > 0)
{
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 1);
var vals = sbVals.ToString().Substring(0, sbVals.Length - 1);
var sql = string.Format(stub, TableName, keys, vals);
result.CommandText = sql;
}
else throw new InvalidOperationException("Can't parse this object to the database - there are no properties set");
return result;
}
/// <summary>
/// Creates a command for use with transactions - internal stuff mostly, but here for you to play with
/// </summary>
public virtual DbCommand CreateUpdateCommand(object o, object key)
{
var expando = o.ToExpando();
var settings = (IDictionary<string, object>)expando;
var sbKeys = new StringBuilder();
var stub = "UPDATE {0} SET {1} WHERE {2} = @{3}";
var args = new List<object>();
var result = CreateCommand(stub, null);
int counter = 0;
foreach (var item in settings)
{
var val = item.Value;
if (!item.Key.Equals(PrimaryKeyField, StringComparison.CurrentCultureIgnoreCase) && item.Value != null)
{
result.AddParam(val);
sbKeys.AppendFormat("{0} = @{1}, \r\n", item.Key, counter.ToString());
counter++;
}
}
if (counter > 0)
{
//add the key
result.AddParam(key);
//strip the last commas
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 4);
result.CommandText = string.Format(stub, TableName, keys, PrimaryKeyField, counter);
}
else throw new InvalidOperationException("No parsable object was sent in - could not divine any name/value pairs");
return result;
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public virtual DbCommand CreateDeleteCommand(string where = "", object key = null, params object[] args)
{
var sql = string.Format("DELETE FROM {0} ", TableName);
if (key != null)
{
sql += string.Format("WHERE {0}=@0", PrimaryKeyField);
args = new object[] { key };
}
else if (!string.IsNullOrEmpty(where))
{
sql += where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase) ? where : "WHERE " + where;
}
return CreateCommand(sql, null, args);
}
/// <summary>
/// Adds a record to the database. You can pass in an Anonymous object, an ExpandoObject,
/// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString
/// </summary>
public virtual object Insert(object o)
{
dynamic result = 0;
using (var conn = OpenConnection())
{
var cmd = CreateInsertCommand(o);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
cmd.CommandText = "select last_insert_rowid()";
result = cmd.ExecuteScalar();
}
return result;
}
/// <summary>
/// Updates a record in the database. You can pass in an Anonymous object, an ExpandoObject,
/// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString
/// </summary>
public virtual int Update(object o, object key)
{
return Execute(CreateUpdateCommand(o, key));
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public int Delete(object key = null, string where = "", params object[] args)
{
return Execute(CreateDeleteCommand(where: where, key: key, args: args));
}
/// <summary>
/// Returns all records complying with the passed-in WHERE clause and arguments,
/// ordered as specified, limited (TOP) by limit.
/// </summary>
public virtual IEnumerable<dynamic> All(string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args)
{
string sql = BuildSelect(where, orderBy, limit);
return Query(string.Format(sql, columns, TableName), args);
}
private static string BuildSelect(string where, string orderBy, int limit)
{
string sql = limit > 0 ? "SELECT TOP " + limit + " {0} FROM {1} " : "SELECT {0} FROM {1} ";
if (!string.IsNullOrEmpty(where))
sql += where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase) ? where : "WHERE " + where;
if (!String.IsNullOrEmpty(orderBy))
sql += orderBy.Trim().StartsWith("order by", StringComparison.CurrentCultureIgnoreCase) ? orderBy : " ORDER BY " + orderBy;
return sql;
}
/// <summary>
/// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords.
/// </summary>
public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args)
{
dynamic result = new ExpandoObject();
var countSQL = string.Format("SELECT COUNT({0}) FROM {1}", PrimaryKeyField, TableName);
if (String.IsNullOrEmpty(orderBy))
orderBy = PrimaryKeyField;
if (!string.IsNullOrEmpty(where))
{
if (!where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase))
{
where = "WHERE " + where;
}
}
var sql = string.Format("select {0} FROM {3} {4} ORDER BY {2} ", columns, pageSize, orderBy, TableName, where);
var pageStart = (currentPage - 1) * pageSize;
sql += string.Format(" LIMIT {0},{1}",pageStart, pageSize);
countSQL += where;
result.TotalRecords = Scalar(countSQL, args);
result.TotalPages = result.TotalRecords / pageSize;
if (result.TotalRecords % pageSize > 0)
result.TotalPages += 1;
result.Items = Query(string.Format(sql, columns, TableName), args);
return result;
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(string where, params object[] args)
{
var sql = string.Format("SELECT * FROM {0} WHERE {1}", TableName, where);
return Query(sql, args).FirstOrDefault();
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(object key, string columns = "*")
{
var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns, TableName, PrimaryKeyField);
return Query(sql, key).FirstOrDefault();
}
/// <summary>
/// A helpful query tool
/// </summary>
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
//parse the method
var constraints = new List<string>();
var counter = 0;
var info = binder.CallInfo;
// accepting named args only... SKEET!
if (info.ArgumentNames.Count != args.Length)
{
throw new InvalidOperationException("Please use named arguments for this type of query - the column name, orderby, columns, etc");
}
//first should be "FindBy, Last, Single, First"
var op = binder.Name;
var columns = " * ";
string orderBy = string.Format(" ORDER BY {0}", PrimaryKeyField);
string where = "";
var whereArgs = new List<object>();
//loop the named args - see if we have order, columns and constraints
if (info.ArgumentNames.Count > 0)
{
for (int i = 0; i < args.Length; i++)
{
var name = info.ArgumentNames[i].ToLower();
switch (name)
{
case "orderby":
orderBy = " ORDER BY " + args[i];
break;
case "columns":
columns = args[i].ToString();
break;
default:
constraints.Add(string.Format(" {0} = @{1}", name, counter));
whereArgs.Add(args[i]);
counter++;
break;
}
}
}
//Build the WHERE bits
if (constraints.Count > 0)
{
where = " WHERE " + string.Join(" AND ", constraints.ToArray());
}
//probably a bit much here but... yeah this whole thing needs to be refactored...
if (op.ToLower() == "count")
{
result = Scalar("SELECT COUNT(*) FROM " + TableName + where, whereArgs.ToArray());
}
else if (op.ToLower() == "sum")
{
result = Scalar("SELECT SUM(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
}
else if (op.ToLower() == "max")
{
result = Scalar("SELECT MAX(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
}
else if (op.ToLower() == "min")
{
result = Scalar("SELECT MIN(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
}
else if (op.ToLower() == "avg")
{
result = Scalar("SELECT AVG(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
}
else
{
//build the SQL
string sql = "SELECT TOP 1 " + columns + " FROM " + TableName + where;
var justOne = op.StartsWith("First") || op.StartsWith("Last") || op.StartsWith("Get");
//Be sure to sort by DESC on the PK (PK Sort is the default)
if (op.StartsWith("Last"))
{
orderBy = orderBy + " DESC ";
}
else
{
//default to multiple
sql = "SELECT " + columns + " FROM " + TableName + where;
}
if (justOne)
{
//return a single record
result = Query(sql + orderBy, whereArgs.ToArray()).FirstOrDefault();
}
else
{
//return lots
result = Query(sql + orderBy, whereArgs.ToArray());
}
}
return true;
}
}
}
| |
#pragma warning disable 1587
#region Header
///
/// JsonMapper.cs
/// JSON to .Net object and object to JSON conversions.
///
/// The authors disclaim copyright to this source code. For more details, see
/// the COPYING file included with this distribution.
///
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using Amazon.Util;
namespace ThirdParty.Json.LitJson
{
internal struct PropertyMetadata
{
public MemberInfo Info;
public bool IsField;
public Type Type;
}
internal struct ArrayMetadata
{
private Type element_type;
private bool is_array;
private bool is_list;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsArray {
get { return is_array; }
set { is_array = value; }
}
public bool IsList {
get { return is_list; }
set { is_list = value; }
}
}
internal struct ObjectMetadata
{
private Type element_type;
private bool is_dictionary;
private IDictionary<string, PropertyMetadata> properties;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsDictionary {
get { return is_dictionary; }
set { is_dictionary = value; }
}
public IDictionary<string, PropertyMetadata> Properties {
get { return properties; }
set { properties = value; }
}
}
internal delegate void ExporterFunc (object obj, JsonWriter writer);
public delegate void ExporterFunc<T> (T obj, JsonWriter writer);
internal delegate object ImporterFunc (object input);
public delegate TValue ImporterFunc<TJson, TValue> (TJson input);
public delegate IJsonWrapper WrapperFactory ();
public class JsonMapper
{
#region Fields
private static int max_nesting_depth;
private static IFormatProvider datetime_format;
private static IDictionary<Type, ExporterFunc> base_exporters_table;
private static IDictionary<Type, ExporterFunc> custom_exporters_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> base_importers_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> custom_importers_table;
private static IDictionary<Type, ArrayMetadata> array_metadata;
private static readonly object array_metadata_lock = new Object ();
private static IDictionary<Type,
IDictionary<Type, MethodInfo>> conv_ops;
private static readonly object conv_ops_lock = new Object ();
private static IDictionary<Type, ObjectMetadata> object_metadata;
private static readonly object object_metadata_lock = new Object ();
private static IDictionary<Type,
IList<PropertyMetadata>> type_properties;
private static readonly object type_properties_lock = new Object ();
private static JsonWriter static_writer;
private static readonly object static_writer_lock = new Object ();
#endregion
#region Constructors
static JsonMapper ()
{
max_nesting_depth = 100;
array_metadata = new Dictionary<Type, ArrayMetadata> ();
conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> ();
object_metadata = new Dictionary<Type, ObjectMetadata> ();
type_properties = new Dictionary<Type,
IList<PropertyMetadata>> ();
static_writer = new JsonWriter ();
datetime_format = DateTimeFormatInfo.InvariantInfo;
base_exporters_table = new Dictionary<Type, ExporterFunc> ();
custom_exporters_table = new Dictionary<Type, ExporterFunc> ();
base_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
custom_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
RegisterBaseExporters ();
RegisterBaseImporters ();
}
#endregion
#region Private Methods
private static void AddArrayMetadata (Type type)
{
if (array_metadata.ContainsKey (type))
return;
ArrayMetadata data = new ArrayMetadata ();
data.IsArray = type.IsArray;
var typeInfo = TypeFactory.GetTypeInfo(type);
if (typeInfo.GetInterface("System.Collections.IList") != null)
data.IsList = true;
foreach (PropertyInfo p_info in typeInfo.GetProperties())
{
if (p_info.Name != "Item")
continue;
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (int))
data.ElementType = p_info.PropertyType;
}
lock (array_metadata_lock) {
try {
array_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddObjectMetadata (Type type)
{
if (object_metadata.ContainsKey (type))
return;
ObjectMetadata data = new ObjectMetadata ();
var typeInfo = TypeFactory.GetTypeInfo(type);
if (typeInfo.GetInterface("System.Collections.IDictionary") != null)
data.IsDictionary = true;
data.Properties = new Dictionary<string, PropertyMetadata> ();
foreach (PropertyInfo p_info in typeInfo.GetProperties())
{
if (p_info.Name == "Item") {
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (string))
data.ElementType = p_info.PropertyType;
continue;
}
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.Type = p_info.PropertyType;
data.Properties.Add (p_info.Name, p_data);
}
foreach (FieldInfo f_info in typeInfo.GetFields())
{
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
p_data.Type = f_info.FieldType;
data.Properties.Add (f_info.Name, p_data);
}
lock (object_metadata_lock) {
try {
object_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddTypeProperties (Type type)
{
if (type_properties.ContainsKey (type))
return;
var typeInfo = TypeFactory.GetTypeInfo(type);
IList<PropertyMetadata> props = new List<PropertyMetadata> ();
foreach (PropertyInfo p_info in typeInfo.GetProperties())
{
if (p_info.Name == "Item")
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.IsField = false;
props.Add (p_data);
}
foreach (FieldInfo f_info in typeInfo.GetFields())
{
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
props.Add (p_data);
}
lock (type_properties_lock) {
try {
type_properties.Add (type, props);
} catch (ArgumentException) {
return;
}
}
}
private static MethodInfo GetConvOp (Type t1, Type t2)
{
lock (conv_ops_lock) {
if (! conv_ops.ContainsKey (t1))
conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
}
var typeInfoT1 = TypeFactory.GetTypeInfo(t1);
var typeInfoT2 = TypeFactory.GetTypeInfo(t2);
if (conv_ops[t1].ContainsKey (t2))
return conv_ops[t1][t2];
MethodInfo op = typeInfoT1.GetMethod(
"op_Implicit", new ITypeInfo[] { typeInfoT2 });
lock (conv_ops_lock) {
try {
conv_ops[t1].Add (t2, op);
} catch (ArgumentException) {
return conv_ops[t1][t2];
}
}
return op;
}
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
var inst_typeInfo = TypeFactory.GetTypeInfo(inst_type);
if (reader.Token == JsonToken.ArrayEnd)
return null;
if (reader.Token == JsonToken.Null) {
if (!inst_typeInfo.IsClass)
throw new JsonException (String.Format (
"Can't assign null to an instance of type {0}",
inst_type));
return null;
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType ();
var json_typeInfo = TypeFactory.GetTypeInfo(json_type);
if (inst_typeInfo.IsAssignableFrom(json_typeInfo))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
inst_type)) {
ImporterFunc importer =
custom_importers_table[json_type][inst_type];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
inst_type)) {
ImporterFunc importer =
base_importers_table[json_type][inst_type];
return importer (reader.Value);
}
// Maybe it's an enum
if (inst_typeInfo.IsEnum)
return Enum.ToObject (inst_type, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (inst_type, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new List<object> ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (reader.Token == JsonToken.ArrayEnd)
break;
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart) {
AddObjectMetadata (inst_type);
ObjectMetadata t_data = object_metadata[inst_type];
instance = Activator.CreateInstance (inst_type);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey (property)) {
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField) {
((FieldInfo) prop_data.Info).SetValue (
instance, ReadValue (prop_data.Type, reader));
} else {
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue (
instance,
ReadValue (prop_data.Type, reader),
null);
else
ReadValue (prop_data.Type, reader);
}
} else {
if (! t_data.IsDictionary)
throw new JsonException (String.Format (
"The type {0} doesn't have the " +
"property '{1}'", inst_type, property));
((IDictionary) instance).Add (
property, ReadValue (
t_data.ElementType, reader));
}
}
}
return instance;
}
private static IJsonWrapper ReadValue (WrapperFactory factory,
JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null)
return null;
IJsonWrapper instance = factory ();
if (reader.Token == JsonToken.String) {
instance.SetString ((string) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Double) {
instance.SetDouble ((double) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Int) {
instance.SetInt ((int) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Long) {
instance.SetLong ((long) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Boolean) {
instance.SetBoolean ((bool) reader.Value);
return instance;
}
if (reader.Token == JsonToken.ArrayStart) {
instance.SetJsonType (JsonType.Array);
while (true) {
IJsonWrapper item = ReadValue (factory, reader);
// nij - added check to see if the item is not null. This is to handle arrays within arrays.
// In those cases when the outer array read the inner array an item was returned back the current
// reader.Token is at the ArrayEnd for the inner array.
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
((IList) instance).Add (item);
}
}
else if (reader.Token == JsonToken.ObjectStart) {
instance.SetJsonType (JsonType.Object);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
((IDictionary) instance)[property] = ReadValue (
factory, reader);
}
}
return instance;
}
private static void RegisterBaseExporters ()
{
base_exporters_table[typeof (byte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((byte) obj));
};
base_exporters_table[typeof (char)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((char) obj));
};
base_exporters_table[typeof (DateTime)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((DateTime) obj,
datetime_format));
};
base_exporters_table[typeof (decimal)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((decimal) obj);
};
base_exporters_table[typeof (sbyte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((sbyte) obj));
};
base_exporters_table[typeof (short)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((short) obj));
};
base_exporters_table[typeof (ushort)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((ushort) obj));
};
base_exporters_table[typeof (uint)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToUInt64 ((uint) obj));
};
base_exporters_table[typeof (ulong)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((ulong) obj);
};
}
private static void RegisterBaseImporters ()
{
ImporterFunc importer;
importer = delegate (object input) {
return Convert.ToByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (byte), importer);
importer = delegate (object input) {
return Convert.ToUInt64 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ulong), importer);
importer = delegate (object input) {
return Convert.ToSByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (sbyte), importer);
importer = delegate (object input) {
return Convert.ToInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (short), importer);
importer = delegate (object input) {
return Convert.ToUInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ushort), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToSingle ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (float), importer);
importer = delegate (object input) {
return Convert.ToDouble ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (double), importer);
importer = delegate (object input) {
return Convert.ToDecimal ((double) input);
};
RegisterImporter (base_importers_table, typeof (double),
typeof (decimal), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((long) input);
};
RegisterImporter (base_importers_table, typeof (long),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToChar ((string) input);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (char), importer);
importer = delegate (object input) {
return Convert.ToDateTime ((string) input, datetime_format);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (DateTime), importer);
}
private static void RegisterImporter (
IDictionary<Type, IDictionary<Type, ImporterFunc>> table,
Type json_type, Type value_type, ImporterFunc importer)
{
if (! table.ContainsKey (json_type))
table.Add (json_type, new Dictionary<Type, ImporterFunc> ());
table[json_type][value_type] = importer;
}
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string) entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type = obj.GetType ();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (p_info.GetValue (obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
#endregion
public static string ToJson (object obj)
{
lock (static_writer_lock) {
static_writer.Reset ();
WriteValue (obj, static_writer, true, 0);
return static_writer.ToString ();
}
}
public static void ToJson (object obj, JsonWriter writer)
{
WriteValue (obj, writer, false, 0);
}
public static JsonData ToObject (JsonReader reader)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, reader);
}
public static JsonData ToObject (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json_reader);
}
public static JsonData ToObject (string json)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json);
}
public static T ToObject<T> (JsonReader reader)
{
return (T) ReadValue (typeof (T), reader);
}
public static T ToObject<T> (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (T) ReadValue (typeof (T), json_reader);
}
public static T ToObject<T> (string json)
{
JsonReader reader = new JsonReader (json);
return (T) ReadValue (typeof (T), reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
JsonReader reader)
{
return ReadValue (factory, reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
string json)
{
JsonReader reader = new JsonReader (json);
return ReadValue (factory, reader);
}
public static void RegisterExporter<T> (ExporterFunc<T> exporter)
{
ExporterFunc exporter_wrapper =
delegate (object obj, JsonWriter writer) {
exporter ((T) obj, writer);
};
custom_exporters_table[typeof (T)] = exporter_wrapper;
}
public static void RegisterImporter<TJson, TValue> (
ImporterFunc<TJson, TValue> importer)
{
ImporterFunc importer_wrapper =
delegate (object input) {
return importer ((TJson) input);
};
RegisterImporter (custom_importers_table, typeof (TJson),
typeof (TValue), importer_wrapper);
}
public static void UnregisterExporters ()
{
custom_exporters_table.Clear ();
}
public static void UnregisterImporters ()
{
custom_importers_table.Clear ();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="OutputStreamSourceStage.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Akka.Dispatch;
using Akka.IO;
using Akka.Streams.Implementation.Stages;
using Akka.Streams.Stage;
using Akka.Util;
using static Akka.Streams.Implementation.IO.OutputStreamSourceStage;
namespace Akka.Streams.Implementation.IO
{
/// <summary>
/// INTERNAL API
/// </summary>
internal class OutputStreamSourceStage : GraphStageWithMaterializedValue<SourceShape<ByteString>, Stream>
{
#region internal classes
/// <summary>
/// TBD
/// </summary>
internal interface IAdapterToStageMessage { }
/// <summary>
/// TBD
/// </summary>
internal class Flush : IAdapterToStageMessage
{
/// <summary>
/// TBD
/// </summary>
public static readonly Flush Instance = new Flush();
private Flush()
{
}
}
/// <summary>
/// TBD
/// </summary>
internal class Close : IAdapterToStageMessage
{
/// <summary>
/// TBD
/// </summary>
public static readonly Close Instance = new Close();
private Close()
{
}
}
/// <summary>
/// TBD
/// </summary>
internal interface IDownstreamStatus { }
/// <summary>
/// TBD
/// </summary>
internal class Ok : IDownstreamStatus
{
/// <summary>
/// TBD
/// </summary>
public static readonly Ok Instance = new Ok();
private Ok()
{
}
}
/// <summary>
/// TBD
/// </summary>
internal class Canceled : IDownstreamStatus
{
/// <summary>
/// TBD
/// </summary>
public static readonly Canceled Instance = new Canceled();
private Canceled()
{
}
}
/// <summary>
/// TBD
/// </summary>
internal interface IStageWithCallback
{
/// <summary>
/// TBD
/// </summary>
/// <param name="msg">TBD</param>
/// <returns>TBD</returns>
Task WakeUp(IAdapterToStageMessage msg);
}
private sealed class Logic : GraphStageLogic, IStageWithCallback
{
private readonly OutputStreamSourceStage _stage;
private readonly AtomicReference<IDownstreamStatus> _downstreamStatus;
private readonly string _dispatcherId;
private readonly Action<Tuple<IAdapterToStageMessage, TaskCompletionSource<NotUsed>>> _upstreamCallback;
private readonly OnPullRunnable _pullTask;
private readonly CancellationTokenSource _cancellation = new CancellationTokenSource();
private BlockingCollection<ByteString> _dataQueue;
private TaskCompletionSource<NotUsed> _flush;
private TaskCompletionSource<NotUsed> _close;
private MessageDispatcher _dispatcher;
public Logic(OutputStreamSourceStage stage, BlockingCollection<ByteString> dataQueue, AtomicReference<IDownstreamStatus> downstreamStatus, string dispatcherId) : base(stage.Shape)
{
_stage = stage;
_dataQueue = dataQueue;
_downstreamStatus = downstreamStatus;
_dispatcherId = dispatcherId;
var downstreamCallback = GetAsyncCallback((Either<ByteString, Exception> result) =>
{
if (result.IsLeft)
OnPush(result.Value as ByteString);
else
FailStage(result.Value as Exception);
});
_upstreamCallback =
GetAsyncCallback<Tuple<IAdapterToStageMessage, TaskCompletionSource<NotUsed>>>(OnAsyncMessage);
_pullTask = new OnPullRunnable(downstreamCallback, dataQueue, _cancellation.Token);
SetHandler(_stage._out, onPull: OnPull, onDownstreamFinish: OnDownstreamFinish);
}
public override void PreStart()
{
_dispatcher = ActorMaterializerHelper.Downcast(Materializer).System.Dispatchers.Lookup(_dispatcherId);
base.PreStart();
}
public override void PostStop()
{
// interrupt any pending blocking take
_cancellation.Cancel(false);
base.PostStop();
}
private void OnDownstreamFinish()
{
//assuming there can be no further in messages
_downstreamStatus.Value = Canceled.Instance;
_dataQueue = null;
CompleteStage();
}
private sealed class OnPullRunnable : IRunnable
{
private readonly Action<Either<ByteString, Exception>> _callback;
private readonly BlockingCollection<ByteString> _dataQueue;
private readonly CancellationToken _cancellationToken;
public OnPullRunnable(Action<Either<ByteString, Exception>> callback, BlockingCollection<ByteString> dataQueue, CancellationToken cancellationToken)
{
_callback = callback;
_dataQueue = dataQueue;
_cancellationToken = cancellationToken;
}
public void Run()
{
try
{
_callback(new Left<ByteString, Exception>(_dataQueue.Take(_cancellationToken)));
}
catch (OperationCanceledException)
{
_callback(new Left<ByteString, Exception>(ByteString.Empty));
}
catch (Exception ex)
{
_callback(new Right<ByteString, Exception>(ex));
}
}
}
private void OnPull() => _dispatcher.Schedule(_pullTask);
private void OnPush(ByteString data)
{
if (_downstreamStatus.Value is Ok)
{
Push(_stage._out, data);
SendResponseIfNeeded();
}
}
public Task WakeUp(IAdapterToStageMessage msg)
{
var p = new TaskCompletionSource<NotUsed>();
_upstreamCallback(new Tuple<IAdapterToStageMessage, TaskCompletionSource<NotUsed>>(msg, p));
return p.Task;
}
private void OnAsyncMessage(Tuple<IAdapterToStageMessage, TaskCompletionSource<NotUsed>> @event)
{
if (@event.Item1 is Flush)
{
_flush = @event.Item2;
SendResponseIfNeeded();
}
else if (@event.Item1 is Close)
{
_close = @event.Item2;
SendResponseIfNeeded();
}
}
private void UnblockUpsteam()
{
if (_flush != null)
{
_flush.TrySetResult(NotUsed.Instance);
_flush = null;
return;
}
if (_close == null)
return;
_downstreamStatus.Value = Canceled.Instance;
_close.TrySetResult(NotUsed.Instance);
_close = null;
CompleteStage();
}
private void SendResponseIfNeeded()
{
if (_downstreamStatus.Value is Canceled || _dataQueue.Count == 0)
UnblockUpsteam();
}
}
#endregion
private readonly TimeSpan _writeTimeout;
private readonly Outlet<ByteString> _out = new Outlet<ByteString>("OutputStreamSource.out");
/// <summary>
/// TBD
/// </summary>
/// <param name="writeTimeout">TBD</param>
public OutputStreamSourceStage(TimeSpan writeTimeout)
{
_writeTimeout = writeTimeout;
Shape = new SourceShape<ByteString>(_out);
}
/// <summary>
/// TBD
/// </summary>
public override SourceShape<ByteString> Shape { get; }
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.OutputStreamSource;
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
public override ILogicAndMaterializedValue<Stream> CreateLogicAndMaterializedValue(Attributes inheritedAttributes)
{
// has to be in this order as module depends on shape
var maxBuffer = inheritedAttributes.GetAttribute(new Attributes.InputBuffer(16, 16)).Max;
if (maxBuffer <= 0)
throw new ArgumentException("Buffer size must be greater than 0");
var dataQueue = new BlockingCollection<ByteString>(maxBuffer);
var downstreamStatus = new AtomicReference<IDownstreamStatus>(Ok.Instance);
var dispatcherId =
inheritedAttributes.GetAttribute(
DefaultAttributes.IODispatcher.GetAttributeList<ActorAttributes.Dispatcher>().First()).Name;
var logic = new Logic(this, dataQueue, downstreamStatus, dispatcherId);
return new LogicAndMaterializedValue<Stream>(logic,
new OutputStreamAdapter(dataQueue, downstreamStatus, logic, _writeTimeout));
}
}
/// <summary>
/// TBD
/// </summary>
internal class OutputStreamAdapter : Stream
{
#region not supported
/// <summary>
/// TBD
/// </summary>
/// <param name="offset">TBD</param>
/// <param name="origin">TBD</param>
/// <exception cref="NotSupportedException">TBD</exception>
/// <returns>TBD</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException("This stream can only write");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="value">TBD</param>
/// <exception cref="NotSupportedException">TBD</exception>
public override void SetLength(long value)
{
throw new NotSupportedException("This stream can only write");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="buffer">TBD</param>
/// <param name="offset">TBD</param>
/// <param name="count">TBD</param>
/// <exception cref="NotSupportedException">TBD</exception>
/// <returns>TBD</returns>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException("This stream can only write");
}
/// <summary>
/// TBD
/// </summary>
/// <exception cref="NotSupportedException">TBD</exception>
public override long Length
{
get
{
throw new NotSupportedException("This stream can only write");
}
}
/// <summary>
/// TBD
/// </summary>
/// <exception cref="NotSupportedException">TBD</exception>
public override long Position
{
get
{
throw new NotSupportedException("This stream can only write");
}
set
{
throw new NotSupportedException("This stream can only write");
}
}
#endregion
private static readonly Exception PublisherClosedException = new IOException("Reactive stream is terminated, no writes are possible");
private readonly BlockingCollection<ByteString> _dataQueue;
private readonly AtomicReference<IDownstreamStatus> _downstreamStatus;
private readonly IStageWithCallback _stageWithCallback;
private readonly TimeSpan _writeTimeout;
private bool _isActive = true;
private bool _isPublisherAlive = true;
/// <summary>
/// TBD
/// </summary>
/// <param name="dataQueue">TBD</param>
/// <param name="downstreamStatus">TBD</param>
/// <param name="stageWithCallback">TBD</param>
/// <param name="writeTimeout">TBD</param>
public OutputStreamAdapter(BlockingCollection<ByteString> dataQueue,
AtomicReference<IDownstreamStatus> downstreamStatus,
IStageWithCallback stageWithCallback, TimeSpan writeTimeout)
{
_dataQueue = dataQueue;
_downstreamStatus = downstreamStatus;
_stageWithCallback = stageWithCallback;
_writeTimeout = writeTimeout;
}
private void Send(Action sendAction)
{
if (_isActive)
{
if (_isPublisherAlive)
sendAction();
else
throw PublisherClosedException;
}
else
throw new IOException("OutputStream is closed");
}
private void SendData(ByteString data)
{
Send(() =>
{
_dataQueue.Add(data);
if (_downstreamStatus.Value is Canceled)
{
_isPublisherAlive = false;
throw PublisherClosedException;
}
});
}
private void SendMessage(IAdapterToStageMessage msg, bool handleCancelled = true)
{
Send(() =>
{
_stageWithCallback.WakeUp(msg).Wait(_writeTimeout);
if (_downstreamStatus.Value is Canceled && handleCancelled)
{
//Publisher considered to be terminated at earliest convenience to minimize messages sending back and forth
_isPublisherAlive = false;
throw PublisherClosedException;
}
});
}
/// <summary>
/// TBD
/// </summary>
public override void Flush() => SendMessage(OutputStreamSourceStage.Flush.Instance);
/// <summary>
/// TBD
/// </summary>
/// <param name="buffer">TBD</param>
/// <param name="offset">TBD</param>
/// <param name="count">TBD</param>
public override void Write(byte[] buffer, int offset, int count)
=> SendData(ByteString.FromBytes(buffer, offset, count));
/// <summary>
/// TBD
/// </summary>
/// <param name="disposing">TBD</param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
SendMessage(OutputStreamSourceStage.Close.Instance, false);
_isActive = false;
}
/// <summary>
/// TBD
/// </summary>
public override bool CanRead => false;
/// <summary>
/// TBD
/// </summary>
public override bool CanSeek => false;
/// <summary>
/// TBD
/// </summary>
public override bool CanWrite => true;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using GameplayKit;
namespace FourInARow {
public class Board : NSObject, IGKGameModel {
public const int Width = 7;
public const int Height = 6;
public Chip[] Cells { get; private set; }
public Player CurrentPlayer { get; set; }
public bool IsFull {
get {
for (int column = 0; column < Width; column++) {
if (CanMoveInColumn (column))
return false;
}
return true;
}
}
public Board ()
{
CurrentPlayer = Player.RedPlayer;
Cells = new Chip [Width * Height];
}
public Chip ChipInColumnRow (int column, int row)
{
var index = row + column * Height;
return (index >= Cells.Length) ? Chip.None : Cells [index];
}
public bool CanMoveInColumn (int column)
{
return NextEmptySlotInColumn (column) >= 0;
}
public void AddChipInColumn (Chip chip, int column)
{
int row = NextEmptySlotInColumn (column);
if (row >= 0)
SetChipInColumnRow (chip, column, row);
}
public IGKGameModelPlayer[] GetPlayers ()
{
return Player.AllPlayers;
}
public IGKGameModelPlayer GetActivePlayer ()
{
return CurrentPlayer;
}
public NSObject Copy (NSZone zone)
{
var board = new Board ();
board.SetGameModel (this);
return board;
}
public void SetGameModel (IGKGameModel gameModel)
{
var board = (Board)gameModel;
UpdateChipsFromBoard (board);
CurrentPlayer = board.CurrentPlayer;
}
public IGKGameModelUpdate[] GetGameModelUpdates (IGKGameModelPlayer player)
{
var moves = new List<Move> ();
for (int column = 0; column < Width; column++) {
if (CanMoveInColumn (column))
moves.Add (Move.MoveInColumn (column));
}
return moves.ToArray ();
}
public void ApplyGameModelUpdate (IGKGameModelUpdate gameModelUpdate)
{
AddChipInColumn (CurrentPlayer.Chip, ((Move)gameModelUpdate).Column);
CurrentPlayer = CurrentPlayer.Opponent;
}
[Export ("scoreForPlayer:")]
public nint ScorForPlayer (Player player)
{
var playerRunCounts = RunCountsForPlayer (player);
int playerTotal = playerRunCounts.Sum ();
var opponentRunCounts = RunCountsForPlayer (player.Opponent);
int opponentTotal = opponentRunCounts.Sum ();
// Return the sum of player runs minus the sum of opponent runs.
return playerTotal - opponentTotal;
}
public bool IsWin (Player player)
{
var runCounts = RunCountsForPlayer (player);
return runCounts.Max () >= Player.CountToWin;
}
bool IsLoss (Player player)
{
return IsWin (player.Opponent);
}
int[] RunCountsForPlayer (Player player)
{
var chip = player.Chip;
var counts = new List<int> ();
// Detect horizontal runs.
for (int row = 0; row < Height; row++) {
int runCount = 0;
for (int column = 0; column < Width; column++) {
if (ChipInColumnRow (column, row) == chip) {
++runCount;
} else {
if (runCount > 0)
counts.Add (runCount);
runCount = 0;
}
}
if (runCount > 0)
counts.Add (runCount);
}
// Detect vertical runs.
for (int column = 0; column < Width; column++) {
int runCount = 0;
for (int row = 0; row < Height; row++) {
if (ChipInColumnRow (column, row) == chip) {
++runCount;
} else {
if (runCount > 0)
counts.Add (runCount);
runCount = 0;
}
}
if (runCount > 0)
counts.Add (runCount);
}
// Detect diagonal (northeast) runs
for (int startColumn = -Height; startColumn < Width; startColumn++) {
int runCount = 0;
for (int offset = 0; offset < Height; offset++) {
int column = startColumn + offset;
if (column < 0 || column > Width)
continue;
if (ChipInColumnRow (column, offset) == chip) {
++runCount;
} else {
if (runCount > 0)
counts.Add (runCount);
runCount = 0;
}
}
if (runCount > 0)
counts.Add (runCount);
}
// Detect diagonal (northwest) runs
for (int startColumn = 0; startColumn < Width + Height; startColumn++) {
int runCount = 0;
for (int offset = 0; offset < Height; offset++) {
int column = startColumn - offset;
if (column < 0 || column > Width)
continue;
if (ChipInColumnRow (column, offset) == chip) {
++runCount;
} else {
if (runCount > 0)
counts.Add (runCount);
runCount = 0;
}
}
if (runCount > 0)
counts.Add (runCount);
}
return counts.ToArray ();
}
void UpdateChipsFromBoard (Board otherBoard)
{
Array.Copy (otherBoard.Cells, Cells, Cells.Length);
}
void SetChipInColumnRow (Chip chip, int column, int row)
{
Cells [row + column * Height] = chip;
}
int NextEmptySlotInColumn (int column)
{
for (int row = 0; row < Height; row++) {
if (ChipInColumnRow (column, row) == Chip.None)
return row;
}
return -1;
}
}
}
| |
// Copyright 2017 Google 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Threading;
using System.Linq;
using UnityEngine;
using System.Text;
using PolyToolkitInternal.model.util;
namespace PolyToolkitInternal.caching {
/// <summary>
/// A persistent disk-based LRU cache that can store associations of strings to arbitrary data.
///
/// This can be used, for example, to implement a download cache for remote assets. This
/// class is agnostic to the actual meaning of the keys and values. To this class, keys are just
/// unique strings and values are just opaque byte arrays.
///
/// This cache automatically offloads heavy work (I/O, decoding, etc) to a background thread to avoid
/// blocking the main thread.
///
/// NOTE: We're not currently handling I/O errors -- the cache assumes that the file system works
/// perfectly, which is a pretty fair assumption since we're using a hidden directory under
/// AppData\Local\.... that normal users don't normally access (or even know about).
/// Unless the user goes and messes around with the permissions of the directory, everything should
/// work correctly. If we do get an I/O error (which would be rare), then we will just crash.
/// </summary>
[ExecuteInEditMode]
public class PersistentBlobCache : MonoBehaviour {
private const string BLOB_FILE_EXT = ".blob";
public delegate void CacheReadCallback(bool success, byte[] data);
/// <summary>
/// Indicates whether Setup() was completed.
/// </summary>
private bool setupDone = false;
/// <summary>
/// Maximum number of entries allowed in the cache.
/// </summary>
private int maxEntries;
/// <summary>
/// Maximum total bytes allowed in the cache.
/// </summary>
private long maxSizeBytes;
/// <summary>
/// Root path to the cache.
/// </summary>
private string rootPath;
/// <summary>
/// MD5 hash computing function.
/// </summary>
private MD5 md5;
/// <summary>
/// Maps key hash to cache entry.
/// This is owned by the BACKGROUND thread.
/// </summary>
private Dictionary<string, CacheEntry> cacheEntries = new Dictionary<string, CacheEntry>();
/// <summary>
/// Requests that are pending background work.
/// </summary>
private ConcurrentQueue<CacheRequest> requestsPendingWork = new ConcurrentQueue<CacheRequest>();
/// <summary>
/// Requests for which the background work is done, and which are pending delivery of callback in the
/// main thread.
/// </summary>
private ConcurrentQueue<CacheRequest> requestsPendingDelivery = new ConcurrentQueue<CacheRequest>();
/// <summary>
/// Recycle pool of requests (to avoid reduce allocation).
/// </summary>
private ConcurrentQueue<CacheRequest> requestsRecyclePool = new ConcurrentQueue<CacheRequest>();
/// <summary>
/// Sets up a cache with the given characteristics.
/// </summary>
/// <param name="rootPath">The absolute path to the root of the cache.</param>
/// <param name="maxEntries">The maximum number of entries in the cache.</param>
/// <param name="maxSizeBytes">The maximum combined size of all entries in the cache.</param>
public void Setup(string rootPath, int maxEntries, long maxSizeBytes) {
this.rootPath = rootPath;
this.maxEntries = maxEntries;
this.maxSizeBytes = maxSizeBytes;
// Check that we have a reasonable config:
PolyUtils.AssertNotNullOrEmpty(rootPath, "rootPath can't be null or empty");
PolyUtils.AssertTrue(Directory.Exists(rootPath), "rootPath must be an existing directory: " + rootPath);
PolyUtils.AssertTrue(maxEntries >= 256, "maxEntries must be >= 256");
PolyUtils.AssertTrue(maxSizeBytes >= 1048576, "maxSizeBytes must be >= 1MB");
PtDebug.LogVerboseFormat("PBC initializing, root {0}, max entries {1}, max size {2}",
rootPath, maxEntries, maxSizeBytes);
md5 = MD5.Create();
InitializeCache();
setupDone = true;
Thread backgroundThread = new Thread(BackgroundThreadMain);
backgroundThread.IsBackground = true;
backgroundThread.Start();
}
/// <summary>
/// Requests a read from the cache.
/// </summary>
/// <param name="key">The key to read.</param>
/// <param name="maxAgeMillis">Maximum age for a cache hit. If the copy we have on cache is older
/// than this, the request will fail. Use -1 to mean "any age".</param>
/// <param name="callback">The callback that is to be called (asynchronously) when the read operation
/// finishes. This callback will be called on the MAIN thread.</param>
public void RequestRead(string key, long maxAgeMillis, CacheReadCallback callback) {
string hash = GetHash(key);
CacheRequest request;
if (!requestsRecyclePool.Dequeue(out request)) {
request = new CacheRequest();
}
request.type = RequestType.READ;
request.key = key;
request.hash = hash;
request.readCallback = callback;
request.maxAgeMillis = maxAgeMillis;
PtDebug.LogVerboseFormat("PBC: enqueing READ request for {0}", key);
requestsPendingWork.Enqueue(request);
}
/// <summary>
/// Requests a write to the cache. The data will be written asynchronously.
/// </summary>
/// <param name="key">The key to write.</param>
/// <param name="data">The data to write.</param>
public void RequestWrite(string key, byte[] data) {
string hash = GetHash(key);
CacheRequest request;
if (!requestsRecyclePool.Dequeue(out request)) {
request = new CacheRequest();
}
request.type = RequestType.WRITE;
request.key = key;
request.hash = hash;
request.data = data;
PtDebug.LogVerboseFormat("PBC: enqueing WRITE request for {0}", key);
requestsPendingWork.Enqueue(request);
}
/// <summary>
/// Requests that the cache be cleared. The cache will be cleared asynchronously.
/// </summary>
public void RequestClear() {
CacheRequest request;
if (!requestsRecyclePool.Dequeue(out request)) {
request = new CacheRequest();
}
request.type = RequestType.CLEAR;
PtDebug.LogVerboseFormat("PBC: enqueing CLEAR request.");
requestsPendingWork.Enqueue(request);
}
/// <summary>
/// Checks for pending deliveries and delivers them.
/// </summary>
private void Update() {
if (!setupDone) return;
// To avoid locking the queue on every frame, exit early if the volatile count is 0.
if (requestsPendingDelivery.VolatileCount == 0) return;
// Check for a pending delivery.
// Note that for performance reasons, we limit ourselves to delivering one result per frame.
CacheRequest delivery;
if (!requestsPendingDelivery.Dequeue(out delivery)) {
return;
}
PtDebug.LogVerboseFormat("PBC: delivering result on {0} ({1}, {2} bytes).",
delivery.hash, delivery.success ? "SUCCESS" : "FAILURE", delivery.data != null ? delivery.data.Length : -1);
// Deliver the results to the callback.
delivery.readCallback(delivery.success, delivery.data);
// Recycle the request for reuse.
delivery.Reset();
requestsRecyclePool.Enqueue(delivery);
}
/// <summary>
/// Initializes the cache (reads the cache state from disk).
/// </summary>
private void InitializeCache() {
foreach (string file in Directory.GetFiles(rootPath)) {
if (file.EndsWith(BLOB_FILE_EXT)) {
FileInfo finfo = new FileInfo(file);
string hash = Path.GetFileNameWithoutExtension(file).ToLowerInvariant();
cacheEntries[hash] = new CacheEntry(hash, finfo.Length, TicksToMillis(finfo.LastWriteTimeUtc.Ticks));
PtDebug.LogVerboseFormat("PBC: loaded existing cache item: {0} => {1} bytes",
hash, cacheEntries[hash].fileSize);
}
}
}
/// <summary>
/// Returns the hash of the given key.
/// </summary>
/// <param name="key">The input string.</param>
/// <returns>The hash of the input string, in lowercase hexadecimal format.</returns>
private string GetHash(string key) {
byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(key));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++) {
// x2 is 2-digit hexadecimal format (like "d8")
sb.Append(hashBytes[i].ToString("x2"));
}
// x4 is 4-digit hexadecimal format (like "a1b2").
return sb.ToString() + key.Length.ToString("x4");
}
/// <summary>
/// Returns the full path corresponding to a hash value.
/// </summary>
/// <param name="hash">The hash value</param>
/// <returns>The full path to the file that stores the asset with the indicated hash.</returns>
private string HashToFullPath(string hash) {
return Path.Combine(rootPath, hash + BLOB_FILE_EXT);
}
/// <summary>
/// (Background thread). Main function that constantly checks the queues for pending requests and executes
/// them as they arrive.
/// </summary>
private void BackgroundThreadMain() {
try {
while (true) {
CacheRequest request;
// Wait until the next request comes in.
if (!requestsPendingWork.WaitAndDequeue(/* waitTime */ 5000, out request)) {
continue;
}
// Process it.
switch (request.type) {
case RequestType.READ:
BackgroundHandleReadRequest(request);
break;
case RequestType.WRITE:
BackgroundHandleWriteRequest(request);
break;
case RequestType.CLEAR:
BackgroundHandleClearRequest(request);
break;
default:
PolyUtils.Throw("Invalid cache request type, should be READ, WRITE or CLEAR.");
break;
}
}
} catch (ThreadAbortException) {
// That's ok (happens on project shutdown).
} catch (Exception ex) {
Debug.LogErrorFormat("Cache background thread crashed: " + ex);
}
}
/// <summary>
/// (Background thread). Handles a read request, reading it from disk and scheduling the delivery
/// of the results to the caller.
/// </summary>
/// <param name="readRequest">The read request to execute.</param>
private void BackgroundHandleReadRequest(CacheRequest readRequest) {
PtDebug.LogVerboseFormat("PBC: executing read request for {0} ({1})", readRequest.key,
readRequest.hash);
string fullPath = HashToFullPath(readRequest.hash);
CacheEntry entry;
if (!cacheEntries.TryGetValue(readRequest.hash, out entry)) {
// Not in the cache
readRequest.data = null;
readRequest.success = false;
} else if (readRequest.maxAgeMillis > 0 && entry.AgeMillis > readRequest.maxAgeMillis) {
// Too old.
readRequest.data = null;
readRequest.success = false;
} else if (!File.Exists(fullPath)) {
// Too old.
readRequest.data = null;
readRequest.success = false;
} else {
// Found it.
readRequest.data = File.ReadAllBytes(fullPath);
readRequest.success = true;
// Update the read timestamp.
entry.readTimestampMillis = TicksToMillis(DateTime.UtcNow.Ticks);
}
// Schedule the result for delivery to the caller.
requestsPendingDelivery.Enqueue(readRequest);
}
/// <summary>
/// (Background thread). Handles a write request. Writes the data to disk.
/// </summary>
/// <param name="writeRequest">The write request to execute.</param>
private void BackgroundHandleWriteRequest(CacheRequest writeRequest) {
PtDebug.LogVerboseFormat("PBC: executing write request for {0}", writeRequest.hash);
string fullPath = HashToFullPath(writeRequest.hash);
string tempPath = Path.Combine(Path.GetDirectoryName(fullPath), "temp.dat");
// In the event of a crash or hardware issues -- e.g., user trips on the power cord, our write
// to disk might be interrupted in an inconsistent state. So instead of writing directly to
// the destination file, we write to a temporary file and then move.
File.WriteAllBytes(tempPath, writeRequest.data);
if (File.Exists(fullPath)) File.Delete(fullPath);
File.Move(tempPath, fullPath);
// Update the file size and last used time information in the cache.
CacheEntry entry;
if (!cacheEntries.TryGetValue(writeRequest.hash, out entry)) {
entry = cacheEntries[writeRequest.hash] = new CacheEntry(writeRequest.hash);
}
entry.fileSize = writeRequest.data.Length;
entry.writeTimestampMillis = TicksToMillis(DateTime.UtcNow.Ticks);
// We are done with writeRequest, so we can recycle it.
writeRequest.Reset();
requestsRecyclePool.Enqueue(writeRequest);
// Check if the cache needs trimming.
TrimCache();
}
/// <summary>
/// (Background thread). Clears the entire cache.
/// </summary>
private void BackgroundHandleClearRequest(CacheRequest clearRequest) {
PtDebug.LogVerboseFormat("Clearing the cache.");
foreach (string file in Directory.GetFiles(rootPath, "*" + BLOB_FILE_EXT)) {
File.Delete(file);
}
cacheEntries.Clear();
clearRequest.Reset();
requestsRecyclePool.Enqueue(clearRequest);
}
private void TrimCache() {
long totalSize = 0;
foreach (CacheEntry cacheEntry in cacheEntries.Values) {
totalSize += cacheEntry.fileSize;
}
if (totalSize <= maxSizeBytes && cacheEntries.Count <= maxEntries) {
// We're within budget, no need to trim the cache.
return;
}
// Sort the entries from oldest to newest. This is the order in which we will evict them.
Queue<CacheEntry> entriesOldestToNewest =
new Queue<CacheEntry>(cacheEntries.Values.OrderBy(entry => entry.writeTimestampMillis));
// Each iteration evicts the oldest item, until we're back under budget.
while (totalSize > maxSizeBytes || cacheEntries.Count > maxEntries) {
PtDebug.LogVerboseFormat("PBC: trimming cache, bytes {0}/{1}, entries {2}/{3}",
totalSize, maxSizeBytes, cacheEntries.Values.Count, maxEntries);
// What's the oldest file?
if (entriesOldestToNewest.Count == 0) break;
CacheEntry oldest = entriesOldestToNewest.Dequeue();
// Delete this file.
string filePath = HashToFullPath(oldest.hash);
if (File.Exists(filePath)) {
File.Delete(filePath);
}
cacheEntries.Remove(oldest.hash);
// Update our accounting
totalSize -= oldest.fileSize;
}
PtDebug.LogVerboseFormat("PBC: end of trim, bytes {0}/{1}, entries {2}/{3}",
totalSize, maxSizeBytes, cacheEntries.Count, maxEntries);
}
private static long TicksToMillis(long ticks) {
// According to the docs: "A single tick represents one hundred nanoseconds or one ten-millionth of a
// second. There are 10,000 ticks in a millisecond, or 10 million ticks in a second."
// https://msdn.microsoft.com/en-us/library/system.datetime.ticks(v=vs.110).aspx
return ticks / 10000L;
}
private void OnEnable() {
#if UNITY_EDITOR
if (!Application.isPlaying) {
// In the Unity Editor, we need to install a delegate to get Update() frequently
// (otherwise we'd only get it when something in the scene changes).
UnityEditor.EditorApplication.update += Update;
}
#endif
}
private void OnDisable() {
#if UNITY_EDITOR
if (!Application.isPlaying) {
// In the Unity Editor, we need to install a delegate to get Update() frequently
// (otherwise we'd only get it when something in the scene changes).
UnityEditor.EditorApplication.update -= Update;
}
#endif
}
/// <summary>
/// Represents each entry in the cache.
/// </summary>
private class CacheEntry {
/// <summary>
/// Hash of the entry's key.
/// </summary>
public string hash;
/// <summary>
/// Size of the file, in bytes.
/// </summary>
public long fileSize = 0;
/// <summary>
/// Time in millis when the file was last written to.
/// </summary>
public long writeTimestampMillis = 0;
/// <summary>
/// Time in millis when the file was last read.
/// </summary>
public long readTimestampMillis = 0;
/// <summary>
/// Age of the file (millis since it was last written).
/// </summary>
public long AgeMillis { get { return TicksToMillis(DateTime.UtcNow.Ticks) - writeTimestampMillis; } }
public CacheEntry(string hash) { this.hash = hash; }
public CacheEntry(string hash, long fileSize, long writeTimestampMillis) {
this.hash = hash;
this.fileSize = fileSize;
this.writeTimestampMillis = writeTimestampMillis;
}
}
public enum RequestType {
// Read a file from the cache.
READ,
// Write a file to the cache.
WRITE,
// Clear the entire cache.
CLEAR
}
/// <summary>
/// Represents a cache operation request.
///
/// We reuse the same class for read and write requests (even though it might be a bit confusing)
/// because we pool these objects to avoid allocation.
/// </summary>
private class CacheRequest {
/// <summary>
/// Type of request (see RequestType for details).
/// </summary>
public RequestType type;
/// <summary>
/// The key to read or write.
/// </summary>
public string key;
/// <summary>
/// The hash of the key.
/// </summary>
public string hash;
/// <summary>
/// The callback to call when the request is complete (for READ requests only).
/// </summary>
public CacheReadCallback readCallback;
/// <summary>
/// The request data. For READ requests, this is an out parameter that points to the
/// data at the end of the operation. For WRITE requests, this is an in parameter that
/// points to the data to write.
/// </summary>
public byte[] data;
/// <summary>
/// For READ requests, this is the maximum accepted age of the cached copy, in millis.
/// Ignored for WRITE requests.
/// </summary>
public long maxAgeMillis;
/// <summary>
/// Indicates whether or not the request was successful. Only used for READ requests.
/// </summary>
public bool success;
public CacheRequest() {
Reset();
}
public void Reset() {
type = RequestType.READ;
hash = null;
readCallback = null;
success = false;
data = null;
maxAgeMillis = -1;
}
}
}
}
| |
// 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 System.IO.Tests
{
public class Directory_Move : FileSystemTest
{
#region Utilities
public virtual void Move(string sourceDir, string destDir)
{
Directory.Move(sourceDir, destDir);
}
#endregion
#region UniversalTests
[Fact]
public void NullPath()
{
Assert.Throws<ArgumentNullException>(() => Move(null, "."));
Assert.Throws<ArgumentNullException>(() => Move(".", null));
}
[Fact]
public void EmptyPath()
{
Assert.Throws<ArgumentException>(() => Move(string.Empty, "."));
Assert.Throws<ArgumentException>(() => Move(".", string.Empty));
}
[Fact]
public void NonExistentDirectory()
{
DirectoryInfo valid = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<DirectoryNotFoundException>(() => Move(GetTestFilePath(), valid.FullName));
Assert.Throws<DirectoryNotFoundException>(() => Move(valid.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName())));
}
[Fact]
public void MoveOntoExistingDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<IOException>(() => Move(testDir.FullName, testDir.FullName));
}
[Fact]
public void MoveIntoCurrentDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<IOException>(() => Move(testDir.FullName, Path.Combine(testDir.FullName, ".")));
}
[Fact]
public void MoveOntoParentDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<IOException>(() => Move(testDir.FullName, Path.Combine(testDir.FullName, "..")));
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/1008
public void BasicMove()
{
string testDirSource = Path.Combine(TestDirectory, GetTestFileName());
string testDirDest = Path.Combine(TestDirectory, GetTestFileName());
Directory.CreateDirectory(testDirSource);
Move(testDirSource, testDirDest);
Assert.True(Directory.Exists(testDirDest));
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/1008
public void MultipleMoves()
{
string testDir = GetTestFilePath();
string testDirSource = Path.Combine(testDir, GetTestFileName());
string testDirDest1 = Path.Combine(testDir, GetTestFileName());
string testDirDest2 = Path.Combine(testDir, GetTestFileName());
Directory.CreateDirectory(testDirSource);
Move(testDirSource, testDirDest1);
Move(testDirDest1, testDirDest2);
Assert.True(Directory.Exists(testDirDest2));
Assert.False(Directory.Exists(testDirDest1));
Assert.False(Directory.Exists(testDirSource));
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/1008
public void DirectoryNameWithSpaces()
{
string testDirSource = Path.Combine(TestDirectory, GetTestFileName());
string testDirDest = Path.Combine(TestDirectory, " e n d");
Directory.CreateDirectory(testDirSource);
Move(testDirSource, testDirDest);
Assert.True(Directory.Exists(testDirDest));
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/1008
public void TrailingDirectorySeparators()
{
string testDirSource = Path.Combine(TestDirectory, GetTestFileName());
string testDirDest = Path.Combine(TestDirectory, GetTestFileName());
Directory.CreateDirectory(testDirSource);
Move(testDirSource + Path.DirectorySeparatorChar, testDirDest + Path.DirectorySeparatorChar);
Assert.True(Directory.Exists(testDirDest));
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/1008
public void IncludeSubdirectories()
{
string testDirSource = Path.Combine(TestDirectory, GetTestFileName());
string testDirSubDirectory = GetTestFileName();
string testDirDest = Path.Combine(TestDirectory, GetTestFileName());
Directory.CreateDirectory(testDirSource);
Directory.CreateDirectory(Path.Combine(testDirSource, testDirSubDirectory));
Move(testDirSource, testDirDest);
Assert.True(Directory.Exists(testDirDest));
Assert.False(Directory.Exists(testDirSource));
Assert.True(Directory.Exists(Path.Combine(testDirDest, testDirSubDirectory)));
}
[Fact]
public void Path_Longer_Than_MaxLongPath_Throws_Exception()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
Assert.All((IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath())), (path) =>
{
Assert.Throws<PathTooLongException>(() => Move(testDir, path));
Assert.Throws<PathTooLongException>(() => Move(path, testDir));
});
}
#endregion
#region PlatformSpecific
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot)]
[PlatformSpecific(TestPlatforms.Windows)] // Long path succeeds
public void Path_With_Longer_Than_MaxDirectory_Succeeds()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
Assert.True(Directory.Exists(testDir), "test directory should exist");
Assert.All((IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath())), (path) =>
{
string baseDestinationPath = Path.GetDirectoryName(path);
if (!Directory.Exists(baseDestinationPath))
{
Directory.CreateDirectory(baseDestinationPath);
}
Assert.True(Directory.Exists(baseDestinationPath), "base destination path should exist");
Move(testDir, path);
Assert.False(Directory.Exists(testDir), "source directory should exist");
Assert.True(Directory.Exists(path), "destination directory should exist");
Move(path, testDir);
Assert.False(Directory.Exists(path), "source directory should exist");
Assert.True(Directory.Exists(testDir), "destination directory should exist");
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Wild characters in path, wild chars are normal chars on Unix
public void WindowsWildCharacterPath()
{
Assert.Throws<ArgumentException>(() => Move("*", GetTestFilePath()));
Assert.Throws<ArgumentException>(() => Move(TestDirectory, "*"));
Assert.Throws<ArgumentException>(() => Move(TestDirectory, "Test*t"));
Assert.Throws<ArgumentException>(() => Move(TestDirectory, "*Test"));
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/1008
[PlatformSpecific(TestPlatforms.AnyUnix)] // Wild characters in path are allowed
public void UnixWildCharacterPath()
{
// Wildcards are allowed in paths for Unix move commands as literals as well as functional wildcards,
// but to implement the latter in .NET would be confusing (e.g. having a DirectoryInfo represent multiple directories),
// so the implementation assumes the former.
// Thus, any "*" characters will act the same as any other character when used in a file/directory name.
string testDir = GetTestFilePath();
string testDirSource = Path.Combine(testDir, "*");
string testDirShouldntMove = Path.Combine(testDir, "*t");
string testDirDest = Path.Combine(testDir, "*" + GetTestFileName());
Directory.CreateDirectory(testDirSource);
Directory.CreateDirectory(testDirShouldntMove);
Move(testDirSource, testDirDest);
Assert.True(Directory.Exists(testDirDest));
Assert.False(Directory.Exists(testDirSource));
Assert.True(Directory.Exists(testDirShouldntMove));
Move(testDirDest, testDirSource);
Assert.False(Directory.Exists(testDirDest));
Assert.True(Directory.Exists(testDirSource));
Assert.True(Directory.Exists(testDirShouldntMove));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Whitespace path causes ArgumentException
public void WindowsWhitespacePath()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<ArgumentException>(() => Move(testDir.FullName, " "));
Assert.Throws<ArgumentException>(() => Move(testDir.FullName, "\n"));
Assert.Throws<ArgumentException>(() => Move(testDir.FullName, ""));
Assert.Throws<ArgumentException>(() => Move(testDir.FullName, ">"));
Assert.Throws<ArgumentException>(() => Move(testDir.FullName, "<"));
Assert.Throws<ArgumentException>(() => Move(testDir.FullName, "\0"));
Assert.Throws<ArgumentException>(() => Move(testDir.FullName, "\t"));
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/1008
[PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace path allowed
public void UnixWhitespacePath()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testDirToMove = Path.Combine(testDir.FullName, GetTestFileName());
Directory.CreateDirectory(testDirToMove);
Move(testDirToMove, Path.Combine(testDir.FullName, " "));
Move(Path.Combine(testDir.FullName, " "), Path.Combine(testDir.FullName, "\n"));
Move(Path.Combine(testDir.FullName, "\n"), Path.Combine(testDir.FullName, "\t"));
Move(Path.Combine(testDir.FullName, "\t"), Path.Combine(testDir.FullName, ">"));
Move(Path.Combine(testDir.FullName, ">"), Path.Combine(testDir.FullName, "< "));
Assert.True(Directory.Exists(Path.Combine(testDir.FullName, "< ")));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Moving to existing directory causes IOException
public void WindowsExistingDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testDirSource = Path.Combine(testDir.FullName, GetTestFileName());
string testDirDest = Path.Combine(testDir.FullName, GetTestFileName());
Directory.CreateDirectory(testDirSource);
Directory.CreateDirectory(testDirDest);
Assert.Throws<IOException>(() => Move(testDirSource, testDirDest));
Assert.True(Directory.Exists(testDirDest));
Assert.True(Directory.Exists(testDirSource));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // drive labels
public void BetweenDriveLabels()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string path = Path.GetFullPath(testDir.FullName);
if (path.Substring(0, 3) == @"d:\" || path.Substring(0, 3) == @"D:\")
Assert.Throws<IOException>(() => Move(path, "C:\\DoesntExist"));
else
Assert.Throws<IOException>(() => Move(path, "D:\\DoesntExist"));
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/1008
[PlatformSpecific(TestPlatforms.AnyUnix)] // Moving to existing directory allowed for empty directory, but causes IOException for non-empty directory
public void UnixExistingDirectory()
{
// Moving to an-empty directory is supported on Unix, but moving to a non-empty directory is not
string testDirSource = GetTestFilePath();
string testDirDestEmpty = GetTestFilePath();
string testDirDestNonEmpty = GetTestFilePath();
Directory.CreateDirectory(testDirSource);
Directory.CreateDirectory(testDirDestEmpty);
Directory.CreateDirectory(testDirDestNonEmpty);
using (File.Create(Path.Combine(testDirDestNonEmpty, GetTestFileName())))
{
Assert.Throws<IOException>(() => Move(testDirSource, testDirDestNonEmpty));
Assert.True(Directory.Exists(testDirDestNonEmpty));
Assert.True(Directory.Exists(testDirSource));
}
Move(testDirSource, testDirDestEmpty);
Assert.True(Directory.Exists(testDirDestEmpty));
Assert.False(Directory.Exists(testDirSource));
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Xunit;
namespace System.Reflection.Tests
{
public static class SignatureTypeTests
{
[Fact]
public static void IsSignatureType()
{
// Executing [Theory] logic manually. Signature Types cannot be used in theory data because Xunit preemptively invokes an unguarded
// System.Type pretty printer that invokes members that Signature Types don't support.
foreach (object[] pair in IsSignatureTypeTestData)
{
Type type = (Type)(pair[0]);
bool expected = (bool)(pair[1]);
Assert.Equal(expected, type.IsSignatureType);
}
}
private static IEnumerable<object[]> IsSignatureTypeTestData
{
get
{
yield return new object[] { typeof(int), false };
yield return new object[] { typeof(int).MakeArrayType(), false };
yield return new object[] { typeof(int).MakeArrayType(1), false };
yield return new object[] { typeof(int).MakeArrayType(2), false };
yield return new object[] { typeof(int).MakeByRefType(), false };
yield return new object[] { typeof(int).MakePointerType(), false };
yield return new object[] { typeof(List<>).MakeGenericType(typeof(int)), false };
yield return new object[] { typeof(List<>).GetGenericArguments()[0], false };
Type sigType = Type.MakeGenericMethodParameter(2);
yield return new object[] { sigType, true };
yield return new object[] { sigType.MakeArrayType(), true };
yield return new object[] { sigType.MakeArrayType(1), true };
yield return new object[] { sigType.MakeArrayType(2), true };
yield return new object[] { sigType.MakeByRefType(), true };
yield return new object[] { sigType.MakePointerType(), true };
yield return new object[] { typeof(List<>).MakeGenericType(sigType), true };
}
}
[Fact]
public static void GetMethodWithGenericParameterCount()
{
Type t = typeof(TestClass1);
const BindingFlags bf = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly;
Type[] args = { typeof(int) };
MethodInfo m;
Assert.Throws<AmbiguousMatchException>(() => t.GetMethod("Moo", bf, null, args, null));
for (int genericParameterCount = 0; genericParameterCount < 4; genericParameterCount++)
{
m = t.GetMethod("Moo", genericParameterCount, bf, null, args, null);
Assert.NotNull(m);
AssertIsMarked(m, genericParameterCount);
// Verify that generic parameter count filtering occurs before candidates are passed to the binder.
m = t.GetMethod("Moo", genericParameterCount, bf, new InflexibleBinder(genericParameterCount), args, null);
Assert.NotNull(m);
AssertIsMarked(m, genericParameterCount);
}
m = t.GetMethod("Moo", 4, bf, null, args, null);
Assert.Null(m);
}
private sealed class InflexibleBinder : Binder
{
public InflexibleBinder(int genericParameterCount)
{
_genericParameterCount = genericParameterCount;
}
public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture) => throw null;
public sealed override MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state) => throw null;
public sealed override object ChangeType(object value, Type type, CultureInfo culture) => throw null;
public sealed override void ReorderArgumentArray(ref object[] args, object state) => throw null;
public sealed override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
{
foreach (MethodBase methodBase in match)
{
Assert.True(methodBase is MethodInfo methodInfo && methodInfo.GetGenericArguments().Length == _genericParameterCount);
}
return Type.DefaultBinder.SelectMethod(bindingAttr, match, types, modifiers);
}
public sealed override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers) { throw null; }
private readonly int _genericParameterCount;
}
[Fact]
public static void GetMethodWithNegativeGenericParameterCount()
{
Type t = typeof(TestClass1);
const BindingFlags bf = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly;
Type[] args = { typeof(int) };
Assert.Throws<ArgumentException>(() => t.GetMethod("Moo", -1, bf, null, args, null));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void GetMethodOverloadTest(bool exactBinding)
{
Type t = typeof(TestClass2);
BindingFlags bf = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly;
if (exactBinding)
{
bf |= BindingFlags.ExactBinding;
}
Type[] args = { Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(1).MakeArrayType() };
MethodInfo moo = t.GetMethod("Moo", 2, bf, null, args, null);
AssertIsMarked(moo, 3);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void SignatureTypeComparisonLogicCodeCoverage(bool exactBinding)
{
Type t = typeof(TestClass3<,>);
MethodInfo[] methods = t.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
BindingFlags bf = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly;
if (exactBinding)
{
bf |= BindingFlags.ExactBinding;
}
foreach (MethodInfo m in methods)
{
ParameterInfo[] parameters = m.GetParameters();
Type[] sigTypes = new Type[parameters.Length];
for (int i = 0; i < sigTypes.Length; i++)
{
sigTypes[i] = parameters[i].ParameterType.ToSignatureType();
}
MethodInfo match = t.GetMethod("Moo", m.GetGenericArguments().Length, bf, null, sigTypes, null);
Assert.NotNull(match);
Assert.True(m.HasSameMetadataDefinitionAs(match));
}
}
[Fact]
public static void SigTypeResolutionResilience()
{
// Make sure the framework can't be tricked into throwing an exception because it tried to look up a nonexistent method generic parameter
// or trying to construct a generic type where the constraints don't validate.
Type t = typeof(TestClass4<>);
Type[] args = { typeof(TestClass4<>).MakeGenericType(Type.MakeGenericMethodParameter(1)), Type.MakeGenericMethodParameter(500) };
CountingBinder binder = new CountingBinder();
Assert.Null(t.GetMethod("Moo", BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, binder, args, null));
Assert.Equal(3, binder.NumCandidatesReceived);
}
private sealed class CountingBinder : Binder
{
public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture) => throw null;
public sealed override MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state) => throw null;
public sealed override object ChangeType(object value, Type type, CultureInfo culture) => throw null;
public sealed override void ReorderArgumentArray(ref object[] args, object state) => throw null;
public sealed override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
{
NumCandidatesReceived += match.Length;
return Type.DefaultBinder.SelectMethod(bindingAttr, match, types, modifiers);
}
public sealed override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers) { throw null; }
public int NumCandidatesReceived { get; private set; }
}
[Theory]
[InlineData(0)]
[InlineData(3)]
[InlineData(400)]
[InlineData(int.MaxValue)]
public static void MakeGenericMethodParameter(int position)
{
Type t = Type.MakeGenericMethodParameter(position);
Assert.True(t.IsGenericParameter);
Assert.Equal(position, t.GenericParameterPosition);
TestSignatureTypeInvariants(t);
}
[Theory]
[InlineData(-1)]
[InlineData(-5)]
[InlineData(int.MinValue)]
public static void MakeGenericMethodParameterNegative(int position)
{
Assert.Throws<ArgumentException>(() => Type.MakeGenericMethodParameter(position));
}
[Fact]
public static void MakeSignatureArrayType()
{
Type t = Type.MakeGenericMethodParameter(5);
t = t.MakeArrayType();
Assert.True(t.IsArray);
Assert.True(t.IsSZArray);
Assert.Equal(1, t.GetArrayRank());
Type et = t.GetElementType();
Assert.True(et.IsSignatureType);
Assert.True(et.IsGenericParameter);
Assert.Equal(5, et.GenericParameterPosition);
TestSignatureTypeInvariants(t);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public static void MakeSignatureMdArrayType(int rank)
{
Type t = Type.MakeGenericMethodParameter(5);
t = t.MakeArrayType(rank);
Assert.True(t.IsArray);
Assert.True(t.IsVariableBoundArray);
Assert.Equal(rank, t.GetArrayRank());
TestSignatureTypeInvariants(t);
}
[Fact]
public static void MakeSignatureByRefType()
{
Type t = Type.MakeGenericMethodParameter(5);
t = t.MakeByRefType();
Assert.True(t.IsByRef);
Type et = t.GetElementType();
Assert.True(et.IsSignatureType);
Assert.True(et.IsGenericParameter);
Assert.Equal(5, et.GenericParameterPosition);
TestSignatureTypeInvariants(t);
}
[Fact]
public static void MakeSignaturePointerType()
{
Type t = Type.MakeGenericMethodParameter(5);
t = t.MakePointerType();
Assert.True(t.IsPointer);
Type et = t.GetElementType();
Assert.True(et.IsSignatureType);
Assert.True(et.IsGenericParameter);
Assert.Equal(5, et.GenericParameterPosition);
TestSignatureTypeInvariants(t);
}
[Theory]
[InlineData(typeof(List<>))]
[InlineData(typeof(Span<>))]
public static void MakeSignatureConstructedGenericType(Type genericTypeDefinition)
{
Type t = Type.MakeGenericMethodParameter(5);
t = genericTypeDefinition.MakeGenericType(t);
Assert.True(t.IsConstructedGenericType);
Assert.Equal(genericTypeDefinition, t.GetGenericTypeDefinition());
Assert.Equal(1, t.GenericTypeArguments.Length);
Type et = t.GenericTypeArguments[0];
Assert.True(et.IsSignatureType);
Assert.True(et.IsGenericParameter);
Assert.Equal(5, et.GenericParameterPosition);
TestSignatureTypeInvariants(t);
}
private static Type ToSignatureType(this Type type)
{
if (type.IsTypeDefinition)
return type;
if (type.IsSZArray)
return type.GetElementType().ToSignatureType().MakeArrayType();
if (type.IsVariableBoundArray)
return type.GetElementType().ToSignatureType().MakeArrayType(type.GetArrayRank());
if (type.IsByRef)
return type.GetElementType().ToSignatureType().MakeByRefType();
if (type.IsPointer)
return type.GetElementType().ToSignatureType().MakePointerType();
if (type.IsConstructedGenericType)
{
Type[] genericTypeArguments = type.GenericTypeArguments.Select(t => t.ToSignatureType()).ToArray();
return type.GetGenericTypeDefinition().MakeGenericType(genericTypeArguments);
}
if (type.IsGenericParameter)
{
if (type.DeclaringMethod == null)
return type;
return Type.MakeGenericMethodParameter(type.GenericParameterPosition);
}
throw new Exception("Unknown type flavor.");
}
private static void AssertIsMarked(MemberInfo member, int value)
{
MarkerAttribute marker = member.GetCustomAttribute<MarkerAttribute>(inherit: false);
Assert.NotNull(marker);
Assert.Equal(value, marker.Value);
}
[AttributeUsage(AttributeTargets.All, Inherited = false)]
private sealed class MarkerAttribute : Attribute
{
public MarkerAttribute(int value)
{
Value = value;
}
public int Value { get; }
}
private sealed class TestClass1
{
[Marker(0)] public static void Moo(int x) { }
[Marker(1)] public static void Moo<T1>(int x) { }
[Marker(2)] public static void Moo<T1, T2>(int x) { }
[Marker(3)] public static void Moo<T1, T2, T3>(int x) {}
}
private class TestClass2
{
[Marker(0)] public static void Moo(int x, int[] y) { }
[Marker(1)] public static void Moo<T>(T x, T[] y) { }
[Marker(2)] public static void Moo<T>(int x, int[] y) { }
[Marker(3)] public static void Moo<T, U>(T x, U[] y) { }
[Marker(4)] public static void Moo<T, U>(int x, int[] y) { }
}
private class TestClass3<T,U>
{
public static void Moo(T p1, T[] p2, T[,] p3, ref T p4, TestClass3<T, T> p5, ref TestClass3<T, T[]>[,] p6) { }
public static void Moo(U p1, U[] p2, U[,] p3, ref U p4, TestClass3<U, U> p5, ref TestClass3<U, U[]>[,] p6) { }
public static void Moo<M>(T p1, T[] p2, T[,] p3, ref T p4, TestClass3<T, T> p5, ref TestClass3<T, T[]>[,] p6) { }
public static void Moo<M>(U p1, U[] p2, U[,] p3, ref U p4, TestClass3<U, U> p5, ref TestClass3<U, U[]>[,] p6) { }
public static void Moo<M>(M p1, M[] p2, M[,] p3, ref M p4, TestClass3<M, M> p5, ref TestClass3<M, M[]>[,] p6) { }
public static void Moo<M, N>(T p1, T[] p2, T[,] p3, ref T p4, TestClass3<T, T> p5, ref TestClass3<T, T[]>[,] p6) { }
public static void Moo<M, N>(U p1, U[] p2, U[,] p3, ref U p4, TestClass3<U, U> p5, ref TestClass3<U, U[]>[,] p6) { }
public static void Moo<M, N>(M p1, M[] p2, M[,] p3, ref M p4, TestClass3<M, M> p5, ref TestClass3<M, M[]>[,] p6) { }
public static void Moo<M, N>(N p1, N[] p2, N[,] p3, ref N p4, TestClass3<N, N> p5, ref TestClass3<N, N[]>[,] p6) { }
}
private class TestClass4<T> where T: NoOneSubclasses, new()
{
public static void Moo<M>(int p1, int p2) where M : NoOneSubclassesThisEither { }
public static void Moo<N, O>(TestClass4<N> p1, int p2) where N : NoOneSubclasses, new() { }
public static void Moo<N, O>(O p1, int p2) where N : NoOneSubclasses, new() { }
}
private class NoOneSubclasses { }
private class NoOneSubclassesThisEither { }
private static void TestSignatureTypeInvariants(Type type)
{
Assert.True(type.IsSignatureType);
Assert.False(type.IsTypeDefinition);
Assert.False(type.IsGenericTypeDefinition);
Assert.NotNull(type.Name);
Assert.Null(type.FullName);
Assert.Null(type.AssemblyQualifiedName);
Assert.NotNull(type.ToString());
Assert.Equal(MemberTypes.TypeInfo, type.MemberType);
Assert.Same(type, type.UnderlyingSystemType);
// SignatureTypes don't override Equality/GetHashCode at this time, but they don't promise never to do so either.
// Thus, we'll only test the most basic behavior.
Assert.True(type.Equals((object)type));
Assert.True(type.Equals((Type)type));
Assert.False(type.Equals((object)null));
Assert.False(type.Equals((Type)null));
int _ = type.GetHashCode();
bool categorized = false;
if (type.IsArray)
{
Assert.False(categorized);
categorized = true;
Assert.True(type.HasElementType);
Assert.True(type.IsSZArray != type.IsVariableBoundArray);
Assert.Equal(type.GetElementType().ContainsGenericParameters, type.ContainsGenericParameters);
string elementTypeName = type.GetElementType().Name;
if (type.IsSZArray)
{
Assert.Equal(1, type.GetArrayRank());
Assert.Equal(elementTypeName + "[]", type.Name);
}
else
{
int rank = type.GetArrayRank();
Assert.True(rank >= 1);
if (rank == 1)
{
Assert.Equal(elementTypeName + "[*]", type.Name);
}
else
{
Assert.Equal(elementTypeName + "[" + new string(',', rank - 1) + "]", type.Name);
}
}
}
if (type.IsByRef)
{
Assert.False(categorized);
categorized = true;
Assert.True(type.HasElementType);
Assert.Equal(type.GetElementType().ContainsGenericParameters, type.ContainsGenericParameters);
string elementTypeName = type.GetElementType().Name;
Assert.Equal(elementTypeName + "&", type.Name);
}
if (type.IsPointer)
{
Assert.False(categorized);
categorized = true;
Assert.True(type.HasElementType);
Assert.Equal(type.GetElementType().ContainsGenericParameters, type.ContainsGenericParameters);
string elementTypeName = type.GetElementType().Name;
Assert.Equal(elementTypeName + "*", type.Name);
}
if (type.IsConstructedGenericType)
{
Assert.False(categorized);
categorized = true;
Assert.True(type.IsGenericType);
Assert.False(type.HasElementType);
Type genericTypeDefinition = type.GetGenericTypeDefinition();
Assert.Equal(genericTypeDefinition.IsByRefLike, type.IsByRefLike);
Assert.NotNull(genericTypeDefinition);
Assert.True(genericTypeDefinition.IsGenericTypeDefinition);
Type[] genericTypeArguments = type.GetGenericArguments();
Type[] genericTypeArgumentsClone = type.GetGenericArguments();
Assert.NotSame(genericTypeArguments, genericTypeArgumentsClone);
Type[] genericTypeArgumentsFromProperty = type.GenericTypeArguments;
Type[] genericTypeArgumentsFromPropertyClone = type.GenericTypeArguments;
Assert.NotSame(genericTypeArgumentsFromProperty, genericTypeArgumentsFromPropertyClone);
for (int i = 0; i < genericTypeArguments.Length; i++)
{
if (genericTypeArguments[i].IsSignatureType)
{
TestSignatureTypeInvariants(genericTypeArguments[i]);
}
}
Assert.Equal(genericTypeDefinition.Name, type.Name);
Assert.Equal(genericTypeDefinition.Namespace, type.Namespace);
bool containsGenericParameters = false;
for (int i = 0; i < genericTypeArguments.Length; i++)
{
containsGenericParameters = containsGenericParameters || genericTypeArguments[i].ContainsGenericParameters;
}
Assert.Equal(containsGenericParameters, type.ContainsGenericParameters);
}
if (type.IsGenericParameter)
{
Assert.False(categorized);
categorized = true;
Assert.False(type.HasElementType);
Assert.True(type.ContainsGenericParameters);
Assert.Null(type.Namespace);
int position = type.GenericParameterPosition;
Assert.True(position >= 0);
Assert.Equal("!!" + position, type.Name);
}
Assert.True(categorized);
if (type.HasElementType)
{
TestSignatureTypeInvariants(type.GetElementType());
Assert.Equal(type.GetElementType().Namespace, type.Namespace);
}
else
{
Assert.Null(type.GetElementType());
}
if (!type.IsConstructedGenericType)
{
Assert.Throws<InvalidOperationException>(() => type.GetGenericTypeDefinition());
Assert.Equal(0, type.GetGenericArguments().Length);
Assert.Equal(0, type.GenericTypeArguments.Length);
Assert.False(type.IsGenericType);
Assert.False(type.IsByRefLike);
}
if (!type.IsArray)
{
Assert.Throws<ArgumentException>(() => type.GetArrayRank());
}
if (!type.IsGenericParameter)
{
Assert.Throws<InvalidOperationException>(() => type.GenericParameterPosition);
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.UnitTests.Cmdlets.StorageServices
{
using System;
using System.Net;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Management.CloudService.Test.Utilities;
using Microsoft.WindowsAzure.Management.Extensions;
using Microsoft.WindowsAzure.Management.Model;
using Microsoft.WindowsAzure.Management.ServiceManagement.HostedServices;
using Microsoft.WindowsAzure.Management.Test.Stubs;
using Microsoft.WindowsAzure.Management.Test.Tests.Utilities;
using Microsoft.WindowsAzure.ServiceManagement;
[TestClass]
public class MoveAzureDeploymentCommandTests : TestBase
{
FileSystemHelper files;
[TestInitialize]
public void SetupTest()
{
CmdletSubscriptionExtensions.SessionManager = new InMemorySessionManager();
files = new FileSystemHelper(this);
files.CreateAzureSdkDirectoryAndImportPublishSettings();
}
[TestCleanup]
public void CleanupTest()
{
files.Dispose();
}
public class MoveAzureDeploymentTestInputParameters
{
public string Description { get; set; }
public bool ProductionExists { get; set; }
public bool StagingExists { get; set; }
public bool ThrowsException { get; set; }
public Type ExceptionType { get; set; }
public Deployment ProductionDeployment { get; set; }
public Deployment StagingDeployment { get; set; }
}
public void ExecuteTestCase(MoveAzureDeploymentTestInputParameters parameters)
{
var channel = new SimpleServiceManagement
{
GetDeploymentBySlotThunk = ar =>
{
if (ar.Values["deploymentSlot"].ToString() == DeploymentSlotType.Production)
{
if (parameters.ProductionDeployment == null)
{
throw new ServiceManagementClientException(HttpStatusCode.NotFound, new ServiceManagementError(), String.Empty);
}
return parameters.ProductionDeployment;
}
if (ar.Values["deploymentSlot"].ToString() == DeploymentSlotType.Staging)
{
if (parameters.StagingDeployment == null)
{
throw new ServiceManagementClientException(HttpStatusCode.NotFound, new ServiceManagementError(), String.Empty);
}
return parameters.StagingDeployment;
}
return null;
},
SwapDeploymentThunk = ar =>
{
var input = (SwapDeploymentInput)ar.Values["input"];
if (input.Production == null && parameters.ProductionDeployment == null)
{
if (input.SourceDeployment != parameters.StagingDeployment.Name)
{
Assert.Fail("Expected values Staging/Prod'{0},{1}', found '{2},{3}'",
parameters.StagingDeployment.Name, null, input.SourceDeployment, null);
}
}
else if (input.Production != parameters.ProductionDeployment.Name || input.SourceDeployment != parameters.StagingDeployment.Name)
{
Assert.Fail("Expected values Staging/Prod'{0},{1}', found '{2},{3}'",
parameters.StagingDeployment.Name, parameters.ProductionDeployment.Name, input.SourceDeployment, input.Production);
}
}
};
// Test
var moveAzureDeployment = new MoveAzureDeploymentCommand(channel)
{
ShareChannel = true,
CommandRuntime = new MockCommandRuntime(),
ServiceName = "testService",
CurrentSubscription = new SubscriptionData
{
SubscriptionId = "testId"
}
};
try
{
moveAzureDeployment.ExecuteCommand();
if(parameters.ThrowsException)
{
Assert.Fail(parameters.Description);
}
}
catch (Exception e)
{
if(e.GetType() != parameters.ExceptionType)
{
Assert.Fail("Expected exception type is {0}, however found {1}", parameters.ExceptionType, e.GetType());
}
if(!parameters.ThrowsException)
{
Assert.Fail("{0} fails unexpectedly: {1}", parameters.Description, e);
}
}
}
[TestMethod]
public void NoProductionAndNoStagingDeployment()
{
ExecuteTestCase(new MoveAzureDeploymentTestInputParameters
{
Description = MethodBase.GetCurrentMethod().Name,
ThrowsException = true,
ExceptionType = typeof(ArgumentOutOfRangeException),
ProductionDeployment = null,
StagingDeployment = null,
});
}
[TestMethod]
public void ProductionExistsWithNoStagingDeployment()
{
ExecuteTestCase(new MoveAzureDeploymentTestInputParameters
{
Description = MethodBase.GetCurrentMethod().Name,
ThrowsException = true,
ExceptionType = typeof(ArgumentOutOfRangeException),
ProductionDeployment = new Deployment
{
Name = "productionDeployment",
RoleList = new RoleList
{
new Role
{
RoleType = String.Empty
}
}
},
StagingDeployment = null,
});
}
[TestMethod]
public void ProductionExistsWithPersistenVMRoleNoStagingDeployment()
{
ExecuteTestCase(new MoveAzureDeploymentTestInputParameters
{
Description = MethodBase.GetCurrentMethod().Name,
ThrowsException = true,
ExceptionType = typeof(ArgumentException),
ProductionDeployment = new Deployment
{
Name = "productionDeployment",
RoleList = new RoleList
{
new Role
{
RoleType = "PersistentVMRole"
}
}
},
StagingDeployment = null,
});
}
[TestMethod]
public void NoProductionWithStagingDeploymentWithPersistenVMRole()
{
ExecuteTestCase(new MoveAzureDeploymentTestInputParameters
{
Description = MethodBase.GetCurrentMethod().Name,
ThrowsException = true,
ExceptionType = typeof(ArgumentException),
ProductionDeployment = null,
StagingDeployment = new Deployment
{
Name = "stagingDeployment",
RoleList = new RoleList
{
new Role
{
RoleType = "PersistentVMRole"
}
}
},
});
}
[TestMethod]
public void NoProductionWithStagingDeployment()
{
ExecuteTestCase(new MoveAzureDeploymentTestInputParameters
{
Description = MethodBase.GetCurrentMethod().Name,
ThrowsException = false,
ExceptionType = null,
ProductionDeployment = null,
StagingDeployment = new Deployment
{
Name = "stagingDeployment",
RoleList = new RoleList
{
new Role
{
RoleType = String.Empty
}
}
},
});
}
[TestMethod]
public void ProductionDeploymentExistsWithStagingDeployment()
{
ExecuteTestCase(new MoveAzureDeploymentTestInputParameters
{
Description = MethodBase.GetCurrentMethod().Name,
ThrowsException = false,
ExceptionType = null,
ProductionDeployment = new Deployment
{
Name = "prodDeployment",
RoleList = new RoleList
{
new Role
{
RoleType = String.Empty
}
}
},
StagingDeployment = new Deployment
{
Name = "stagingDeployment",
RoleList = new RoleList
{
new Role
{
RoleType = String.Empty
}
}
},
});
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Java.Nio.Channels.Spi.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Java.Nio.Channels.Spi
{
/// <summary>
/// <para><c> SelectorProvider </c> is an abstract base class that declares methods for providing instances of DatagramChannel, Pipe, java.nio.channels.Selector , ServerSocketChannel, and SocketChannel. All the methods of this class are thread-safe.</para><para>A provider instance can be retrieved through a system property or the configuration file in a jar file; if no provider is available that way then the system default provider is returned. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/SelectorProvider
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/SelectorProvider", AccessFlags = 1057)]
public abstract partial class SelectorProvider
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a new <c> SelectorProvider </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal SelectorProvider() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets a provider instance by executing the following steps when called for the first time: <ul><li><para>if the system property "java.nio.channels.spi.SelectorProvider" is set, the value of this property is the class name of the provider returned; </para></li><li><para>if there is a provider-configuration file named "java.nio.channels.spi.SelectorProvider" in META-INF/services of a jar file valid in the system class loader, the first class name is the provider's class name; </para></li><li><para>otherwise, a system default provider will be returned. </para></li></ul></para><para></para>
/// </summary>
/// <returns>
/// <para>the provider. </para>
/// </returns>
/// <java-name>
/// provider
/// </java-name>
[Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 41)]
public static global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.Spi.SelectorProvider);
}
/// <summary>
/// <para>Creates a new open <c> DatagramChannel </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the new channel. </para>
/// </returns>
/// <java-name>
/// openDatagramChannel
/// </java-name>
[Dot42.DexImport("openDatagramChannel", "()Ljava/nio/channels/DatagramChannel;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.DatagramChannel OpenDatagramChannel() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Creates a new <c> Pipe </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the new pipe. </para>
/// </returns>
/// <java-name>
/// openPipe
/// </java-name>
[Dot42.DexImport("openPipe", "()Ljava/nio/channels/Pipe;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.Pipe OpenPipe() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Creates a new selector.</para><para></para>
/// </summary>
/// <returns>
/// <para>the new selector. </para>
/// </returns>
/// <java-name>
/// openSelector
/// </java-name>
[Dot42.DexImport("openSelector", "()Ljava/nio/channels/spi/AbstractSelector;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.Spi.AbstractSelector OpenSelector() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Creates a new open <c> ServerSocketChannel </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the new channel. </para>
/// </returns>
/// <java-name>
/// openServerSocketChannel
/// </java-name>
[Dot42.DexImport("openServerSocketChannel", "()Ljava/nio/channels/ServerSocketChannel;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.ServerSocketChannel OpenServerSocketChannel() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Create a new open <c> SocketChannel </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the new channel. </para>
/// </returns>
/// <java-name>
/// openSocketChannel
/// </java-name>
[Dot42.DexImport("openSocketChannel", "()Ljava/nio/channels/SocketChannel;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.SocketChannel OpenSocketChannel() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the channel inherited from the process that created this VM. On Android, this method always returns null because stdin and stdout are never connected to a socket.</para><para></para>
/// </summary>
/// <returns>
/// <para>the channel. </para>
/// </returns>
/// <java-name>
/// inheritedChannel
/// </java-name>
[Dot42.DexImport("inheritedChannel", "()Ljava/nio/channels/Channel;", AccessFlags = 1)]
public virtual global::Java.Nio.Channels.IChannel InheritedChannel() /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.IChannel);
}
}
/// <summary>
/// <para><c> AbstractSelectionKey </c> is the base implementation class for selection keys. It implements validation and cancellation methods. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/AbstractSelectionKey
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/AbstractSelectionKey", AccessFlags = 1057)]
public abstract partial class AbstractSelectionKey : global::Java.Nio.Channels.SelectionKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a new <c> AbstractSelectionKey </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal AbstractSelectionKey() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates whether this key is valid. A key is valid as long as it has not been canceled.</para><para></para>
/// </summary>
/// <returns>
/// <para><c> true </c> if this key has not been canceled, <c> false </c> otherwise. </para>
/// </returns>
/// <java-name>
/// isValid
/// </java-name>
[Dot42.DexImport("isValid", "()Z", AccessFlags = 17)]
public override bool IsValid() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Cancels this key. </para><para>A key that has been canceled is no longer valid. Calling this method on an already canceled key does nothing. </para>
/// </summary>
/// <java-name>
/// cancel
/// </java-name>
[Dot42.DexImport("cancel", "()V", AccessFlags = 17)]
public override void Cancel() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para><c> AbstractSelectableChannel </c> is the base implementation class for selectable channels. It declares methods for registering, unregistering and closing selectable channels. It is thread-safe. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/AbstractSelectableChannel
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/AbstractSelectableChannel", AccessFlags = 1057)]
public abstract partial class AbstractSelectableChannel : global::Java.Nio.Channels.SelectableChannel
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a new <c> AbstractSelectableChannel </c> .</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V", AccessFlags = 4)]
protected internal AbstractSelectableChannel(global::Java.Nio.Channels.Spi.SelectorProvider selectorProvider) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the selector provider that has created this channel.</para><para><para>java.nio.channels.SelectableChannel::provider() </para></para>
/// </summary>
/// <returns>
/// <para>this channel's selector provider. </para>
/// </returns>
/// <java-name>
/// provider
/// </java-name>
[Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 17)]
public override global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.Spi.SelectorProvider);
}
/// <summary>
/// <para>Indicates whether this channel is registered with one or more selectors.</para><para></para>
/// </summary>
/// <returns>
/// <para><c> true </c> if this channel is registered with a selector, <c> false </c> otherwise. </para>
/// </returns>
/// <java-name>
/// isRegistered
/// </java-name>
[Dot42.DexImport("isRegistered", "()Z", AccessFlags = 49)]
public override bool IsRegistered() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Gets this channel's selection key for the specified selector.</para><para></para>
/// </summary>
/// <returns>
/// <para>the selection key for the channel or <c> null </c> if this channel has not been registered with <c> selector </c> . </para>
/// </returns>
/// <java-name>
/// keyFor
/// </java-name>
[Dot42.DexImport("keyFor", "(Ljava/nio/channels/Selector;)Ljava/nio/channels/SelectionKey;", AccessFlags = 49)]
public override global::Java.Nio.Channels.SelectionKey KeyFor(global::Java.Nio.Channels.Selector selector) /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.SelectionKey);
}
/// <summary>
/// <para>Registers this channel with the specified selector for the specified interest set. If the channel is already registered with the selector, the interest set is updated to <c> interestSet </c> and the corresponding selection key is returned. If the channel is not yet registered, this method calls the <c> register </c> method of <c> selector </c> and adds the selection key to this channel's key set.</para><para></para>
/// </summary>
/// <returns>
/// <para>the selection key for this registration. </para>
/// </returns>
/// <java-name>
/// register
/// </java-name>
[Dot42.DexImport("register", "(Ljava/nio/channels/Selector;ILjava/lang/Object;)Ljava/nio/channels/SelectionKey;" +
"", AccessFlags = 17)]
public override global::Java.Nio.Channels.SelectionKey Register(global::Java.Nio.Channels.Selector selector, int interestSet, object attachment) /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.SelectionKey);
}
/// <summary>
/// <para>Implements the channel closing behavior. Calls <c> implCloseSelectableChannel() </c> first, then loops through the list of selection keys and cancels them, which unregisters this channel from all selectors it is registered with.</para><para></para>
/// </summary>
/// <java-name>
/// implCloseChannel
/// </java-name>
[Dot42.DexImport("implCloseChannel", "()V", AccessFlags = 52)]
protected internal override void ImplCloseChannel() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Implements the closing function of the SelectableChannel. This method is called from <c> implCloseChannel() </c> .</para><para></para>
/// </summary>
/// <java-name>
/// implCloseSelectableChannel
/// </java-name>
[Dot42.DexImport("implCloseSelectableChannel", "()V", AccessFlags = 1028)]
protected internal abstract void ImplCloseSelectableChannel() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Indicates whether this channel is in blocking mode.</para><para></para>
/// </summary>
/// <returns>
/// <para><c> true </c> if this channel is blocking, <c> false </c> otherwise. </para>
/// </returns>
/// <java-name>
/// isBlocking
/// </java-name>
[Dot42.DexImport("isBlocking", "()Z", AccessFlags = 17)]
public override bool IsBlocking() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Gets the object used for the synchronization of <c> register </c> and <c> configureBlocking </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the synchronization object. </para>
/// </returns>
/// <java-name>
/// blockingLock
/// </java-name>
[Dot42.DexImport("blockingLock", "()Ljava/lang/Object;", AccessFlags = 17)]
public override object BlockingLock() /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Sets the blocking mode of this channel. A call to this method blocks if other calls to this method or to <c> register </c> are executing. The actual setting of the mode is done by calling <c> implConfigureBlocking(boolean) </c> .</para><para><para>java.nio.channels.SelectableChannel::configureBlocking(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this channel. </para>
/// </returns>
/// <java-name>
/// configureBlocking
/// </java-name>
[Dot42.DexImport("configureBlocking", "(Z)Ljava/nio/channels/SelectableChannel;", AccessFlags = 17)]
public override global::Java.Nio.Channels.SelectableChannel ConfigureBlocking(bool blockingMode) /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.SelectableChannel);
}
/// <summary>
/// <para>Implements the configuration of blocking/non-blocking mode.</para><para></para>
/// </summary>
/// <java-name>
/// implConfigureBlocking
/// </java-name>
[Dot42.DexImport("implConfigureBlocking", "(Z)V", AccessFlags = 1028)]
protected internal abstract void ImplConfigureBlocking(bool blocking) /* MethodBuilder.Create */ ;
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal AbstractSelectableChannel() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para><c> AbstractInterruptibleChannel </c> is the root class for interruptible channels. </para><para>The basic usage pattern for an interruptible channel is to invoke <c> begin() </c> before any I/O operation that potentially blocks indefinitely, then <c> end(boolean) </c> after completing the operation. The argument to the <c> end </c> method should indicate if the I/O operation has actually completed so that any change may be visible to the invoker. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/AbstractInterruptibleChannel
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/AbstractInterruptibleChannel", AccessFlags = 1057)]
public abstract partial class AbstractInterruptibleChannel : global::Java.Nio.Channels.IChannel, global::Java.Nio.Channels.IInterruptibleChannel
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal AbstractInterruptibleChannel() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns true if this channel is open. </para>
/// </summary>
/// <java-name>
/// isOpen
/// </java-name>
[Dot42.DexImport("isOpen", "()Z", AccessFlags = 49)]
public bool IsOpen() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Closes an open channel. If the channel is already closed then this method has no effect, otherwise it closes the receiver via the <c> implCloseChannel </c> method. </para><para>If an attempt is made to perform an operation on a closed channel then a java.nio.channels.ClosedChannelException is thrown. </para><para>If multiple threads attempt to simultaneously close a channel, then only one thread will run the closure code and the others will be blocked until the first one completes.</para><para><para>java.nio.channels.Channel::close() </para></para>
/// </summary>
/// <java-name>
/// close
/// </java-name>
[Dot42.DexImport("close", "()V", AccessFlags = 17)]
public void Close() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates the beginning of a code section that includes an I/O operation that is potentially blocking. After this operation, the application should invoke the corresponding <c> end(boolean) </c> method. </para>
/// </summary>
/// <java-name>
/// begin
/// </java-name>
[Dot42.DexImport("begin", "()V", AccessFlags = 20)]
protected internal void Begin() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates the end of a code section that has been started with <c> begin() </c> and that includes a potentially blocking I/O operation.</para><para></para>
/// </summary>
/// <java-name>
/// end
/// </java-name>
[Dot42.DexImport("end", "(Z)V", AccessFlags = 20)]
protected internal void End(bool success) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Implements the channel closing behavior. </para><para>Closes the channel with a guarantee that the channel is not currently closed through another invocation of <c> close() </c> and that the method is thread-safe. </para><para>Any outstanding threads blocked on I/O operations on this channel must be released with either a normal return code, or by throwing an <c> AsynchronousCloseException </c> .</para><para></para>
/// </summary>
/// <java-name>
/// implCloseChannel
/// </java-name>
[Dot42.DexImport("implCloseChannel", "()V", AccessFlags = 1028)]
protected internal abstract void ImplCloseChannel() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><c> AbstractSelector </c> is the base implementation class for selectors. It realizes the interruption of selection by <c> begin </c> and <c> end </c> . It also holds the cancellation and the deletion of the key set. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/AbstractSelector
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/AbstractSelector", AccessFlags = 1057)]
public abstract partial class AbstractSelector : global::Java.Nio.Channels.Selector
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V", AccessFlags = 4)]
protected internal AbstractSelector(global::Java.Nio.Channels.Spi.SelectorProvider selectorProvider) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Closes this selector. This method does nothing if this selector is already closed. The actual closing must be implemented by subclasses in <c> implCloseSelector() </c> . </para>
/// </summary>
/// <java-name>
/// close
/// </java-name>
[Dot42.DexImport("close", "()V", AccessFlags = 17)]
public override void Close() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Implements the closing of this channel. </para>
/// </summary>
/// <java-name>
/// implCloseSelector
/// </java-name>
[Dot42.DexImport("implCloseSelector", "()V", AccessFlags = 1028)]
protected internal abstract void ImplCloseSelector() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns true if this selector is open. </para>
/// </summary>
/// <java-name>
/// isOpen
/// </java-name>
[Dot42.DexImport("isOpen", "()Z", AccessFlags = 17)]
public override bool IsOpen() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns this selector's provider. </para>
/// </summary>
/// <java-name>
/// provider
/// </java-name>
[Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 17)]
public override global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.Spi.SelectorProvider);
}
/// <summary>
/// <para>Returns this channel's set of canceled selection keys. </para>
/// </summary>
/// <java-name>
/// cancelledKeys
/// </java-name>
[Dot42.DexImport("cancelledKeys", "()Ljava/util/Set;", AccessFlags = 20, Signature = "()Ljava/util/Set<Ljava/nio/channels/SelectionKey;>;")]
protected internal global::Java.Util.ISet<global::Java.Nio.Channels.SelectionKey> CancelledKeys() /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<global::Java.Nio.Channels.SelectionKey>);
}
/// <summary>
/// <para>Registers <c> channel </c> with this selector.</para><para></para>
/// </summary>
/// <returns>
/// <para>the key related to the channel and this selector. </para>
/// </returns>
/// <java-name>
/// register
/// </java-name>
[Dot42.DexImport("register", "(Ljava/nio/channels/spi/AbstractSelectableChannel;ILjava/lang/Object;)Ljava/nio/c" +
"hannels/SelectionKey;", AccessFlags = 1028)]
protected internal abstract global::Java.Nio.Channels.SelectionKey Register(global::Java.Nio.Channels.Spi.AbstractSelectableChannel channel, int operations, object attachment) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Deletes the key from the channel's key set. </para>
/// </summary>
/// <java-name>
/// deregister
/// </java-name>
[Dot42.DexImport("deregister", "(Ljava/nio/channels/spi/AbstractSelectionKey;)V", AccessFlags = 20)]
protected internal void Deregister(global::Java.Nio.Channels.Spi.AbstractSelectionKey key) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates the beginning of a code section that includes an I/O operation that is potentially blocking. After this operation, the application should invoke the corresponding <c> end(boolean) </c> method. </para>
/// </summary>
/// <java-name>
/// begin
/// </java-name>
[Dot42.DexImport("begin", "()V", AccessFlags = 20)]
protected internal void Begin() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates the end of a code section that has been started with <c> begin() </c> and that includes a potentially blocking I/O operation. </para>
/// </summary>
/// <java-name>
/// end
/// </java-name>
[Dot42.DexImport("end", "()V", AccessFlags = 20)]
protected internal void End() /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal AbstractSelector() /* TypeBuilder.AddDefaultConstructor */
{
}
}
}
| |
//
// MergeDb.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (C) 2008-2010 Novell, Inc.
// Copyright (C) 2010 Ruben Vermeersch
// Copyright (C) 2008-2009 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections.Generic;
using Gtk;
using FSpot;
using FSpot.Core;
using FSpot.Database;
using FSpot.Extensions;
using FSpot.Query;
using FSpot.Utils;
using Mono.Unix;
using Hyena;
using Hyena.Widgets;
namespace FSpot.Tools.MergeDb
{
public class MergeDb : ICommand
{
Db from_db;
Db to_db;
Roll [] new_rolls;
MergeDbDialog mdd;
Dictionary<uint, Tag> tag_map; //Key is a TagId from from_db, Value is a Tag from to_db
Dictionary<uint, uint> roll_map;
public void Run (object o, EventArgs e)
{
from_db = new Db ();
to_db = App.Instance.Database;
//ShowDialog ();
mdd = new MergeDbDialog (this);
mdd.FileChooser.FileSet += HandleFileSet;
mdd.Dialog.Response += HandleResponse;
mdd.ShowAll ();
}
internal Db FromDb {
get { return from_db; }
}
void HandleFileSet (object o, EventArgs e)
{
try {
string tempfilename = System.IO.Path.GetTempFileName ();
System.IO.File.Copy (mdd.FileChooser.Filename, tempfilename, true);
from_db.Init (tempfilename, true);
FillRolls ();
mdd.Rolls = new_rolls;
mdd.SetSensitive ();
} catch (Exception ex) {
string msg = Catalog.GetString ("Error opening the selected file");
string desc = String.Format (Catalog.GetString ("The file you selected is not a valid or supported database.\n\nReceived exception \"{0}\"."), ex.Message);
HigMessageDialog md = new HigMessageDialog (mdd.Dialog, DialogFlags.DestroyWithParent,
Gtk.MessageType.Error,
ButtonsType.Ok,
msg,
desc);
md.Run ();
md.Destroy ();
Log.Exception (ex);
}
}
void FillRolls ()
{
List<Roll> from_rolls = new List<Roll> (from_db.Rolls.GetRolls ());
Roll [] to_rolls = to_db.Rolls.GetRolls ();
foreach (Roll tr in to_rolls)
foreach (Roll fr in from_rolls.ToArray ())
if (tr.Time == fr.Time)
from_rolls.Remove (fr);
new_rolls = from_rolls.ToArray ();
}
void HandleResponse (object obj, ResponseArgs args) {
if (args.ResponseId == ResponseType.Accept) {
PhotoQuery query = new PhotoQuery (from_db.Photos);
query.RollSet = mdd.ActiveRolls == null ? null : new RollSet (mdd.ActiveRolls);
DoMerge (query, mdd.ActiveRolls, mdd.Copy);
}
mdd.Dialog.Destroy ();
}
public static void Merge (string path, Db to_db)
{
Log.WarningFormat ("Will merge db {0} into main f-spot db {1}", path, FSpot.Core.Global.BaseDirectory + "/photos.db" );
Db from_db = new Db ();
from_db.Init (path, true);
//MergeDb mdb = new MergeDb (from_db, to_db);
}
void DoMerge (PhotoQuery query, Roll [] rolls, bool copy)
{
tag_map = new Dictionary<uint, Tag> ();
roll_map = new Dictionary<uint, uint> ();
Log.Warning ("Merging tags");
MergeTags (from_db.Tags.RootCategory);
Log.Warning ("Creating the rolls");
CreateRolls (rolls);
Log.Warning ("Importing photos");
ImportPhotos (query, copy);
}
void MergeTags (Tag tag_to_merge)
{
TagStore from_store = from_db.Tags;
TagStore to_store = to_db.Tags;
if (tag_to_merge != from_store.RootCategory) { //Do not merge RootCategory
Tag dest_tag = to_store.GetTagByName (tag_to_merge.Name);
if (dest_tag == null) {
Category parent = (tag_to_merge.Category == from_store.RootCategory) ?
to_store.RootCategory :
to_store.GetTagByName (tag_to_merge.Category.Name) as Category;
dest_tag = to_store.CreateTag (parent, tag_to_merge.Name, false);
//FIXME: copy the tag icon and commit
}
tag_map [tag_to_merge.Id] = dest_tag;
}
if (!(tag_to_merge is Category))
return;
foreach (Tag t in (tag_to_merge as Category).Children)
MergeTags (t);
}
void CreateRolls (Roll [] rolls)
{
if (rolls == null)
rolls = from_db.Rolls.GetRolls ();
RollStore from_store = from_db.Rolls;
RollStore to_store = to_db.Rolls;
foreach (Roll roll in rolls) {
if (from_store.PhotosInRoll (roll) == 0)
continue;
roll_map [roll.Id] = (to_store.Create (roll.Time).Id);
}
}
void ImportPhotos (PhotoQuery query, bool copy)
{
foreach (Photo p in query.Photos)
ImportPhoto (p, copy);
}
Dictionary<string, string> path_map = null;
Dictionary<string, string> PathMap {
get {
if (path_map == null)
path_map = new Dictionary<string, string> ();
return path_map;
}
}
void ImportPhoto (Photo photo, bool copy)
{
Log.WarningFormat ("Importing {0}", photo.Name);
PhotoStore to_store = to_db.Photos;
string photo_path = photo.VersionUri (Photo.OriginalVersionId).AbsolutePath;
while (!System.IO.File.Exists (photo_path)) {
Log.Debug ("Not found, trying the mappings...");
foreach (string key in PathMap.Keys) {
string path = photo_path;
path = path.Replace (key, PathMap [key]);
Log.DebugFormat ("Replaced path {0}", path);
if (System.IO.File.Exists (path)) {
photo_path = path;
break;;
}
}
if (System.IO.File.Exists (photo_path)) {
Log.Debug ("Exists!!!");
continue;
}
string [] parts = photo_path.Split (new char[] {'/'});
if (parts.Length > 6) {
string folder = String.Join ("/", parts, 0, parts.Length - 4);
PickFolderDialog pfd = new PickFolderDialog (mdd.Dialog, folder);
string new_folder = pfd.Run ();
pfd.Dialog.Destroy ();
if (new_folder == null) //Skip
return;
Log.DebugFormat ("{0} maps to {1}", folder, new_folder);
PathMap[folder] = new_folder;
} else
Log.Debug ("point me to the file");
Log.DebugFormat ("FNF: {0}", photo_path);
}
string destination;
Photo newp;
if (copy)
destination = FindImportDestination (new Hyena.SafeUri (photo_path), photo.Time).AbsolutePath;
else
destination = photo_path;
var dest_uri = new SafeUri (photo_path);
photo.DefaultVersionId = 1;
photo.DefaultVersion.Uri = dest_uri;
if (photo.DefaultVersion.ImportMD5 == String.Empty) {
(photo.DefaultVersion as PhotoVersion).ImportMD5 = HashUtils.GenerateMD5 (photo.DefaultVersion.Uri);
}
if (photo_path != destination) {
System.IO.File.Copy (photo_path, destination);
try {
File.SetAttributes (destination, File.GetAttributes (destination) & ~FileAttributes.ReadOnly);
DateTime create = File.GetCreationTime (photo_path);
File.SetCreationTime (destination, create);
DateTime mod = File.GetLastWriteTime (photo_path);
File.SetLastWriteTime (destination, mod);
} catch (IOException) {
// we don't want an exception here to be fatal.
}
}
newp = to_store.CreateFrom (photo, roll_map [photo.RollId]);
if (newp == null)
return;
foreach (Tag t in photo.Tags) {
Log.WarningFormat ("Tagging with {0}", t.Name);
newp.AddTag (tag_map [t.Id]);
}
foreach (uint version_id in photo.VersionIds)
if (version_id != Photo.OriginalVersionId) {
PhotoVersion version = photo.GetVersion (version_id) as PhotoVersion;
uint newv = newp.AddVersion (version.BaseUri, version.Filename, version.Name, version.IsProtected);
if (version_id == photo.DefaultVersionId)
newp.DefaultVersionId = newv;
}
//FIXME Import extra info (time, description, rating)
newp.Time = photo.Time;
newp.Description = photo.Description;
newp.Rating = photo.Rating;
to_store.Commit (newp);
}
SafeUri FindImportDestination (SafeUri uri, DateTime time)
{
// Find a new unique location inside the photo folder
string name = uri.GetFilename ();
var dest_uri = FSpot.Core.Global.PhotoUri.Append (time.Year.ToString ())
.Append (String.Format ("{0:D2}", time.Month))
.Append (String.Format ("{0:D2}", time.Day));
EnsureDirectory (dest_uri);
// If the destination we'd like to use is the file itself return that
if (dest_uri.Append (name) == uri)
return uri;
// Find an unused name
int i = 1;
var dest = dest_uri.Append (name);
var file = GLib.FileFactory.NewForUri (dest);
while (file.Exists) {
var filename = uri.GetFilenameWithoutExtension ();
var extension = uri.GetExtension ();
dest = dest_uri.Append (String.Format ("{0}-{1}{2}", filename, i++, extension));
file = GLib.FileFactory.NewForUri (dest);
}
return dest;
}
void EnsureDirectory (SafeUri uri)
{
var parts = uri.AbsolutePath.Split('/');
SafeUri current = new SafeUri (uri.Scheme + ":///", true);
for (int i = 0; i < parts.Length; i++) {
current = current.Append (parts [i]);
var file = GLib.FileFactory.NewForUri (current);
if (!file.Exists) {
file.MakeDirectory (null);
}
}
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// RangeVariableV2
/// </summary>
[DataContract]
public partial class RangeVariableV2 : IEquatable<RangeVariableV2>
{
/// <summary>
/// Initializes a new instance of the <see cref="RangeVariableV2" /> class.
/// </summary>
[JsonConstructorAttribute]
protected RangeVariableV2() { }
/// <summary>
/// Initializes a new instance of the <see cref="RangeVariableV2" /> class.
/// </summary>
/// <param name="Count">Count.</param>
/// <param name="Order">Order.</param>
/// <param name="Name">Name.</param>
/// <param name="Alias">Alias.</param>
/// <param name="Description">Description.</param>
/// <param name="BaseVariable">BaseVariable.</param>
/// <param name="Year">Year.</param>
/// <param name="Field">Field (required).</param>
public RangeVariableV2(string Count = null, string Order = null, string Name = null, string Alias = null, string Description = null, string BaseVariable = null, string Year = null, List<FieldV2> Field = null)
{
// to ensure "Field" is required (not null)
if (Field == null)
{
throw new InvalidDataException("Field is a required property for RangeVariableV2 and cannot be null");
}
else
{
this.Field = Field;
}
this.Count = Count;
this.Order = Order;
this.Name = Name;
this.Alias = Alias;
this.Description = Description;
this.BaseVariable = BaseVariable;
this.Year = Year;
}
/// <summary>
/// Gets or Sets Count
/// </summary>
[DataMember(Name="count", EmitDefaultValue=false)]
public string Count { get; set; }
/// <summary>
/// Gets or Sets Order
/// </summary>
[DataMember(Name="order", EmitDefaultValue=false)]
public string Order { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Alias
/// </summary>
[DataMember(Name="alias", EmitDefaultValue=false)]
public string Alias { get; set; }
/// <summary>
/// Gets or Sets Description
/// </summary>
[DataMember(Name="description", EmitDefaultValue=false)]
public string Description { get; set; }
/// <summary>
/// Gets or Sets BaseVariable
/// </summary>
[DataMember(Name="baseVariable", EmitDefaultValue=false)]
public string BaseVariable { get; set; }
/// <summary>
/// Gets or Sets Year
/// </summary>
[DataMember(Name="year", EmitDefaultValue=false)]
public string Year { get; set; }
/// <summary>
/// Gets or Sets Field
/// </summary>
[DataMember(Name="field", EmitDefaultValue=false)]
public List<FieldV2> Field { 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 RangeVariableV2 {\n");
sb.Append(" Count: ").Append(Count).Append("\n");
sb.Append(" Order: ").Append(Order).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Alias: ").Append(Alias).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" BaseVariable: ").Append(BaseVariable).Append("\n");
sb.Append(" Year: ").Append(Year).Append("\n");
sb.Append(" Field: ").Append(Field).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 string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as RangeVariableV2);
}
/// <summary>
/// Returns true if RangeVariableV2 instances are equal
/// </summary>
/// <param name="other">Instance of RangeVariableV2 to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RangeVariableV2 other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Count == other.Count ||
this.Count != null &&
this.Count.Equals(other.Count)
) &&
(
this.Order == other.Order ||
this.Order != null &&
this.Order.Equals(other.Order)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Alias == other.Alias ||
this.Alias != null &&
this.Alias.Equals(other.Alias)
) &&
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.BaseVariable == other.BaseVariable ||
this.BaseVariable != null &&
this.BaseVariable.Equals(other.BaseVariable)
) &&
(
this.Year == other.Year ||
this.Year != null &&
this.Year.Equals(other.Year)
) &&
(
this.Field == other.Field ||
this.Field != null &&
this.Field.SequenceEqual(other.Field)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Count != null)
hash = hash * 59 + this.Count.GetHashCode();
if (this.Order != null)
hash = hash * 59 + this.Order.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Alias != null)
hash = hash * 59 + this.Alias.GetHashCode();
if (this.Description != null)
hash = hash * 59 + this.Description.GetHashCode();
if (this.BaseVariable != null)
hash = hash * 59 + this.BaseVariable.GetHashCode();
if (this.Year != null)
hash = hash * 59 + this.Year.GetHashCode();
if (this.Field != null)
hash = hash * 59 + this.Field.GetHashCode();
return hash;
}
}
}
}
| |
// 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.CSharp.Symbols;
using Roslyn.Utilities;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal enum DisplayClassVariableKind
{
Local,
Parameter,
This,
}
/// <summary>
/// A field in a display class that represents a captured
/// variable: either a local, a parameter, or "this".
/// </summary>
internal sealed class DisplayClassVariable
{
internal readonly string Name;
internal readonly DisplayClassVariableKind Kind;
internal readonly DisplayClassInstance DisplayClassInstance;
internal readonly ConsList<FieldSymbol> DisplayClassFields;
internal DisplayClassVariable(string name, DisplayClassVariableKind kind, DisplayClassInstance displayClassInstance, ConsList<FieldSymbol> displayClassFields)
{
Debug.Assert(displayClassFields.Any());
this.Name = name;
this.Kind = kind;
this.DisplayClassInstance = displayClassInstance;
this.DisplayClassFields = displayClassFields;
// Verify all type parameters are substituted.
Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.Type));
}
internal TypeSymbol Type
{
get { return this.DisplayClassFields.Head.Type; }
}
internal Symbol ContainingSymbol
{
get { return this.DisplayClassInstance.ContainingSymbol; }
}
internal DisplayClassVariable ToOtherMethod(MethodSymbol method, TypeMap typeMap)
{
var otherInstance = this.DisplayClassInstance.ToOtherMethod(method, typeMap);
return SubstituteFields(otherInstance, typeMap);
}
internal BoundExpression ToBoundExpression(CSharpSyntaxNode syntax)
{
var expr = this.DisplayClassInstance.ToBoundExpression(syntax);
var fields = ArrayBuilder<FieldSymbol>.GetInstance();
fields.AddRange(this.DisplayClassFields);
fields.ReverseContents();
foreach (var field in fields)
{
expr = new BoundFieldAccess(syntax, expr, field, constantValueOpt: null) { WasCompilerGenerated = true };
}
fields.Free();
return expr;
}
internal DisplayClassVariable SubstituteFields(DisplayClassInstance otherInstance, TypeMap typeMap)
{
var otherFields = SubstituteFields(this.DisplayClassFields, typeMap);
return new DisplayClassVariable(this.Name, this.Kind, otherInstance, otherFields);
}
private static ConsList<FieldSymbol> SubstituteFields(ConsList<FieldSymbol> fields, TypeMap typeMap)
{
if (!fields.Any())
{
return ConsList<FieldSymbol>.Empty;
}
var head = SubstituteField(fields.Head, typeMap);
var tail = SubstituteFields(fields.Tail, typeMap);
return tail.Prepend(head);
}
private static FieldSymbol SubstituteField(FieldSymbol field, TypeMap typeMap)
{
Debug.Assert(!field.IsStatic);
Debug.Assert(!field.IsReadOnly || GeneratedNames.GetKind(field.Name) == GeneratedNameKind.AnonymousTypeField);
Debug.Assert(field.CustomModifiers.Length == 0);
// CONSIDER: Instead of digging fields out of the unsubstituted type and then performing substitution
// on each one individually, we could dig fields out of the substituted type.
return new EEDisplayClassFieldSymbol(typeMap.SubstituteNamedType(field.ContainingType), field.Name, typeMap.SubstituteType(field.Type).Type);
}
private sealed class EEDisplayClassFieldSymbol : FieldSymbol
{
private readonly NamedTypeSymbol _container;
private readonly string _name;
private readonly TypeSymbol _type;
internal EEDisplayClassFieldSymbol(NamedTypeSymbol container, string name, TypeSymbol type)
{
_container = container;
_name = name;
_type = type;
}
public override Symbol AssociatedSymbol
{
get { throw ExceptionUtilities.Unreachable; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override ImmutableArray<CustomModifier> CustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
public override Accessibility DeclaredAccessibility
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { throw ExceptionUtilities.Unreachable; }
}
public override bool IsConst
{
get { return false; }
}
public override bool IsReadOnly
{
get { return false; }
}
public override bool IsStatic
{
get { return false; }
}
public override bool IsVolatile
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { throw ExceptionUtilities.Unreachable; }
}
public override string Name
{
get { return _name; }
}
internal override bool HasRuntimeSpecialName
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool HasSpecialName
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool IsNotSerialized
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override MarshalPseudoCustomAttributeData MarshallingInformation
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override int? TypeLayoutOffset
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes)
{
throw ExceptionUtilities.Unreachable;
}
internal override TypeSymbol GetFieldType(ConsList<FieldSymbol> fieldsBeingBound)
{
return _type;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DeadCode.WME.Global;
using DeadCode.WME.ScriptParser;
using DeadCode.WME.DocMaker;
namespace Integrator
{
public partial class ModGeshi : IntegratorModule
{
//////////////////////////////////////////////////////////////////////////
public ModGeshi()
{
InitializeComponent();
}
//////////////////////////////////////////////////////////////////////////
private void OnDownloadLink(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("http://www.geshi.org/");
}
//////////////////////////////////////////////////////////////////////////
private void OnBrowseDir(object sender, EventArgs e)
{
FolderBrowserDialog Dlg = new FolderBrowserDialog();
Dlg.Description = "Select output directory.";
if (Directory.Exists(TxtOutputDir.Text)) Dlg.SelectedPath = TxtOutputDir.Text;
if (Dlg.ShowDialog() == DialogResult.OK)
{
TxtOutputDir.Text = Dlg.SelectedPath;
}
}
//////////////////////////////////////////////////////////////////////////
override public void SaveSettings(SettingsNode RootNode)
{
RootNode.SetValue("GeshiOutputDir", TxtOutputDir.Text);
}
//////////////////////////////////////////////////////////////////////////
override public void LoadSettings(SettingsNode RootNode)
{
TxtOutputDir.Text = RootNode.GetString("GeshiOutputDir");
}
//////////////////////////////////////////////////////////////////////////
private void OnGenerate(object sender, EventArgs e)
{
if (!Directory.Exists(TxtOutputDir.Text))
{
MessageBox.Show("Please specify a valid output directory.", ParentForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
try
{
string Filename = Path.Combine(TxtOutputDir.Text, "script.php");
using (StreamWriter sw = new StreamWriter(Filename, false, Encoding.Default))
{
sw.WriteLine("<?php");
sw.WriteLine("/*************************************************************************************");
sw.WriteLine("* script.php");
sw.WriteLine("* --------------");
sw.WriteLine("* WME Script language file for GeSHi.");
sw.WriteLine("* Generated by WME Integrator ");
sw.WriteLine("************************************************************************************/");
sw.WriteLine("");
sw.WriteLine("$language_data = array (");
sw.WriteLine(" 'LANG_NAME' => 'WME Script',");
sw.WriteLine(" 'COMMENT_SINGLE' => array(1 => '//'),");
sw.WriteLine(" 'COMMENT_MULTI' => array('/*' => '*/'),");
sw.WriteLine(" 'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,");
sw.WriteLine(" 'QUOTEMARKS' => array('\"'),");
sw.WriteLine(" 'ESCAPE_CHAR' => '~',");
sw.WriteLine(" 'KEYWORDS' => array(");
sw.WriteLine(" 1 => array(");
WordHolder wh;
// keywords
wh = new WordHolder();
foreach (string Keyword in ScriptTokenizer.Keywords)
{
wh.AddWord(Keyword);
}
sw.WriteLine(" " + wh.GetWords());
sw.WriteLine(" ),");
sw.WriteLine(" 2 => array(");
// read XML docs
ScriptInfo Info = new ScriptInfo();
Info.ReadXml(WmeUtils.XmlDocsPath);
// methods
wh = new WordHolder();
foreach (ScriptObject Obj in Info.Objects)
{
foreach (ScriptMethod Method in Obj.Methods)
{
foreach (string Header in Method.Headers)
{
int Brace = Header.IndexOf("(");
if (Brace >= 0)
{
wh.AddWord(Header.Substring(0, Brace).Trim());
}
}
}
}
sw.WriteLine(" " + wh.GetWords());
sw.WriteLine(" ),");
sw.WriteLine(" 3 => array(");
// attributes
wh = new WordHolder();
foreach (ScriptObject Obj in Info.Objects)
{
foreach (ScriptAttribute Attr in Obj.Attributes)
{
if (Attr.Name.StartsWith("[")) continue;
wh.AddWord(Attr.Name);
}
}
sw.WriteLine(" " + wh.GetWords());
sw.WriteLine(" ),");
sw.WriteLine(" 4 => array(");
sw.WriteLine(" '#region', '#endregion', '#include'");
sw.WriteLine(" )");
sw.WriteLine(" ),");
sw.WriteLine(" 'SYMBOLS' => array(");
sw.WriteLine(" '(', ')', '[', ']', '{', '}', '!', '@', '%', '&', '*', '|', '/', '<', '>'");
sw.WriteLine(" ),");
sw.WriteLine(" 'CASE_SENSITIVE' => array(");
sw.WriteLine(" GESHI_COMMENTS => false,");
sw.WriteLine(" 1 => true,");
sw.WriteLine(" 2 => true,");
sw.WriteLine(" 3 => true,");
sw.WriteLine(" 4 => true");
sw.WriteLine(" ),");
sw.WriteLine(" 'STYLES' => array(");
sw.WriteLine(" 'KEYWORDS' => array(");
sw.WriteLine(" 1 => 'color: #0000FF;',");
sw.WriteLine(" 2 => 'color: #800000;',");
sw.WriteLine(" 3 => 'color: #2B91AF;',");
sw.WriteLine(" 4 => 'color: #800080;'");
sw.WriteLine(" ),");
sw.WriteLine(" 'COMMENTS' => array(");
sw.WriteLine(" 1 => 'color: #007F00; font-style: italic;',");
sw.WriteLine(" 'MULTI' => 'color: #007F00; font-style: italic;'");
sw.WriteLine(" ),");
sw.WriteLine(" 'ESCAPE_CHAR' => array(");
sw.WriteLine(" 0 => 'color: #000000; font-weight: bold;'");
sw.WriteLine(" ),");
sw.WriteLine(" 'BRACKETS' => array(");
sw.WriteLine(" 0 => 'color: #000000;'");
sw.WriteLine(" ),");
sw.WriteLine(" 'STRINGS' => array(");
sw.WriteLine(" 0 => 'color: #808080;'");
sw.WriteLine(" ),");
sw.WriteLine(" 'NUMBERS' => array(");
sw.WriteLine(" 0 => 'color: #CC0000;'");
sw.WriteLine(" ),");
sw.WriteLine(" 'METHODS' => array(");
sw.WriteLine(" 1 => 'color: #404040;'");
sw.WriteLine(" ),");
sw.WriteLine(" 'SYMBOLS' => array(");
sw.WriteLine(" 0 => 'color: #66cc66;'");
sw.WriteLine(" ),");
sw.WriteLine(" 'REGEXPS' => array(),");
sw.WriteLine(" 'SCRIPT' => array()");
sw.WriteLine(" ),");
sw.WriteLine(" 'URLS' => array(");
sw.WriteLine(" 1 => '',");
sw.WriteLine(" 2 => 'http://www.google.com/search?q={FNAME}+site:docs.dead-code.org/wme/generated&hl=en&lr=&as_qdr=all&filter=0',");
sw.WriteLine(" 3 => 'http://www.google.com/search?q={FNAME}+site:docs.dead-code.org/wme/generated&hl=en&lr=&as_qdr=all&filter=0',");
sw.WriteLine(" 4 => ''");
sw.WriteLine(" ),");
sw.WriteLine(" 'OOLANG' => true,");
sw.WriteLine(" 'OBJECT_SPLITTERS' => array(");
sw.WriteLine(" 1 => '.'");
sw.WriteLine(" ),");
sw.WriteLine(" 'REGEXPS' => array(),");
sw.WriteLine(" 'STRICT_MODE_APPLIES' => GESHI_NEVER,");
sw.WriteLine(" 'SCRIPT_DELIMITERS' => array(),");
sw.WriteLine(" 'HIGHLIGHT_STRICT_BLOCK' => array()");
sw.WriteLine(");");
sw.WriteLine("");
sw.WriteLine("?>");
}
}
catch
{
}
}
//////////////////////////////////////////////////////////////////////////
private class WordHolder
{
List<string> Words = new List<string>();
//////////////////////////////////////////////////////////////////////////
public void AddWord(string Word)
{
if (Word == null || Word == string.Empty) return;
if (!Words.Contains(Word)) Words.Add(Word);
}
//////////////////////////////////////////////////////////////////////////
public string GetWords()
{
int Counter = 0;
string Ret = "";
Words.Sort();
for (int i = Words.Count - 1; i >= 0; i--)
{
if (Counter >= 10)
{
Ret = Ret + "\n ";
Counter = 0;
}
Ret += "'" + Words[i] + "'";
if (i > 0) Ret += ", ";
Counter++;
}
return Ret;
}
};
}
}
| |
/* Copyright (c) 2007 Stefanos Apostolopoulos
* See license.txt for license info
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using OpenTK.Graphics;
namespace OpenTK.Platform.X11
{
/// \internal
/// <summary>
/// Provides methods to create and control an opengl context on the X11 platform.
/// This class supports OpenTK, and is not intended for use by OpenTK programs.
/// </summary>
internal sealed class X11GLContext : DesktopGraphicsContext
{
// We assume that we cannot move a GL context to a different display connection.
// For this reason, we'll "lock" onto the display of the window used in the context
// constructor and we'll throw an exception if the user ever tries to make the context
// current on window originating from a different display.
private IntPtr display;
private X11WindowInfo currentWindow;
private bool vsync_ext_supported;
private bool vsync_mesa_supported;
private bool vsync_sgi_supported;
private bool vsync_tear_supported;
private int sgi_swap_interval = 1; // As defined in GLX_SGI_swap_control
private readonly X11GraphicsMode ModeSelector = new X11GraphicsMode();
private string extensions = null;
static X11GLContext()
{
new Glx().LoadEntryPoints();
}
public X11GLContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shared, bool direct,
int major, int minor, GraphicsContextFlags flags)
{
if (mode == null)
{
throw new ArgumentNullException("mode");
}
if (window == null)
{
throw new ArgumentNullException("window");
}
// Do not move this lower, as almost everything requires the Display
// property to be correctly set.
Display = ((X11WindowInfo)window).Display;
// Check that GLX is supported. We cannot proceed to create
// an OpenGL context without the GLX extension.
int error_base;
int event_base;
int glx_major;
int glx_minor;
using (new XLock(Display))
{
bool supported = Glx.QueryExtension(Display, out error_base, out event_base);
supported &= Glx.QueryVersion(Display, out glx_major, out glx_minor);
if (supported)
{
Debug.Print("[X11] GLX supported. Version is {0}.{1}", glx_major, glx_minor);
}
else
{
throw new NotSupportedException("[X11] GLX extension is not supported.");
}
}
IntPtr visual = IntPtr.Zero;
IntPtr fbconfig = IntPtr.Zero;
// Once a window has a visual, we cannot use a different
// visual on the OpenGL context, or glXMakeCurrent might fail.
// Note: we should only check X11WindowInfo.Visual, as that
// is the only property that can be set by Utilities.CreateX11WindowInfo.
currentWindow = (X11WindowInfo)window;
if (currentWindow.Visual != IntPtr.Zero)
{
visual = currentWindow.Visual;
fbconfig = currentWindow.FBConfig;
Mode = currentWindow.GraphicsMode;
}
if (Mode == null || !Mode.Index.HasValue)
{
Mode = ModeSelector.SelectGraphicsMode(mode, out visual, out fbconfig);
}
ContextHandle shareHandle = shared != null ?
(shared as IGraphicsContextInternal).Context : (ContextHandle)IntPtr.Zero;
Debug.Write("Creating X11GLContext context: ");
Debug.Write(direct ? "direct, " : "indirect, ");
Debug.WriteLine(shareHandle.Handle == IntPtr.Zero ? "not shared... " :
String.Format("shared with ({0})... ", shareHandle));
// Try using the new context creation method. If it fails, fall back to the old one.
// For each of these methods, we try two times to create a context:
// one with the "direct" flag intact, the other with the flag inversed.
// HACK: It seems that Catalyst 9.1 - 9.4 on Linux have problems with contexts created through
// GLX_ARB_create_context, including hideous input lag, no vsync and other madness.
// Use legacy context creation if the user doesn't request a 3.0+ context.
if (fbconfig != IntPtr.Zero && (major * 10 + minor >= 30) && SupportsCreateContextAttribs(Display, currentWindow))
{
Handle = CreateContextAttribs(Display, currentWindow.Screen,
fbconfig, direct, major, minor, flags, shareHandle);
}
if (Handle == ContextHandle.Zero)
{
Handle = CreateContextLegacy(Display, visual, direct, shareHandle);
}
if (Handle != ContextHandle.Zero)
{
Debug.Print("Context created (id: {0}).", Handle);
}
else
{
throw new GraphicsContextException("Failed to create OpenGL context. Glx.CreateContext call returned 0.");
}
using (new XLock(Display))
{
if (!Glx.IsDirect(Display, Handle.Handle))
{
Debug.Print("Warning: Context is not direct.");
}
}
}
public X11GLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shared, bool direct,
int major, int minor, GraphicsContextFlags flags)
{
if (handle == ContextHandle.Zero)
{
throw new ArgumentException("handle");
}
if (window == null)
{
throw new ArgumentNullException("window");
}
Handle = handle;
currentWindow = (X11WindowInfo)window;
Display = currentWindow.Display;
}
private static ContextHandle CreateContextAttribs(
IntPtr display, int screen, IntPtr fbconfig,
bool direct, int major, int minor,
GraphicsContextFlags flags, ContextHandle shareContext)
{
Debug.Write("Using GLX_ARB_create_context... ");
IntPtr context = IntPtr.Zero;
{
// We need the FB config for the current GraphicsMode.
List<int> attributes = new List<int>();
attributes.Add((int)ArbCreateContext.MajorVersion);
attributes.Add(major);
attributes.Add((int)ArbCreateContext.MinorVersion);
attributes.Add(minor);
if (flags != 0)
{
attributes.Add((int)ArbCreateContext.Flags);
attributes.Add((int)GetARBContextFlags(flags));
attributes.Add((int)ArbCreateContext.ProfileMask);
attributes.Add((int)GetARBProfileFlags(flags));
}
// According to the docs, " <attribList> specifies a list of attributes for the context.
// The list consists of a sequence of <name,value> pairs terminated by the
// value 0. [...]"
// Is this a single 0, or a <0, 0> pair? (Defensive coding: add two zeroes just in case).
attributes.Add(0);
attributes.Add(0);
using (new XLock(display))
{
context = Glx.Arb.CreateContextAttribs(display, fbconfig, shareContext.Handle, direct, attributes.ToArray());
if (context == IntPtr.Zero)
{
Debug.Write(String.Format("failed. Trying direct: {0}... ", !direct));
context = Glx.Arb.CreateContextAttribs(display, fbconfig, shareContext.Handle, !direct, attributes.ToArray());
}
}
if (context == IntPtr.Zero)
{
Debug.WriteLine("failed.");
}
else
{
Debug.WriteLine("success!");
}
}
return new ContextHandle(context);
}
private static ContextHandle CreateContextLegacy(IntPtr display,
IntPtr info, bool direct, ContextHandle shareContext)
{
Debug.Write("Using legacy context creation... ");
IntPtr context;
using (new XLock(display))
{
context = Glx.CreateContext(display, info, shareContext.Handle, direct);
if (context == IntPtr.Zero)
{
Debug.WriteLine(String.Format("failed. Trying direct: {0}... ", !direct));
context = Glx.CreateContext(display, info, shareContext.Handle, !direct);
}
}
return new ContextHandle(context);
}
private IntPtr Display
{
get { return display; }
set
{
if (value == IntPtr.Zero)
{
throw new ArgumentOutOfRangeException();
}
if (display != IntPtr.Zero)
{
throw new InvalidOperationException("The display connection may not be changed after being set.");
}
display = value;
}
}
private static ArbCreateContext GetARBContextFlags(GraphicsContextFlags flags)
{
ArbCreateContext result = 0;
result |= (flags & GraphicsContextFlags.Debug) != 0 ? ArbCreateContext.DebugBit : 0;
return result;
}
private static ArbCreateContext GetARBProfileFlags(GraphicsContextFlags flags)
{
ArbCreateContext result = 0;
result |= (flags & GraphicsContextFlags.ForwardCompatible) != 0 ?
ArbCreateContext.CoreProfileBit : ArbCreateContext.CompatibilityProfileBit;
return result;
}
private bool SupportsExtension(IntPtr display, X11WindowInfo window, string e)
{
if (window == null)
{
throw new ArgumentNullException("window");
}
if (e == null)
{
throw new ArgumentNullException("e");
}
if (window.Display != display)
{
throw new InvalidOperationException();
}
if (String.IsNullOrEmpty(extensions))
{
using (new XLock(display))
{
extensions = Glx.QueryExtensionsString(display, window.Screen);
}
}
return !String.IsNullOrEmpty(extensions) && extensions.Contains(e);
}
private bool SupportsCreateContextAttribs(IntPtr display, X11WindowInfo window)
{
return
SupportsExtension(display, window, "GLX_ARB_create_context") &&
SupportsExtension(display, window, "GLX_ARB_create_context_profile");
}
public override void SwapBuffers()
{
if (Display == IntPtr.Zero || currentWindow.Handle == IntPtr.Zero)
{
throw new InvalidOperationException(
String.Format("Window is invalid. Display ({0}), Handle ({1}).", Display, currentWindow.Handle));
}
using (new XLock(Display))
{
Glx.SwapBuffers(Display, currentWindow.Handle);
}
}
public override void MakeCurrent(IWindowInfo window)
{
if (window == currentWindow && IsCurrent)
{
return;
}
if (window != null && ((X11WindowInfo)window).Display != Display)
{
throw new InvalidOperationException("MakeCurrent() may only be called on windows originating from the same display that spawned this GL context.");
}
if (window == null)
{
Debug.Write(String.Format("Releasing context {0} from thread {1} (Display: {2})... ",
Handle, System.Threading.Thread.CurrentThread.ManagedThreadId, Display));
bool result;
result = Glx.MakeCurrent(Display, IntPtr.Zero, IntPtr.Zero);
if (result)
{
currentWindow = null;
}
Debug.Print("{0}", result ? "done!" : "failed.");
}
else
{
X11WindowInfo w = (X11WindowInfo)window;
bool result;
Debug.Write(String.Format("Making context {0} current on thread {1} (Display: {2}, Screen: {3}, Window: {4})... ",
Handle, System.Threading.Thread.CurrentThread.ManagedThreadId, Display, w.Screen, w.Handle));
if (Display == IntPtr.Zero || w.Handle == IntPtr.Zero || Handle == ContextHandle.Zero)
{
throw new InvalidOperationException("Invalid display, window or context.");
}
result = Glx.MakeCurrent(Display, w.Handle, Handle);
if (result)
{
currentWindow = w;
}
if (!result)
{
throw new GraphicsContextException("Failed to make context current.");
}
else
{
Debug.WriteLine("done!");
}
}
currentWindow = (X11WindowInfo)window;
}
public override bool IsCurrent
{
get
{
return Glx.GetCurrentContext() == Handle.Handle;
}
}
public override int SwapInterval
{
get
{
if (currentWindow == null)
{
Debug.Print("Context must be current");
throw new InvalidOperationException();
}
using (new XLock(display))
{
if (vsync_ext_supported)
{
int value;
Glx.QueryDrawable(Display, currentWindow.Handle, GLXAttribute.SWAP_INTERVAL_EXT, out value);
return value;
}
else if (vsync_mesa_supported)
{
return Glx.Mesa.GetSwapInterval();
}
else if (vsync_sgi_supported)
{
return sgi_swap_interval;
}
return 0;
}
}
set
{
if (currentWindow == null)
{
Debug.Print("Context must be current");
throw new InvalidOperationException();
}
if (value < 0 && !vsync_tear_supported)
{
value = 1;
}
ErrorCode error_code = 0;
using (new XLock(Display))
{
if (vsync_ext_supported)
{
Glx.Ext.SwapInterval(Display, currentWindow.Handle, value);
}
else if (vsync_mesa_supported)
{
error_code = Glx.Mesa.SwapInterval(value);
}
else if (vsync_sgi_supported)
{
error_code = Glx.Sgi.SwapInterval(value);
}
}
if (error_code == X11.ErrorCode.NO_ERROR)
{
sgi_swap_interval = value;
}
else
{
Debug.Print("VSync = {0} failed, error code: {1}.", value, error_code);
}
}
}
public override void LoadAll()
{
// Note: GLX entry points are always available, even
// for extensions that are not currently supported by
// the underlying driver. This means we can only check
// the extension strings for support, not the entry
// points themselves.
vsync_ext_supported =
SupportsExtension(display, currentWindow, "GLX_EXT_swap_control");
vsync_mesa_supported =
SupportsExtension(display, currentWindow, "GLX_MESA_swap_control");
vsync_sgi_supported =
SupportsExtension(display, currentWindow, "GLX_SGI_swap_control");
vsync_tear_supported =
SupportsExtension(display, currentWindow, "GLX_EXT_swap_control_tear");
Debug.Print("Context supports vsync: {0}.",
vsync_ext_supported || vsync_mesa_supported || vsync_sgi_supported);
Debug.Print("Context supports adaptive vsync: {0}.",
vsync_tear_supported);
base.LoadAll();
}
public override IntPtr GetAddress(IntPtr function)
{
using (new XLock(Display))
{
return Glx.GetProcAddress(function);
}
}
protected override void Dispose(bool manuallyCalled)
{
if (!IsDisposed)
{
if (manuallyCalled)
{
IntPtr display = Display;
if (IsCurrent)
{
Glx.MakeCurrent(display, IntPtr.Zero, IntPtr.Zero);
}
using (new XLock(display))
{
Glx.DestroyContext(display, Handle);
}
}
}
else
{
Debug.Print("[Warning] {0} leaked.", this.GetType().Name);
}
IsDisposed = true;
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using Amazon.Glacier.Model;
using Amazon.Glacier.Transfer.Internal;
using Amazon.Runtime;
using Amazon.Util;
namespace Amazon.Glacier.Transfer
{
/// <summary>
/// Provides a high level API for managing transfers to and from Amazon Glacier. This removes
/// complexities such as breaking files into parts and computing check sums.
/// </summary>
public class ArchiveTransferManager : IDisposable
{
#region Private/internal members
// Threshold for when to use multipart upload operations
internal const long MULTIPART_UPLOAD_SIZE_THRESHOLD = 1024L * 1024L * 10L;
private bool shouldDispose;
private bool disposed;
private IAmazonGlacier glacierClient;
/// <summary>
/// The Glacier client used by the ArchiveTransferManager.
/// </summary>
internal AmazonGlacierClient GlacierClient
{
get { return this.glacierClient as AmazonGlacierClient; }
}
#endregion
#region Dispose Pattern Implementation
/// <summary>
/// Implements the Dispose pattern
/// </summary>
/// <param name="disposing">Whether this object is being disposed via a call to Dispose
/// or garbage collected.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing && glacierClient != null)
{
if (shouldDispose)
{
glacierClient.Dispose();
}
glacierClient = null;
}
this.disposed = true;
}
}
/// <summary>
/// Disposes of all managed and unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// The destructor for the client class.
/// </summary>
~ArchiveTransferManager()
{
this.Dispose(false);
}
#endregion
#region Constructors
/// <summary>
/// Constructs an ArchiveTransferManager object for the specified Amazon Glacier region endpoint using the credentials
/// loaded from the application's default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">Amazon Glacier region endpoint</param>
public ArchiveTransferManager(RegionEndpoint region)
{
this.glacierClient = new AmazonGlacierClient(region);
this.shouldDispose = true;
}
/// <summary>
/// Constructs an ArchiveTransferManager object using an existing Amazon Glacier client.
/// </summary>
/// <param name="glacier">An AmazonGlacier client that used to make service calls.</param>
public ArchiveTransferManager(IAmazonGlacier glacier)
{
this.glacierClient = glacier;
this.shouldDispose = false;
}
/// <summary>
/// Constructs an ArchiveTransferManager object using the specified AWS credentials and Amazon Glacier region endpoint.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">Amazon Glacier region endpoint</param>
public ArchiveTransferManager(AWSCredentials credentials, RegionEndpoint region)
: this(new AmazonGlacierClient(credentials, region))
{
this.shouldDispose = true;
}
/// <summary>
/// Constructs an ArchiveTransferManager object with the specified AWS Access Key ID, AWS Secret Key, and Amazon Glacier region endpoint.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">Amazon Glacier region endpoint</param>
public ArchiveTransferManager(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(new AmazonGlacierClient(awsAccessKeyId, awsSecretAccessKey, region))
{
this.shouldDispose = true;
}
#endregion
#region Public memebers
/// <summary>
/// Creates a vault.
/// </summary>
/// <param name="vaultName">The name of the vault to create.</param>
public void CreateVault(string vaultName)
{
CreateVaultRequest request = new CreateVaultRequest() { VaultName = vaultName };
((Amazon.Runtime.Internal.IAmazonWebServiceRequest)request).AddBeforeRequestHandler(new UserAgentPostFix("CreateVault").UserAgentRequestEventHandlerSync);
this.glacierClient.CreateVault(request);
}
/// <summary>
/// Deletes the specified vault. Before deletion, the vault must be empty of all archives.
/// </summary>
/// <param name="vaultName">The name of the vault to delete.</param>
public void DeleteVault(string vaultName)
{
DeleteVaultRequest request = new DeleteVaultRequest() { VaultName = vaultName };
((Amazon.Runtime.Internal.IAmazonWebServiceRequest)request).AddBeforeRequestHandler(new UserAgentPostFix("DeleteVault").UserAgentRequestEventHandlerSync);
this.glacierClient.DeleteVault(request);
}
/// <summary>
/// Deletes an archive specified by vault name and archive ID.
/// </summary>
/// <param name="vaultName">The name of the vault containing the archive.</param>
/// <param name="archiveId">The archive ID of the archive to delete.</param>
public void DeleteArchive(string vaultName, string archiveId)
{
DeleteArchiveRequest request = new DeleteArchiveRequest() { VaultName = vaultName, ArchiveId = archiveId };
((Amazon.Runtime.Internal.IAmazonWebServiceRequest)request).AddBeforeRequestHandler(new UserAgentPostFix("DeleteArchive").UserAgentRequestEventHandlerSync);
this.glacierClient.DeleteArchive(request);
}
#endregion
#region Upload
/// <summary>
/// Uploads the specified file to Amazon Glacier for archival storage in the
/// specified vault in the specified user's account. For small archives, this
/// method uploads the archive directly to Glacier. For larger archives,
/// this method uses Glacier's multipart upload API to split the upload
/// into multiple parts for better error recovery if any errors are
/// encountered while streaming the data to Amazon Glacier.
/// </summary>
/// <param name="vaultName">The name of the vault to upload the file to.</param>
/// <param name="archiveDescription">A description for the archive.</param>
/// <param name="filepath">The file path to the file to upload.</param>
/// <returns>The results of the upload including the archive ID.</returns>
public UploadResult Upload(string vaultName, string archiveDescription, string filepath)
{
return Upload(vaultName, archiveDescription, filepath, new UploadOptions());
}
/// <summary>
/// <para>
/// Uploads the specified file to Amazon Glacier for archival storage in the
/// specified vault in the specified user's account. For small archives, this
/// method uploads the archive directly to Glacier. For larger archives,
/// this method uses Glacier's multipart upload API to split the upload
/// into multiple parts for better error recovery if any errors are
/// encountered while streaming the data to Amazon Glacier.
/// </para>
/// </summary>
/// <param name="vaultName">The name of the vault to download the archive from.</param>
/// <param name="archiveDescription">A description for the archive.</param>
/// <param name="filepath">The file path to the file to upload.</param>
/// <param name="options">Additional options that can be used for the upload.</param>
/// <returns>The results of the upload including the archive ID.</returns>
public UploadResult Upload(string vaultName, string archiveDescription, string filepath, UploadOptions options)
{
FileInfo fi = new FileInfo(filepath);
BaseUploadCommand command;
if (fi.Length > MULTIPART_UPLOAD_SIZE_THRESHOLD)
command = new MultipartUploadCommand(this, vaultName, archiveDescription, filepath, options);
else
command = new SinglepartUploadCommand(this, vaultName, archiveDescription, filepath, options);
command.Execute();
return command.UploadResult;
}
#endregion
#region Download
/// <summary>
/// <para>
/// Downloads an Amazon Glacier archive from the specified vault for the
/// current user's account. Saves the archive to the specified file.
/// </para>
///
/// <para>
/// This method creates an Amazon SNS topic, and an Amazon SQS queue that is subscribed
/// to that topic. It then initiates the archive retrieval job and polls the queue
/// for the archive to be available. This polling takes about 4 hours. Once the archive
/// is available, download will begin.
/// </para>
/// </summary>
/// <param name="filePath">The file path to save the archive to.</param>
/// <param name="vaultName">The name of the vault to download the archive from.</param>
/// <param name="archiveId">The unique ID of the archive to download.</param>
public void Download(string vaultName, string archiveId, string filePath)
{
Download(vaultName, archiveId, filePath, new DownloadOptions());
}
/// <summary>
/// <para>
/// Downloads an archive from Amazon Glacier from the specified vault for the
/// current user's account. Saves the archive to the specified file.
/// </para>
///
/// <para>
/// This method creates an Amazon SNS topic, and an Amazon SQS queue that is subscribed
/// to that topic. It then initiates the archive retrieval job and polls the queue
/// for the archive to be available. This polling takes about 4 hours. Once the archive
/// is available, download will begin.
/// </para>
///
/// <para>
/// Additional options can be set using the UploadDirectoryOptions object. For example, you
/// can set the FilesTransferProgress property to a delegate to track progress.
/// </para>
/// </summary>
/// <param name="filePath">The file path to save the archive at.</param>
/// <param name="vaultName">The name of the vault to download the archive from.</param>
/// <param name="archiveId">The unique ID of the archive to download.</param>
/// <param name="options">Additional options that can be used for the download.</param>
public void Download(string vaultName, string archiveId, string filePath, DownloadOptions options)
{
using (var command = new DownloadFileCommand(this, vaultName, archiveId, filePath, options))
{
command.Execute();
}
}
#endregion
#region Download Job
/// <summary>
/// <para>
/// Downloads the results from a completed archive retrieval. Saves the job output
/// to the specified file.
/// </para>
/// <para>
/// If there is an error during download the download will be retried from the last point read.
/// Once the download is complete the checksum will be compared.
/// </para>
/// </summary>
/// <param name="vaultName">The name of the vault to download the job output from.</param>
/// <param name="jobId">The unique job ID for an archive retrieval job.</param>
/// <param name="filePath">The file path to save the job output at.</param>
public void DownloadJob(string vaultName, string jobId, string filePath)
{
var command = new DownloadJobCommand(this, vaultName, jobId, filePath, new DownloadOptions());
command.Execute();
}
/// <summary>
/// <para>
/// Downloads the results from a completed archive retrieval. Saves the job output
/// to the specified file.
/// </para>
/// <para>
/// If there is an error during download the download will be retried from the last point read.
/// Once the download is complete the checksum will be compared.
/// </para>
/// </summary>
/// <param name="vaultName">The name of the vault to download the job output from.</param>
/// <param name="jobId">The unique job ID for an archive retrieval job.</param>
/// <param name="filePath">The file path to save the job output at.</param>
/// <param name="options">Additional options that can be used for the download.</param>
public void DownloadJob(string vaultName, string jobId, string filePath, DownloadOptions options)
{
var command = new DownloadJobCommand(this, vaultName, jobId, filePath, options);
command.Execute();
}
#endregion
#region Initiate Archive Retieval
/// <summary>
/// This method initiates an archive retieval job for the specified archive and returns back the job id.
/// Once the job is complete
/// </summary>
/// <param name="vaultName">The name of the vault that contains the archive to initiate the job for.</param>
/// <param name="archiveId">The archive id that the download job will retrieve.</param>
/// <returns>The job id for the initiated job.</returns>
public string InitiateArchiveRetrievalJob(string vaultName, string archiveId)
{
return InitiateArchiveRetrievalJob(vaultName, archiveId, null);
}
/// <summary>
/// This method initiates an archive retieval job for the specified archive and returns back the job id.
/// Once the job is complete
/// </summary>
/// <param name="vaultName">The name of the vault that contains the archive to initiate the job for.</param>
/// <param name="archiveId">The archive id that the download job will retrieve.</param>
/// <param name="options">Additional options that can be used for initiating archive retrieval.</param>
/// <returns>The job id for the initiated job.</returns>
public string InitiateArchiveRetrievalJob(string vaultName, string archiveId, InitiateArchiveRetrievalOptions options)
{
InitiateJobRequest jobRequest = new InitiateJobRequest()
{
VaultName = vaultName,
JobParameters = new JobParameters()
{
ArchiveId = archiveId,
Type = "archive-retrieval"
}
};
if (options != null)
{
jobRequest.AccountId = options.AccountId;
jobRequest.JobParameters.SNSTopic = options.SNSTopic;
}
var jobId = glacierClient.InitiateJob(jobRequest).JobId;
return jobId;
}
#endregion
}
internal class UserAgentPostFix
{
string operation;
internal UserAgentPostFix(string operation)
{
this.operation = operation;
}
internal void UserAgentRequestEventHandlerSync(object sender, RequestEventArgs args)
{
WebServiceRequestEventArgs wsArgs = args as WebServiceRequestEventArgs;
if (wsArgs != null)
{
string currentUserAgent = wsArgs.Headers[AWSSDKUtils.UserAgentHeader];
wsArgs.Headers[AWSSDKUtils.UserAgentHeader] = currentUserAgent + " ArchiveTransferManager/" + this.operation;
}
}
}
}
| |
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 Presentation.TorreHanoi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
var controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
var actionName = api.ActionDescriptor.ActionName;
var parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
var 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))
{
var sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (var mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
var sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (var factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
var controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
var actionName = api.ActionDescriptor.ActionName;
var parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
var 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:
var requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
var reader = new StreamReader(ms);
var serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
var aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
var objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
var 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
{
var 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)
{
var parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
var 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)
{
var stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using QRCodeDecoder = MessagingToolkit.QRCode.Codec.QRCodeDecoder;
using InvalidDataBlockException = MessagingToolkit.QRCode.ExceptionHandler.InvalidDataBlockException;
using DebugCanvas = MessagingToolkit.QRCode.Codec.Util.DebugCanvas;
using SystemUtils = MessagingToolkit.QRCode.Codec.Util.SystemUtils;
namespace MessagingToolkit.QRCode.Codec.Reader
{
public class QRCodeDataBlockReader
{
virtual internal int NextMode
{
get
{
//canvas.println("data blocks:"+ (blocks.length - numErrorCorrectionCode));
if ((blockPointer > blocks.Length - numErrorCorrectionCode - 2))
return 0;
else
return getNextBits(4);
}
}
virtual public sbyte[] DataByte
{
get
{
canvas.println("Reading data blocks.");
System.IO.MemoryStream output = new System.IO.MemoryStream();
try
{
do
{
int mode = NextMode;
//canvas.println("mode: " + mode);
if (mode == 0)
{
if (output.Length > 0)
break;
else
throw new InvalidDataBlockException("Empty data block");
}
//if (mode != 1 && mode != 2 && mode != 4 && mode != 8)
// break;
//}
if (mode != MODE_NUMBER && mode != MODE_ROMAN_AND_NUMBER && mode != MODE_8BIT_BYTE && mode != MODE_KANJI)
{
/* canvas.println("Invalid mode: " + mode);
mode = guessMode(mode);
canvas.println("Guessed mode: " + mode); */
throw new InvalidDataBlockException("Invalid mode: " + mode + " in (block:" + blockPointer + " bit:" + bitPointer + ")");
}
dataLength = getDataLength(mode);
if (dataLength < 1)
throw new InvalidDataBlockException("Invalid data length: " + dataLength);
//canvas.println("length: " + dataLength);
switch (mode)
{
case MODE_NUMBER:
//canvas.println("Mode: Figure");
sbyte[] temp_sbyteArray;
temp_sbyteArray = SystemUtils.ToSByteArray(SystemUtils.ToByteArray(getFigureString(dataLength)));
output.Write(SystemUtils.ToByteArray(temp_sbyteArray), 0, temp_sbyteArray.Length);
break;
case MODE_ROMAN_AND_NUMBER:
//canvas.println("Mode: Roman&Figure");
sbyte[] temp_sbyteArray2;
temp_sbyteArray2 = SystemUtils.ToSByteArray(SystemUtils.ToByteArray(getRomanAndFigureString(dataLength)));
output.Write(SystemUtils.ToByteArray(temp_sbyteArray2), 0, temp_sbyteArray2.Length);
break;
case MODE_8BIT_BYTE:
//canvas.println("Mode: 8bit Byte");
sbyte[] temp_sbyteArray3;
temp_sbyteArray3 = get8bitByteArray(dataLength);
output.Write(SystemUtils.ToByteArray(temp_sbyteArray3), 0, temp_sbyteArray3.Length);
break;
case MODE_KANJI:
//canvas.println("Mode: Kanji");
sbyte[] temp_sbyteArray4;
temp_sbyteArray4 = SystemUtils.ToSByteArray(SystemUtils.ToByteArray(getKanjiString(dataLength)));
output.Write(SystemUtils.ToByteArray(temp_sbyteArray4), 0, temp_sbyteArray4.Length);
break;
}
//
//canvas.println("DataLength: " + dataLength);
//Console.out.println(dataString);
}
while (true);
}
catch (System.IndexOutOfRangeException e)
{
SystemUtils.WriteStackTrace(e, Console.Error);
throw new InvalidDataBlockException("Data Block Error in (block:" + blockPointer + " bit:" + bitPointer + ")");
}
catch (System.IO.IOException e)
{
throw new InvalidDataBlockException(e.Message);
}
return SystemUtils.ToSByteArray(output.ToArray());
}
}
virtual public String DataString
{
get
{
canvas.println("Reading data blocks...");
String dataString = "";
do
{
int mode = NextMode;
canvas.println("mode: " + mode);
if (mode == 0)
break;
//if (mode != 1 && mode != 2 && mode != 4 && mode != 8)
// break;
//}
if (mode != MODE_NUMBER && mode != MODE_ROMAN_AND_NUMBER && mode != MODE_8BIT_BYTE && mode != MODE_KANJI)
{
// mode = guessMode(mode);
// do not guesswork
//Console.out.println("guessed mode: " + mode);
}
dataLength = getDataLength(mode);
canvas.println(System.Convert.ToString(blocks[blockPointer]));
System.Console.Out.WriteLine("length: " + dataLength);
switch (mode)
{
case MODE_NUMBER:
//canvas.println("Mode: Figure");
dataString += getFigureString(dataLength);
break;
case MODE_ROMAN_AND_NUMBER:
//canvas.println("Mode: Roman&Figure");
dataString += getRomanAndFigureString(dataLength);
break;
case MODE_8BIT_BYTE:
//canvas.println("Mode: 8bit Byte");
dataString += get8bitByteString(dataLength);
break;
case MODE_KANJI:
//canvas.println("Mode: Kanji");
dataString += getKanjiString(dataLength);
break;
}
//canvas.println("DataLength: " + dataLength);
//Console.out.println(dataString);
}
while (true);
System.Console.Out.WriteLine("");
return dataString;
}
}
internal int[] blocks;
internal int dataLengthMode;
internal int blockPointer;
internal int bitPointer;
internal int dataLength;
internal int numErrorCorrectionCode;
internal DebugCanvas canvas;
const int MODE_NUMBER = 1;
const int MODE_ROMAN_AND_NUMBER = 2;
const int MODE_8BIT_BYTE = 4;
const int MODE_KANJI = 8;
int[][] sizeOfDataLengthInfo = new int[][] { new int[] { 10, 9, 8, 8 }, new int[] { 12, 11, 16, 10 }, new int[] { 14, 13, 16, 12 } };
public QRCodeDataBlockReader(int[] blocks, int version, int numErrorCorrectionCode)
{
blockPointer = 0;
bitPointer = 7;
dataLength = 0;
this.blocks = blocks;
this.numErrorCorrectionCode = numErrorCorrectionCode;
if (version <= 9)
dataLengthMode = 0;
else if (version >= 10 && version <= 26)
dataLengthMode = 1;
else if (version >= 27 && version <= 40)
dataLengthMode = 2;
canvas = QRCodeDecoder.Canvas;
}
internal virtual int getNextBits(int numBits)
{
int bits = 0;
if (numBits < bitPointer + 1)
{
// next word fits into current data block
int mask = 0;
for (int i = 0; i < numBits; i++)
{
mask += (1 << i);
}
mask <<= (bitPointer - numBits + 1);
bits = (blocks[blockPointer] & mask) >> (bitPointer - numBits + 1);
bitPointer -= numBits;
return bits;
}
else if (numBits < bitPointer + 1 + 8)
{
// next word crosses 2 data blocks
int mask1 = 0;
for (int i = 0; i < bitPointer + 1; i++)
{
mask1 += (1 << i);
}
bits = (blocks[blockPointer] & mask1) << (numBits - (bitPointer + 1));
blockPointer++;
bits += ((blocks[blockPointer]) >> (8 - (numBits - (bitPointer + 1))));
bitPointer = bitPointer - numBits % 8;
if (bitPointer < 0)
{
bitPointer = 8 + bitPointer;
}
return bits;
}
else if (numBits < bitPointer + 1 + 16)
{
// next word crosses 3 data blocks
int mask1 = 0; // mask of first block
int mask3 = 0; // mask of 3rd block
//bitPointer + 1 : number of bits of the 1st block
//8 : number of the 2nd block (note that use already 8bits because next word uses 3 data blocks)
//numBits - (bitPointer + 1 + 8) : number of bits of the 3rd block
for (int i = 0; i < bitPointer + 1; i++)
{
mask1 += (1 << i);
}
int bitsFirstBlock = (blocks[blockPointer] & mask1) << (numBits - (bitPointer + 1));
blockPointer++;
int bitsSecondBlock = blocks[blockPointer] << (numBits - (bitPointer + 1 + 8));
blockPointer++;
for (int i = 0; i < numBits - (bitPointer + 1 + 8); i++)
{
mask3 += (1 << i);
}
mask3 <<= 8 - (numBits - (bitPointer + 1 + 8));
int bitsThirdBlock = (blocks[blockPointer] & mask3) >> (8 - (numBits - (bitPointer + 1 + 8)));
bits = bitsFirstBlock + bitsSecondBlock + bitsThirdBlock;
bitPointer = bitPointer - (numBits - 8) % 8;
if (bitPointer < 0)
{
bitPointer = 8 + bitPointer;
}
return bits;
}
else
{
System.Console.Out.WriteLine("ERROR!");
return 0;
}
}
internal virtual int guessMode(int mode)
{
//correct modes: 0001 0010 0100 1000
//possible data: 0000 0011 0101 1001 0110 1010 1100
// 0111 1101 1011 1110 1111
// MODE_NUMBER = 1;
// MODE_ROMAN_AND_NUMBER = 2;
// MODE_8BIT_BYTE = 4;
// MODE_KANJI = 8;
switch (mode)
{
case 3:
return MODE_NUMBER;
case 5:
return MODE_8BIT_BYTE;
case 6:
return MODE_8BIT_BYTE;
case 7:
return MODE_8BIT_BYTE;
case 9:
return MODE_KANJI;
case 10:
return MODE_KANJI;
case 11:
return MODE_KANJI;
case 12:
return MODE_8BIT_BYTE;
case 13:
return MODE_8BIT_BYTE;
case 14:
return MODE_8BIT_BYTE;
case 15:
return MODE_8BIT_BYTE;
default:
return MODE_KANJI;
}
}
internal virtual int getDataLength(int modeIndicator)
{
int index = 0;
while (true)
{
if ((modeIndicator >> index) == 1)
break;
index++;
}
return getNextBits(sizeOfDataLengthInfo[dataLengthMode][index]);
}
internal virtual String getFigureString(int dataLength)
{
int length = dataLength;
int intData = 0;
String strData = "";
do
{
if (length >= 3)
{
intData = getNextBits(10);
if (intData < 100)
strData += "0";
if (intData < 10)
strData += "0";
length -= 3;
}
else if (length == 2)
{
intData = getNextBits(7);
if (intData < 10)
strData += "0";
length -= 2;
}
else if (length == 1)
{
intData = getNextBits(4);
length -= 1;
}
strData += System.Convert.ToString(intData);
}
while (length > 0);
return strData;
}
internal virtual String getRomanAndFigureString(int dataLength)
{
int length = dataLength;
int intData = 0;
String strData = "";
char[] tableRomanAndFigure = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':'};
do
{
if (length > 1)
{
intData = getNextBits(11);
int firstLetter = intData / 45;
int secondLetter = intData % 45;
strData += System.Convert.ToString(tableRomanAndFigure[firstLetter]);
strData += System.Convert.ToString(tableRomanAndFigure[secondLetter]);
length -= 2;
}
else if (length == 1)
{
intData = getNextBits(6);
strData += System.Convert.ToString(tableRomanAndFigure[intData]);
length -= 1;
}
}
while (length > 0);
return strData;
}
public virtual sbyte[] get8bitByteArray(int dataLength)
{
int length = dataLength;
int intData = 0;
System.IO.MemoryStream output = new System.IO.MemoryStream();
do
{
canvas.println("Length: " + length);
intData = getNextBits(8);
output.WriteByte((byte) intData);
length--;
}
while (length > 0);
return SystemUtils.ToSByteArray(output.ToArray());
}
internal virtual String get8bitByteString(int dataLength)
{
int length = dataLength;
int intData = 0;
String strData = "";
do
{
intData = getNextBits(8);
strData += (char) intData;
length--;
}
while (length > 0);
return strData;
}
internal virtual String getKanjiString(int dataLength)
{
int length = dataLength;
int intData = 0;
String unicodeString = "";
do
{
intData = getNextBits(13);
int lowerByte = intData % 0xC0;
int higherByte = intData / 0xC0;
int tempWord = (higherByte << 8) + lowerByte;
int shiftjisWord = 0;
if (tempWord + 0x8140 <= 0x9FFC)
{
// between 8140 - 9FFC on Shift_JIS character set
shiftjisWord = tempWord + 0x8140;
}
else
{
// between E040 - EBBF on Shift_JIS character set
shiftjisWord = tempWord + 0xC140;
}
sbyte[] tempByte = new sbyte[2];
tempByte[0] = (sbyte) (shiftjisWord >> 8);
tempByte[1] = (sbyte) (shiftjisWord & 0xFF);
unicodeString += new String(SystemUtils.ToCharArray(SystemUtils.ToByteArray(tempByte)));
length--;
}
while (length > 0);
return unicodeString;
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System.Collections.Generic;
using System.IO;
using DiscUtils.Streams;
namespace DiscUtils.Ntfs
{
internal class FileRecord : FixupRecordBase
{
private ushort _firstAttributeOffset;
private bool _haveIndex;
private uint _index; // Self-reference (on XP+)
public FileRecord(int sectorSize)
: base("FILE", sectorSize) {}
public FileRecord(int sectorSize, int recordLength, uint index)
: base("FILE", sectorSize, recordLength)
{
ReInitialize(sectorSize, recordLength, index);
}
public uint AllocatedSize { get; private set; }
public List<AttributeRecord> Attributes { get; private set; }
public FileRecordReference BaseFile { get; set; }
public AttributeRecord FirstAttribute
{
get { return Attributes.Count > 0 ? Attributes[0] : null; }
}
public FileRecordFlags Flags { get; set; }
public ushort HardLinkCount { get; set; }
public bool IsMftRecord
{
get
{
return MasterFileTableIndex == MasterFileTable.MftIndex ||
(BaseFile.MftIndex == MasterFileTable.MftIndex && BaseFile.SequenceNumber != 0);
}
}
public uint LoadedIndex { get; set; }
public ulong LogFileSequenceNumber { get; private set; }
public uint MasterFileTableIndex
{
get { return _haveIndex ? _index : LoadedIndex; }
}
public ushort NextAttributeId { get; private set; }
public uint RealSize { get; private set; }
public FileRecordReference Reference
{
get { return new FileRecordReference(MasterFileTableIndex, SequenceNumber); }
}
public ushort SequenceNumber { get; set; }
public static FileAttributeFlags ConvertFlags(FileRecordFlags source)
{
FileAttributeFlags result = FileAttributeFlags.None;
if ((source & FileRecordFlags.IsDirectory) != 0)
{
result |= FileAttributeFlags.Directory;
}
if ((source & FileRecordFlags.HasViewIndex) != 0)
{
result |= FileAttributeFlags.IndexView;
}
if ((source & FileRecordFlags.IsMetaFile) != 0)
{
result |= FileAttributeFlags.Hidden | FileAttributeFlags.System;
}
return result;
}
public void ReInitialize(int sectorSize, int recordLength, uint index)
{
Initialize("FILE", sectorSize, recordLength);
SequenceNumber++;
Flags = FileRecordFlags.None;
AllocatedSize = (uint)recordLength;
NextAttributeId = 0;
_index = index;
HardLinkCount = 0;
BaseFile = new FileRecordReference(0);
Attributes = new List<AttributeRecord>();
_haveIndex = true;
}
/// <summary>
/// Gets an attribute by it's id.
/// </summary>
/// <param name="id">The attribute's id.</param>
/// <returns>The attribute, or <c>null</c>.</returns>
public AttributeRecord GetAttribute(ushort id)
{
foreach (AttributeRecord attrRec in Attributes)
{
if (attrRec.AttributeId == id)
{
return attrRec;
}
}
return null;
}
/// <summary>
/// Gets an unnamed attribute.
/// </summary>
/// <param name="type">The attribute type.</param>
/// <returns>The attribute, or <c>null</c>.</returns>
public AttributeRecord GetAttribute(AttributeType type)
{
return GetAttribute(type, null);
}
/// <summary>
/// Gets an named attribute.
/// </summary>
/// <param name="type">The attribute type.</param>
/// <param name="name">The name of the attribute.</param>
/// <returns>The attribute, or <c>null</c>.</returns>
public AttributeRecord GetAttribute(AttributeType type, string name)
{
foreach (AttributeRecord attrRec in Attributes)
{
if (attrRec.AttributeType == type && attrRec.Name == name)
{
return attrRec;
}
}
return null;
}
public override string ToString()
{
foreach (AttributeRecord attr in Attributes)
{
if (attr.AttributeType == AttributeType.FileName)
{
StructuredNtfsAttribute<FileNameRecord> fnAttr =
(StructuredNtfsAttribute<FileNameRecord>)
NtfsAttribute.FromRecord(null, new FileRecordReference(0), attr);
return fnAttr.Content.FileName;
}
}
return "No Name";
}
/// <summary>
/// Creates a new attribute.
/// </summary>
/// <param name="type">The type of the new attribute.</param>
/// <param name="name">The name of the new attribute.</param>
/// <param name="indexed">Whether the attribute is marked as indexed.</param>
/// <param name="flags">Flags for the new attribute.</param>
/// <returns>The id of the new attribute.</returns>
public ushort CreateAttribute(AttributeType type, string name, bool indexed, AttributeFlags flags)
{
ushort id = NextAttributeId++;
Attributes.Add(
new ResidentAttributeRecord(
type,
name,
id,
indexed,
flags));
Attributes.Sort();
return id;
}
/// <summary>
/// Creates a new non-resident attribute.
/// </summary>
/// <param name="type">The type of the new attribute.</param>
/// <param name="name">The name of the new attribute.</param>
/// <param name="flags">Flags for the new attribute.</param>
/// <returns>The id of the new attribute.</returns>
public ushort CreateNonResidentAttribute(AttributeType type, string name, AttributeFlags flags)
{
ushort id = NextAttributeId++;
Attributes.Add(
new NonResidentAttributeRecord(
type,
name,
id,
flags,
0,
new List<DataRun>()));
Attributes.Sort();
return id;
}
/// <summary>
/// Creates a new attribute.
/// </summary>
/// <param name="type">The type of the new attribute.</param>
/// <param name="name">The name of the new attribute.</param>
/// <param name="flags">Flags for the new attribute.</param>
/// <param name="firstCluster">The first cluster to assign to the attribute.</param>
/// <param name="numClusters">The number of sequential clusters to assign to the attribute.</param>
/// <param name="bytesPerCluster">The number of bytes in each cluster.</param>
/// <returns>The id of the new attribute.</returns>
public ushort CreateNonResidentAttribute(AttributeType type, string name, AttributeFlags flags,
long firstCluster, ulong numClusters, uint bytesPerCluster)
{
ushort id = NextAttributeId++;
Attributes.Add(
new NonResidentAttributeRecord(
type,
name,
id,
flags,
firstCluster,
numClusters,
bytesPerCluster));
Attributes.Sort();
return id;
}
/// <summary>
/// Adds an existing attribute.
/// </summary>
/// <param name="attrRec">The attribute to add.</param>
/// <returns>The new Id of the attribute.</returns>
/// <remarks>This method is used to move an attribute between different MFT records.</remarks>
public ushort AddAttribute(AttributeRecord attrRec)
{
attrRec.AttributeId = NextAttributeId++;
Attributes.Add(attrRec);
Attributes.Sort();
return attrRec.AttributeId;
}
/// <summary>
/// Removes an attribute by it's id.
/// </summary>
/// <param name="id">The attribute's id.</param>
public void RemoveAttribute(ushort id)
{
for (int i = 0; i < Attributes.Count; ++i)
{
if (Attributes[i].AttributeId == id)
{
Attributes.RemoveAt(i);
break;
}
}
}
public void Reset()
{
Attributes.Clear();
Flags = FileRecordFlags.None;
HardLinkCount = 0;
NextAttributeId = 0;
RealSize = 0;
}
internal long GetAttributeOffset(ushort id)
{
int firstAttrPos = (ushort)MathUtilities.RoundUp((_haveIndex ? 0x30 : 0x2A) + UpdateSequenceSize, 8);
int offset = firstAttrPos;
foreach (AttributeRecord attr in Attributes)
{
if (attr.AttributeId == id)
{
return offset;
}
offset += attr.Size;
}
return -1;
}
internal void Dump(TextWriter writer, string indent)
{
writer.WriteLine(indent + "FILE RECORD (" + ToString() + ")");
writer.WriteLine(indent + " Magic: " + Magic);
writer.WriteLine(indent + " Update Seq Offset: " + UpdateSequenceOffset);
writer.WriteLine(indent + " Update Seq Count: " + UpdateSequenceCount);
writer.WriteLine(indent + " Update Seq Number: " + UpdateSequenceNumber);
writer.WriteLine(indent + " Log File Seq Num: " + LogFileSequenceNumber);
writer.WriteLine(indent + " Sequence Number: " + SequenceNumber);
writer.WriteLine(indent + " Hard Link Count: " + HardLinkCount);
writer.WriteLine(indent + " Flags: " + Flags);
writer.WriteLine(indent + " Record Real Size: " + RealSize);
writer.WriteLine(indent + " Record Alloc Size: " + AllocatedSize);
writer.WriteLine(indent + " Base File: " + BaseFile);
writer.WriteLine(indent + " Next Attribute Id: " + NextAttributeId);
writer.WriteLine(indent + " Attribute Count: " + Attributes.Count);
writer.WriteLine(indent + " Index (Self Ref): " + _index);
}
protected override void Read(byte[] buffer, int offset)
{
LogFileSequenceNumber = EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x08);
SequenceNumber = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 0x10);
HardLinkCount = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 0x12);
_firstAttributeOffset = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 0x14);
Flags = (FileRecordFlags)EndianUtilities.ToUInt16LittleEndian(buffer, offset + 0x16);
RealSize = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0x18);
AllocatedSize = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0x1C);
BaseFile = new FileRecordReference(EndianUtilities.ToUInt64LittleEndian(buffer, offset + 0x20));
NextAttributeId = EndianUtilities.ToUInt16LittleEndian(buffer, offset + 0x28);
if (UpdateSequenceOffset >= 0x30)
{
_index = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0x2C);
_haveIndex = true;
}
Attributes = new List<AttributeRecord>();
int focus = _firstAttributeOffset;
while (true)
{
int length;
AttributeRecord attr = AttributeRecord.FromBytes(buffer, focus, out length);
if (attr == null)
{
break;
}
Attributes.Add(attr);
focus += length;
}
}
protected override ushort Write(byte[] buffer, int offset)
{
ushort headerEnd = (ushort)(_haveIndex ? 0x30 : 0x2A);
_firstAttributeOffset = (ushort)MathUtilities.RoundUp(headerEnd + UpdateSequenceSize, 0x08);
RealSize = (uint)CalcSize();
EndianUtilities.WriteBytesLittleEndian(LogFileSequenceNumber, buffer, offset + 0x08);
EndianUtilities.WriteBytesLittleEndian(SequenceNumber, buffer, offset + 0x10);
EndianUtilities.WriteBytesLittleEndian(HardLinkCount, buffer, offset + 0x12);
EndianUtilities.WriteBytesLittleEndian(_firstAttributeOffset, buffer, offset + 0x14);
EndianUtilities.WriteBytesLittleEndian((ushort)Flags, buffer, offset + 0x16);
EndianUtilities.WriteBytesLittleEndian(RealSize, buffer, offset + 0x18);
EndianUtilities.WriteBytesLittleEndian(AllocatedSize, buffer, offset + 0x1C);
EndianUtilities.WriteBytesLittleEndian(BaseFile.Value, buffer, offset + 0x20);
EndianUtilities.WriteBytesLittleEndian(NextAttributeId, buffer, offset + 0x28);
if (_haveIndex)
{
EndianUtilities.WriteBytesLittleEndian((ushort)0, buffer, offset + 0x2A); // Alignment field
EndianUtilities.WriteBytesLittleEndian(_index, buffer, offset + 0x2C);
}
int pos = _firstAttributeOffset;
foreach (AttributeRecord attr in Attributes)
{
pos += attr.Write(buffer, offset + pos);
}
EndianUtilities.WriteBytesLittleEndian(uint.MaxValue, buffer, offset + pos);
return headerEnd;
}
protected override int CalcSize()
{
int firstAttrPos = (ushort)MathUtilities.RoundUp((_haveIndex ? 0x30 : 0x2A) + UpdateSequenceSize, 8);
int size = firstAttrPos;
foreach (AttributeRecord attr in Attributes)
{
size += attr.Size;
}
return MathUtilities.RoundUp(size + 4, 8); // 0xFFFFFFFF terminator on attributes
}
}
}
| |
using i64 = System.Int64;
using u8 = System.Byte;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** Header file for the Virtual DataBase Engine (VDBE)
**
** This header defines the interface to the virtual database engine
** or VDBE. The VDBE implements an abstract machine that runs a
** simple program to access and modify the underlying database.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#if !_SQLITE_VDBE_H_
//#define _SQLITE_VDBE_H_
//#include <stdio.h>
/*
** A single VDBE is an opaque structure named "Vdbe". Only routines
** in the source file sqliteVdbe.c are allowed to see the insides
** of this structure.
*/
//typedef struct Vdbe Vdbe;
/*
** The names of the following types declared in vdbeInt.h are required
** for the VdbeOp definition.
*/
//typedef struct VdbeFunc VdbeFunc;
//typedef struct Mem Mem;
//typedef struct SubProgram SubProgram;
/*
** A single instruction of the virtual machine has an opcode
** and as many as three operands. The instruction is recorded
** as an instance of the following structure:
*/
public class union_p4
{ /* fourth parameter */
public int i; /* Integer value if p4type==P4_INT32 */
public object p; /* Generic pointer */
//public string z; /* Pointer to data for string (char array) types */
public string z; // In C# string is unicode, so use byte[] instead
public i64 pI64; /* Used when p4type is P4_INT64 */
public double pReal; /* Used when p4type is P4_REAL */
public FuncDef pFunc; /* Used when p4type is P4_FUNCDEF */
public VdbeFunc pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
public CollSeq pColl; /* Used when p4type is P4_COLLSEQ */
public Mem pMem; /* Used when p4type is P4_MEM */
public VTable pVtab; /* Used when p4type is P4_VTAB */
public KeyInfo pKeyInfo; /* Used when p4type is P4_KEYINFO */
public int[] ai; /* Used when p4type is P4_INTARRAY */
public SubProgram pProgram; /* Used when p4type is P4_SUBPROGRAM */
public dxDel pFuncDel; /* Used when p4type is P4_FUNCDEL */
} ;
public class VdbeOp
{
public u8 opcode; /* What operation to perform */
public int p4type; /* One of the P4_xxx constants for p4 */
public u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
public u8 p5; /* Fifth parameter is an unsigned character */
#if DEBUG_CLASS_VDBEOP || DEBUG_CLASS_ALL
public int _p1; /* First operand */
public int p1
{
get { return _p1; }
set { _p1 = value; }
}
public int _p2; /* Second parameter (often the jump destination) */
public int p2
{
get { return _p2; }
set { _p2 = value; }
}
public int _p3; /* The third parameter */
public int p3
{
get { return _p3; }
set { _p3 = value; }
}
#else
public int p1; /* First operand */
public int p2; /* Second parameter (often the jump destination) */
public int p3; /* The third parameter */
#endif
public union_p4 p4 = new union_p4();
#if SQLITE_DEBUG || DEBUG
public string zComment; /* Comment to improve readability */
#endif
#if VDBE_PROFILE
public int cnt; /* Number of times this instruction was executed */
public u64 cycles; /* Total time spend executing this instruction */
#endif
};
//typedef struct VdbeOp VdbeOp;
/*
** A sub-routine used to implement a trigger program.
*/
public class SubProgram
{
public VdbeOp[] aOp; /* Array of opcodes for sub-program */
public int nOp; /* Elements in aOp[] */
public int nMem; /* Number of memory cells required */
public int nCsr; /* Number of cursors required */
public int token; /* id that may be used to recursive triggers */
public SubProgram pNext; /* Next sub-program already visited */
};
/*
** A smaller version of VdbeOp used for the VdbeAddOpList() function because
** it takes up less space.
*/
public struct VdbeOpList
{
public u8 opcode; /* What operation to perform */
public int p1; /* First operand */
public int p2; /* Second parameter (often the jump destination) */
public int p3; /* Third parameter */
public VdbeOpList(u8 opcode, int p1, int p2, int p3)
{
this.opcode = opcode;
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
};
//typedef struct VdbeOpList VdbeOpList;
/*
** Allowed values of VdbeOp.p4type
*/
private const int P4_NOTUSED = 0; /* The P4 parameter is not used */
private const int P4_DYNAMIC = (-1); /* Pointer to a string obtained from sqliteMalloc=(); */
private const int P4_STATIC = (-2); /* Pointer to a static string */
private const int P4_COLLSEQ = (-4); /* P4 is a pointer to a CollSeq structure */
private const int P4_FUNCDEF = (-5); /* P4 is a pointer to a FuncDef structure */
private const int P4_KEYINFO = (-6); /* P4 is a pointer to a KeyInfo structure */
private const int P4_VDBEFUNC = (-7); /* P4 is a pointer to a VdbeFunc structure */
private const int P4_MEM = (-8); /* P4 is a pointer to a Mem* structure */
private const int P4_TRANSIENT = 0; /* P4 is a pointer to a transient string */
private const int P4_VTAB = (-10); /* P4 is a pointer to an sqlite3_vtab structure */
private const int P4_MPRINTF = (-11); /* P4 is a string obtained from sqlite3_mprintf=(); */
private const int P4_REAL = (-12); /* P4 is a 64-bit floating point value */
private const int P4_INT64 = (-13); /* P4 is a 64-bit signed integer */
private const int P4_INT32 = (-14); /* P4 is a 32-bit signed integer */
private const int P4_INTARRAY = (-15); /* #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
private const int P4_SUBPROGRAM = (-18);/* #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
** is made. That copy is freed when the Vdbe is finalized. But if the
** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
** gets freed when the Vdbe is finalized so it still should be obtained
** from a single sqliteMalloc(). But no copy is made and the calling
** function should *not* try to free the KeyInfo.
*/
private const int P4_KEYINFO_HANDOFF = (-16); // #define P4_KEYINFO_HANDOFF (-16)
private const int P4_KEYINFO_STATIC = (-17); // #define P4_KEYINFO_STATIC (-17)
/*
** The Vdbe.aColName array contains 5n Mem structures, where n is the
** number of columns of data returned by the statement.
*/
//#define COLNAME_NAME 0
//#define COLNAME_DECLTYPE 1
//#define COLNAME_DATABASE 2
//#define COLNAME_TABLE 3
//#define COLNAME_COLUMN 4
//#if SQLITE_ENABLE_COLUMN_METADATA
//# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
//#else
//# ifdef SQLITE_OMIT_DECLTYPE
//# define COLNAME_N 1 /* Store only the name */
//# else
//# define COLNAME_N 2 /* Store the name and decltype */
//# endif
//#endif
private const int COLNAME_NAME = 0;
private const int COLNAME_DECLTYPE = 1;
private const int COLNAME_DATABASE = 2;
private const int COLNAME_TABLE = 3;
private const int COLNAME_COLUMN = 4;
#if SQLITE_ENABLE_COLUMN_METADATA
const int COLNAME_N = 5; /* Number of COLNAME_xxx symbols */
#else
# if SQLITE_OMIT_DECLTYPE
const int COLNAME_N = 1; /* Number of COLNAME_xxx symbols */
# else
private const int COLNAME_N = 2;
# endif
#endif
/*
** The following macro converts a relative address in the p2 field
** of a VdbeOp structure into a negative number so that
** sqlite3VdbeAddOpList() knows that the address is relative. Calling
** the macro again restores the address.
*/
//#define ADDR(X) (-1-(X))
private static int ADDR(int x)
{
return -1 - x;
}
/*
** The makefile scans the vdbe.c source file and creates the "opcodes.h"
** header file that defines a number for each opcode used by the VDBE.
*/
//#include "opcodes.h"
/*
** Prototypes for the VDBE interface. See comments on the implementation
** for a description of what each of these routines does.
*/
/*
** Prototypes for the VDBE interface. See comments on the implementation
** for a description of what each of these routines does.
*/
//Vdbe *sqlite3VdbeCreate(sqlite3);
//int sqlite3VdbeAddOp0(Vdbe*,int);
//int sqlite3VdbeAddOp1(Vdbe*,int,int);
//int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
//int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
//int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,string zP4,int);
//int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
//int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
//void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char);
//void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
//void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
//void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
//void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
//void sqlite3VdbeJumpHere(Vdbe*, int addr);
//void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
//void sqlite3VdbeChangeP4(Vdbe*, int addr, string zP4, int N);
//void sqlite3VdbeUsesBtree(Vdbe*, int);
//VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
//int sqlite3VdbeMakeLabel(Vdbe);
//void sqlite3VdbeRunOnlyOnce(Vdbe);
//void sqlite3VdbeDelete(Vdbe);
//void sqlite3VdbeDeleteObject(sqlite3*,Vdbe);
//void sqlite3VdbeMakeReady(Vdbe*,Parse);
//int sqlite3VdbeFinalize(Vdbe);
//void sqlite3VdbeResolveLabel(Vdbe*, int);
//int sqlite3VdbeCurrentAddr(Vdbe);
//#if SQLITE_DEBUG
// int sqlite3VdbeAssertMayAbort(Vdbe *, int);
// void sqlite3VdbeTrace(Vdbe*,FILE);
//#endif
//void sqlite3VdbeResetStepResult(Vdbe);
//void sqlite3VdbeRewind(Vdbe);
//int sqlite3VdbeReset(Vdbe);
//void sqlite3VdbeSetNumCols(Vdbe*,int);
//int sqlite3VdbeSetColName(Vdbe*, int, int, string , void()(void));
//void sqlite3VdbeCountChanges(Vdbe);
//sqlite3 *sqlite3VdbeDb(Vdbe);
//void sqlite3VdbeSetSql(Vdbe*, string z, int n, int);
//void sqlite3VdbeSwap(Vdbe*,Vdbe);
//VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int);
//sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
//void sqlite3VdbeSetVarmask(Vdbe*, int);
//#if !SQLITE_OMIT_TRACE
// char *sqlite3VdbeExpandSql(Vdbe*, const char);
//#endif
//UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
//void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord);
//int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord);
//#if !SQLITE_OMIT_TRIGGER
//void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram );
//#endif
#if !NDEBUG
//void sqlite3VdbeComment(Vdbe*, const char*, ...);
private static void VdbeComment(Vdbe v, string zFormat, params object[] ap)
{
sqlite3VdbeComment(v, zFormat, ap);
}//# define VdbeComment(X) sqlite3VdbeComment X
//void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
private static void VdbeNoopComment(Vdbe v, string zFormat, params object[] ap)
{
sqlite3VdbeNoopComment(v, zFormat, ap);
}//# define VdbeNoopComment(X) sqlite3VdbeNoopComment X
#else
//# define VdbeComment(X)
static void VdbeComment( Vdbe v, string zFormat, params object[] ap ) { }
//# define VdbeNoopComment(X)
static void VdbeNoopComment( Vdbe v, string zFormat, params object[] ap ) { }
#endif
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Xamarin;
namespace SensusService
{
public class Logger
{
private const int MAX_LOG_SIZE_MEGABYTES = 20;
private string _path;
private LoggingLevel _level;
private TextWriter[] _otherOutputs;
private List<string> _messageBuffer;
private Regex _extraWhiteSpace;
public LoggingLevel Level
{
get { return _level; }
set { _level = value; }
}
public Logger(string path, LoggingLevel level, params TextWriter[] otherOutputs)
{
_path = path;
_level = level;
_otherOutputs = otherOutputs;
_messageBuffer = new List<string>();
_extraWhiteSpace = new Regex(@"\s\s+");
}
public void Log(string message, LoggingLevel level, Type callingType, bool throwException = false)
{
// if we're throwing an exception, use the caller's version of the message instead of our modified version below.
Exception ex = null;
if (throwException)
ex = new Exception(message);
if (level <= _level)
{
// remove newlines and extra white space, and only log if the result is non-empty
message = _extraWhiteSpace.Replace(message.Replace('\r', ' ').Replace('\n', ' ').Trim(), " ");
if (!string.IsNullOrWhiteSpace(message))
{
// add timestamp and calling type type
message = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + ": " + (callingType == null ? "" : "[" + callingType.Name + "] ") + message;
lock (_messageBuffer)
{
_messageBuffer.Add(message);
if (_otherOutputs != null)
foreach (TextWriter otherOutput in _otherOutputs)
{
try
{
otherOutput.WriteLine(message);
}
catch (Exception writeException)
{
Console.Error.WriteLine("Failed to write to output: " + writeException.Message);
}
}
// append buffer to file periodically
if (_messageBuffer.Count % 100 == 0)
{
try
{
CommitMessageBuffer();
}
catch (Exception commitException)
{
// try switching the log path to a random file, since access violations might prevent us from writing the current _path (e.g., in the case of crashes)
_path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), Guid.NewGuid().ToString() + ".txt");
_messageBuffer.Add("Switched log path to \"" + _path + "\" due to exception: " + commitException.Message);
}
}
}
}
}
if (ex != null)
throw ex;
}
public void CommitMessageBuffer()
{
lock (_messageBuffer)
{
if (_messageBuffer.Count > 0)
{
try
{
using (StreamWriter file = new StreamWriter(_path, true))
{
foreach (string bufferedMessage in _messageBuffer)
file.WriteLine(bufferedMessage);
}
// keep log file under a certain size by reading the most recent MAX_LOG_SIZE_MEGABYTES.
long currSizeBytes = new FileInfo(_path).Length;
if (currSizeBytes > MAX_LOG_SIZE_MEGABYTES * 1024 * 1024)
{
int newSizeBytes = (MAX_LOG_SIZE_MEGABYTES - 5) * 1024 * 1024;
byte[] newBytes = new byte[newSizeBytes];
using (FileStream file = new FileStream(_path, FileMode.Open, FileAccess.Read))
{
file.Position = currSizeBytes - newSizeBytes;
file.Read(newBytes, 0, newSizeBytes);
}
File.Delete(_path);
File.WriteAllBytes(_path, newBytes);
}
}
catch (Exception ex)
{
Log("Error committing message buffer: " + ex.Message, SensusService.LoggingLevel.Normal, GetType());
}
_messageBuffer.Clear();
}
}
}
public List<string> Read(int maxMessages, bool mostRecentFirst)
{
lock (_messageBuffer)
{
CommitMessageBuffer();
List<string> messages = new List<string>();
try
{
using (StreamReader file = new StreamReader(_path))
{
if (maxMessages > 0)
{
int numLines = 0;
while (file.ReadLine() != null)
++numLines;
file.BaseStream.Position = 0;
file.DiscardBufferedData();
int linesToSkip = Math.Max(numLines - maxMessages, 0);
for (int i = 1; i <= linesToSkip; ++i)
file.ReadLine();
}
string line;
while ((line = file.ReadLine()) != null)
messages.Add(line);
}
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Error reading log file: " + ex.Message, SensusService.LoggingLevel.Normal, GetType());
}
if (mostRecentFirst)
messages.Reverse();
return messages;
}
}
public void CopyTo(string path)
{
lock (_messageBuffer)
{
CommitMessageBuffer();
try
{
File.Copy(_path, path);
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Failed to copy log file to \"" + path + "\": " + ex.Message, SensusService.LoggingLevel.Normal, GetType());
}
}
}
public virtual void Clear()
{
lock (_messageBuffer)
{
try
{
File.Delete(_path);
}
catch (Exception)
{
}
_messageBuffer.Clear();
}
}
}
}
| |
using Starcounter;
using System;
using System.Collections.Generic;
using System.Linq;
using Products.Helpers;
using System.Globalization;
namespace Products
{
partial class ProductSalesPage : Json, IBound<Product>
{
public DateTime FilterDateFrom
{
get
{
DateTime date;
if (!DateTime.TryParseExact(DateFrom, ServerDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
date = FilterDateTo.AddDays(-7);
}
return date;
}
}
public DateTime FilterDateTo
{
get
{
DateTime date;
if (!DateTime.TryParseExact(DateTo, ServerDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
date = DateTime.Now;
}
return date;
}
}
public bool IsAdd { get; set; }
public List<Organization> SelectedOrganizations
{
get { return _selectedOrganizations; }
set
{
_selectedOrganizations = value;
LoadSales(Data);
}
}
private readonly Random _r = new Random();
private List<Organization> _selectedOrganizations = new List<Organization>();
protected override void OnData()
{
base.OnData();
LoadSales(Data, IsAdd);
DateFrom = FilterDateFrom.ToString(ServerDateFormat);
DateTo = FilterDateTo.ToString(ServerDateFormat);
Dataset.Duration = (FilterDateTo - FilterDateFrom).Days + 1;
}
public void LoadSales(Product product, bool isAdd = false)
{
Dataset.Items.Clear();
Dataset.Events.Clear();
Dataset.Duration = (FilterDateTo - FilterDateFrom).Days + 1;
Dataset.Duration = Dataset.Duration < 0 ? 0 : Dataset.Duration;
if (product == null || isAdd)
return;
if (this.Data != product)
{
this.Data = product;
return;
}
List<Transfer> transfers = new List<Transfer>(GetSales());
foreach (Transfer t in transfers)
{
AddTimelineItem(t);
}
AddPredictedTimelineItem();
List<Event> events = new List<Event>(GetEvents());
foreach (Event e in events)
{
AddTimelineEvent(e);
}
}
private void Handle(Input.Event action)
{
if (Data == null || IsAdd)
return;
AddTimelineEvent(AddTestEvent());
}
private IEnumerable<Transfer> GetSales()
{
DateTime from = FilterDateFrom;
DateTime to = FilterDateTo.AddDays(1);
return SelectedOrganizations.SelectMany(org =>
Db.SQL<Transfer>($"SELECT t FROM {typeof(Transfer)} t WHERE t.ProductInstance.Product = ? AND t.When >= ? AND t.When < ? AND t.\"From\" = ? AND t.To <> ?",
Data, from, to, org, org));
}
private IEnumerable<Event> GetEvents()
{
DateTime from = FilterDateFrom;
DateTime to = FilterDateTo.AddDays(1);
return Db.SQL<Event>($"SELECT t FROM {typeof(Event)} t WHERE t.BeginTime >= ? AND t.BeginTime < ? OR t.EndTime >= ? AND t.EndTime < ?", from, to, from, to);
}
private void AddPredictedTimelineItem()
{
int lastIndex = (int)(DateTime.Now - FilterDateFrom).TotalDays + 1;
if (lastIndex < 1)
return;
var prevItem = Dataset.Items.FirstOrDefault(val => val.Index == lastIndex - 1);
var lastItem = Dataset.Items.FirstOrDefault(val => val.Index == lastIndex);
if (lastItem != null)
{
int index = lastIndex + 1;
string key = GetTimelineItemKey(index);
var item = Dataset.Items.FirstOrDefault(val => val.Index == index) ?? Dataset.Items.Add();
item.Key = key;
item.Index = index;
item.Predicted = lastItem.Value;
if (prevItem != null)
lastItem.Predicted = prevItem.Value;
}
}
private string GetTimelineItemKey(int index)
{
return string.Format("{0}{1}{2}{3:yyyyMMdd}{4:yyyyMMdd}", Data.GetObjectID(), string.Join("", SelectedOrganizations.Select(val => val.GetObjectID())), index, DateFrom, DateTo);
}
private void AddTimelineItem(Transfer t)
{
if (t.When < FilterDateFrom)
return;
int index = (int)(t.When - FilterDateFrom).TotalDays + 1;
string key = GetTimelineItemKey(index);
var item = Dataset.Items.FirstOrDefault(val => val.Index == index) ?? Dataset.Items.Add();
item.Key = key;
item.Index = index;
item.Value += t.ProductInstance.Quantity;
}
private void AddTimelineEvent(Event e)
{
decimal from = (decimal)(e.BeginTime - FilterDateFrom).TotalDays;
decimal to = (decimal)(e.EndTime - FilterDateFrom).TotalDays;
string eventType = "Normal";
var item = Dataset.Events.Add();
item.Key = e.GetObjectID();
item.Name = e.Name + " " + (e.EventInfo != null ? e.EventInfo.Name : string.Empty);
item.Type = eventType;
item.From = from;
item.To = to;
}
private Event AddTestEvent()
{
DateTime dateBegin = FilterDateFrom;
int totalHours = (int)(FilterDateTo - dateBegin).TotalHours;
if (totalHours <= 0)
totalHours = 1;
dateBegin = dateBegin.AddHours(_r.Next(totalHours));
DateTime dateEnd = dateBegin;
dateEnd = dateEnd.AddHours(_r.Next(totalHours));
Event e = new Event() { BeginTime = dateBegin, EndTime = dateEnd, Name = "Event " + (Dataset.Events.Count + 1) };
Transaction.Commit();
return e;
}
private Organization GetCustomer()
{
string name = "Customer";
Organization org = Db.SQL<Organization>($"SELECT o FROM {typeof(Organization)} o WHERE o.Name = ?", name).FirstOrDefault();
if (org == null)
org = new Organization() { Name = name };
return org;
}
private Organization GetSupplier()
{
return Organizations.GetSupplier();
}
private void Handle(Input.DateFrom input)
{
DateFrom = input.Value;
LoadSales(Data, IsAdd);
}
private void Handle(Input.DateTo input)
{
DateTo = input.Value;
LoadSales(Data, IsAdd);
}
}
}
| |
using System;
namespace Cosmos.System
{
/// <summary>
/// ConsoleKeyEx extensions class.
/// </summary>
public static class ConsoleKeyExExtensions
{
/// <summary>
/// Convert ConsoleKeyEx to ConsoleKey.
/// </summary>
/// <param name="keyEx">KeyEx to convert.</param>
/// <returns>ConsoleKey value.</returns>
/// <exception cref="Exception">Thorwn if KeyEx not implemented.</exception>
public static ConsoleKey ToConsoleKey(this ConsoleKeyEx keyEx)
{
switch (keyEx)
{
case ConsoleKeyEx.NoName:
return ConsoleKey.NoName;
case ConsoleKeyEx.Escape:
return ConsoleKey.Escape;
case ConsoleKeyEx.F1:
return ConsoleKey.F1;
case ConsoleKeyEx.F2:
return ConsoleKey.F2;
case ConsoleKeyEx.F3:
return ConsoleKey.F3;
case ConsoleKeyEx.F4:
return ConsoleKey.F4;
case ConsoleKeyEx.F5:
return ConsoleKey.F5;
case ConsoleKeyEx.F6:
return ConsoleKey.F6;
case ConsoleKeyEx.F7:
return ConsoleKey.F7;
case ConsoleKeyEx.F8:
return ConsoleKey.F8;
case ConsoleKeyEx.F9:
return ConsoleKey.F9;
case ConsoleKeyEx.F10:
return ConsoleKey.F10;
case ConsoleKeyEx.F11:
return ConsoleKey.F11;
case ConsoleKeyEx.F12:
return ConsoleKey.F12;
case ConsoleKeyEx.PrintScreen:
return ConsoleKey.PrintScreen;
case ConsoleKeyEx.D1:
return ConsoleKey.D1;
case ConsoleKeyEx.D2:
return ConsoleKey.D2;
case ConsoleKeyEx.D3:
return ConsoleKey.D3;
case ConsoleKeyEx.D4:
return ConsoleKey.D4;
case ConsoleKeyEx.D5:
return ConsoleKey.D5;
case ConsoleKeyEx.D6:
return ConsoleKey.D6;
case ConsoleKeyEx.D7:
return ConsoleKey.D7;
case ConsoleKeyEx.D8:
return ConsoleKey.D8;
case ConsoleKeyEx.D9:
return ConsoleKey.D9;
case ConsoleKeyEx.D0:
return ConsoleKey.D0;
case ConsoleKeyEx.Backspace:
return ConsoleKey.Backspace;
case ConsoleKeyEx.Tab:
return ConsoleKey.Tab;
case ConsoleKeyEx.Q:
return ConsoleKey.Q;
case ConsoleKeyEx.W:
return ConsoleKey.W;
case ConsoleKeyEx.E:
return ConsoleKey.E;
case ConsoleKeyEx.R:
return ConsoleKey.R;
case ConsoleKeyEx.T:
return ConsoleKey.T;
case ConsoleKeyEx.Y:
return ConsoleKey.Y;
case ConsoleKeyEx.U:
return ConsoleKey.U;
case ConsoleKeyEx.I:
return ConsoleKey.I;
case ConsoleKeyEx.O:
return ConsoleKey.O;
case ConsoleKeyEx.P:
return ConsoleKey.P;
case ConsoleKeyEx.Enter:
return ConsoleKey.Enter;
case ConsoleKeyEx.A:
return ConsoleKey.A;
case ConsoleKeyEx.S:
return ConsoleKey.S;
case ConsoleKeyEx.D:
return ConsoleKey.D;
case ConsoleKeyEx.F:
return ConsoleKey.F;
case ConsoleKeyEx.G:
return ConsoleKey.G;
case ConsoleKeyEx.H:
return ConsoleKey.H;
case ConsoleKeyEx.J:
return ConsoleKey.J;
case ConsoleKeyEx.K:
return ConsoleKey.K;
case ConsoleKeyEx.L:
return ConsoleKey.L;
case ConsoleKeyEx.Z:
return ConsoleKey.Z;
case ConsoleKeyEx.X:
return ConsoleKey.X;
case ConsoleKeyEx.C:
return ConsoleKey.C;
case ConsoleKeyEx.V:
return ConsoleKey.V;
case ConsoleKeyEx.B:
return ConsoleKey.B;
case ConsoleKeyEx.N:
return ConsoleKey.N;
case ConsoleKeyEx.M:
return ConsoleKey.M;
case ConsoleKeyEx.Spacebar:
return ConsoleKey.Spacebar;
case ConsoleKeyEx.Insert:
return ConsoleKey.Insert;
case ConsoleKeyEx.Home:
return ConsoleKey.Home;
case ConsoleKeyEx.PageUp:
return ConsoleKey.PageUp;
case ConsoleKeyEx.Delete:
return ConsoleKey.Delete;
case ConsoleKeyEx.End:
return ConsoleKey.End;
case ConsoleKeyEx.PageDown:
return ConsoleKey.PageDown;
case ConsoleKeyEx.UpArrow:
return ConsoleKey.UpArrow;
case ConsoleKeyEx.DownArrow:
return ConsoleKey.DownArrow;
case ConsoleKeyEx.LeftArrow:
return ConsoleKey.LeftArrow;
case ConsoleKeyEx.RightArrow:
return ConsoleKey.RightArrow;
case ConsoleKeyEx.Sleep:
return ConsoleKey.Sleep;
case ConsoleKeyEx.BiggerThan:
case ConsoleKeyEx.ExclamationPoint:
case ConsoleKeyEx.Period:
return ConsoleKey.OemPeriod;
case ConsoleKeyEx.LowerThan:
case ConsoleKeyEx.Comma:
return ConsoleKey.OemComma;
case ConsoleKeyEx.NumPeriod:
return ConsoleKey.Decimal;
case ConsoleKeyEx.NumEnter:
return ConsoleKey.Enter;
case ConsoleKeyEx.Num0:
return ConsoleKey.D0;
case ConsoleKeyEx.Num1:
return ConsoleKey.D1;
case ConsoleKeyEx.Num2:
return ConsoleKey.D2;
case ConsoleKeyEx.Num3:
return ConsoleKey.D3;
case ConsoleKeyEx.Num4:
return ConsoleKey.D4;
case ConsoleKeyEx.Num5:
return ConsoleKey.D5;
case ConsoleKeyEx.Num6:
return ConsoleKey.D6;
case ConsoleKeyEx.Num7:
return ConsoleKey.D7;
case ConsoleKeyEx.Num8:
return ConsoleKey.D8;
case ConsoleKeyEx.Num9:
return ConsoleKey.D9;
case ConsoleKeyEx.NumDivide:
return ConsoleKey.Divide;
case ConsoleKeyEx.NumMultiply:
return ConsoleKey.Multiply;
case ConsoleKeyEx.NumMinus:
return ConsoleKey.OemMinus;
case ConsoleKeyEx.NumPlus:
return ConsoleKey.OemPlus;
case ConsoleKeyEx.Backslash:
return ConsoleKey.Oem5;
case ConsoleKeyEx.LBracket:
return ConsoleKey.Oem4;
case ConsoleKeyEx.RBracket:
return ConsoleKey.Oem6;
case ConsoleKeyEx.Minus:
return ConsoleKey.OemMinus;
case ConsoleKeyEx.Apostrophe:
return ConsoleKey.Oem7;
case ConsoleKeyEx.Slash:
return ConsoleKey.Oem2;
case ConsoleKeyEx.Equal:
return ConsoleKey.OemPlus;
case ConsoleKeyEx.Backquote:
return ConsoleKey.Oem3;
case ConsoleKeyEx.Semicolon:
case ConsoleKeyEx.Colon:
return ConsoleKey.Oem1;
case ConsoleKeyEx.OEM102:
return ConsoleKey.Oem102;
case ConsoleKeyEx.LWin:
return ConsoleKey.LeftWindows;
case ConsoleKeyEx.RWin:
return ConsoleKey.RightWindows;
default:
throw new Exception("KeyEx not implemented!");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
public readonly struct MethodDefinition
{
private readonly MetadataReader _reader;
// Workaround: JIT doesn't generate good code for nested structures, so use RowId.
private readonly uint _treatmentAndRowId;
internal MethodDefinition(MetadataReader reader, uint treatmentAndRowId)
{
Debug.Assert(reader != null);
Debug.Assert(treatmentAndRowId != 0);
_reader = reader;
_treatmentAndRowId = treatmentAndRowId;
}
private int RowId
{
get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); }
}
private MethodDefTreatment Treatment
{
get { return (MethodDefTreatment)(_treatmentAndRowId >> TokenTypeIds.RowIdBitCount); }
}
private MethodDefinitionHandle Handle
{
get { return MethodDefinitionHandle.FromRowId(RowId); }
}
public StringHandle Name
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetName(Handle);
}
return GetProjectedName();
}
}
public BlobHandle Signature
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetSignature(Handle);
}
return GetProjectedSignature();
}
}
public MethodSignature<TType> DecodeSignature<TType, TGenericContext>(ISignatureTypeProvider<TType, TGenericContext> provider, TGenericContext genericContext)
{
var decoder = new SignatureDecoder<TType, TGenericContext>(provider, _reader, genericContext);
var blobReader = _reader.GetBlobReader(Signature);
return decoder.DecodeMethodSignature(ref blobReader);
}
public int RelativeVirtualAddress
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetRva(Handle);
}
return GetProjectedRelativeVirtualAddress();
}
}
public MethodAttributes Attributes
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetFlags(Handle);
}
return GetProjectedFlags();
}
}
public MethodImplAttributes ImplAttributes
{
get
{
if (Treatment == 0)
{
return _reader.MethodDefTable.GetImplFlags(Handle);
}
return GetProjectedImplFlags();
}
}
public TypeDefinitionHandle GetDeclaringType()
{
return _reader.GetDeclaringType(Handle);
}
public ParameterHandleCollection GetParameters()
{
return new ParameterHandleCollection(_reader, Handle);
}
public GenericParameterHandleCollection GetGenericParameters()
{
return _reader.GenericParamTable.FindGenericParametersForMethod(Handle);
}
public MethodImport GetImport()
{
int implMapRid = _reader.ImplMapTable.FindImplForMethod(Handle);
if (implMapRid == 0)
{
return default(MethodImport);
}
return _reader.ImplMapTable.GetImport(implMapRid);
}
public CustomAttributeHandleCollection GetCustomAttributes()
{
return new CustomAttributeHandleCollection(_reader, Handle);
}
public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes()
{
return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle);
}
#region Projections
private StringHandle GetProjectedName()
{
if ((Treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.DisposeMethod)
{
return StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.Dispose);
}
return _reader.MethodDefTable.GetName(Handle);
}
private MethodAttributes GetProjectedFlags()
{
MethodAttributes flags = _reader.MethodDefTable.GetFlags(Handle);
MethodDefTreatment treatment = Treatment;
if ((treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.HiddenInterfaceImplementation)
{
flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Private;
}
if ((treatment & MethodDefTreatment.MarkAbstractFlag) != 0)
{
flags |= MethodAttributes.Abstract;
}
if ((treatment & MethodDefTreatment.MarkPublicFlag) != 0)
{
flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public;
}
return flags | MethodAttributes.HideBySig;
}
private MethodImplAttributes GetProjectedImplFlags()
{
MethodImplAttributes flags = _reader.MethodDefTable.GetImplFlags(Handle);
switch (Treatment & MethodDefTreatment.KindMask)
{
case MethodDefTreatment.DelegateMethod:
flags |= MethodImplAttributes.Runtime;
break;
case MethodDefTreatment.DisposeMethod:
case MethodDefTreatment.AttributeMethod:
case MethodDefTreatment.InterfaceMethod:
case MethodDefTreatment.HiddenInterfaceImplementation:
case MethodDefTreatment.Other:
flags |= MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall;
break;
}
return flags;
}
private BlobHandle GetProjectedSignature()
{
return _reader.MethodDefTable.GetSignature(Handle);
}
private int GetProjectedRelativeVirtualAddress()
{
return 0;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function SpineToy::create(%this)
{
// Set the sandbox drag mode availability.
Sandbox.allowManipulation( pan );
// Set the manipulation mode.
Sandbox.useManipulation( pan );
%this.asset = "SpineToy:goblins";
%this.skin = "goblin";
%this.animation = "walk";
addSelectionOption( "goblin,goblingirl", "Select Skin", 4, "setSkin", false, "Sets the skin for the skeleton object." );
// Reset the toy.
SpineToy.reset();
}
//-----------------------------------------------------------------------------
function SpineToy::destroy(%this)
{
}
//-----------------------------------------------------------------------------
function SpineToy::reset(%this)
{
// Clear the scene.
SandboxScene.clear();
if (%this.resetSchedule !$= "")
cancel(%this.resetSchedule);
// Set the camera size.
SandboxWindow.setCameraSize( 40, 30 );
%this.createBackground();
%this.createGoblin();
}
//-----------------------------------------------------------------------------
function SpineToy::setSkeleton(%this, %value)
{
%this.asset = %value;
if (%value $= "SpineToy:goblins")
%this.setSkin("goblin");
else
%this.setSkin("default");
}
//-----------------------------------------------------------------------------
function SpineToy::setSkin(%this, %value)
{
%this.skin = %value;
%this.walker.Skin = %this.skin;
}
//-----------------------------------------------------------------------------
function SpineToy::createGoblin(%this)
{
// Create the skeleton object
%goblin = new SkeletonObject();
// Assign it an asset
%goblin.Asset = %this.asset;
%goblin.Skin = %this.skin;
// Set the animation name
%goblin.setAnimationName(%this.animation, true);
%goblin.RootBoneScale = 0.025;
%goblin.setRootBoneOffset(0, -5);
%goblin.position = "-25 -8";
%goblin.SceneLayer = 29;
%goblin.setLinearVelocity(7.5, 0);
%this.walker = %goblin;
%this.resetSchedule = %this.schedule(8000, resetWalker);
// Add it to the scene
SandboxScene.add(%goblin);
}
//-----------------------------------------------------------------------------
function SpineToy::createSpineBoy(%this)
{
// Create the skeleton object
%object = new SkeletonObject()
{
class = "SpineBoy";
};
%object.Asset = "SpineToy:TestSkeleton";
%object.setAnimationName("walk", true);
%object.RootBoneScale = 0.025;
%object.SceneLayer = 29;
%object.Position = 0;
%object.setMix("walk", "jump", 0.2);
%object.setMix("jump", "walk", 0.4);
SandboxScene.add(%object);
%object.schedule(4000, "doJump");
}
//-----------------------------------------------------------------------------
function SpineBoy::onAnimationFinished(%this, %animationName)
{
if (%animationName $= "jump")
{
%this.setAnimationName("walk", true);
%this.schedule(4000, "doJump");
}
}
//-----------------------------------------------------------------------------
function SpineBoy::doJump(%this)
{
%this.setAnimationName("jump", false);
}
//-----------------------------------------------------------------------------
function SpineToy::resetWalker(%this)
{
%this.walker.setPosition("-25 -8");
%this.resetSchedule = %this.schedule(8000, resetWalker);
}
//-----------------------------------------------------------------------------
function SpineToy::createBackground(%this)
{
// Create the sprite.
%object = new Sprite();
// Set the sprite as "static" so it is not affected by gravity.
%object.setBodyType( static );
// Always try to configure a scene-object prior to adding it to a scene for best performance.
// Set the position.
%object.Position = "0 0";
// Set the size.
%object.Size = "40 30";
// Set to the furthest background layer.
%object.SceneLayer = 31;
// Set an image.
%object.Image = "SpineToy:background";
// Add the sprite to the scene.
SandboxScene.add( %object );
%this.createPowerup(-14, 6);
%this.createPowerup(14, 6);
// Create the skeleton object
%animatedMenu = new SkeletonObject();
// Assign it an asset
%animatedMenu.Asset = "SpineToy:spinosaurus";
// Set properties
%animatedMenu.setAnimationName("Animation", false);
%duration = %animatedMenu.getAnimationDuration();
%animatedMenu.schedule(%duration*1000, "setAnimationName", "loop", true);
%animatedMenu.position = "0 0";
%animatedMenu.SceneLayer = 30;
%animatedMenu.RootBoneScale = 0.025;
%animatedMenu.setRootBoneOffset(0, -10);
// Add it to the scene
SandboxScene.add(%animatedMenu);
}
//-----------------------------------------------------------------------------
function SpineToy::createPowerup(%this, %xPos, %yPos)
{
// Create the skeleton object
%powerup = new SkeletonObject();
// Assign it an asset
%powerup.Asset = "SpineToy:powerup";
// Set properties
%powerup.setAnimationName("Animation", true);
%powerup.position = %xPos SPC %yPos;
%powerup.SceneLayer = 30;
%powerup.RootBoneScale = 0.025;
%powerup.setRootBoneOffset(0, -5);
// Add it to the scene
SandboxScene.add(%powerup);
}
//-----------------------------------------------------------------------------
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Config
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using NLog.Common;
using NLog.Conditions;
using NLog.Filters;
using NLog.Internal;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using NLog.Time;
/// <summary>
/// Provides registration information for named items (targets, layouts, layout renderers, etc.) managed by NLog.
///
/// Everything of an assembly could be loaded by <see cref="RegisterItemsFromAssembly(System.Reflection.Assembly)"/>
/// </summary>
public class ConfigurationItemFactory
{
private static ConfigurationItemFactory _defaultInstance;
private readonly IFactory[] _allFactories;
private readonly Factory<Target, TargetAttribute> _targets;
private readonly Factory<Filter, FilterAttribute> _filters;
private readonly LayoutRendererFactory _layoutRenderers;
private readonly Factory<Layout, LayoutAttribute> _layouts;
private readonly MethodFactory _conditionMethods;
private readonly Factory<LayoutRenderer, AmbientPropertyAttribute> _ambientProperties;
private readonly Factory<TimeSource, TimeSourceAttribute> _timeSources;
private IJsonConverter _jsonSerializer = DefaultJsonSerializer.Instance;
private IObjectTypeTransformer _objectTypeTransformer = ObjectReflectionCache.Instance;
/// <summary>
/// Called before the assembly will be loaded.
/// </summary>
public static event EventHandler<AssemblyLoadingEventArgs> AssemblyLoading;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigurationItemFactory"/> class.
/// </summary>
/// <param name="assemblies">The assemblies to scan for named items.</param>
public ConfigurationItemFactory(params Assembly[] assemblies)
{
CreateInstance = FactoryHelper.CreateInstance;
_targets = new Factory<Target, TargetAttribute>(this);
_filters = new Factory<Filter, FilterAttribute>(this);
_layoutRenderers = new LayoutRendererFactory(this);
_layouts = new Factory<Layout, LayoutAttribute>(this);
_conditionMethods = new MethodFactory(classType => MethodFactory.ExtractClassMethods<ConditionMethodsAttribute, ConditionMethodAttribute>(classType));
_ambientProperties = new Factory<LayoutRenderer, AmbientPropertyAttribute>(this);
_timeSources = new Factory<TimeSource, TimeSourceAttribute>(this);
_allFactories = new IFactory[]
{
_targets,
_filters,
_layoutRenderers,
_layouts,
_conditionMethods,
_ambientProperties,
_timeSources,
};
foreach (var asm in assemblies)
{
RegisterItemsFromAssembly(asm);
}
}
/// <summary>
/// Gets or sets default singleton instance of <see cref="ConfigurationItemFactory"/>.
/// </summary>
/// <remarks>
/// This property implements lazy instantiation so that the <see cref="ConfigurationItemFactory"/> is not built before
/// the internal logger is configured.
/// </remarks>
public static ConfigurationItemFactory Default
{
get => _defaultInstance ?? (_defaultInstance = BuildDefaultFactory());
set => _defaultInstance = value;
}
/// <summary>
/// Gets or sets the creator delegate used to instantiate configuration objects.
/// </summary>
/// <remarks>
/// By overriding this property, one can enable dependency injection or interception for created objects.
/// </remarks>
public ConfigurationItemCreator CreateInstance { get; set; }
/// <summary>
/// Gets the <see cref="Target"/> factory.
/// </summary>
/// <value>The target factory.</value>
public INamedItemFactory<Target, Type> Targets => _targets;
/// <summary>
/// Gets the <see cref="Filter"/> factory.
/// </summary>
/// <value>The filter factory.</value>
public INamedItemFactory<Filter, Type> Filters => _filters;
/// <summary>
/// gets the <see cref="LayoutRenderer"/> factory
/// </summary>
/// <remarks>not using <see cref="_layoutRenderers"/> due to backwards-compatibility.</remarks>
/// <returns></returns>
internal LayoutRendererFactory GetLayoutRenderers()
{
return _layoutRenderers;
}
/// <summary>
/// Gets the <see cref="LayoutRenderer"/> factory.
/// </summary>
/// <value>The layout renderer factory.</value>
public INamedItemFactory<LayoutRenderer, Type> LayoutRenderers => _layoutRenderers;
/// <summary>
/// Gets the <see cref="LayoutRenderer"/> factory.
/// </summary>
/// <value>The layout factory.</value>
public INamedItemFactory<Layout, Type> Layouts => _layouts;
/// <summary>
/// Gets the ambient property factory.
/// </summary>
/// <value>The ambient property factory.</value>
public INamedItemFactory<LayoutRenderer, Type> AmbientProperties => _ambientProperties;
/// <summary>
/// Legacy interface, no longer used by the NLog engine
/// </summary>
[Obsolete("Use JsonConverter property instead. Marked obsolete on NLog 4.5")]
public IJsonSerializer JsonSerializer
{
get => _jsonSerializer as IJsonSerializer;
set => _jsonSerializer = value != null ? (IJsonConverter)new JsonConverterLegacy(value) : DefaultJsonSerializer.Instance;
}
/// <summary>
/// Gets or sets the JSON serializer to use with <see cref="WebServiceTarget"/> or <see cref="JsonLayout"/>
/// </summary>
public IJsonConverter JsonConverter
{
get => _jsonSerializer;
set => _jsonSerializer = value ?? DefaultJsonSerializer.Instance;
}
/// <summary>
/// Gets or sets the string serializer to use with <see cref="LogEventInfo.MessageTemplateParameters"/>
/// </summary>
public IValueFormatter ValueFormatter
{
get => MessageTemplates.ValueFormatter.Instance;
set => MessageTemplates.ValueFormatter.Instance = value;
}
/// <summary>
/// Gets or sets the custom object-type transformation for use in <see cref="JsonLayout"/>, <see cref="XmlLayout"/> or <see cref="NLog.LayoutRenderers.Wrappers.ObjectPathRendererWrapper"/>
/// </summary>
internal IObjectTypeTransformer ObjectTypeTransformer
{
get => _objectTypeTransformer;
set => _objectTypeTransformer = value ?? ObjectReflectionCache.Instance;
}
/// <summary>
/// Gets or sets the parameter converter to use with <see cref="DatabaseTarget"/>, <see cref="WebServiceTarget"/> or <see cref="TargetWithContext"/>
/// </summary>
public IPropertyTypeConverter PropertyTypeConverter { get; set; } = new PropertyTypeConverter();
/// <summary>
/// Perform message template parsing and formatting of LogEvent messages (True = Always, False = Never, Null = Auto Detect)
/// </summary>
/// <remarks>
/// - Null (Auto Detect) : NLog-parser checks <see cref="LogEventInfo.Message"/> for positional parameters, and will then fallback to string.Format-rendering.
/// - True: Always performs the parsing of <see cref="LogEventInfo.Message"/> and rendering of <see cref="LogEventInfo.FormattedMessage"/> using the NLog-parser (Allows custom formatting with <see cref="ValueFormatter"/>)
/// - False: Always performs parsing and rendering using string.Format (Fastest if not using structured logging)
/// </remarks>
public bool? ParseMessageTemplates
{
get
{
if (ReferenceEquals(LogEventInfo.DefaultMessageFormatter, LogEventInfo.StringFormatMessageFormatter))
{
return false;
}
else if (ReferenceEquals(LogEventInfo.DefaultMessageFormatter, LogMessageTemplateFormatter.Default.MessageFormatter))
{
return true;
}
else
{
return null;
}
}
set => LogEventInfo.SetDefaultMessageFormatter(value);
}
/// <summary>
/// Gets the time source factory.
/// </summary>
/// <value>The time source factory.</value>
public INamedItemFactory<TimeSource, Type> TimeSources => _timeSources;
/// <summary>
/// Gets the condition method factory.
/// </summary>
/// <value>The condition method factory.</value>
public INamedItemFactory<MethodInfo, MethodInfo> ConditionMethods => _conditionMethods;
/// <summary>
/// Gets the condition method factory (precompiled)
/// </summary>
/// <value>The condition method factory.</value>
internal MethodFactory ConditionMethodDelegates => _conditionMethods;
/// <summary>
/// Registers named items from the assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
public void RegisterItemsFromAssembly(Assembly assembly)
{
RegisterItemsFromAssembly(assembly, string.Empty);
}
/// <summary>
/// Registers named items from the assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <param name="itemNamePrefix">Item name prefix.</param>
public void RegisterItemsFromAssembly(Assembly assembly, string itemNamePrefix)
{
if (AssemblyLoading != null)
{
var args = new AssemblyLoadingEventArgs(assembly);
AssemblyLoading.Invoke(null, args);
if (args.Cancel)
{
InternalLogger.Info("Loading assembly '{0}' is canceled", assembly.FullName);
return;
}
}
InternalLogger.Debug("ScanAssembly('{0}')", assembly.FullName);
var typesToScan = assembly.SafeGetTypes();
PreloadAssembly(typesToScan);
foreach (IFactory f in _allFactories)
{
f.ScanTypes(typesToScan, itemNamePrefix);
}
}
/// <summary>
/// Call Preload for NLogPackageLoader
/// </summary>
/// <remarks>
/// Every package could implement a class "NLogPackageLoader" (namespace not important) with the public static method "Preload" (no arguments)
/// This method will be called just before registering all items in the assembly.
/// </remarks>
/// <param name="typesToScan"></param>
public void PreloadAssembly(Type[] typesToScan)
{
var types = typesToScan.Where(t => t.Name.Equals("NLogPackageLoader", StringComparison.OrdinalIgnoreCase));
foreach (var type in types)
{
CallPreload(type);
}
}
/// <summary>
/// Call the Preload method for <paramref name="type"/>. The Preload method must be static.
/// </summary>
/// <param name="type"></param>
private void CallPreload(Type type)
{
if (type == null)
{
return;
}
InternalLogger.Debug("Found for preload'{0}'", type.FullName);
var preloadMethod = type.GetMethod("Preload");
if (preloadMethod != null)
{
if (preloadMethod.IsStatic)
{
InternalLogger.Debug("NLogPackageLoader contains Preload method");
//only static, so first param null
try
{
var parameters = CreatePreloadParameters(preloadMethod, this);
preloadMethod.Invoke(null, parameters);
InternalLogger.Debug("Preload successfully invoked for '{0}'", type.FullName);
}
catch (Exception e)
{
InternalLogger.Warn(e, "Invoking Preload for '{0}' failed", type.FullName);
}
}
else
{
InternalLogger.Debug("NLogPackageLoader contains a preload method, but isn't static");
}
}
else
{
InternalLogger.Debug("{0} doesn't contain Preload method", type.FullName);
}
}
private static object[] CreatePreloadParameters(MethodInfo preloadMethod, ConfigurationItemFactory configurationItemFactory)
{
var firstParam = preloadMethod.GetParameters().FirstOrDefault();
object[] parameters = null;
if (firstParam?.ParameterType == typeof(ConfigurationItemFactory))
{
parameters = new object[] {configurationItemFactory};
}
return parameters;
}
/// <summary>
/// Clears the contents of all factories.
/// </summary>
public void Clear()
{
foreach (IFactory f in _allFactories)
{
f.Clear();
}
}
/// <summary>
/// Registers the type.
/// </summary>
/// <param name="type">The type to register.</param>
/// <param name="itemNamePrefix">The item name prefix.</param>
public void RegisterType(Type type, string itemNamePrefix)
{
foreach (IFactory f in _allFactories)
{
f.RegisterType(type, itemNamePrefix);
}
}
/// <summary>
/// Builds the default configuration item factory.
/// </summary>
/// <returns>Default factory.</returns>
private static ConfigurationItemFactory BuildDefaultFactory()
{
var nlogAssembly = typeof(ILogger).GetAssembly();
var factory = new ConfigurationItemFactory(nlogAssembly);
factory.RegisterExtendedItems();
#if !SILVERLIGHT && !NETSTANDARD1_3
try
{
var assemblyLocation = string.Empty;
var extensionDlls = ArrayHelper.Empty<string>();
var fileLocations = GetAutoLoadingFileLocations();
foreach (var fileLocation in fileLocations)
{
if (string.IsNullOrEmpty(fileLocation.Key))
continue;
if (string.IsNullOrEmpty(assemblyLocation))
assemblyLocation = fileLocation.Key;
extensionDlls = GetNLogExtensionFiles(fileLocation.Key);
if (extensionDlls.Length > 0)
{
assemblyLocation = fileLocation.Key;
break;
}
}
InternalLogger.Debug("Start auto loading, location: {0}", assemblyLocation);
LoadNLogExtensionAssemblies(factory, nlogAssembly, extensionDlls);
}
catch (System.Security.SecurityException ex)
{
InternalLogger.Warn(ex, "Seems that we do not have permission");
if (ex.MustBeRethrown())
{
throw;
}
}
catch (UnauthorizedAccessException ex)
{
InternalLogger.Warn(ex, "Seems that we do not have permission");
if (ex.MustBeRethrown())
{
throw;
}
}
InternalLogger.Debug("Auto loading done");
#endif
return factory;
}
#if !SILVERLIGHT && !NETSTANDARD1_3
private static void LoadNLogExtensionAssemblies(ConfigurationItemFactory factory, Assembly nlogAssembly, string[] extensionDlls)
{
HashSet<string> alreadyRegistered = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
nlogAssembly.FullName
};
foreach (var extensionDll in extensionDlls)
{
InternalLogger.Info("Auto loading assembly file: {0}", extensionDll);
var success = false;
try
{
var extensionAssembly = AssemblyHelpers.LoadFromPath(extensionDll);
InternalLogger.LogAssemblyVersion(extensionAssembly);
factory.RegisterItemsFromAssembly(extensionAssembly);
alreadyRegistered.Add(extensionAssembly.FullName);
success = true;
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
{
throw;
}
InternalLogger.Warn(ex, "Auto loading assembly file: {0} failed! Skipping this file.", extensionDll);
//TODO NLog 5, check MustBeRethrown()
}
if (success)
{
InternalLogger.Info("Auto loading assembly file: {0} succeeded!", extensionDll);
}
}
#if !NETSTANDARD1_0
var allAssemblies = LogFactory.CurrentAppDomain.GetAssemblies();
foreach (var assembly in allAssemblies)
{
if (assembly.FullName.StartsWith("NLog.", StringComparison.OrdinalIgnoreCase) && !alreadyRegistered.Contains(assembly.FullName))
{
factory.RegisterItemsFromAssembly(assembly);
}
if (assembly.FullName.StartsWith("NLog.Extensions.Logging,", StringComparison.OrdinalIgnoreCase)
|| assembly.FullName.StartsWith("NLog.Web,", StringComparison.OrdinalIgnoreCase)
|| assembly.FullName.StartsWith("NLog.Web.AspNetCore,", StringComparison.OrdinalIgnoreCase)
|| assembly.FullName.StartsWith("Microsoft.Extensions.Logging,", StringComparison.OrdinalIgnoreCase)
|| assembly.FullName.StartsWith("Microsoft.Extensions.Logging.Abstractions,", StringComparison.OrdinalIgnoreCase)
|| assembly.FullName.StartsWith("Microsoft.Extensions.Logging.Filter,", StringComparison.OrdinalIgnoreCase)
|| assembly.FullName.StartsWith("Microsoft.Logging,", StringComparison.OrdinalIgnoreCase))
{
LogManager.AddHiddenAssembly(assembly);
}
}
#endif
}
internal static IEnumerable<KeyValuePair<string, Assembly>> GetAutoLoadingFileLocations()
{
var nlogAssembly = typeof(ILogger).GetAssembly();
var assemblyLocation = PathHelpers.TrimDirectorySeparators(AssemblyHelpers.GetAssemblyFileLocation(nlogAssembly));
InternalLogger.Debug("Auto loading based on NLog-Assembly found location: {0}", assemblyLocation);
if (!string.IsNullOrEmpty(assemblyLocation))
yield return new KeyValuePair<string, Assembly>(assemblyLocation, nlogAssembly);
var entryAssembly = Assembly.GetEntryAssembly();
var entryLocation = PathHelpers.TrimDirectorySeparators(AssemblyHelpers.GetAssemblyFileLocation(entryAssembly));
InternalLogger.Debug("Auto loading based on GetEntryAssembly-Assembly found location: {0}", entryLocation);
if (!string.IsNullOrEmpty(entryLocation) && !string.Equals(entryLocation, assemblyLocation, StringComparison.OrdinalIgnoreCase))
yield return new KeyValuePair<string, Assembly>(entryLocation, entryAssembly);
// TODO Consider to prioritize AppDomain.PrivateBinPath
var baseDirectory = PathHelpers.TrimDirectorySeparators(LogFactory.CurrentAppDomain.BaseDirectory);
InternalLogger.Debug("Auto loading based on AppDomain-BaseDirectory found location: {0}", baseDirectory);
if (!string.IsNullOrEmpty(baseDirectory) && !string.Equals(baseDirectory, assemblyLocation, StringComparison.OrdinalIgnoreCase))
yield return new KeyValuePair<string, Assembly>(baseDirectory, null);
}
private static string[] GetNLogExtensionFiles(string assemblyLocation)
{
try
{
InternalLogger.Debug("Search for auto loading files in location: {0}", assemblyLocation);
if (string.IsNullOrEmpty(assemblyLocation))
{
return ArrayHelper.Empty<string>();
}
var extensionDlls = Directory.GetFiles(assemblyLocation, "NLog*.dll")
.Select(Path.GetFileName)
.Where(x => !x.Equals("NLog.dll", StringComparison.OrdinalIgnoreCase))
.Where(x => !x.Equals("NLog.UnitTests.dll", StringComparison.OrdinalIgnoreCase))
.Where(x => !x.Equals("NLog.Extended.dll", StringComparison.OrdinalIgnoreCase))
.Select(x => Path.Combine(assemblyLocation, x));
return extensionDlls.ToArray();
}
catch (DirectoryNotFoundException ex)
{
InternalLogger.Warn(ex, "Skipping auto loading location because assembly directory does not exist: {0}", assemblyLocation);
if (ex.MustBeRethrown())
{
throw;
}
return ArrayHelper.Empty<string>();
}
catch (System.Security.SecurityException ex)
{
InternalLogger.Warn(ex, "Skipping auto loading location because access not allowed to assembly directory: {0}", assemblyLocation);
if (ex.MustBeRethrown())
{
throw;
}
return ArrayHelper.Empty<string>();
}
catch (UnauthorizedAccessException ex)
{
InternalLogger.Warn(ex, "Skipping auto loading location because access not allowed to assembly directory: {0}", assemblyLocation);
if (ex.MustBeRethrown())
{
throw;
}
return ArrayHelper.Empty<string>();
}
}
#endif
/// <summary>
/// Registers items in NLog.Extended.dll using late-bound types, so that we don't need a reference to NLog.Extended.dll.
/// </summary>
private void RegisterExtendedItems()
{
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD
string suffix = typeof(ILogger).AssemblyQualifiedName;
string myAssemblyName = "NLog,";
var p = suffix?.IndexOf(myAssemblyName, StringComparison.OrdinalIgnoreCase);
if (p >= 0)
{
// register types
string extendedAssemblySuffix = ", NLog.Extended," + suffix.Substring(p.Value + myAssemblyName.Length);
string targetsNamespace = typeof(DebugTarget).Namespace;
_targets.RegisterNamedType("MSMQ", targetsNamespace + ".MessageQueueTarget" + extendedAssemblySuffix);
}
#endif
#if !SILVERLIGHT && !NET3_5 && !NET4_0
_layoutRenderers.RegisterNamedType("configsetting", "NLog.Extensions.Logging.ConfigSettingLayoutRenderer, NLog.Extensions.Logging");
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Hydra.Framework.ImageProcessing.Analysis.Maths
{
//
//**********************************************************************
/// <summary>
/// Gaussian function
/// </summary>
//**********************************************************************
//
public class Gaussian
{
#region Private Member Variables
//
//**********************************************************************
/// <summary>
/// Sigma
/// </summary>
//**********************************************************************
//
private double sigma_m = 1.0;
//
//**********************************************************************
/// <summary>
/// Squared Sigma
/// </summary>
//**********************************************************************
//
private double sqrSigma_m = 1.0;
#endregion
#region Constructors
//
//**********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="T:Gaussian"/> class.
/// </summary>
//**********************************************************************
//
public Gaussian()
{
}
//
//**********************************************************************
/// <summary>
/// Initialises a new instance of the <see cref="T:Gaussian"/> class.
/// </summary>
/// <param name="sigma">The sigma.</param>
//**********************************************************************
//
public Gaussian(double sigma)
{
sigma_m = sigma;
}
#endregion
#region Properties
//
//**********************************************************************
/// <summary>
/// Gets or sets the Sigma property.
/// </summary>
/// <value>The sigma.</value>
//**********************************************************************
//
public double Sigma
{
get
{
return sigma_m;
}
set
{
sigma_m = Math.Max(0.00000001, value);
sqrSigma_m = sigma_m * sigma_m;
}
}
#endregion
#region Public Methods
//
//**********************************************************************
/// <summary>
/// 1-D Gaussian function
/// </summary>
/// <param name="x">The x.</param>
/// <returns></returns>
//**********************************************************************
//
public double Function(double x)
{
return Math.Exp(x * x / (-2 * sqrSigma_m)) / (Math.Sqrt(2 * Math.PI) * sigma_m);
}
//
//**********************************************************************
/// <summary>
/// 2-D Gaussian function
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <returns></returns>
//**********************************************************************
//
public double Function2D(double x, double y)
{
return Math.Exp((x * x + y * y) / (-2 * sqrSigma_m)) / (2 * Math.PI * sqrSigma_m);
}
//
//**********************************************************************
/// <summary>
/// 1-D Gaussian kernel
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
//**********************************************************************
//
public double[] Kernel(int size)
{
//
// check for evem size and for out of range
//
if (((size % 2) == 0) ||
(size < 3) || (size > 101))
{
throw new ArgumentException();
}
// raduis
int r = size / 2;
// kernel
double[] kernel = new double[size];
//
// compute kernel
//
for (int x = -r, i = 0; i < size; x++, i++)
{
kernel[i] = Function(x);
}
return kernel;
}
//
//**********************************************************************
/// <summary>
/// 2-D Gaussian kernel
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
//**********************************************************************
//
public double[,] Kernel2D(int size)
{
//
// check for evem size and for out of range
//
if (((size % 2) == 0) ||
(size < 3) || (size > 101))
{
throw new ArgumentException();
}
// raduis
int r = size / 2;
// kernel
double[,] kernel = new double[size, size];
//
// compute kernel
//
for (int y = -r, i = 0; i < size; y++, i++)
{
for (int x = -r, j = 0; j < size; x++, j++)
{
kernel[i, j] = Function2D(x, y);
}
}
return kernel;
}
//
//**********************************************************************
/// <summary>
/// 1-D Gaussian kernel (discret)
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
//**********************************************************************
//
public int[] KernelDiscret(int size)
{
double[] kernel = Kernel(size);
double min = kernel[0], factor = min;
double minError = double.MaxValue;
//
// try some factors for more accurate discretization
//
for (int k = 1; k <= 5; k++)
{
double error = 0.0;
double f = (double) k / min;
//
// for all values
//
for (int i = 0; i < size; i++)
{
double v = kernel[i] * f;
double e = v - (int) v;
error += e * e;
}
//
// check error
//
if (error < minError)
{
minError = error;
factor = f;
}
}
int[] intKernel = new int[size];
//
// discretization
//
for (int i = 0; i < size; i++)
{
intKernel[i] = (int)(kernel[i] * factor);
}
return intKernel;
}
//
//**********************************************************************
/// <summary>
/// 2-D Gaussian kernel (discret)
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
//**********************************************************************
//
public int[,] KernelDiscret2D(int size)
{
double[,] kernel = Kernel2D(size);
double min = kernel[0, 0], max = kernel[size >> 1, size >> 1];
double factor = min;
double minError = double.MaxValue;
//
// try some factors for more accurate discretization
//
for (int k = 1; k <= 5; k++)
{
double error = 0.0;
double f = (double) k / min;
//
// avoid too large values
//
if (max * f > ushort.MaxValue)
{
f = (double) ushort.MaxValue / max;
}
//
// for each row
//
for (int i = 0; i < size; i++)
{
//
// for each column
//
for (int j = 0; j < size; j++)
{
double v = kernel[i, j] * f;
double e = v - (int) v;
error += e * e;
}
}
//
// check error
//
if (error < minError)
{
minError = error;
factor = f;
}
}
int[,] intKernel = new int[size, size];
//
// discretization
//
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
intKernel[i, j] = (int)(kernel[i, j] * factor);
}
}
return intKernel;
}
#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.Generic;
using System.Text;
using System.Resources;
using System.Collections;
using System.Text.RegularExpressions;
using System.Xml;
namespace XenAPI
{
public partial class Failure : Exception
{
public const string INTERNAL_ERROR = "INTERNAL_ERROR";
public const string MESSAGE_PARAMETER_COUNT_MISMATCH = "MESSAGE_PARAMETER_COUNT_MISMATCH";
private static ResourceManager errorDescriptions = XenAPI.FriendlyErrorNames.ResourceManager;
private readonly List<string> errorDescription;
private string errorText;
private string shortError;
public List<string> ErrorDescription
{
get
{
return errorDescription;
}
}
public string ShortMessage
{
get
{
return shortError;
}
}
public override string Message
{
get
{
return errorText;
}
}
public Failure(params string[] err)
: this(new List<string>(err))
{}
public Failure(List<string> errDescription)
{
errorDescription = errDescription;
Setup();
}
public void Setup()
{
if (ErrorDescription.Count > 0)
{
try
{
string formatString;
try
{
formatString = errorDescriptions.GetString(ErrorDescription[0]);
}
catch
{
formatString = null;
}
if (formatString == null)
{
// If we don't have a translation, just combine all the error results from the server
List<string> cleanBits = new List<string>();
foreach (string s in ErrorDescription)
{
// Only show non-empty bits of ErrorDescription.
// Also, trim the bits, since the server occasionally sends spurious newlines.
if (s.Trim().Length > 0)
{
cleanBits.Add(s.Trim());
}
}
this.errorText = string.Join(" - ", cleanBits.ToArray());
}
else
{
// We need a string array to pass to String.Format, and it must not contain the 0th element.
string[] objects = new string[ErrorDescription.Count - 1];
for (int i = 1; i < ErrorDescription.Count; i++)
objects[i - 1] = ErrorDescription[i];
this.errorText = String.Format(formatString, objects);
}
}
catch (Exception)
{
this.errorText = ErrorDescription[0];
}
try
{
shortError = errorDescriptions.GetString(ErrorDescription[0] + "-SHORT") ?? errorText;
}
catch (Exception)
{
shortError = this.errorText;
}
// now try and parse CSLG failures (these have embedded xml)
TryParseCslg();
}
}
/// <summary>
/// Tries the parse CSLG failures. These have embedded xml. The useful part (from the user's perspective) is copied to errorText.
/// </summary>
/// <returns>A value specifying whether a CSLG error was found.</returns>
private bool TryParseCslg()
{
//failure.ErrorDescription[2]:
//<StorageLinkServiceError>
// <Fault>Host ivory has not yet been added to the service. [err=Object was not found]</Fault>
// <Detail>
// <errorCode>6</errorCode>
// <messageId></messageId>
// <defaultMessage>Host ivory has not yet been added to the service. [err=Object was not found]</defaultMessage>
// <severity>2</severity>
// <errorFunction>CXSSHostUtil::getHost</errorFunction>
// <errorLine>113</errorLine>
// <errorFile>.\\xss_util_host.cpp</errorFile>
// </Detail>
// </StorageLinkServiceError>
if (ErrorDescription.Count > 2 && ErrorDescription[2] != null && ErrorDescription[0] != null && ErrorDescription[0].StartsWith("SR_BACKEND_FAILURE"))
{
Match m = Regex.Match(ErrorDescription[2], @"<StorageLinkServiceError>.*</StorageLinkServiceError>", RegexOptions.Singleline);
if (m.Success)
{
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(m.Value);
}
catch (XmlException)
{
return false;
}
XmlNodeList nodes = doc.SelectNodes("/StorageLinkServiceError/Fault");
if (nodes != null && nodes.Count > 0 && !string.IsNullOrEmpty(nodes[0].InnerText))
{
if (string.IsNullOrEmpty(errorText))
{
errorText = nodes[0].InnerText;
}
else
{
errorText = string.Format("{0} ({1})", errorText, nodes[0].InnerText);
}
return true;
}
}
}
return false;
}
public override string ToString()
{
return Message;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="OutputStreamSinkSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using Akka.Actor;
using Akka.IO;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using Xunit;
using Xunit.Abstractions;
namespace Akka.Streams.Tests.IO
{
public class OutputStreamSinkSpec :AkkaSpec
{
#region Internal classes
private sealed class VoidOutputStream : Stream
{
private readonly TestProbe _p;
public VoidOutputStream(TestProbe p)
{
_p = p;
}
public override void Flush()
{
throw new System.NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new System.NotImplementedException();
}
public override void SetLength(long value)
{
throw new System.NotImplementedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new System.NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
=> _p.Ref.Tell(ByteString.Create(buffer, offset, count).DecodeString());
public override bool CanRead { get; }
public override bool CanSeek { get; }
public override bool CanWrite { get; } = true;
public override long Length { get; }
public override long Position { get; set; }
}
private sealed class CloseOutputStream : Stream
{
private readonly TestProbe _p;
public CloseOutputStream(TestProbe p)
{
_p = p;
}
public override void Flush()
{
throw new System.NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new System.NotImplementedException();
}
public override void SetLength(long value)
{
throw new System.NotImplementedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new System.NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new System.NotImplementedException();
}
public override void Close() => _p.Ref.Tell("closed");
public override bool CanRead { get; }
public override bool CanSeek { get; }
public override bool CanWrite { get; } = true;
public override long Length { get; }
public override long Position { get; set; }
}
private sealed class CompletionOutputStream : Stream
{
private readonly TestProbe _p;
public CompletionOutputStream(TestProbe p)
{
_p = p;
}
public override void Flush()
{
throw new System.NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new System.NotImplementedException();
}
public override void SetLength(long value)
{
throw new System.NotImplementedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new System.NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
=> _p.Ref.Tell(ByteString.Create(buffer, offset, count).DecodeString());
public override void Close() => _p.Ref.Tell("closed");
public override bool CanRead { get; }
public override bool CanSeek { get; }
public override bool CanWrite { get; } = true;
public override long Length { get; }
public override long Position { get; set; }
}
#endregion
private readonly ActorMaterializer _materializer;
public OutputStreamSinkSpec(ITestOutputHelper helper) : base(Utils.UnboundedMailboxConfig, helper)
{
Sys.Settings.InjectTopLevelFallback(ActorMaterializer.DefaultConfig());
var settings = ActorMaterializerSettings.Create(Sys).WithDispatcher("akka.actor.default-dispatcher");
_materializer = Sys.Materializer(settings);
}
[Fact]
public void OutputStreamSink_must_write_bytes_to_void_OutputStream()
{
this.AssertAllStagesStopped(() =>
{
var p = CreateTestProbe();
var datas = new List<ByteString>
{
ByteString.FromString("a"),
ByteString.FromString("c"),
ByteString.FromString("c")
};
var completion = Source.From(datas)
.RunWith(StreamConverters.FromOutputStream(() => new VoidOutputStream(p)), _materializer);
p.ExpectMsg(datas[0].DecodeString());
p.ExpectMsg(datas[1].DecodeString());
p.ExpectMsg(datas[2].DecodeString());
completion.Wait(TimeSpan.FromSeconds(3));
}, _materializer);
}
[Fact]
public void OutputStreamSink_must_close_underlying_stream_when_error_received()
{
this.AssertAllStagesStopped(() =>
{
var p = CreateTestProbe();
Source.Failed<ByteString>(new Exception("Boom!"))
.RunWith(StreamConverters.FromOutputStream(() => new CloseOutputStream(p)), _materializer);
p.ExpectMsg("closed");
}, _materializer);
}
[Fact]
public void OutputStreamSink_must_close_underlying_stream_when_completion_received()
{
this.AssertAllStagesStopped(() =>
{
var p = CreateTestProbe();
Source.Empty<ByteString>()
.RunWith(StreamConverters.FromOutputStream(() => new CompletionOutputStream(p)), _materializer);
p.ExpectMsg("closed");
}, _materializer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Order;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running;
using GraphQL.Execution;
using GraphQL.Language;
using GraphQL.Language.AST;
using GraphQL.StarWars;
using GraphQL.StarWars.Types;
using GraphQL.SystemTextJson;
using GraphQL.Types;
using GraphQL.Validation;
using GraphQLParser.AST;
using Microsoft.Extensions.DependencyInjection;
namespace GraphQL.Benchmarks
{
[MemoryDiagnoser]
[Config(typeof(BenchmarkConfig))]
//[RPlotExporter, CsvMeasurementsExporter]
public class DetailedBenchmark : IBenchmark
{
private class BenchmarkConfig : ManualConfig
{
public BenchmarkConfig()
{
Orderer = new GroupbyQueryOrderer();
}
private class GroupbyQueryOrderer : IOrderer
{
public IEnumerable<BenchmarkCase> GetExecutionOrder(ImmutableArray<BenchmarkCase> benchmarksCase) => benchmarksCase;
public IEnumerable<BenchmarkCase> GetSummaryOrder(ImmutableArray<BenchmarkCase> benchmarksCase, Summary summary) => benchmarksCase;
public string GetHighlightGroupKey(BenchmarkCase benchmarkCase) => null;
public string GetLogicalGroupKey(ImmutableArray<BenchmarkCase> allBenchmarksCases, BenchmarkCase benchmarkCase) => benchmarkCase.Descriptor.WorkloadMethodDisplayInfo;
public IEnumerable<IGrouping<string, BenchmarkCase>> GetLogicalGroupOrder(IEnumerable<IGrouping<string, BenchmarkCase>> logicalGroups) => logicalGroups;
public bool SeparateLogicalGroups => true;
}
}
private BenchmarkInfo _bIntrospection;
private BenchmarkInfo _bHero;
private BenchmarkInfo _bVariable;
private BenchmarkInfo _bLiteral;
private readonly DocumentExecuter _documentExecuter = new DocumentExecuter();
[GlobalSetup]
public void GlobalSetup()
{
Func<ISchema> starWarsSchemaBuilder = () =>
{
var services = new ServiceCollection();
services.AddSingleton<StarWarsData>();
services.AddSingleton<StarWarsQuery>();
services.AddSingleton<StarWarsMutation>();
services.AddSingleton<HumanType>();
services.AddSingleton<HumanInputType>();
services.AddSingleton<DroidType>();
services.AddSingleton<CharacterInterface>();
services.AddSingleton<EpisodeEnum>();
services.AddSingleton<ISchema, StarWarsSchema>();
var provider = services.BuildServiceProvider();
var schema = provider.GetRequiredService<ISchema>();
schema.Initialize();
return schema;
};
_bIntrospection = new BenchmarkInfo(Queries.Introspection, null, starWarsSchemaBuilder);
_bHero = new BenchmarkInfo(Queries.Hero, null, starWarsSchemaBuilder);
Func<ISchema> variableSchemaBuilder = () =>
{
var services = new ServiceCollection();
services.AddSingleton<VariableBenchmark.MyQueryGraphType>();
services.AddSingleton<VariableBenchmark.MyInputObjectGraphType>();
services.AddSingleton<VariableBenchmark.MySubInputObjectGraphType>();
services.AddSingleton<ISchema, VariableBenchmark.MySchema>();
var provider = services.BuildServiceProvider();
var schema = provider.GetRequiredService<ISchema>();
schema.Initialize();
return schema;
};
_bVariable = new BenchmarkInfo(Queries.VariablesVariable, Benchmarks.Variables.VariablesVariable, variableSchemaBuilder);
_bLiteral = new BenchmarkInfo(Queries.VariablesLiteral, null, variableSchemaBuilder);
}
[Benchmark]
public void Introspection()
{
Run(_bIntrospection);
}
[Benchmark]
public void Hero()
{
Run(_bHero);
}
[Benchmark]
public void Variables()
{
Run(_bVariable);
}
[Benchmark]
public void Literal()
{
Run(_bLiteral);
}
private void Run(BenchmarkInfo benchmarkInfo)
{
switch (Stage)
{
case StageEnum.Build:
benchmarkInfo.BuildSchema();
break;
case StageEnum.TypicalExecution:
_documentExecuter.ExecuteAsync(o =>
{
o.Schema = benchmarkInfo.Schema;
o.Query = benchmarkInfo.Query;
o.Inputs = benchmarkInfo.InputsString?.ToInputs();
}).GetAwaiter().GetResult();
break;
case StageEnum.Parse:
benchmarkInfo.Parse();
break;
case StageEnum.Convert:
benchmarkInfo.Convert();
break;
case StageEnum.Validate:
benchmarkInfo.Validate();
break;
case StageEnum.DeserializeVars:
benchmarkInfo.DeserializeInputs();
break;
case StageEnum.ParseVariables:
benchmarkInfo.ParseVariables();
break;
case StageEnum.Execute:
benchmarkInfo.Execute();
break;
case StageEnum.Serialize:
benchmarkInfo.Serialize();
break;
default:
throw new InvalidOperationException();
}
}
//[Params(StageEnum.Build, StageEnum.TypicalExecution, StageEnum.Serialize)]
[Params(StageEnum.Build, StageEnum.Parse, StageEnum.Convert, StageEnum.Validate, StageEnum.DeserializeVars, StageEnum.ParseVariables, StageEnum.Execute, StageEnum.Serialize)]
public StageEnum Stage { get; set; }
void IBenchmark.RunProfiler()
{
Stage = StageEnum.Build;
Introspection();
}
public enum StageEnum
{
Build,
Parse,
Convert,
Validate,
DeserializeVars,
ParseVariables,
Execute,
Serialize,
TypicalExecution,
}
public class BenchmarkInfo
{
public ISchema Schema;
public Func<ISchema> SchemaBuilder;
public string Query;
public string InputsString;
public GraphQLDocument GraphQLDocument;
public Document Document;
public Operation Operation;
public Inputs Inputs;
public Language.AST.Variables Variables;
public ExecutionResult ExecutionResult;
public BenchmarkInfo(string query, string inputs, Func<ISchema> schemaBuilder)
{
// this exercises all the code in case of any errors, in addition to prep for each stage of testing
SchemaBuilder = schemaBuilder;
Schema = BuildSchema();
Query = query;
GraphQLDocument = Parse();
Document = Convert();
Operation = Document.Operations.FirstOrDefault();
InputsString = inputs;
Inputs = DeserializeInputs();
Variables = ParseVariables();
ExecutionResult = Execute();
_ = Serialize();
}
public ISchema BuildSchema()
{
return SchemaBuilder();
}
public GraphQLDocument Parse()
{
return GraphQLParser.Parser.Parse(Query, new GraphQLParser.ParserOptions { Ignore = GraphQLParser.IgnoreOptions.IgnoreComments });
}
public Document Convert()
{
return CoreToVanillaConverter.Convert(GraphQLDocument);
}
public Inputs DeserializeInputs()
{
return InputsString?.ToInputs();
}
public Language.AST.Variables ParseVariables()
{
return Inputs == null ? null : new ValidationContext().GetVariableValues(Schema, Operation.Variables, Inputs);
}
private static readonly DocumentValidator _documentValidator = new DocumentValidator();
public IValidationResult Validate()
{
return _documentValidator.ValidateAsync(
Schema,
Document,
null,
null,
Inputs).Result.validationResult;
}
private static readonly ParallelExecutionStrategy _parallelExecutionStrategy = new ParallelExecutionStrategy();
public ExecutionResult Execute()
{
var context = new ExecutionContext
{
Document = Document,
Schema = Schema,
RootValue = null,
UserContext = new Dictionary<string, object>(),
Operation = Operation,
Variables = Variables,
Errors = new ExecutionErrors(),
Extensions = new Dictionary<string, object>(),
CancellationToken = default,
Metrics = Instrumentation.Metrics.None,
Listeners = new List<IDocumentExecutionListener>(),
ThrowOnUnhandledException = true,
UnhandledExceptionDelegate = context => { },
MaxParallelExecutionCount = int.MaxValue,
RequestServices = null
};
return _parallelExecutionStrategy.ExecuteAsync(context).Result;
}
private static readonly DocumentWriter _documentWriter = new DocumentWriter();
public System.IO.MemoryStream Serialize()
{
var mem = new System.IO.MemoryStream();
_documentWriter.WriteAsync(mem, ExecutionResult).GetAwaiter().GetResult();
mem.Position = 0;
return mem;
}
}
}
}
| |
//Copyright ?2014 Sony Computer Entertainment America LLC. See License.txt.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Threading;
using Sce.Atf.Applications.Controls;
using Sce.Atf.Controls;
using Keys = Sce.Atf.Input.Keys;
namespace Sce.Atf.Applications
{
/// <summary>
/// Service to handle commands in menus and toolbars</summary>
[Export(typeof(ICommandService))]
[Export(typeof(IInitializable))]
[Export(typeof(CommandService))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class CommandService : CommandServiceBase
{
/// <summary>
/// Constructor</summary>
/// <param name="mainForm">Main application form</param>
[ImportingConstructor]
public CommandService(Form mainForm)
{
m_mainForm = mainForm;
m_mainForm.Load += mainForm_Load;
m_mainMenuStrip = new MenuStrip();
m_mainMenuStrip.Name = "Main Menu";
m_mainMenuStrip.Dock = DockStyle.Top;
}
#region IInitializable Members
/// <summary>
/// Finishes initializing component by subscribing to event</summary>
public override void Initialize()
{
base.Initialize();
// Application idle event is a convenient time to update toolbar button state
Application.Idle += Application_Idle;
}
#endregion
#region ICommandService Members
/// <summary>
/// Registers a command for a command client</summary>
/// <param name="info">Command description; standard commands are defined as static
/// members on the CommandInfo class</param>
/// <param name="client">Client that handles the command</param>
public override void RegisterCommand(CommandInfo info, ICommandClient client)
{
// Use cloned one if the command info is already taken by somebody else
if (info.CommandService != null)
info = info.Clone();
base.RegisterCommand(info, client);
if (info != null && client != null && info.CheckCanDoClients.Contains(client))
{
m_checkCanDoClients.Add(info, client);
m_checkCanDoClientsToUpdate.Add(info);
}
m_commandsSorted = false;
}
/// <summary>
/// Unregisters a command for a command client</summary>
/// <param name="commandTag">Command tag that identifies CommandInfo used to register
/// the command</param>
/// <param name="client">Client that handles the command</param>
public override void UnregisterCommand(object commandTag, ICommandClient client)
{
CommandInfo info = GetCommandInfo(commandTag);
if (info != null && client != null && info.CheckCanDoClients.Contains(client))
{
m_checkCanDoClients.Remove(info, client);
m_checkCanDoClientsToUpdate.Remove(info);
}
base.UnregisterCommand(commandTag, client);
RemoveToolStripItem(commandTag);
}
/// <summary>
/// Decrements the count of commands associated with the specified MenuInfo</summary>
/// <param name="menuInfo">MenuInfo whose command count is decremented</param>
protected override void DecrementMenuCommandCount(MenuInfo menuInfo)
{
base.DecrementMenuCommandCount(menuInfo);
if (menuInfo.Commands == 0)
m_menuToolStripItems[menuInfo].Visible = false;
}
/// <summary>
/// Creates and returns a context (right click popup) menu.
/// Does not raise any events.</summary>
/// <param name="commandTags">Commands in menu; nulls indicate separators</param>
/// <returns>ContextMenuStrip for context menu</returns>
public ContextMenuStrip CreateContextMenu(IEnumerable<object> commandTags)
{
ContextMenuStrip contextMenu = new ContextMenuStrip();
int itemCount;
foreach (object commandTag in commandTags)
{
// check for separator
if (commandTag == null)
{
itemCount = contextMenu.Items.Count;
if (itemCount > 0 &&
!(contextMenu.Items[itemCount - 1] is ToolStripSeparator))
{
contextMenu.Items.Add(new ToolStripSeparator());
}
continue;
}
// add the command and sort it by groups since the last separator
CommandInfo info = GetCommandInfo(commandTag);
if (info != null && (info.Visibility & CommandVisibility.ContextMenu) != 0)
{
// allow client to update command appearance
UpdateCommand(info);
var menuItem = info.GetMenuItem();
if (menuItem.Enabled || !ContextMenuAutoCompact)
{
ToolStripItemCollection commands = BuildSubMenus(contextMenu.Items, info);
ToolStripMenuItem clone = new ToolStripMenuItem();
clone.Text = menuItem.Text;
clone.Image = menuItem.Image;
clone.Name = menuItem.Name;
clone.Enabled = menuItem.Enabled;
clone.Checked = menuItem.Checked;
clone.Tag = menuItem.Tag;
clone.ToolTipText = menuItem.ToolTipText;
clone.ShortcutKeys = menuItem.ShortcutKeys;
clone.ShortcutKeyDisplayString = menuItem.ShortcutKeyDisplayString;
clone.Click += contextMenu_itemClick;
clone.ForeColor = m_mainMenuStrip.ForeColor;
clone.CheckOnClick = info.CheckOnClick;
commands.Add(clone);
MaintainSeparateGroups(commands, clone, info.GroupTag);
}
}
}
// Remove trailing separator.
itemCount = contextMenu.Items.Count;
if (itemCount > 0 &&
(contextMenu.Items[itemCount - 1] is ToolStripSeparator))
{
contextMenu.Items.RemoveAt(itemCount - 1);
}
SkinService.ApplyActiveSkin(contextMenu);
return contextMenu;
}
/// <summary>
/// Runs a context (right click popup) menu at the given screen point. Raises
/// ContextMenuClosed events.</summary>
/// <param name="commandTags">Commands in menu; nulls indicate separators</param>
/// <param name="screenPoint">Point in screen coordinates</param>
public override void RunContextMenu(IEnumerable<object> commandTags, Point screenPoint)
{
ContextMenuStrip contextMenu = CreateContextMenu(commandTags);
contextMenu.Show(screenPoint);
if (contextMenu.Visible)
contextMenu.Closed += contextMenu_Closed;
else
contextMenu_Closed(contextMenu, new ToolStripDropDownClosedEventArgs(ToolStripDropDownCloseReason.CloseCalled));
}
#endregion
#region ICommandClient Members
/// <summary>
/// Checks whether the client can do the command if it handles it</summary>
/// <param name="commandTag">Command to be done</param>
/// <returns>True if client can do the command</returns>
public override bool CanDoCommand(object commandTag)
{
return CommandId.EditKeyboard.Equals(commandTag);
}
/// <summary>
/// Does the command</summary>
/// <param name="commandTag">Command to be done</param>
public override void DoCommand(object commandTag)
{
if (CommandId.EditKeyboard.Equals(commandTag))
{
// Prepare a list of Shortcut objects to use to populate dialog box and to hold results
var shortcuts = new List<CustomizeKeyboardDialog.Shortcut>();
foreach (KeyValuePair<object, CommandInfo> kvp in m_commandsById)
{
// skip over command without client
if (GetClient(kvp.Value.CommandTag) == null )
continue;
if (!kvp.Value.ShortcutsEditable)
continue;
string commandPath = GetCommandPath(kvp.Value);
var shortcutInfo = new CustomizeKeyboardDialog.Shortcut(kvp.Value, commandPath);
shortcuts.Add(shortcutInfo);
}
CustomizeKeyboardDialog dialog = new CustomizeKeyboardDialog(shortcuts, m_reservedKeys);
dialog.ShowDialog(m_mainForm);
if (dialog.DialogResult == DialogResult.OK && dialog.Modified)
{
// commit changes
m_shortcuts.Clear();
foreach (CustomizeKeyboardDialog.Shortcut shortcutInfo in shortcuts)
{
// We have to clear them all, then add them one-by-one.
shortcutInfo.Info.ClearShortcuts();
foreach (Keys keys in shortcutInfo.Keys)
SetShortcut(keys, shortcutInfo.Info);
}
}
}
}
#endregion
/// <summary>
/// Helper function to return properly sized images based on user preferences</summary>
/// <param name="imageName">Image name</param>
/// <returns>Image of given name</returns>
public Image GetProperlySizedImage(string imageName)
{
Image image = null;
if (!string.IsNullOrEmpty(imageName))
{
if (m_imageSize == ImageSizes.Size16x16)
image = ResourceUtil.GetImage16(imageName);
else if (m_imageSize == ImageSizes.Size24x24)
image = ResourceUtil.GetImage24(imageName);
else if (m_imageSize == ImageSizes.Size32x32)
image = ResourceUtil.GetImage32(imageName);
}
return image;
}
/// <summary>
/// Handler for image size changed event for derived classes to override</summary>
protected override void OnImageSizeChanged()
{
RefreshImages();
}
/// <summary>
/// This function refreshes all images associated with registered commands.
/// This is particularly useful when application image sizes change, and
/// when a skin that modifies images is loaded.</summary>
public override void RefreshImages()
{
foreach (CommandInfo info in m_commands)
{
RefreshImage(info);
}
}
/// <summary>
/// This function redraws a particular menu item's icon. This is useful if only a
/// specific icon has been changed; for example, on mouseover.</summary>
/// <param name="info">The command whose icon needs a refresh</param>
public override void RefreshImage(CommandInfo info)
{
Image image = GetProperlySizedImage(info.ImageName);
if (image != null)
{
var button = info.GetButton();
button.AutoSize = true;
button.ImageScaling = ToolStripItemImageScaling.None;
button.Image = image;
// Update the menu image too, but don't set AutoSize, as the menu icons
// should always stay the same size.
var menu = info.GetMenuItem();
menu.Image = image;
}
}
/// <summary>
/// Occurs when the right-click context menu has closed. Is always raised after
/// RunContextMenu returns.</summary>
public event EventHandler ContextMenuClosed;
/// <summary>
/// Populates menu control and toolbar with all registered menus and commands</summary>
public void BuildDefaultMenusAndToolbars()
{
// try to get toolstrip container for toolbars
if (m_toolStripContainer == null)
{
foreach (Control control in m_mainForm.Controls)
{
m_toolStripContainer = control as ToolStripContainer;
if (m_toolStripContainer != null)
break;
}
}
// build menus (but not their contents)
m_mainMenuStrip.SuspendLayout();
m_mainMenuStrip.Items.Clear();
foreach (MenuInfo menuInfo in m_menus)
{
ToolStripMenuItem menuItem = m_menuToolStripItems[menuInfo];
menuItem.DropDownItems.Add("Dummy"); // to trigger drop down
// we will build the menu just-in-time, when its drop down is opening
menuItem.DropDownOpening += menuItem_DropDownOpening;
// we will clear the menu when it's closed
menuItem.DropDownClosed += menuItem_DropDownClosed;
m_mainMenuStrip.Items.Add(menuItem);
}
m_mainMenuStrip.ResumeLayout();
m_mainMenuStrip.PerformLayout();
// build toolbars
var toolStrips = new List<ToolStrip>();
for (int i = m_menus.Count - 1; i >= 0; i--)
{
MenuInfo menuInfo = m_menus[i];
ToolStrip toolStrip = menuInfo.GetToolStrip();
toolStrips.Add(toolStrip);
foreach (CommandInfo commandInfo in m_commands)
{
if (TagsEqual(menuInfo.MenuTag, commandInfo.MenuTag))
{
if ((commandInfo.Visibility & CommandVisibility.Toolbar) != 0 &&
GetClient(commandInfo.CommandTag) != null)
{
ToolStripButton btn = commandInfo.GetButton();
if (commandInfo.CheckOnClick)
{
btn.CheckOnClick = true;
commandInfo.GetMenuItem().CheckOnClick = true;
btn.CheckedChanged += SynchronizeCheckedState;
commandInfo.GetMenuItem().CheckedChanged += SynchronizeCheckedState;
}
toolStrip.Items.Add(btn);
}
}
}
toolStrip.Dock = DockStyle.None;
AddCustomizationDropDown(toolStrip);
toolStrip.Visible = (toolStrip.Items.Count > 1);
}
if (m_toolStripContainer != null)
{
m_toolStripContainer.TopToolStripPanel.Controls.AddRange(toolStrips.ToArray());
m_toolStripContainer.TopToolStripPanel.Controls.Add(m_mainMenuStrip);
}
else
{
m_mainForm.Controls.Add(m_mainMenuStrip);
}
}
/// <summary>
/// Forces an update for the command associated with the given tag.</summary>
/// <param name="commandTag">Command's tag object</param>
protected override void UpdateCommand(object commandTag)
{
CommandInfo info = GetCommandInfo(commandTag);
if (info != null)
UpdateCommand(info);
//Console.WriteLine("forced update for: " + (info != null ? info.Description : "<unknown>"));
}
/// <summary>
/// Force an update on a particular command</summary>
/// <param name="info">Command to update</param>
public void UpdateCommand(CommandInfo info)
{
ICommandClient client = GetClientOrActiveClient(info.CommandTag);
UpdateCommand(info, client);
}
private void UpdateCommand(CommandInfo info, ICommandClient client)
{
if (m_mainForm.InvokeRequired)
{
m_mainForm.BeginInvoke(new Action<CommandInfo>(UpdateCommand), info);
return;
}
ToolStripMenuItem menuItem;
ToolStripButton menuButton;
info.GetMenuItemAndButton(out menuItem, out menuButton);
CommandState commandState = new CommandState();
commandState.Text = info.DisplayedMenuText;
commandState.Check = menuItem.Checked;
bool enabled = false;
if (client != null)
{
enabled = client.CanDoCommand(info.CommandTag);
if (enabled)
client.UpdateCommand(info.CommandTag, commandState);
}
string menuText = commandState.Text.Trim();
menuItem.Text = menuButton.Text = menuText;
menuItem.Checked = menuButton.Checked = commandState.Check;
menuItem.Enabled = menuButton.Enabled = enabled;
}
// Synchronize Checked state between the menu and button
private void SynchronizeCheckedState(object sender, EventArgs e)
{
if (sender is ToolStripButton)
{
var checkedPair = m_commandControls.FirstOrDefault(x => x.Value.Button == sender);
if (checkedPair.Value != null)
{
checkedPair.Value.MenuItem.Checked = checkedPair.Value.Button.Checked;
}
}
else if (sender is ToolStripMenuItem)
{
var checkedPair = m_commandControls.FirstOrDefault(x => x.Value.MenuItem == sender);
if (checkedPair.Value != null)
{
checkedPair.Value.Button.Checked = checkedPair.Value.MenuItem.Checked;
}
}
}
// wait until latest possible time to build menus and toolbars
private void mainForm_Load(object sender, EventArgs e)
{
BuildDefaultMenusAndToolbars();
}
private void menuItem_DropDownOpening(object sender, EventArgs e)
{
// make sure commands are sorted
if (!m_commandsSorted)
{
m_commands.Sort(new CommandComparer());
m_commandsSorted = true;
}
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
menuItem.DropDownItems.Clear();
MenuInfo menuInfo = GetMenuInfo(menuItem.Tag);
foreach (CommandInfo commandInfo in m_commands)
{
if (TagsEqual(commandInfo.MenuTag, menuInfo.MenuTag) &&
(commandInfo.Visibility & CommandVisibility.ApplicationMenu) != 0 &&
GetClient(commandInfo.CommandTag) != null)
{
AddMenuCommand(menuItem.DropDownItems, commandInfo);
menuItem.DropDown.BackColor = m_mainMenuStrip.BackColor;
}
}
}
private void menuItem_DropDownClosed(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
menuItem.DropDownItems.Clear();
menuItem.DropDownItems.Add("Dummy"); // to trigger drop down
}
private void item_Click(object sender, EventArgs e)
{
// See if the user clicked the icon portion of the menu item and set the IconClicked property that
// interested commands can check.
IconClicked = IsMouseOverIcon(sender as ToolStripItem);
// clear status text
if (m_statusService != null)
m_statusService.ShowStatus(string.Empty);
ToolStripItem item = sender as ToolStripItem;
object tag = item.Tag;
if (tag != null)
{
ICommandClient client = GetClientOrActiveClient(tag);
if (client != null && client.CanDoCommand(tag))
client.DoCommand(tag);
}
IconClicked = false;
}
/// <summary>
/// Gets or sets whether a context menu is triggering</summary>
public static bool ContextMenuIsTriggering { get; set; }
private void contextMenu_itemClick(object sender, EventArgs e)
{
ContextMenuIsTriggering = true;
item_Click(sender, e);
ContextMenuIsTriggering = false;
}
private void menuItem_MouseEnter(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
object tag = menuItem.Tag;
if (tag != null)
{
CommandInfo commandInfo = m_commandsById[tag];
if (m_statusService != null)
m_statusService.ShowStatus(commandInfo.Description);
}
}
private void menuItem_MouseMove(object sender, MouseEventArgs e)
{
m_menuMouseLocation = e.Location;
var menuItem = sender as ToolStripMenuItem;
if (menuItem != null)
{
object tag = menuItem.Tag;
if ((tag != null) && (tag is IPinnable))
{
if (IsMouseOverIcon(menuItem))
m_mouseIsOverCommandIcon = m_commandsById[tag];
else
m_mouseIsOverCommandIcon = null;
CommandState commandState = new CommandState(menuItem.Text, menuItem.Checked);
UpdatePinnableCommand(tag, commandState);
}
}
}
private void menuItem_MouseLeave(object sender, EventArgs e)
{
// clear status text
if (m_statusService != null)
m_statusService.ShowStatus(string.Empty);
// Clear mouseover status
m_menuMouseLocation = Point.Empty;
m_mouseIsOverCommandIcon = null;
var menuItem = sender as ToolStripMenuItem;
if (menuItem != null)
{
object tag = menuItem.Tag;
if ((tag != null) && (tag is IPinnable))
{
CommandState commandState = new CommandState(menuItem.Text, menuItem.Checked);
UpdatePinnableCommand(tag, commandState);
}
}
}
/// <summary>
/// Utility function to get the command's client and call UpdateCommand.</summary>
/// <param name="commandTag">The command to update</param>
/// <param name="state">Command's state</param>
private void UpdatePinnableCommand(object commandTag, CommandState state)
{
ICommandClient client = GetClientOrActiveClient(commandTag);
if (client != null && client.CanDoCommand(commandTag))
client.UpdateCommand(commandTag, state);
}
/// <summary>
/// Indicates which command's icon the mouse is currently over, or null if none. This can be used to
/// modify a menu icon on mouseover.</summary>
public override CommandInfo MouseIsOverCommandIcon
{
get { return m_mouseIsOverCommandIcon; }
}
/// <summary>
/// Determines whether the mouse pointer is currently over the icon portion of the menu item</summary>
private bool IsMouseOverIcon(ToolStripItem menuItem)
{
// NOTE: There doesn't appear to be a way to test against the actual current position and size of
// the icon, as menuItem.Image.GetBounds() returns the size of the image that was assigned to the
// menu, not the (possibly scaled) size it's actually displayed at. So this uses various other
// settings to yield a "good enough" result. Should revisit at some point and see if there's a
// more direct/precise way to do this.
if ((menuItem != null) && (m_menuMouseLocation != Point.Empty))
{
if (menuItem.Image != null)
{
var contentBounds = menuItem.ContentRectangle;
var iconBounds = new Rectangle(new Point(contentBounds.Left, contentBounds.Top), SystemInformation.MenuButtonSize);
if (m_menuMouseLocation.X > iconBounds.Left && m_menuMouseLocation.X <= iconBounds.Right)
{
return true;
}
}
}
return false;
}
/// <summary>
/// Updates tool bar buttons when application goes idle</summary>
private void Application_Idle(object sender, EventArgs e)
{
// Don't use 'foreach', in case commands are registered during UpdateCommand().
for (int i = 0; i < m_commands.Count; ++i)
{
CommandInfo info = m_commands[i];
ICommandClient client = GetClientOrActiveClient(info.CommandTag);
if (client != null && m_checkCanDoClients.ContainsKeyValue(info, client))
continue;
UpdateCommand(info, client);
}
// Update CommandInfos "on demand", in response to their ICommandClients.
if (m_checkCanDoClientsToUpdate.Count > 0)
{
CommandInfo[] additionalInfos = m_checkCanDoClientsToUpdate.ToArray();
foreach (CommandInfo info in additionalInfos)
{
// duplicate CommandInfos don't get added to m_commands
if (info.CommandService != null)
UpdateCommand(info);
}
m_checkCanDoClientsToUpdate.Clear();
}
}
private void OnCheckCanDo(object sender, EventArgs e)
{
m_checkCanDoClientsToUpdate.Add((CommandInfo) sender);
}
private void contextMenu_Closed(object sender, ToolStripDropDownClosedEventArgs e)
{
if (ContextMenuClosed != null)
ContextMenuClosed(this, e);
}
/// <summary>
/// Adds a customization drop down menu to the tool strip. Check if this drop down button
/// is already present, in case the standard menus are setup twice (which happens in Legacy applications).</summary>
private void AddCustomizationDropDown(ToolStrip toolStrip)
{
string customizeText = "Customize".Localize();
foreach (ToolStripItem item in toolStrip.Items)
if (item.Text == customizeText)
return;
ToolStripDropDownButton button = new ToolStripDropDownButton(customizeText);
button.Name = toolStrip.Name;
button.Overflow = ToolStripItemOverflow.Always;
button.DropDownOpening += button_DropDownOpening;
toolStrip.Items.Add(button);
}
private void button_DropDownOpening(object sender, EventArgs e)
{
ToolStripDropDownButton button = sender as ToolStripDropDownButton;
button.DropDownItems.Clear();
ContextMenuStrip contextMenu = new ContextMenuStrip();
contextMenu.ItemClicked += contextMenu_DropDownItemClicked;
contextMenu.Closing += contextMenu_Closing;
ToolStrip toolStrip = button.Owner;
foreach (ToolStripItem item in toolStrip.Items)
{
if (item is ToolStripSeparator)
continue;
if (item == button) // can't customize customization!
continue;
ToolStripMenuItem menuItem = new ToolStripMenuItem(item.Text);
menuItem.Checked = item.Visible;
menuItem.Tag = item;
contextMenu.Items.Add(menuItem);
}
button.DropDown = contextMenu;
}
private void contextMenu_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
ToolStripMenuItem menuItem = e.ClickedItem as ToolStripMenuItem;
ToolStripItem item = e.ClickedItem.Tag as ToolStripItem;
item.Visible = !item.Visible; // toggle
menuItem.Checked = !menuItem.Checked;
}
private void contextMenu_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked)
{
// allow multiple items to be selected before closing menu
e.Cancel = true;
}
else
{
// remove drop down menu
ContextMenuStrip contextMenu = sender as ContextMenuStrip;
ToolStripDropDownButton button = contextMenu.OwnerItem as ToolStripDropDownButton;
button.DropDown = null;
}
}
private void RemoveToolStripItem(object commandTag)
{
if (m_toolStripContainer != null)
{
RemoveToolStripItem(commandTag, m_toolStripContainer.LeftToolStripPanel);
RemoveToolStripItem(commandTag, m_toolStripContainer.TopToolStripPanel);
RemoveToolStripItem(commandTag, m_toolStripContainer.RightToolStripPanel);
RemoveToolStripItem(commandTag, m_toolStripContainer.BottomToolStripPanel);
}
}
private void RemoveToolStripItem(object commandTag, ToolStripPanel panel)
{
foreach (ToolStrip toolStrip in panel.Controls)
{
foreach (ToolStripItem item in toolStrip.Items)
{
if (item.Tag == commandTag)
{
toolStrip.Items.Remove(item);
return; // there should be only one occurrence
}
}
}
}
// Adds a command to menus
private void AddMenuCommand(ToolStripItemCollection commands, CommandInfo info)
{
// make sure all necessary sub-menus exist, and get command collection to hold this command
commands = BuildSubMenus(commands, info);
var menuItem = info.GetMenuItem();
menuItem.BackColor = m_mainMenuStrip.BackColor;
menuItem.ForeColor = m_mainMenuStrip.ForeColor;
commands.Add(menuItem);
MaintainSeparateGroups(commands, menuItem, info.GroupTag);
}
// Ensures that submenus exist to hold command
private ToolStripItemCollection BuildSubMenus(ToolStripItemCollection commands, CommandInfo info)
{
string menuText = info.MenuText;
string[] segments;
if (menuText[0] == '@')
segments = new[] { menuText.Substring(1, menuText.Length - 1) };
else
segments = menuText.Split(s_pathDelimiters, 8);
for (int i = 0; i < segments.Length - 1; i++)
{
string segment = segments[i];
ToolStripMenuItem subMenu = null;
for (int j = 0; j < commands.Count; j++)
{
if (segment == commands[j].Text)
{
subMenu = commands[j] as ToolStripMenuItem;
if (subMenu != null)
break;
}
}
if (subMenu == null)
{
subMenu = new ToolStripMenuItem(segment);
subMenu.Name = segment;
commands.Add(subMenu);
MaintainSeparateGroups(commands, subMenu, info.GroupTag);
}
subMenu.BackColor = m_mainMenuStrip.BackColor;
subMenu.ForeColor = m_mainMenuStrip.ForeColor;
commands = subMenu.DropDownItems;
}
return commands;
}
// Maintains separators between different command groups
private void MaintainSeparateGroups(ToolStripItemCollection commands, ToolStripItem item, object groupTag)
{
int index = commands.IndexOf(item);
if (index > 0) // look for previous item
{
ToolStripItem prevItem = commands[index - 1];
object prevTag = prevItem.Tag;
while (prevTag == null)
{
ToolStripMenuItem prevMenuItem = prevItem as ToolStripMenuItem;
if (prevMenuItem == null)
break;
ToolStripItemCollection prevItems = prevMenuItem.DropDownItems;
prevItem = prevItems[prevItems.Count - 1];
prevTag = prevItem.Tag;
}
// add a separator if the new command is from a different group
CommandInfo prevInfo = GetCommandInfo(prevTag);
if (prevInfo != null &&
!TagsEqual(groupTag, prevInfo.GroupTag))
{
commands.Insert(index, new ToolStripSeparator());
}
}
}
/// <summary>
/// Adds this MenuInfo object to m_menus field and creates a ToolStrip for it</summary>
/// <param name="info">MenuInfo object to add</param>
sealed protected override void RegisterMenuInfo(MenuInfo info)
{
base.RegisterMenuInfo(info);
// If it wasn't already done, create a WinForms ToolStrip for this MenuInfo
ToolStrip toolStrip;
if (m_menuToolStrips.TryGetValue(info, out toolStrip) == false)
{
toolStrip = new ToolStripEx();
toolStrip.MouseHover += ToolStripOnMouseHover;
m_menuToolStrips.Add(info, toolStrip);
}
// build toolbar corresponding to menu
{
string str = info.MenuText.Replace("&", "");
str = str.Replace(";", "");
toolStrip.Name = str + "_toolbar";
toolStrip.AllowItemReorder = true; // magic, to enable customization with Alt key
}
// build menu
ToolStripMenuItem menuItem = new ToolStripMenuItem(info.MenuText);
menuItem.Visible = false;
menuItem.Name = info.MenuText + "_menu";
menuItem.Tag = info.MenuTag;
m_menuToolStripItems.Add(info, menuItem);
// Associate the registered MenuInfo with this CommandService. Only can be registered once.
info.CommandService = this;
}
/// <summary>
/// Processes the key as a command shortcut</summary>
/// <param name="key">Key to process</param>
/// <returns>True iff the key was processed as a command shortcut</returns>
public override bool ProcessKey(Keys key)
{
if (key == Keys.F1 && m_lastHoveringToolStrip != null)
{
foreach (var item in m_lastHoveringToolStrip.Items)
{
var button = item as ToolStripButton;
if (button != null)
{
if (button.Selected)
{
foreach (KeyValuePair<CommandInfo, CommandControls> commandAndControl in m_commandControls)
{
if (commandAndControl.Value.Button == button &&
!string.IsNullOrEmpty(commandAndControl.Key.HelpUrl))
{
// There doesn't seem to be a way to prevent the WM_HELP message that gets generated
// during the call to Process.Start(). We can't add a filter to every Control's
// WndProc. So, let's use a static way of stopping WebHelp for a little bit.
WebHelp.SupressHelpRequests = true;
Process.Start(commandAndControl.Key.HelpUrl);
if (m_webHelpTimer == null)
{
m_webHelpTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) };
m_webHelpTimer.Tick +=
(o, e) =>
{
WebHelp.SupressHelpRequests = false;
m_webHelpTimer.Stop();
};
}
m_webHelpTimer.Start();
return true;
}
}
}
}
}
}
return base.ProcessKey(key);
}
private void ToolStripOnMouseHover(object sender, EventArgs eventArgs)
{
m_lastHoveringToolStrip = (ToolStripEx)sender;
}
// Update the WinForms controls when a command's shortcuts have changed
static private void commandInfo_ShortcutsChanged(object sender, System.EventArgs e)
{
var info = (CommandInfo)sender;
if (info == null)
throw new InvalidOperationException("commandInfo_ShortcutsChanged() - sender was not a CommandInfo");
info.RebuildShortcutDisplayString();
}
// Called when a command info has been updated. The toolbar buttons may need to be made
// visible or invisible.
private static void commandInfo_VisibilityChanged(object sender, System.EventArgs e)
{
var info = (CommandInfo)sender;
ToolStripButton button = info.GetButton();
if (button != null)
button.Visible = (info.Visibility & CommandVisibility.Toolbar) != 0;
// ToDo: Check parent? Look for the customizable drop-down button?
}
/// <summary>
/// Registers a unique CommandInfo object</summary>
/// <param name="info">CommandInfo object to register</param>
protected override void RegisterCommandInfo(CommandInfo info)
{
m_commandsSorted = false;
Image image = GetProperlySizedImage(info.ImageName);
string uniqueId = GetCommandPath(info);
// Create the WinForms controls to be associated with the registered MenuInfo
var controls = new CommandControls(
new ToolStripMenuItem(info.DisplayedMenuText, image),
new ToolStripButton(info.MenuText, image)
);
m_commandControls.Add(info, controls);
// Associate the registered MenuInfo with this CommandService. Only can be registered once.
info.CommandService = this;
info.ShortcutsChanged += commandInfo_ShortcutsChanged;
info.VisibilityChanged += commandInfo_VisibilityChanged;
base.RegisterCommandInfo(info);
ToolStripMenuItem menuItem = controls.MenuItem;
menuItem.Name = uniqueId;
menuItem.Tag = info.CommandTag;
menuItem.MouseEnter += menuItem_MouseEnter;
menuItem.MouseLeave += menuItem_MouseLeave;
menuItem.MouseMove += menuItem_MouseMove;
menuItem.Click += item_Click;
ToolStripButton button = controls.Button;
button.AutoSize = true;
button.ImageScaling = ToolStripItemImageScaling.None;
button.Name = uniqueId;
button.DisplayStyle =
(image != null) ? ToolStripItemDisplayStyle.Image : ToolStripItemDisplayStyle.Text;
button.Tag = info.CommandTag;
string toolTipText = info.Description;
if (!string.IsNullOrEmpty(info.HelpUrl))
toolTipText += Environment.NewLine + "Press F1 for more info".Localize();
button.ToolTipText = toolTipText;
button.Click += item_Click;
// This method is only called once per unique CommandInfo, so there's no danger
// of subscribing to the same event multiple times.
info.CheckCanDo += OnCheckCanDo;
}
/// <summary>
/// Unregisters a unique CommandInfo object</summary>
/// <param name="info">CommandInfo object to unregister</param>
protected override void UnregisterCommandInfo(CommandInfo info)
{
info.CheckCanDo -= OnCheckCanDo;
CommandControls controls;
if (m_commandControls.TryGetValue(info, out controls))
{
controls.Dispose();
m_commandControls.Remove(info);
}
info.ShortcutsChanged -= commandInfo_ShortcutsChanged;
info.VisibilityChanged -= commandInfo_VisibilityChanged;
base.UnregisterCommandInfo(info);
}
/// <summary>
/// Increment menu command count</summary>
/// <param name="menuTag">Menu's unique ID tag. Is null if there is no menu item.</param>
/// <returns>MenuInfo for menu</returns>
protected override MenuInfo IncrementMenuCommandCount(object menuTag)
{
MenuInfo menuInfo = base.IncrementMenuCommandCount(menuTag);
if (menuInfo != null && menuInfo.Commands == 1)
m_menuToolStripItems[menuInfo].Visible = true;
return menuInfo;
}
/// <summary>
/// Encapsulates WinForms controls instantiated for a MenuInfo instance</summary>
public class MenuControls
{
/// <summary>
/// Constructor</summary>
/// <param name="menuItem">ToolStripMenuItem</param>
/// <param name="toolStrip">ToolStrip</param>
public MenuControls(ToolStripMenuItem menuItem, ToolStrip toolStrip)
{
MenuItem = menuItem;
ToolStrip = toolStrip;
}
/// <summary>
/// Gets ToolStripMenuItem in MenuControls</summary>
public ToolStripMenuItem MenuItem { get; private set; }
/// <summary>
/// Gets ToolStripMenu in MenuControls</summary>
public ToolStrip ToolStrip { get; private set; }
}
/// <summary>
/// Encapsulates WinForms controls instantiated for a CommandInfo instance</summary>
public class CommandControls : IDisposable
{
/// <summary>
/// Constructor</summary>
/// <param name="menuItem">ToolStripMenuItem</param>
/// <param name="button">ToolStripButton</param>
public CommandControls(ToolStripMenuItem menuItem, ToolStripButton button)
{
MenuItem = menuItem;
Button = button;
}
/// <summary>
/// Gets ToolStripMenuItem</summary>
public ToolStripMenuItem MenuItem { get; private set; }
/// <summary>
/// Gets ToolStripButton</summary>
public ToolStripButton Button { get; private set; }
/// <summary>
/// Disposes of resources</summary>
public void Dispose()
{
if (MenuItem != null) MenuItem.Dispose();
if (Button != null) Button.Dispose();
}
}
/// <summary>
/// Obtains the "dummy" WinForms ToolStripMenuItem for a given MenuInfo instance</summary>
/// <param name="info">MenuInfo instance</param>
/// <returns>"Dummy" ToolStripMenuItem for a given MenuInfo instance</returns>
public ToolStripMenuItem GetMenuToolStripItem(MenuInfo info)
{
if (info == null)
throw new NullReferenceException("MenuInfo argument cannot be null");
return m_menuToolStripItems[info];
}
/// <summary>
/// Gets the WinForms ToolStrip for a given MenuInfo instance</summary>
/// <param name="info">MenuInfo instance</param>
/// <returns>WinForms ToolStrip for given MenuInfo instance</returns>
public ToolStrip GetMenuToolStrip(MenuInfo info)
{
if (info == null)
throw new NullReferenceException("MenuInfo argument cannot be null");
return m_menuToolStrips[info];
}
/// <summary>
/// Sets the WinForms ToolStrip for a given MenuInfo instance. Prevents RegisterMenuInfo()
/// from creating one for it.</summary>
/// <param name="info">MenuInfo</param>
/// <param name="toolStrip">ToolStrip</param>
public void SetMenuToolStrip(MenuInfo info, ToolStrip toolStrip)
{
if (info == null)
throw new NullReferenceException("MenuInfo argument cannot be null");
if (toolStrip == null)
throw new NullReferenceException("ToolStrip argument cannot be null");
m_menuToolStrips.Add(info, toolStrip);
}
/// <summary>
/// Gets the WinForms controls for a given CommandInfo instance</summary>
/// <param name="info">CommandInfo instance</param>
/// <returns>WinForms controls for given CommandInfo instance</returns>
public CommandControls GetCommandControls(CommandInfo info)
{
if (info == null)
throw new NullReferenceException("CommandInfo argument cannot be null");
return m_commandControls[info];
}
private readonly Dictionary<MenuInfo, ToolStrip> m_menuToolStrips =
new Dictionary<MenuInfo, ToolStrip>();
private readonly Dictionary<MenuInfo, ToolStripMenuItem> m_menuToolStripItems =
new Dictionary<MenuInfo, ToolStripMenuItem>();
private readonly Dictionary<CommandInfo, CommandControls> m_commandControls =
new Dictionary<CommandInfo, CommandControls>();
// The CheckCanDo event on these CommandInfos is supported by the associated
// non-null ICommandClients. The temporary to-update list is for one-time updates
// and as a side benefit, this throttles any over-active ICommandClients.
private readonly Multimap<CommandInfo, ICommandClient> m_checkCanDoClients =
new Multimap<CommandInfo, ICommandClient>();
private readonly HashSet<CommandInfo> m_checkCanDoClientsToUpdate =
new HashSet<CommandInfo>();
private readonly Form m_mainForm;
private ToolStripContainer m_toolStripContainer;
private readonly MenuStrip m_mainMenuStrip;
private bool m_commandsSorted;
private Point m_menuMouseLocation = Point.Empty;
private CommandInfo m_mouseIsOverCommandIcon;
private ToolStripEx m_lastHoveringToolStrip;
private DispatcherTimer m_webHelpTimer;
}
/// <summary>
/// Useful extension methods for ICommandService that are specific to WinForms</summary>
public static class WinFormsCommandServices
{
/// <summary>
/// Registers a command for the command client</summary>
/// <param name="commandService">Command service</param>
/// <param name="commandTag">Command's unique ID</param>
/// <param name="menuTag">Containing menu's unique ID, or null</param>
/// <param name="groupTag">Containing menu group's unique ID, or null</param>
/// <param name="menuText">Command text as it appears in menu</param>
/// <param name="description">Command description</param>
/// <param name="shortcut">Command shortcut, or Keys.None if none</param>
/// <param name="imageName">Text identifying image, or null if none</param>
/// <param name="client">Client that performs command</param>
/// <returns>CommandInfo object describing command</returns>
public static CommandInfo RegisterCommand(
this ICommandService commandService,
object commandTag,
object menuTag,
object groupTag,
string menuText,
string description,
System.Windows.Forms.Keys shortcut,
string imageName,
ICommandClient client)
{
CommandInfo info = new CommandInfo(commandTag, menuTag, groupTag, menuText, description, KeysInterop.ToAtf(shortcut), imageName);
commandService.RegisterCommand(info, client);
return info;
}
/// <summary>
/// Registers a command for the command client</summary>
/// <param name="commandService">Command service</param>
/// <param name="commandTag">Command's unique ID</param>
/// <param name="menuTag">Containing menu's unique ID, or null</param>
/// <param name="groupTag">Containing menu group's unique ID, or null</param>
/// <param name="menuText">Command text as it appears in menu</param>
/// <param name="description">Command description</param>
/// <param name="shortcut">Command shortcut, or Keys.None if none</param>
/// <param name="imageName">Text identifying image, or null if none</param>
/// <param name="visibility">Value describing whether command is visible in menus and toolbars</param>
/// <param name="client">Client that performs command</param>
/// <returns>CommandInfo object describing command</returns>
public static CommandInfo RegisterCommand(
this ICommandService commandService,
object commandTag,
object menuTag,
object groupTag,
string menuText,
string description,
System.Windows.Forms.Keys shortcut,
string imageName,
CommandVisibility visibility,
ICommandClient client)
{
CommandInfo info = new CommandInfo(commandTag, menuTag, groupTag, menuText, description, KeysInterop.ToAtf(shortcut), imageName, visibility);
commandService.RegisterCommand(info, client);
return info;
}
/// <summary>
/// Processes the key as a command shortcut</summary>
/// <param name="commandService">Command service</param>
/// <param name="key">Key to process</param>
/// <returns>True iff the key was processed as a command shortcut</returns>
static public bool ProcessKey(this ICommandService commandService, System.Windows.Forms.Keys key)
{
return commandService.ProcessKey(KeysInterop.ToAtf(key));
}
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
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 License
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using JsonFx.Linq;
namespace JsonFx.Model
{
/// <summary>
/// Provides base implementation for standard deserializers
/// </summary>
/// <remarks>
/// This partial class adds LINQ capabilities to the reader.
/// </remarks>
public abstract partial class ModelReader : IQueryableReader
{
#region IQueryableReader Methods
/// <summary>
/// Begins a query of the given input
/// </summary>
/// <param name="input">the input reader</param>
/// <param name="ignored">a value used to trigger Type inference for <typeparamref name="T"/> (e.g. for deserializing anonymous objects)</param>
/// <typeparam name="T">the expected type of the serialized data</typeparam>
IQueryable<T> IQueryableReader.Query<T>(TextReader input, T ignored)
{
return this.Query<T>(input);
}
/// <summary>
/// Begins a query of the given input
/// </summary>
/// <param name="input">the input reader</param>
/// <typeparam name="T">the expected type of the serialized data</typeparam>
IQueryable<T> IQueryableReader.Query<T>(TextReader input)
{
return this.Query<T>(input);
}
/// <summary>
/// Begins a query of the given input
/// </summary>
/// <param name="input">the input text</param>
/// <param name="ignored">a value used to trigger Type inference for <typeparamref name="T"/> (e.g. for deserializing anonymous objects)</param>
/// <typeparam name="T">the expected type of the serialized data</typeparam>
IQueryable<T> IQueryableReader.Query<T>(string input, T ignored)
{
return this.Query<T>(input);
}
/// <summary>
/// Begins a query of the given input
/// </summary>
/// <param name="input">the input text</param>
/// <typeparam name="T">the expected type of the serialized data</typeparam>
IQueryable<T> IQueryableReader.Query<T>(string input)
{
return this.Query<T>(input);
}
/// <summary>
/// Begins a query of the given input
/// </summary>
/// <param name="input">the input reader</param>
/// <param name="ignored">a value used to trigger Type inference for <typeparamref name="T"/> (e.g. for deserializing anonymous objects)</param>
/// <typeparam name="T">the expected type of the serialized data</typeparam>
public Query<T> Query<T>(TextReader input, T ignored)
{
return this.Query<T>(input);
}
/// <summary>
/// Begins a query of the given input
/// </summary>
/// <param name="input">the input reader</param>
/// <typeparam name="T">the expected type of the serialized data</typeparam>
public Query<T> Query<T>(TextReader input)
{
var tokenizer = this.GetTokenizer();
if (tokenizer == null)
{
throw new InvalidOperationException("Tokenizer is invalid");
}
var source = tokenizer.GetTokens(input);
return new Query<T>(this.GetAnalyzer(), source);
}
/// <summary>
/// Serializes the data to the given output
/// </summary>
/// <param name="input">the input reader</param>
public IQueryable Query(TextReader input)
{
var tokenizer = this.GetTokenizer();
if (tokenizer == null)
{
throw new InvalidOperationException("Tokenizer is invalid");
}
var source = tokenizer.GetTokens(input);
return new Query<object>(this.GetAnalyzer(), source);
}
/// <summary>
/// Begins a query of the given input
/// </summary>
/// <param name="input">the input reader</param>
/// <param name="targetType">the expected type of the serialized data</param>
public IQueryable Query(TextReader input, Type targetType)
{
var tokenizer = this.GetTokenizer();
if (tokenizer == null)
{
throw new InvalidOperationException("Tokenizer is invalid");
}
var source = tokenizer.GetTokens(input);
try
{
// TODO: replace with DynamicMethodGenerator.GetTypeFactory?
return (IQueryable)Activator.CreateInstance(typeof(Query<>).MakeGenericType(targetType), new object[] { this.GetAnalyzer(), source });
}
catch (TargetInvocationException ex)
{
// unwrap inner exception
throw ex.InnerException;
}
}
/// <summary>
/// Begins a query of the given input
/// </summary>
/// <param name="input">the input text</param>
/// <param name="ignored">a value used to trigger Type inference for <typeparamref name="T"/> (e.g. for deserializing anonymous objects)</param>
/// <typeparam name="T">the expected type of the serialized data</typeparam>
public Query<T> Query<T>(string input, T ignored)
{
return this.Query<T>(input);
}
/// <summary>
/// Begins a query of the given input
/// </summary>
/// <param name="input">the input text</param>
/// <typeparam name="T">the expected type of the serialized data</typeparam>
public Query<T> Query<T>(string input)
{
var tokenizer = this.GetTokenizer();
if (tokenizer == null)
{
throw new InvalidOperationException("Tokenizer is invalid");
}
var source = tokenizer.GetTokens(input);
return new Query<T>(this.GetAnalyzer(), source);
}
/// <summary>
/// Begins a query of the given input
/// </summary>
/// <param name="input">the input text</param>
public IQueryable Query(string input)
{
var tokenizer = this.GetTokenizer();
if (tokenizer == null)
{
throw new InvalidOperationException("Tokenizer is invalid");
}
var source = tokenizer.GetTokens(input);
return new Query<object>(this.GetAnalyzer(), source);
}
/// <summary>
/// Begins a query of the given input
/// </summary>
/// <param name="input">the input text</param>
/// <param name="targetType">the expected type of the serialized data</param>
public IQueryable Query(string input, Type targetType)
{
var tokenizer = this.GetTokenizer();
if (tokenizer == null)
{
throw new InvalidOperationException("Tokenizer is invalid");
}
var source = tokenizer.GetTokens(input);
try
{
// TODO: replace with DynamicMethodGenerator.GetTypeFactory?
return (IQueryable)Activator.CreateInstance(typeof(Query<>).MakeGenericType(targetType), new object[] { this.GetAnalyzer(), source });
}
catch (TargetInvocationException ex)
{
// unwrap inner exception
throw ex.InnerException;
}
}
#endregion IQueryableReader Methods
}
}
| |
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Generators
{
internal class DHParametersHelper
{
// The primes b/w 2 and ~2^10
/*
3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601
607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997
1009 1013 1019 1021 1031
*/
// Each list has a product < 2^31
private static readonly int[][] _primeLists = new[]
{
new[]{ 3, 5, 7, 11, 13, 17, 19, 23 },
new[]{ 29, 31, 37, 41, 43 },
new[]{ 47, 53, 59, 61, 67 },
new[]{ 71, 73, 79, 83 },
new[]{ 89, 97, 101, 103 },
new[]{ 107, 109, 113, 127 },
new[]{ 131, 137, 139, 149 },
new[]{ 151, 157, 163, 167 },
new[]{ 173, 179, 181, 191 },
new[]{ 193, 197, 199, 211 },
new[]{ 223, 227, 229 },
new[]{ 233, 239, 241 },
new[]{ 251, 257, 263 },
new[]{ 269, 271, 277 },
new[]{ 281, 283, 293 },
new[]{ 307, 311, 313 },
new[]{ 317, 331, 337 },
new[]{ 347, 349, 353 },
new[]{ 359, 367, 373 },
new[]{ 379, 383, 389 },
new[]{ 397, 401, 409 },
new[]{ 419, 421, 431 },
new[]{ 433, 439, 443 },
new[]{ 449, 457, 461 },
new[]{ 463, 467, 479 },
new[]{ 487, 491, 499 },
new[]{ 503, 509, 521 },
new[]{ 523, 541, 547 },
new[]{ 557, 563, 569 },
new[]{ 571, 577, 587 },
new[]{ 593, 599, 601 },
new[]{ 607, 613, 617 },
new[]{ 619, 631, 641 },
new[]{ 643, 647, 653 },
new[]{ 659, 661, 673 },
new[]{ 677, 683, 691 },
new[]{ 701, 709, 719 },
new[]{ 727, 733, 739 },
new[]{ 743, 751, 757 },
new[]{ 761, 769, 773 },
new[]{ 787, 797, 809 },
new[]{ 811, 821, 823 },
new[]{ 827, 829, 839 },
new[]{ 853, 857, 859 },
new[]{ 863, 877, 881 },
new[]{ 883, 887, 907 },
new[]{ 911, 919, 929 },
new[]{ 937, 941, 947 },
new[]{ 953, 967, 971 },
new[]{ 977, 983, 991 },
new[]{ 997, 1009, 1013 },
new[]{ 1019, 1021, 1031 }
};
private static readonly IBigInteger _six = BigInteger.ValueOf(6);
private static readonly int[] _primeProductsInts;
private static readonly IBigInteger[] _primeProductsBigs;
static DHParametersHelper()
{
_primeProductsInts = new int[_primeLists.Length];
_primeProductsBigs = new IBigInteger[_primeLists.Length];
for (var i = 0; i < _primeLists.Length; ++i)
{
var primeList = _primeLists[i];
var product = 1;
for (var j = 0; j < primeList.Length; ++j)
{
product *= primeList[j];
}
_primeProductsInts[i] = product;
_primeProductsBigs[i] = BigInteger.ValueOf(product);
}
}
/// <summary>
/// Finds a pair of prime BigInteger's {p, q: p = 2q + 1}
///
/// (see: Handbook of Applied Cryptography 4.86)
/// </summary>
/// <param name="size">The size.</param>
/// <param name="certainty">The certainty.</param>
/// <param name="random">The random.</param>
/// <returns></returns>
internal static IBigInteger[] GenerateSafePrimes(int size, int certainty, ISecureRandom random)
{
IBigInteger p, q;
var qLength = size - 1;
if (size <= 32)
{
for (; ; )
{
q = new BigInteger(qLength, 2, random);
p = q.ShiftLeft(1).Add(BigInteger.One);
if (p.IsProbablePrime(certainty)
&& (certainty <= 2 || q.IsProbablePrime(certainty)))
break;
}
}
else
{
// Note: Modified from Java version for speed
for (; ; )
{
q = new BigInteger(qLength, 0, random);
retry:
for (var i = 0; i < _primeLists.Length; ++i)
{
var test = q.Remainder(_primeProductsBigs[i]).IntValue;
if (i == 0)
{
var rem3 = test % 3;
if (rem3 != 2)
{
var diff = 2 * rem3 + 2;
q = q.Add(BigInteger.ValueOf(diff));
test = (test + diff) % _primeProductsInts[i];
}
}
var primeList = _primeLists[i];
foreach (var prime in primeList)
{
var qRem = test % prime;
if (qRem != 0 && qRem != (prime >> 1))
continue;
q = q.Add(_six);
goto retry;
}
}
if (q.BitLength != qLength)
continue;
if (!((BigInteger)q).RabinMillerTest(2, random))
continue;
p = q.ShiftLeft(1).Add(BigInteger.One);
if (((BigInteger)p).RabinMillerTest(certainty, random)
&& (certainty <= 2 || ((BigInteger)q).RabinMillerTest(certainty - 2, random)))
break;
}
}
return new[] { p, q };
}
/// <summary>
/// Select a high order element of the multiplicative group Z
///
/// p and q must be s.t. p = 2*q + 1, where p and q are prime (see generateSafePrimes)
/// </summary>
/// <param name="p">The p.</param>
/// <param name="q">The q.</param>
/// <param name="random">The random.</param>
/// <returns></returns>
internal static IBigInteger SelectGenerator(IBigInteger p, IBigInteger q, SecureRandom random)
{
var pMinusTwo = p.Subtract(BigInteger.Two);
IBigInteger g;
/*
* (see: Handbook of Applied Cryptography 4.80)
*/
// do
// {
// g = BigIntegers.CreateRandomInRange(BigInteger.Two, pMinusTwo, random);
// }
// while (g.ModPow(BigInteger.Two, p).Equals(BigInteger.One)
// || g.ModPow(q, p).Equals(BigInteger.One));
/*
* RFC 2631 2.2.1.2 (and see: Handbook of Applied Cryptography 4.81)
*/
do
{
var h = BigIntegers.CreateRandomInRange(BigInteger.Two, pMinusTwo, random);
g = h.ModPow(BigInteger.Two, p);
}
while (g.Equals(BigInteger.One));
return g;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Test.ModuleCore;
using System;
using System.IO;
using System.Text;
using System.Xml;
using XmlCoreTest.Common;
namespace CoreXml.Test.XLinq
{
public partial class XNodeReaderFunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
//[TestCase(Name = "ReadContentAsBase64", Desc = "ReadContentAsBase64")]
public partial class TCReadContentAsBase64 : BridgeHelpers
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string strTextBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public const string strNumBase64 = "0123456789+/";
public override void Init()
{
base.Init();
CreateBase64TestFile(pBase64Xml);
}
public override void Terminate()
{
DeleteTestFile(pBase64Xml);
base.Terminate();
}
private bool VerifyInvalidReadBase64(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return true;
try
{
DataReader.ReadContentAsBase64(buffer, iIndex, iCount);
}
catch (Exception e)
{
bPassed = (e.GetType().ToString() == exceptionType.ToString());
if (!bPassed)
{
TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString());
TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
}
}
return bPassed;
}
protected void TestOnInvalidNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnNodeType(DataReader, nt);
if (!DataReader.CanReadBinaryContent) return;
try
{
byte[] buffer = new byte[1];
int nBytes = DataReader.ReadContentAsBase64(buffer, 0, 1);
}
catch (InvalidOperationException ioe)
{
if (ioe.ToString().IndexOf(nt.ToString()) < 0)
TestLog.Compare(false, "Call threw wrong invalid operation exception on " + nt);
else
return;
}
TestLog.Compare(false, "Call succeeded on " + nt);
}
protected void TestOnNopNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnNodeType(DataReader, nt);
string name = DataReader.Name;
string value = DataReader.Value;
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[1];
int nBytes = DataReader.ReadContentAsBase64(buffer, 0, 1);
TestLog.Compare(nBytes, 0, "nBytes");
TestLog.Compare(VerifyNode(DataReader, nt, name, value), "vn");
}
//[Variation("ReadBase64 Element with all valid value")]
public void TestReadBase64_1()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with all valid Num value", Priority = 0)]
public void TestReadBase64_2()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME3);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, strNumBase64, "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with all valid Text value")]
public void TestReadBase64_3()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, strTextBase64, "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with all valid value (from concatenation), Priority=0")]
public void TestReadBase64_5()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME5);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with Long valid value (from concatenation), Priority=0")]
public void TestReadBase64_6()
{
int base64len = 0;
byte[] base64 = new byte[2000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME6);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
string strExpbase64 = "";
for (int i = 0; i < 10; i++)
strExpbase64 += (strTextBase64 + strNumBase64);
TestLog.Compare(strActbase64, strExpbase64, "Compare All Valid Base64");
}
//[Variation("ReadBase64 with count > buffer size")]
public void ReadBase64_7()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 6, typeof(NotSupportedException)));
}
//[Variation("ReadBase64 with count < 0")]
public void ReadBase64_8()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 2, -1, typeof(NotSupportedException)));
}
//[Variation("ReadBase64 with index > buffer size")]
public void ReadBase64_9()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 5, 1, typeof(NotSupportedException)));
}
//[Variation("ReadBase64 with index < 0")]
public void ReadBase64_10()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, -1, 1, typeof(NotSupportedException)));
}
//[Variation("ReadBase64 with index + count exceeds buffer")]
public void ReadBase64_11()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 10, typeof(NotSupportedException)));
}
//[Variation("ReadBase64 index & count =0")]
public void ReadBase64_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
iCount = DataReader.ReadContentAsBase64(buffer, 0, 0);
TestLog.Compare(iCount, 0, "has to be zero");
}
//[Variation("ReadBase64 Element multiple into same buffer (using offset), Priority=0")]
public void TestReadBase64_13()
{
int base64len = 20;
byte[] base64 = new byte[base64len];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
DataReader.ReadContentAsBase64(base64, i, 2);
strActbase64 = (System.BitConverter.ToChar(base64, i)).ToString();
TestLog.Compare(string.Compare(strActbase64, 0, strTextBase64, i / 2, 1), 0, "Compare All Valid Base64");
}
}
//[Variation("ReadBase64 with buffer == null")]
public void TestReadBase64_14()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
try
{
DataReader.ReadContentAsBase64(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadBase64 after failure")]
public void TestReadBase64_15()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, "ElemErr");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadContentAsBase64(buffer, 0, 1);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_InvalidBase64Value", e, 0, 1);
}
}
//[Variation("Read after partial ReadBase64", Priority = 0)]
public void TestReadBase64_16()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, "ElemNum");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadContentAsBase64(buffer, 0, 8);
TestLog.Compare(nRead, 8, "0");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "1vn");
}
//[Variation("Current node on multiple calls")]
public void TestReadBase64_17()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, "ElemNum");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[30];
int nRead = DataReader.ReadContentAsBase64(buffer, 0, 2);
TestLog.Compare(nRead, 2, "0");
nRead = DataReader.ReadContentAsBase64(buffer, 0, 23);
TestLog.Compare(nRead, 22, "1");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype not end element");
TestLog.Compare(DataReader.Name, "ElemText", "Nodetype not end element");
}
//[Variation("No op node types")]
public void TestReadBase64_18()
{
TestOnInvalidNodeType(XmlNodeType.EndElement);
}
//[Variation("ReadBase64 with incomplete sequence")]
public void TestTextReadBase64_23()
{
byte[] expected = new byte[] { 0, 16, 131, 16, 81 };
byte[] buffer = new byte[10];
string strxml = "<r><ROOT>ABCDEFG</ROOT></r>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "ROOT");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadContentAsBase64(buffer, result, 1)) > 0)
result += nRead;
TestLog.Compare(result, expected.Length, "res");
for (int i = 0; i < result; i++)
TestLog.Compare(buffer[i], expected[i], "buffer[" + i + "]");
}
//[Variation("ReadBase64 when end tag doesn't exist")]
public void TestTextReadBase64_24()
{
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('c', 5000);
try
{
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "B");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
DataReader.ReadContentAsBase64(buffer, 0, 5000);
TestLog.WriteLine("Accepted incomplete element");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
}
//[Variation("ReadBase64 with whitespace in the mIddle")]
public void TestTextReadBase64_26()
{
byte[] buffer = new byte[1];
string strxml = "<abc> AQID B B </abc>";
int nRead;
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
for (int i = 0; i < 4; i++)
{
nRead = DataReader.ReadContentAsBase64(buffer, 0, 1);
TestLog.Compare(nRead, 1, "res" + i);
TestLog.Compare(buffer[0], (byte)(i + 1), "buffer " + i);
}
nRead = DataReader.ReadContentAsBase64(buffer, 0, 1);
TestLog.Compare(nRead, 0, "nRead 0");
}
//[Variation("ReadBase64 with = in the mIddle")]
public void TestTextReadBase64_27()
{
byte[] buffer = new byte[1];
string strxml = "<abc>AQI=ID</abc>";
int nRead;
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
for (int i = 0; i < 2; i++)
{
nRead = DataReader.ReadContentAsBase64(buffer, 0, 1);
TestLog.Compare(nRead, 1, "res" + i);
TestLog.Compare(buffer[0], (byte)(i + 1), "buffer " + i);
}
try
{
DataReader.ReadContentAsBase64(buffer, 0, 1);
TestLog.WriteLine("ReadBase64 with = in the middle succeeded");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_InvalidBase64Value", e, 0, 1);
}
}
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000" })]
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "1000000" })]
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000000" })]
public void RunBase64DoesnNotRunIntoOverflow()
{
int totalfilesize = Convert.ToInt32(Variation.Params[0].ToString());
string ascii = new string('c', totalfilesize);
byte[] bits = Encoding.Unicode.GetBytes(ascii);
string base64str = Convert.ToBase64String(bits);
string fileName = "bug105376_" + Variation.Params[0].ToString() + ".xml";
FilePathUtil.addStream(fileName, new MemoryStream());
StreamWriter sw = new StreamWriter(FilePathUtil.getStream(fileName));
sw.Write("<root><base64>");
sw.Write(base64str);
sw.Write("</base64></root>");
sw.Flush();
XmlReader DataReader = GetReader(fileName);
int SIZE = (totalfilesize - 30);
int SIZE64 = SIZE * 3 / 4;
PositionOnElement(DataReader, "base64");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] base64 = new byte[SIZE64];
int startPos = 0;
int readSize = 4096;
int currentSize = 0;
currentSize = DataReader.ReadContentAsBase64(base64, startPos, readSize);
TestLog.Compare(currentSize, readSize, "Read other than first chunk");
readSize = SIZE64 - readSize;
currentSize = DataReader.ReadContentAsBase64(base64, startPos, readSize);
TestLog.Compare(currentSize, readSize, "Read other than remaining Chunk Size");
readSize = 0;
currentSize = DataReader.ReadContentAsBase64(base64, startPos, readSize);
TestLog.Compare(currentSize, 0, "Read other than Zero Bytes");
DataReader.Dispose();
}
}
//[TestCase(Name = "ReadElementContentAsBase64", Desc = "ReadElementContentAsBase64")]
public partial class TCReadElementContentAsBase64 : BridgeHelpers
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string strTextBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public const string strNumBase64 = "0123456789+/";
public override void Init()
{
base.Init();
CreateBase64TestFile(pBase64Xml);
}
public override void Terminate()
{
DeleteTestFile(pBase64Xml);
base.Terminate();
}
private bool VerifyInvalidReadBase64(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return true;
try
{
DataReader.ReadContentAsBase64(buffer, iIndex, iCount);
}
catch (Exception e)
{
bPassed = (e.GetType().ToString() == exceptionType.ToString());
if (!bPassed)
{
TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString());
TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
}
}
return bPassed;
}
protected void TestOnInvalidNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnNodeType(DataReader, nt);
if (!DataReader.CanReadBinaryContent) return;
try
{
byte[] buffer = new byte[1];
int nBytes = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
}
catch (InvalidOperationException ioe)
{
if (ioe.ToString().IndexOf(nt.ToString()) < 0)
TestLog.Compare(false, "Call threw wrong invalid operation exception on " + nt);
else
return;
}
TestLog.Compare(false, "Call succeeded on " + nt);
}
//[Variation("ReadBase64 Element with all valid value")]
public void TestReadBase64_1()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with all valid Num value", Priority = 0)]
public void TestReadBase64_2()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME3);
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, strNumBase64, "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with all valid Text value")]
public void TestReadBase64_3()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, strTextBase64, "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with all valid value (from concatenation), Priority=0")]
public void TestReadBase64_5()
{
int base64len = 0;
byte[] base64 = new byte[1000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME5);
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
TestLog.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64");
}
//[Variation("ReadBase64 Element with Long valid value (from concatenation), Priority=0")]
public void TestReadBase64_6()
{
int base64len = 0;
byte[] base64 = new byte[2000];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME6);
if (!DataReader.CanReadBinaryContent) return;
base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length);
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
strActbase64 += System.BitConverter.ToChar(base64, i);
}
string strExpbase64 = "";
for (int i = 0; i < 10; i++)
strExpbase64 += (strTextBase64 + strNumBase64);
TestLog.Compare(strActbase64, strExpbase64, "Compare All Valid Base64");
}
//[Variation("ReadBase64 with count > buffer size")]
public void ReadBase64_7()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBase64 with count < 0")]
public void ReadBase64_8()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 2, -1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBase64 with index > buffer size")]
public void ReadBase64_9()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBase64 with index < 0")]
public void ReadBase64_10()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, -1, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBase64 with index + count exceeds buffer")]
public void ReadBase64_11()
{
BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 10, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBase64 index & count =0")]
public void ReadBase64_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return;
iCount = DataReader.ReadElementContentAsBase64(buffer, 0, 0);
TestLog.Compare(iCount, 0, "has to be zero");
}
//[Variation("ReadBase64 Element multiple into same buffer (using offset), Priority=0")]
public void TestReadBase64_13()
{
int base64len = 20;
byte[] base64 = new byte[base64len];
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
string strActbase64 = "";
for (int i = 0; i < base64len; i = i + 2)
{
DataReader.ReadElementContentAsBase64(base64, i, 2);
strActbase64 = (System.BitConverter.ToChar(base64, i)).ToString();
TestLog.Compare(string.Compare(strActbase64, 0, strTextBase64, i / 2, 1), 0, "Compare All Valid Base64");
}
}
//[Variation("ReadBase64 with buffer == null")]
public void TestReadBase64_14()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
try
{
DataReader.ReadElementContentAsBase64(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadBase64 after failure")]
public void TestReadBase64_15()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, "ElemErr");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_InvalidBase64Value", e, 0, 1);
}
}
//[Variation("Read after partial ReadBase64", Priority = 0)]
public void TestReadBase64_16()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, "ElemNum");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 8);
TestLog.Compare(nRead, 8, "0");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "1vn");
}
//[Variation("Current node on multiple calls")]
public void TestReadBase64_17()
{
XmlReader DataReader = GetReader(pBase64Xml);
PositionOnElement(DataReader, "ElemNum");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[30];
int nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 2);
TestLog.Compare(nRead, 2, "0");
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 23);
TestLog.Compare(nRead, 22, "1");
TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Nodetype not end element");
TestLog.Compare(DataReader.Name, "ElemNum", "Nodetype not end element");
}
//[Variation("ReadBase64 with incomplete sequence")]
public void TestTextReadBase64_23()
{
byte[] expected = new byte[] { 0, 16, 131, 16, 81 };
byte[] buffer = new byte[10];
string strxml = "<r><ROOT>ABCDEFG</ROOT></r>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "ROOT");
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadElementContentAsBase64(buffer, result, 1)) > 0)
result += nRead;
TestLog.Compare(result, expected.Length, "res");
for (int i = 0; i < result; i++)
TestLog.Compare(buffer[i], expected[i], "buffer[" + i + "]");
}
//[Variation("ReadBase64 when end tag doesn't exist")]
public void TestTextReadBase64_24()
{
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('c', 5000);
try
{
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "B");
if (!DataReader.CanReadBinaryContent) return;
DataReader.ReadElementContentAsBase64(buffer, 0, 5000);
TestLog.WriteLine("Accepted incomplete element");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
}
//[Variation("ReadBase64 with whitespace in the mIddle")]
public void TestTextReadBase64_26()
{
byte[] buffer = new byte[1];
string strxml = "<abc> AQID B B </abc>";
int nRead;
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
if (!DataReader.CanReadBinaryContent) return;
for (int i = 0; i < 4; i++)
{
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
TestLog.Compare(nRead, 1, "res" + i);
TestLog.Compare(buffer[0], (byte)(i + 1), "buffer " + i);
}
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
TestLog.Compare(nRead, 0, "nRead 0");
}
//[Variation("ReadBase64 with = in the mIddle")]
public void TestTextReadBase64_27()
{
byte[] buffer = new byte[1];
string strxml = "<abc>AQI=ID</abc>";
int nRead;
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
if (!DataReader.CanReadBinaryContent) return;
for (int i = 0; i < 2; i++)
{
nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1);
TestLog.Compare(nRead, 1, "res" + i);
TestLog.Compare(buffer[0], (byte)(i + 1), "buffer " + i);
}
try
{
DataReader.ReadElementContentAsBase64(buffer, 0, 1);
TestLog.WriteLine("ReadBase64 with = in the middle succeeded");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_InvalidBase64Value", e, 0, 1);
}
}
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000" })]
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "1000000" })]
//[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000000" })]
public void ReadBase64DoesNotRunIntoOverflow2()
{
int totalfilesize = Convert.ToInt32(Variation.Params[0].ToString());
string ascii = new string('c', totalfilesize);
byte[] bits = Encoding.Unicode.GetBytes(ascii);
string base64str = Convert.ToBase64String(bits);
string fileName = "bug105376_" + Variation.Params[0].ToString() + ".xml";
FilePathUtil.addStream(fileName, new MemoryStream());
StreamWriter sw = new StreamWriter(FilePathUtil.getStream(fileName));
sw.Write("<root><base64>");
sw.Write(base64str);
sw.Write("</base64></root>");
sw.Flush();
XmlReader DataReader = GetReader(fileName);
int SIZE = (totalfilesize - 30);
int SIZE64 = SIZE * 3 / 4;
PositionOnElement(DataReader, "base64");
if (!DataReader.CanReadBinaryContent) return;
byte[] base64 = new byte[SIZE64];
int startPos = 0;
int readSize = 4096;
int currentSize = 0;
currentSize = DataReader.ReadElementContentAsBase64(base64, startPos, readSize);
TestLog.Compare(currentSize, readSize, "Read other than first chunk");
readSize = SIZE64 - readSize;
currentSize = DataReader.ReadElementContentAsBase64(base64, startPos, readSize);
TestLog.Compare(currentSize, readSize, "Read other than remaining Chunk Size");
readSize = 0;
currentSize = DataReader.ReadElementContentAsBase64(base64, startPos, readSize);
TestLog.Compare(currentSize, 0, "Read other than Zero Bytes");
DataReader.Dispose();
}
//[Variation("SubtreeReader inserted attributes don't work with ReadContentAsBase64")]
public void SubtreeReaderInsertedAttributesWontWorkWithReadContentAsBase64()
{
string strxml1 = "<root xmlns='";
string strxml2 = "'><bar/></root>";
string[] binValue = new string[] { "AAECAwQFBgcI==", "0102030405060708090a0B0c" };
for (int i = 0; i < binValue.Length; i++)
{
string strxml = strxml1 + binValue[i] + strxml2;
using (XmlReader r = GetReader(new StringReader(strxml)))
{
r.Read();
r.Read();
using (XmlReader sr = r.ReadSubtree())
{
if (!sr.CanReadBinaryContent) return;
sr.Read();
sr.MoveToFirstAttribute();
sr.MoveToFirstAttribute();
byte[] bytes = new byte[4];
while ((sr.ReadContentAsBase64(bytes, 0, bytes.Length)) > 0) { }
}
}
}
}
}
}
}
}
| |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using Org.Apache.REEF.Common.Tasks;
using Org.Apache.REEF.Examples.Tasks.HelloTask;
using Org.Apache.REEF.Tang.Annotations;
using Org.Apache.REEF.Tang.Examples;
using Org.Apache.REEF.Tang.Exceptions;
using Org.Apache.REEF.Tang.Implementations.Tang;
using Org.Apache.REEF.Tang.Interface;
using Org.Apache.REEF.Tang.Types;
using Org.Apache.REEF.Tang.Util;
using Xunit;
namespace Org.Apache.REEF.Tang.Tests.ClassHierarchy
{
public class TestClassHierarchy
{
public IClassHierarchy ns = null;
public TestClassHierarchy()
{
if (ns == null)
{
ns = TangFactory.GetTang().GetClassHierarchy(new string[] { FileNames.Examples, FileNames.Common, FileNames.Tasks });
}
}
[Fact]
public void TestString()
{
INode n = null;
try
{
n = ns.GetNode("System");
}
catch (TangApplicationException)
{
}
catch (NameResolutionException)
{
}
Assert.Null(n);
Assert.NotNull(ns.GetNode(typeof(string).AssemblyQualifiedName));
string msg = null;
try
{
ns.GetNode("org.apache");
msg = "Didn't get expected exception";
}
catch (TangApplicationException)
{
}
catch (NameResolutionException)
{
}
Assert.True(msg == null, msg);
}
[Fact]
public void TestInt()
{
INode n = null;
try
{
n = ns.GetNode("System");
}
catch (TangApplicationException)
{
}
catch (NameResolutionException)
{
}
Assert.Null(n);
Assert.NotNull(ns.GetNode(typeof(int).AssemblyQualifiedName));
string msg = null;
try
{
ns.GetNode("org.apache");
msg = "Didn't get expected exception";
}
catch (TangApplicationException)
{
}
catch (NameResolutionException)
{
}
Assert.True(msg == null, msg);
}
[Fact]
public void TestSimpleConstructors()
{
IClassNode cls = (IClassNode)ns.GetNode(typeof(SimpleConstructors).AssemblyQualifiedName);
Assert.True(cls.GetChildren().Count == 0);
IList<IConstructorDef> def = cls.GetInjectableConstructors();
Assert.Equal(3, def.Count);
}
[Fact]
public void TestTimer()
{
IClassNode timerClassNode = (IClassNode)ns.GetNode(typeof(Timer).AssemblyQualifiedName);
INode secondNode = ns.GetNode(typeof(Timer.Seconds).AssemblyQualifiedName);
Assert.Equal(secondNode.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(Timer.Seconds)));
}
[Fact]
public void TestNamedParameterConstructors()
{
var node = ns.GetNode(typeof(NamedParameterConstructors).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(NamedParameterConstructors)));
}
[Fact]
public void TestArray()
{
Type t = (new string[0]).GetType();
INode node = ns.GetNode(t.AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), t.AssemblyQualifiedName);
}
[Fact]
public void TestRepeatConstructorArg()
{
TestNegativeCase(typeof(RepeatConstructorArg),
"Repeated constructor parameter detected. Cannot inject constructor RepeatConstructorArg(int,int).");
}
[Fact]
public void TestRepeatConstructorArgClasses()
{
TestNegativeCase(typeof(RepeatConstructorArgClasses),
"Repeated constructor parameter detected. Cannot inject constructor RepeatConstructorArgClasses(A, A).");
}
[Fact]
public void testLeafRepeatedConstructorArgClasses()
{
INode node = ns.GetNode(typeof(LeafRepeatedConstructorArgClasses).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(LeafRepeatedConstructorArgClasses).AssemblyQualifiedName);
}
[Fact]
public void TestNamedRepeatConstructorArgClasses()
{
INode node = ns.GetNode(typeof(NamedRepeatConstructorArgClasses).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(NamedRepeatConstructorArgClasses).AssemblyQualifiedName);
}
[Fact]
public void TestResolveDependencies()
{
ns.GetNode(typeof(SimpleConstructors).AssemblyQualifiedName);
Assert.NotNull(ns.GetNode(typeof(string).AssemblyQualifiedName));
}
[Fact]
public void TestDocumentedLocalNamedParameter()
{
var node = ns.GetNode(typeof(DocumentedLocalNamedParameter).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(DocumentedLocalNamedParameter)));
}
[Fact]
public void TestNamedParameterTypeMismatch()
{
TestNegativeCase(typeof(NamedParameterTypeMismatch),
"Named parameter type mismatch in NamedParameterTypeMismatch. Constructor expects a System.String but Foo is a System.Int32.");
}
[Fact]
public void TestUnannotatedName()
{
TestNegativeCase(typeof(UnannotatedName),
"Named parameter UnannotatedName is missing its [NamedParameter] attribute.");
}
[Fact]
public void TestAnnotatedNotName()
{
TestNegativeCase(typeof(AnnotatedNotName),
"Found illegal [NamedParameter] AnnotatedNotName does not implement Name<T>.");
}
[Fact]
public void TestAnnotatedNameWrongInterface()
{
TestNegativeCase(typeof(AnnotatedNameWrongInterface),
"Found illegal [NamedParameter] AnnotatedNameWrongInterface does not implement Name<T>.");
}
[Fact]
public void TestAnnotatedNameMultipleInterfaces()
{
TestNegativeCase(typeof(AnnotatedNameMultipleInterfaces),
"Named parameter Org.Apache.REEF.Tang.Implementation.AnnotatedNameMultipleInterfaces implements multiple interfaces. It is only allowed to implement Name<T>.");
}
[Fact]
public void TestUnAnnotatedNameMultipleInterfaces()
{
TestNegativeCase(typeof(UnAnnotatedNameMultipleInterfaces),
"Named parameter Org.Apache.REEF.Tang.Implementation.UnAnnotatedNameMultipleInterfaces is missing its @NamedParameter annotation.");
}
[Fact]
public void TestNameWithConstructor()
{
TestNegativeCase(typeof(NameWithConstructor),
"Named parameter Org.Apache.REEF.Tang.Implementation.NameWithConstructor has a constructor. Named parameters must not declare any constructors.");
}
[Fact]
public void TestNameWithZeroArgInject()
{
TestNegativeCase(typeof(NameWithZeroArgInject),
"Named parameter Org.Apache.REEF.Tang.Implementation.NameWithZeroArgInject has an injectable constructor. Named parameters must not declare any constructors.");
}
[Fact]
public void TestInjectNonStaticLocalArgClass()
{
var node = ns.GetNode(typeof(InjectNonStaticLocalArgClass).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(InjectNonStaticLocalArgClass).AssemblyQualifiedName);
}
[Fact]
public void TestInjectNonStaticLocalType()
{
var node = ns.GetNode(typeof(InjectNonStaticLocalType).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(InjectNonStaticLocalType).AssemblyQualifiedName);
}
[Fact]
public void TestOKShortNames()
{
var node = ns.GetNode(typeof(ShortNameFooA).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(ShortNameFooA).AssemblyQualifiedName);
}
public void TestConflictingShortNames()
{
string msg = null;
try
{
var nodeA = ns.GetNode(typeof(ShortNameFooA).AssemblyQualifiedName);
var nodeB = ns.GetNode(typeof(ShortNameFooB).AssemblyQualifiedName);
msg =
"ShortNameFooA and ShortNameFooB have the same short name" +
nodeA.GetName() + nodeB.GetName();
}
catch (Exception e)
{
Console.WriteLine(e);
}
Assert.True(msg == null, msg);
}
[Fact]
public void TestRoundTripInnerClassNames()
{
INode node = ns.GetNode(typeof(Nested.Inner).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(Nested.Inner).AssemblyQualifiedName);
}
[Fact]
public void TestRoundTripAnonInnerClassNames()
{
INode node1 = ns.GetNode(typeof(AnonNested.X1).AssemblyQualifiedName);
INode node2 = ns.GetNode(typeof(AnonNested.Y1).AssemblyQualifiedName);
Assert.NotEqual(node1.GetFullName(), node2.GetFullName());
Type t1 = ReflectionUtilities.GetTypeByName(node1.GetFullName());
Type t2 = ReflectionUtilities.GetTypeByName(node2.GetFullName());
Assert.NotSame(t1, t2);
}
[Fact]
public void TestNameCantBindWrongSubclassAsDefault()
{
TestNegativeCase(typeof(BadName),
"class org.apache.reef.tang.implementation.BadName defines a default class Int32 with a type that does not extend of its target's type string");
}
[Fact]
public void TestNameCantBindWrongSubclassOfArgumentAsDefault()
{
TestNegativeCase(typeof(BadNameForGeneric),
"class BadNameForGeneric defines a default class Int32 with a type that does not extend of its target's string in ISet<string>");
}
[Fact]
public void TestNameCantBindSubclassOfArgumentAsDefault()
{
ns = TangFactory.GetTang().GetClassHierarchy(new string[] { FileNames.Examples, FileNames.Common, FileNames.Tasks });
INode node = ns.GetNode(typeof(GoodNameForGeneric).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), typeof(GoodNameForGeneric).AssemblyQualifiedName);
}
[Fact]
public void TestInterfaceCantBindWrongImplAsDefault()
{
TestNegativeCase(typeof(IBadIfaceDefault),
"interface IBadIfaceDefault declares its default implementation to be non-subclass class string");
}
private void TestNegativeCase(Type clazz, string message)
{
string msg = null;
try
{
var node = ns.GetNode(typeof(IBadIfaceDefault).AssemblyQualifiedName);
msg = message + node.GetName();
}
catch (Exception)
{
}
Assert.True(msg == null, msg);
}
[Fact]
public void TestParseableDefaultClassNotOK()
{
TestNegativeCase(typeof(BadParsableDefaultClass),
"Named parameter BadParsableDefaultClass defines default implementation for parsable type System.string");
}
[Fact]
public void testGenericTorture1()
{
g(typeof(GenericTorture1));
}
[Fact]
public void testGenericTorture2()
{
g(typeof(GenericTorture2));
}
[Fact]
public void testGenericTorture3()
{
g(typeof(GenericTorture3));
}
[Fact]
public void testGenericTorture4()
{
g(typeof(GenericTorture4));
}
public string s(Type t)
{
return ReflectionUtilities.GetAssemblyQualifiedName(t);
}
public INode g(Type t)
{
INode n = ns.GetNode(s(t));
Assert.NotNull(n);
return n;
}
[Fact]
public void TestHelloTaskNode()
{
var node = ns.GetNode(typeof(HelloTask).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(HelloTask)));
}
[Fact]
public void TestITackNode()
{
var node = ns.GetNode(typeof(ITask).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(ITask)));
}
[Fact]
public void TestNamedParameterIdentifier()
{
var node = ns.GetNode(typeof(TaskConfigurationOptions.Identifier).AssemblyQualifiedName);
Assert.Equal(node.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(TaskConfigurationOptions.Identifier)));
}
[Fact]
public void TestInterface()
{
g(typeof(A));
g(typeof(MyInterface<int>));
g(typeof(MyInterface<string>));
g(typeof(B));
ITang tang = TangFactory.GetTang();
ICsConfigurationBuilder cb = tang.NewConfigurationBuilder();
cb.BindImplementation(GenericType<MyInterface<string>>.Class, GenericType<MyImplString>.Class);
cb.BindImplementation(GenericType<MyInterface<int>>.Class, GenericType<MyImplInt>.Class);
IConfiguration conf = cb.Build();
IInjector i = tang.NewInjector(conf);
var a = (A)i.GetInstance(typeof(A));
var implString = (MyImplString)i.GetInstance(typeof(MyImplString));
var implInt = (MyImplString)i.GetInstance(typeof(MyImplString));
var b = (B)i.GetInstance(typeof(B));
var c = (C)i.GetInstance(typeof(C));
Assert.NotNull(a);
Assert.NotNull(implString);
Assert.NotNull(implInt);
Assert.NotNull(b);
Assert.NotNull(c);
}
// See REEF-1276
[Fact]
public void TestInjectableClassWithParameterAnnotationThrowsMeaningfulException()
{
ITang tang = TangFactory.GetTang();
IInjector i = tang.NewInjector(tang.NewConfigurationBuilder().Build());
Action injection = () => i.GetInstance(typeof(ClazzA));
Assert.Throws<ArgumentException>(injection);
}
}
[NamedParameter]
class GenericTorture1 : Name<ISet<string>>
{
}
[NamedParameter]
class GenericTorture2 : Name<ISet<ISet<string>>>
{
}
[NamedParameter]
class GenericTorture3 : Name<IDictionary<ISet<string>, ISet<string>>>
{
}
[NamedParameter]
class GenericTorture4 : Name<IDictionary<string, string>>
{
}
public interface MyInterface<T>
{
}
public class RepeatConstructorArg
{
[Inject]
public RepeatConstructorArg(int x, int y)
{
}
}
public class RepeatConstructorArgClasses
{
[Inject]
public RepeatConstructorArgClasses(A x, A y)
{
}
}
public class A : MyInterface<int>, MyInterface<string>
{
[Inject]
A()
{
}
}
public class MyImplString : MyInterface<string>
{
[Inject]
public MyImplString()
{
}
}
public class B
{
[Inject]
public B(MyInterface<string> b)
{
}
}
public class MyImplInt : MyInterface<int>
{
[Inject]
public MyImplInt()
{
}
}
public class C
{
[Inject]
public C(MyInterface<int> b)
{
}
}
public class LeafRepeatedConstructorArgClasses
{
public static class A
{
public class AA
{
}
}
public static class B
{
public class AA
{
}
}
public class C
{
[Inject]
public C(A.AA a, B.AA b)
{
}
}
}
class D
{
}
[NamedParameter]
class D1 : Name<D>
{
}
[NamedParameter]
class D2 : Name<D>
{
}
class NamedRepeatConstructorArgClasses
{
[Inject]
public NamedRepeatConstructorArgClasses([Parameter(typeof(D1))] D x, [Parameter(typeof(D2))] D y)
{
}
}
class NamedParameterTypeMismatch
{
[NamedParameter(Documentation = "doc.stuff", DefaultValue = "1")]
class Foo : Name<int>
{
}
[Inject]
public NamedParameterTypeMismatch([Parameter(Value = typeof(Foo))] string s)
{
}
}
class UnannotatedName : Name<string>
{
}
interface I1
{
}
[NamedParameter(Documentation = "c")]
class AnnotatedNotName
{
}
[NamedParameter(Documentation = "c")]
class AnnotatedNameWrongInterface : I1
{
}
class UnAnnotatedNameMultipleInterfaces : Name<object>, I1
{
}
[NamedParameter(Documentation = "c")]
class AnnotatedNameMultipleInterfaces : Name<object>, I1
{
}
[NamedParameter(Documentation = "c")]
class NameWithConstructor : Name<object>
{
private NameWithConstructor(int i)
{
}
}
[NamedParameter]
class NameWithZeroArgInject : Name<object>
{
[Inject]
public NameWithZeroArgInject()
{
}
}
class InjectNonStaticLocalArgClass
{
class NonStaticLocal
{
}
[Inject]
InjectNonStaticLocalArgClass(NonStaticLocal x)
{
}
}
class InjectNonStaticLocalType
{
class NonStaticLocal
{
[Inject]
NonStaticLocal(NonStaticLocal x)
{
}
}
}
[NamedParameter(ShortName = "foo")]
public class ShortNameFooA : Name<string>
{
}
// when same short name is used, exception would throw when building the class hierarchy
[NamedParameter(ShortName = "foo")]
public class ShortNameFooB : Name<int>
{
}
class Nested
{
public class Inner
{
}
}
class AnonNested
{
public interface X
{
}
public class X1 : X
{
// int i;
}
public class Y1 : X
{
// int j;
}
public static X XObj = new X1();
public static X YObj = new Y1();
}
// Negative case: Int32 doesn't match string
[NamedParameter(DefaultClass = typeof(Int32))]
class BadName : Name<string>
{
}
// Negative case: Int32 doesn't match string in the ISet
[NamedParameter(DefaultClass = typeof(Int32))]
class BadNameForGeneric : Name<ISet<string>>
{
}
// Positive case: type matched. ISet is not in parsable list
[NamedParameter(DefaultClass = typeof(string))]
class GoodNameForGeneric : Name<ISet<string>>
{
}
[DefaultImplementation(typeof(string))]
interface IBadIfaceDefault
{
}
// negative case: type matched. However, string is in the parsable list and DefaultClass is not null.
[NamedParameter(DefaultClass = typeof(string))]
class BadParsableDefaultClass : Name<string>
{
}
// ClazzB is injectable and does not need the Parameter annotation in the ClazzA constructor
class ClazzA
{
private ClazzB objectB;
public class ClazzB
{
[Inject]
public ClazzB()
{
}
}
[Inject]
public ClazzA([Parameter(typeof(ClazzB))] ClazzB objectB)
{
this.objectB = objectB;
}
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="WindowTests.cs" company="Steven Kirk">
// Copyright 2015 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class WindowTests
{
[Fact]
public void Setting_Title_Should_Set_Impl_Title()
{
var windowImpl = new Mock<IWindowImpl>();
var windowingPlatform = new MockWindowingPlatform(() => windowImpl.Object);
using (UnitTestApplication.Start(new TestServices(windowingPlatform: windowingPlatform)))
{
var target = new Window();
target.Title = "Hello World";
windowImpl.Verify(x => x.SetTitle("Hello World"));
}
}
[Fact]
public void IsVisible_Should_Initially_Be_False()
{
using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
{
var window = new Window();
Assert.False(window.IsVisible);
}
}
[Fact]
public void IsVisible_Should_Be_True_After_Show()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var window = new Window();
window.Show();
Assert.True(window.IsVisible);
}
}
[Fact]
public void IsVisible_Should_Be_True_After_ShowDialog()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var window = new Window();
var task = window.ShowDialog();
Assert.True(window.IsVisible);
}
}
[Fact]
public void IsVisible_Should_Be_False_After_Hide()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var window = new Window();
window.Show();
window.Hide();
Assert.False(window.IsVisible);
}
}
[Fact]
public void IsVisible_Should_Be_False_After_Close()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var window = new Window();
window.Show();
window.Close();
Assert.False(window.IsVisible);
}
}
[Fact]
public void IsVisible_Should_Be_False_After_Impl_Signals_Close()
{
var windowImpl = new Mock<IWindowImpl>();
windowImpl.SetupProperty(x => x.Closed);
windowImpl.Setup(x => x.Scaling).Returns(1);
var services = TestServices.StyledWindow.With(
windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object));
using (UnitTestApplication.Start(services))
{
var window = new Window();
window.Show();
windowImpl.Object.Closed();
Assert.False(window.IsVisible);
}
}
[Fact]
public void Show_Should_Add_Window_To_OpenWindows()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
ClearOpenWindows();
var window = new Window();
window.Show();
Assert.Equal(new[] { window }, Window.OpenWindows);
}
}
[Fact]
public void Window_Should_Be_Added_To_OpenWindows_Only_Once()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
ClearOpenWindows();
var window = new Window();
window.Show();
window.Show();
window.IsVisible = true;
Assert.Equal(new[] { window }, Window.OpenWindows);
window.Close();
}
}
[Fact]
public void Close_Should_Remove_Window_From_OpenWindows()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
ClearOpenWindows();
var window = new Window();
window.Show();
window.Close();
Assert.Empty(Window.OpenWindows);
}
}
[Fact]
public void Impl_Closing_Should_Remove_Window_From_OpenWindows()
{
var windowImpl = new Mock<IWindowImpl>();
windowImpl.SetupProperty(x => x.Closed);
windowImpl.Setup(x => x.Scaling).Returns(1);
var services = TestServices.StyledWindow.With(
windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object));
using (UnitTestApplication.Start(services))
{
ClearOpenWindows();
var window = new Window();
window.Show();
windowImpl.Object.Closed();
Assert.Empty(Window.OpenWindows);
}
}
[Fact]
public void Showing_Should_Start_Renderer()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var renderer = new Mock<IRenderer>();
var target = new Window(CreateImpl(renderer));
target.Show();
renderer.Verify(x => x.Start(), Times.Once);
}
}
[Fact]
public void ShowDialog_Should_Start_Renderer()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var renderer = new Mock<IRenderer>();
var target = new Window(CreateImpl(renderer));
target.Show();
renderer.Verify(x => x.Start(), Times.Once);
}
}
[Fact]
public void Hiding_Should_Stop_Renderer()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var renderer = new Mock<IRenderer>();
var target = new Window(CreateImpl(renderer));
target.Show();
target.Hide();
renderer.Verify(x => x.Stop(), Times.Once);
}
}
[Fact]
public async Task ShowDialog_With_ValueType_Returns_Default_When_Closed()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var windowImpl = new Mock<IWindowImpl>();
windowImpl.SetupProperty(x => x.Closed);
windowImpl.Setup(x => x.Scaling).Returns(1);
var target = new Window(windowImpl.Object);
var task = target.ShowDialog<bool>();
windowImpl.Object.Closed();
var result = await task;
Assert.False(result);
}
}
[Fact]
public void Window_Should_Be_Centered_When_WindowStartupLocation_Is_CenterScreen()
{
var screen1 = new Mock<Screen>(new Rect(new Size(1920, 1080)), new Rect(new Size(1920, 1040)), true);
var screen2 = new Mock<Screen>(new Rect(new Size(1366, 768)), new Rect(new Size(1366, 728)), false);
var screens = new Mock<IScreenImpl>();
screens.Setup(x => x.AllScreens).Returns(new Screen[] { screen1.Object, screen2.Object });
var windowImpl = new Mock<IWindowImpl>();
windowImpl.SetupProperty(x => x.Position);
windowImpl.Setup(x => x.ClientSize).Returns(new Size(800, 480));
windowImpl.Setup(x => x.Scaling).Returns(1);
windowImpl.Setup(x => x.Screen).Returns(screens.Object);
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var window = new Window(windowImpl.Object);
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
window.Position = new Point(60, 40);
window.Show();
var expectedPosition = new Point(
screen1.Object.WorkingArea.Size.Width / 2 - window.ClientSize.Width / 2,
screen1.Object.WorkingArea.Size.Height / 2 - window.ClientSize.Height / 2);
Assert.Equal(window.Position, expectedPosition);
}
}
[Fact]
public void Window_Should_Be_Centered_Relative_To_Owner_When_WindowStartupLocation_Is_CenterOwner()
{
var parentWindowImpl = new Mock<IWindowImpl>();
parentWindowImpl.SetupProperty(x => x.Position);
parentWindowImpl.Setup(x => x.ClientSize).Returns(new Size(800, 480));
parentWindowImpl.Setup(x => x.MaxClientSize).Returns(new Size(1920, 1080));
parentWindowImpl.Setup(x => x.Scaling).Returns(1);
var windowImpl = new Mock<IWindowImpl>();
windowImpl.SetupProperty(x => x.Position);
windowImpl.Setup(x => x.ClientSize).Returns(new Size(320, 200));
windowImpl.Setup(x => x.MaxClientSize).Returns(new Size(1920, 1080));
windowImpl.Setup(x => x.Scaling).Returns(1);
var parentWindowServices = TestServices.StyledWindow.With(
windowingPlatform: new MockWindowingPlatform(() => parentWindowImpl.Object));
var windowServices = TestServices.StyledWindow.With(
windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object));
using (UnitTestApplication.Start(parentWindowServices))
{
var parentWindow = new Window();
parentWindow.Position = new Point(60, 40);
parentWindow.Show();
using (UnitTestApplication.Start(windowServices))
{
var window = new Window();
window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
window.Position = new Point(60, 40);
window.Owner = parentWindow;
window.Show();
var expectedPosition = new Point(
parentWindow.Position.X + parentWindow.ClientSize.Width / 2 - window.ClientSize.Width / 2,
parentWindow.Position.Y + parentWindow.ClientSize.Height / 2 - window.ClientSize.Height / 2);
Assert.Equal(window.Position, expectedPosition);
}
}
}
private IWindowImpl CreateImpl(Mock<IRenderer> renderer)
{
return Mock.Of<IWindowImpl>(x =>
x.Scaling == 1 &&
x.CreateRenderer(It.IsAny<IRenderRoot>()) == renderer.Object);
}
private void ClearOpenWindows()
{
// HACK: We really need a decent way to have "statics" that can be scoped to
// AvaloniaLocator scopes.
((IList<Window>)Window.OpenWindows).Clear();
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 Microsoft.PackageManagement.Internal.Utility.Plugin;
namespace Microsoft.PackageManagement.MetaProvider.PowerShell.Internal {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using System.Security;
using Microsoft.PackageManagement.Internal.Api;
using Microsoft.PackageManagement.Internal.Implementation;
using Microsoft.PackageManagement.Internal.Utility.Extensions;
using Microsoft.PackageManagement.Internal.Utility.Async;
using Messages = Microsoft.PackageManagement.MetaProvider.PowerShell.Resources.Messages;
public abstract class PsRequest : Request {
internal CommandInfo CommandInfo;
private PowerShellProviderBase _provider;
internal bool IsMethodImplemented {
get {
return CommandInfo != null;
}
}
public IEnumerable<string> PackageSources {
get {
var ps = Sources;
if (ps == null) {
return new string[] {
};
}
return ps.ToArray();
}
}
internal IRequest Extend(params object[] objects) {
return objects.ConcatSingleItem(this).As<IRequest>();
}
internal string GetMessageStringInternal(string messageText) {
return Messages.ResourceManager.GetString(messageText);
}
public PSCredential Credential {
get
{
if (CredentialUsername != null && CredentialPassword != null) {
return new PSCredential(CredentialUsername, CredentialPassword);
}
return null;
}
}
private Hashtable _options;
public Hashtable Options {
get {
if (_options == null) {
_options = new Hashtable();
//quick and dirty, grab all four sets and merge them.
var keys = OptionKeys ?? new string[0];
foreach (var k in keys) {
if (_options.ContainsKey(k)) {
continue;
}
var values = GetOptionValues(k).ToArray();
if (values.Length == 1) {
if (values[0].IsTrue()) {
_options.Add(k, true);
} else if (values[0].IndexOf("SECURESTRING:", StringComparison.OrdinalIgnoreCase) == 0) {
#if !CORECLR
_options.Add(k, values[0].Substring(13).FromProtectedString("salt"));
#endif
} else {
_options.Add(k, values[0]);
}
} else {
_options.Add(k, values);
}
}
}
return _options;
}
}
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "This is required for the PowerShell Providers.")]
public object CloneRequest(Hashtable options = null, ArrayList sources = null, PSCredential credential = null) {
var srcs = (sources ?? new ArrayList()).ToArray().Select(each => each.ToString()).ToArray();
options = options ?? new Hashtable();
var lst = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
foreach (var k in options.Keys) {
if (k != null) {
var obj = options[k];
string[] val = null;
if (obj is string) {
val = new[] {obj as string};
} else {
// otherwise, try to cast it to a collection of string-like-things
var collection = obj as IEnumerable;
if (collection != null) {
val = collection.Cast<object>().Select(each => each.ToString()).ToArray();
} else {
// meh. ToString, and goodnight.
val = new[] {obj.ToString()};
}
}
lst.Add(k.ToString(), val);
}
}
return Extend(new {
GetOptionKeys = new Func<IEnumerable<string>>(() => {return lst.Keys.ToArray();}),
GetOptionValues = new Func<string, IEnumerable<string>>((key) => {
if (lst.ContainsKey(key)) {
return lst[key];
}
return new string[0];
}),
GetSources = new Func<IEnumerable<string>>(() => {return srcs;}),
GetCredentialUsername = new Func<string>(() => {return credential != null ? credential.UserName : null;}),
GetCredentialPassword = new Func<SecureString>(() => {return credential != null ? credential.Password: null;}),
ShouldContinueWithUntrustedPackageSource = new Func<string, string, bool>((pkgName, pkgSource) => {
// chained providers provide locations, and don't rely on 'trusted' flags from the upstream provider.
return true;
})
});
}
public object CallPowerShell(params object[] args) {
if (IsMethodImplemented) {
return _provider.CallPowerShell(this, args);
}
return null;
}
internal static PsRequest New(Object requestObject, PowerShellProviderBase provider, string methodName) {
if (requestObject is IAsyncAction) {
((IAsyncAction)(requestObject)).OnCancel += provider.CancelRequest;
((IAsyncAction)(requestObject)).OnAbort += provider.CancelRequest;
}
var req = requestObject.As<PsRequest>();
req.CommandInfo = provider.GetMethod(methodName);
if (req.CommandInfo == null) {
req.Debug("METHOD_NOT_IMPLEMENTED", methodName);
}
req._provider = provider;
if (req.Options == null) {
req.Debug("req.Options is null");
} else {
req.Debug("Calling New() : MethodName = '{0}'", methodName);
foreach(string key in req.Options.Keys)
{
req.Debug(String.Format(CultureInfo.CurrentCulture, "{0}: {1}", key, req.Options[key]));
}
}
return req;
}
public object SelectProvider(string providerName) {
return PackageManagementService.SelectProviders(providerName, Extend()).FirstOrDefault(each => each.Name.EqualsIgnoreCase(providerName));
}
public IEnumerable<object> SelectProviders(string providerName) {
return PackageManagementService.SelectProviders(providerName, Extend());
}
public object Services {
get {
return ProviderServices;
}
}
public IEnumerable<object> FindPackageByCanonicalId(string packageId, object requestObject) {
return ProviderServices.FindPackageByCanonicalId(packageId, (requestObject ?? new object()) .As<IRequest>());
}
public bool RequirePackageProvider(string packageProviderName, string minimumVersion) {
var pp = (_provider as PowerShellPackageProvider);
return PackageManagementService.RequirePackageProvider(pp == null ? Constants.ProviderNameUnknown : pp.GetPackageProviderName(), packageProviderName, minimumVersion, Extend());
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Network
{
/// <summary>
/// The Network Resource Provider API includes operations for managing the
/// Routes for your subscription.
/// </summary>
internal partial class RouteOperations : IServiceOperations<NetworkResourceProviderClient>, IRouteOperations
{
/// <summary>
/// Initializes a new instance of the RouteOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal RouteOperations(NetworkResourceProviderClient client)
{
this._client = client;
}
private NetworkResourceProviderClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Network.NetworkResourceProviderClient.
/// </summary>
public NetworkResourceProviderClient Client
{
get { return this._client; }
}
/// <summary>
/// The Put route operation creates/updates a route in the specified
/// route table
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// Required. The name of the route table.
/// </param>
/// <param name='routeName'>
/// Required. The name of the route.
/// </param>
/// <param name='routeParameters'>
/// Required. Parameters supplied to the create/update routeoperation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for PUT Routes Api servive call
/// </returns>
public async Task<RoutePutResponse> BeginCreateOrUpdatingAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (routeTableName == null)
{
throw new ArgumentNullException("routeTableName");
}
if (routeName == null)
{
throw new ArgumentNullException("routeName");
}
if (routeParameters == null)
{
throw new ArgumentNullException("routeParameters");
}
if (routeParameters.NextHopType == null)
{
throw new ArgumentNullException("routeParameters.NextHopType");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
tracingParameters.Add("routeParameters", routeParameters);
TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdatingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Network";
url = url + "/routeTables/";
url = url + Uri.EscapeDataString(routeTableName);
url = url + "/routes/";
url = url + Uri.EscapeDataString(routeName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject routeJsonFormatValue = new JObject();
requestDoc = routeJsonFormatValue;
JObject propertiesValue = new JObject();
routeJsonFormatValue["properties"] = propertiesValue;
if (routeParameters.AddressPrefix != null)
{
propertiesValue["addressPrefix"] = routeParameters.AddressPrefix;
}
propertiesValue["nextHopType"] = routeParameters.NextHopType;
if (routeParameters.NextHopIpAddress != null)
{
propertiesValue["nextHopIpAddress"] = routeParameters.NextHopIpAddress;
}
if (routeParameters.ProvisioningState != null)
{
propertiesValue["provisioningState"] = routeParameters.ProvisioningState;
}
if (routeParameters.Name != null)
{
routeJsonFormatValue["name"] = routeParameters.Name;
}
if (routeParameters.Etag != null)
{
routeJsonFormatValue["etag"] = routeParameters.Etag;
}
if (routeParameters.Id != null)
{
routeJsonFormatValue["id"] = routeParameters.Id;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RoutePutResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RoutePutResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Route routeInstance = new Route();
result.Route = routeInstance;
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
JToken addressPrefixValue = propertiesValue2["addressPrefix"];
if (addressPrefixValue != null && addressPrefixValue.Type != JTokenType.Null)
{
string addressPrefixInstance = ((string)addressPrefixValue);
routeInstance.AddressPrefix = addressPrefixInstance;
}
JToken nextHopTypeValue = propertiesValue2["nextHopType"];
if (nextHopTypeValue != null && nextHopTypeValue.Type != JTokenType.Null)
{
string nextHopTypeInstance = ((string)nextHopTypeValue);
routeInstance.NextHopType = nextHopTypeInstance;
}
JToken nextHopIpAddressValue = propertiesValue2["nextHopIpAddress"];
if (nextHopIpAddressValue != null && nextHopIpAddressValue.Type != JTokenType.Null)
{
string nextHopIpAddressInstance = ((string)nextHopIpAddressValue);
routeInstance.NextHopIpAddress = nextHopIpAddressInstance;
}
JToken provisioningStateValue = propertiesValue2["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
routeInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
routeInstance.Name = nameInstance;
}
JToken etagValue = responseDoc["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
routeInstance.Etag = etagInstance;
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
routeInstance.Id = idInstance;
}
JToken errorValue = responseDoc["error"];
if (errorValue != null && errorValue.Type != JTokenType.Null)
{
Error errorInstance = new Error();
result.Error = errorInstance;
JToken codeValue = errorValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = errorValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = errorValue["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
JToken detailsArray = errorValue["details"];
if (detailsArray != null && detailsArray.Type != JTokenType.Null)
{
foreach (JToken detailsValue in ((JArray)detailsArray))
{
ErrorDetails errorDetailsInstance = new ErrorDetails();
errorInstance.Details.Add(errorDetailsInstance);
JToken codeValue2 = detailsValue["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
errorDetailsInstance.Code = codeInstance2;
}
JToken targetValue2 = detailsValue["target"];
if (targetValue2 != null && targetValue2.Type != JTokenType.Null)
{
string targetInstance2 = ((string)targetValue2);
errorDetailsInstance.Target = targetInstance2;
}
JToken messageValue2 = detailsValue["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
errorDetailsInstance.Message = messageInstance2;
}
}
}
JToken innerErrorValue = errorValue["innerError"];
if (innerErrorValue != null && innerErrorValue.Type != JTokenType.Null)
{
string innerErrorInstance = ((string)innerErrorValue);
errorInstance.InnerError = innerErrorInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The delete route operation deletes the specified route from a route
/// table.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// Required. The name of the route table.
/// </param>
/// <param name='routeName'>
/// Required. The name of the route.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// If the resource provide needs to return an error to any operation,
/// it should return the appropriate HTTP error code and a message
/// body as can be seen below.The message should be localized per the
/// Accept-Language header specified in the original request such
/// thatit could be directly be exposed to users
/// </returns>
public async Task<UpdateOperationResponse> BeginDeletingAsync(string resourceGroupName, string routeTableName, string routeName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (routeTableName == null)
{
throw new ArgumentNullException("routeTableName");
}
if (routeName == null)
{
throw new ArgumentNullException("routeName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Network";
url = url + "/routeTables/";
url = url + Uri.EscapeDataString(routeTableName);
url = url + "/routes/";
url = url + Uri.EscapeDataString(routeName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
UpdateOperationResponse result = null;
// Deserialize Response
result = new UpdateOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Put route operation creates/updates a route in the specified
/// route table
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// Required. The name of the route table.
/// </param>
/// <param name='routeName'>
/// Required. The name of the route.
/// </param>
/// <param name='routeParameters'>
/// Required. Parameters supplied to the create/update route operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, CancellationToken cancellationToken)
{
NetworkResourceProviderClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
tracingParameters.Add("routeParameters", routeParameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
RoutePutResponse response = await client.Routes.BeginCreateOrUpdatingAsync(resourceGroupName, routeTableName, routeName, routeParameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
AzureAsyncOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != Microsoft.Azure.Management.Network.Models.OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// The delete route operation deletes the specified route from a route
/// table.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// Required. The name of the route table.
/// </param>
/// <param name='routeName'>
/// Required. The name of the route.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string routeTableName, string routeName, CancellationToken cancellationToken)
{
NetworkResourceProviderClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
UpdateOperationResponse response = await client.Routes.BeginDeletingAsync(resourceGroupName, routeTableName, routeName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
AzureAsyncOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != Microsoft.Azure.Management.Network.Models.OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// The Get route operation retreives information about the specified
/// route from the route table.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// Required. The name of the route table.
/// </param>
/// <param name='routeName'>
/// Required. The name of the route.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for GetRoute Api service call
/// </returns>
public async Task<RouteGetResponse> GetAsync(string resourceGroupName, string routeTableName, string routeName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (routeTableName == null)
{
throw new ArgumentNullException("routeTableName");
}
if (routeName == null)
{
throw new ArgumentNullException("routeName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Network";
url = url + "/routeTables/";
url = url + Uri.EscapeDataString(routeTableName);
url = url + "/routes/";
url = url + Uri.EscapeDataString(routeName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RouteGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RouteGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Route routeInstance = new Route();
result.Route = routeInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken addressPrefixValue = propertiesValue["addressPrefix"];
if (addressPrefixValue != null && addressPrefixValue.Type != JTokenType.Null)
{
string addressPrefixInstance = ((string)addressPrefixValue);
routeInstance.AddressPrefix = addressPrefixInstance;
}
JToken nextHopTypeValue = propertiesValue["nextHopType"];
if (nextHopTypeValue != null && nextHopTypeValue.Type != JTokenType.Null)
{
string nextHopTypeInstance = ((string)nextHopTypeValue);
routeInstance.NextHopType = nextHopTypeInstance;
}
JToken nextHopIpAddressValue = propertiesValue["nextHopIpAddress"];
if (nextHopIpAddressValue != null && nextHopIpAddressValue.Type != JTokenType.Null)
{
string nextHopIpAddressInstance = ((string)nextHopIpAddressValue);
routeInstance.NextHopIpAddress = nextHopIpAddressInstance;
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
routeInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
routeInstance.Name = nameInstance;
}
JToken etagValue = responseDoc["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
routeInstance.Etag = etagInstance;
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
routeInstance.Id = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List network security rule opertion retrieves all the routes in
/// a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// Required. The name of the route table.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for ListRoute Api servive call
/// </returns>
public async Task<RouteListResponse> ListAsync(string resourceGroupName, string routeTableName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (routeTableName == null)
{
throw new ArgumentNullException("routeTableName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Network";
url = url + "/routeTables/";
url = url + Uri.EscapeDataString(routeTableName);
url = url + "/routes";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RouteListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RouteListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Route routeJsonFormatInstance = new Route();
result.Routes.Add(routeJsonFormatInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken addressPrefixValue = propertiesValue["addressPrefix"];
if (addressPrefixValue != null && addressPrefixValue.Type != JTokenType.Null)
{
string addressPrefixInstance = ((string)addressPrefixValue);
routeJsonFormatInstance.AddressPrefix = addressPrefixInstance;
}
JToken nextHopTypeValue = propertiesValue["nextHopType"];
if (nextHopTypeValue != null && nextHopTypeValue.Type != JTokenType.Null)
{
string nextHopTypeInstance = ((string)nextHopTypeValue);
routeJsonFormatInstance.NextHopType = nextHopTypeInstance;
}
JToken nextHopIpAddressValue = propertiesValue["nextHopIpAddress"];
if (nextHopIpAddressValue != null && nextHopIpAddressValue.Type != JTokenType.Null)
{
string nextHopIpAddressInstance = ((string)nextHopIpAddressValue);
routeJsonFormatInstance.NextHopIpAddress = nextHopIpAddressInstance;
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
routeJsonFormatInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
routeJsonFormatInstance.Name = nameInstance;
}
JToken etagValue = valueValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
routeJsonFormatInstance.Etag = etagInstance;
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
routeJsonFormatInstance.Id = idInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using Xunit;
using Xunit.Sdk;
namespace Jint.Tests.Ecma
{
public class Test_12_2_1 : EcmaTest
{
[Fact]
[Trait("Category", "12.2.1")]
public void EvalAFunctionDeclaringAVarNamedEvalThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-1-s.js", false);
}
[Fact(Skip = "Indirect eval call also imply changes to the parser logic")]
[Trait("Category", "12.2.1")]
public void StrictModeAnIndirectEvalAssigningIntoEvalDoesNotThrow()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-10-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAsVarIdentifierInEvalCodeIsAllowed()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-11.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAsLocalVarIdentifierThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-12-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAsLocalVarIdentifierIsAllowed()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-12.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAssignmentThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-13-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAFunctionExprDeclaringAVarNamedArgumentsThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-14-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAFunctionExprAssigningIntoArgumentsThrowsASyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-15-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void AFunctionConstructorCalledAsAFunctionDeclaringAVarNamedArgumentsDoesNotThrowASyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-16-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void AFunctionConstructorCalledAsAFunctionAssigningIntoArgumentsWillNotThrowAnyErrorIfContainedWithinStrictModeAndItsBodyDoesNotStartWithStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-17-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ADirectEvalDeclaringAVarNamedArgumentsThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-18-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ADirectEvalAssigningIntoArgumentsThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-19-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void StrictModeSyntaxerrorIsThrownIfAVariabledeclarationOccursWithinStrictCodeAndItsIdentifierIsEval()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-1gs.js", true);
}
[Fact]
[Trait("Category", "12.2.1")]
public void EvalAFunctionAssigningIntoEvalThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-2-s.js", false);
}
[Fact(Skip = "Indirect eval call also imply changes to the parser logic")]
[Trait("Category", "12.2.1")]
public void StrictModeAnIndirectEvalDeclaringAVarNamedArgumentsDoesNotThrow()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-20-s.js", false);
}
[Fact(Skip = "Indirect eval call also imply changes to the parser logic")]
[Trait("Category", "12.2.1")]
public void StrictModeAnIndirectEvalAssigningIntoArgumentsDoesNotThrow()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-21-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAsGlobalVarIdentifierThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-22-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAsLocalVarIdentifierAssignedToThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-23-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void EvalAsLocalVarIdentifierAssignedToThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-24-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAsLocalVarIdentifierThrowsSyntaxerrorInStrictMode2()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-25-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void EvalAsLocalVarIdentifierThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-26-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void EvalAsLocalVarIdentifierAssignedToThrowsSyntaxerrorInStrictMode2()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-27-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAsLocalVarIdentifierAssignedToThrowsSyntaxerrorInStrictMode2()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-28-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void EvalAsLocalVarIdentifierThrowsSyntaxerrorInStrictMode2()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-29-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void EvalAFunctionExprDeclaringAVarNamedEvalThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-3-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAsLocalVarIdentifierThrowsSyntaxerrorInStrictMode3()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-30-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void EvalAsLocalVarIdentifierDefinedTwiceThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-31-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAsLocalVarIdentifierDefinedTwiceAndAssignedOnceThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-32-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ArgumentsAsLocalVarIdentifierThrowsSyntaxerrorInStrictMode4()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-33-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ForVarEvalInThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-34-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ForVarEval42InThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-35-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ForVarArgumentsInThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-36-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void ForVarArguments42InThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-37-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void EvalAFunctionExprAssigningIntoEvalThrowsASyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-4-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void StrictModeSyntaxerrorIsThrownIfAVariabledeclarationnoinOccursWithinStrictCodeAndItsIdentifierIsArguments()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-4gs.js", true);
}
[Fact]
[Trait("Category", "12.2.1")]
public void StrictModeAFunctionDeclaringVarNamedEvalDoesNotThrowSyntaxerror()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-5-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void EvalAFunctionAssigningIntoEvalWillNotThrowAnyErrorIfContainedWithinStrictModeAndItsBodyDoesNotStartWithStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-6-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void EvalADirectEvalDeclaringAVarNamedEvalThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-7-s.js", false);
}
[Fact]
[Trait("Category", "12.2.1")]
public void EvalADirectEvalAssigningIntoEvalThrowsSyntaxerrorInStrictMode()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-8-s.js", false);
}
[Fact(Skip = "Indirect eval call also imply changes to the parser logic")]
[Trait("Category", "12.2.1")]
public void StrictModeAnIndirectEvalDeclaringAVarNamedEvalDoesNotThrow()
{
RunTest(@"TestCases/ch12/12.2/12.2.1/12.2.1-9-s.js", false);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
// Class: RegionInfo
//
// Purpose: This class represents settings specified by de jure or
// de facto standards for a particular country/region. In
// contrast to CultureInfo, the RegionInfo does not represent
// preferences of the user and does not depend on the user's
// language or culture.
//
// Date: March 31, 1999
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
[System.Runtime.InteropServices.ComVisible(true)]
public class RegionInfo
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//
// Variables.
//
//
// Name of this region (ie: es-US): serialized, the field used for deserialization
//
internal String m_name;
//
// The CultureData instance that we are going to read data from.
//
internal CultureData m_cultureData;
//
// The RegionInfo for our current region
//
internal static volatile RegionInfo s_currentRegionInfo;
////////////////////////////////////////////////////////////////////////
//
// RegionInfo Constructors
//
// Note: We prefer that a region be created with a full culture name (ie: en-US)
// because otherwise the native strings won't be right.
//
// In Silverlight we enforce that RegionInfos must be created with a full culture name
//
////////////////////////////////////////////////////////////////////////
[System.Security.SecuritySafeCritical] // auto-generated
public RegionInfo(String name)
{
if (name == null)
throw new ArgumentNullException("name");
if (name.Length == 0) //The InvariantCulture has no matching region
{
throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, "name");
}
Contract.EndContractBlock();
//
// For CoreCLR we only want the region names that are full culture names
//
this.m_cultureData = CultureData.GetCultureDataForRegion(name, true);
if (this.m_cultureData == null)
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.Argument_InvalidCultureName, name), "name");
// Not supposed to be neutral
if (this.m_cultureData.IsNeutralCulture)
throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), "name");
SetName(name);
}
[System.Security.SecuritySafeCritical] // auto-generated
internal RegionInfo(CultureData cultureData)
{
this.m_cultureData = cultureData;
this.m_name = this.m_cultureData.SREGIONNAME;
}
[System.Security.SecurityCritical] // auto-generated
private void SetName(string name)
{
// Use the name of the region we found
this.m_name = this.m_cultureData.SREGIONNAME;
}
////////////////////////////////////////////////////////////////////////
//
// GetCurrentRegion
//
// This instance provides methods based on the current user settings.
// These settings are volatile and may change over the lifetime of the
// thread.
//
////////////////////////////////////////////////////////////////////////
public static RegionInfo CurrentRegion
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
RegionInfo temp = s_currentRegionInfo;
if (temp == null)
{
temp = new RegionInfo(CultureInfo.CurrentCulture.m_cultureData);
// Need full name for custom cultures
temp.m_name = temp.m_cultureData.SREGIONNAME;
s_currentRegionInfo = temp;
}
return temp;
}
}
////////////////////////////////////////////////////////////////////////
//
// GetName
//
// Returns the name of the region (ie: en-US)
//
////////////////////////////////////////////////////////////////////////
public virtual String Name
{
get
{
Contract.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already");
return (m_name);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetEnglishName
//
// Returns the name of the region in English. (ie: United States)
//
////////////////////////////////////////////////////////////////////////
public virtual String EnglishName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SENGCOUNTRY);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetDisplayName
//
// Returns the display name (localized) of the region. (ie: United States
// if the current UI language is en-US)
//
////////////////////////////////////////////////////////////////////////
public virtual String DisplayName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SLOCALIZEDCOUNTRY);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetNativeName
//
// Returns the native name of the region. (ie: Deutschland)
// WARNING: You need a full locale name for this to make sense.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public virtual String NativeName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SNATIVECOUNTRY);
}
}
////////////////////////////////////////////////////////////////////////
//
// TwoLetterISORegionName
//
// Returns the two letter ISO region name (ie: US)
//
////////////////////////////////////////////////////////////////////////
public virtual String TwoLetterISORegionName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SISO3166CTRYNAME);
}
}
////////////////////////////////////////////////////////////////////////
//
// IsMetric
//
// Returns true if this region uses the metric measurement system
//
////////////////////////////////////////////////////////////////////////
public virtual bool IsMetric
{
get
{
int value = this.m_cultureData.IMEASURE;
return (value == 0);
}
}
////////////////////////////////////////////////////////////////////////
//
// CurrencySymbol
//
// Currency Symbol for this locale, ie: Fr. or $
//
////////////////////////////////////////////////////////////////////////
public virtual String CurrencySymbol
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SCURRENCY);
}
}
////////////////////////////////////////////////////////////////////////
//
// ISOCurrencySymbol
//
// ISO Currency Symbol for this locale, ie: CHF
//
////////////////////////////////////////////////////////////////////////
public virtual String ISOCurrencySymbol
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SINTLSYMBOL);
}
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same RegionInfo as the current instance.
//
// RegionInfos are considered equal if and only if they have the same name
// (ie: en-US)
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
RegionInfo that = value as RegionInfo;
if (that != null)
{
return this.Name.Equals(that.Name);
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for RegionInfo
// A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.Name.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns the name of the Region, ie: es-US
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return (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.
//
//
//
// This class encapsulates security decisions about an application.
//
namespace System.Security.Policy {
using System.Collections;
using System.Collections.Generic;
#if FEATURE_CLICKONCE
using System.Deployment.Internal.Isolation;
using System.Deployment.Internal.Isolation.Manifest;
#endif
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
#if FEATURE_SERIALIZATION
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
#endif // FEATURE_SERIALIZATION
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Security.Util;
using System.Text;
using System.Threading;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public enum ApplicationVersionMatch {
MatchExactVersion,
MatchAllVersions
}
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public sealed class ApplicationTrust : EvidenceBase, ISecurityEncodable
{
#if FEATURE_CLICKONCE
private ApplicationIdentity m_appId;
private bool m_appTrustedToRun;
private bool m_persist;
private object m_extraInfo;
private SecurityElement m_elExtraInfo;
#endif
private PolicyStatement m_psDefaultGrant;
private IList<StrongName> m_fullTrustAssemblies;
// Permission special flags for the default grant set in this ApplicationTrust. This should be
// updated in sync with any updates to the default grant set.
//
// In the general case, these values cannot be trusted - we only store a reference to the
// DefaultGrantSet, and return the reference directly, which means that code can update the
// permission set without our knowledge. That would lead to the flags getting out of sync with the
// grant set.
//
// However, we only care about these flags when we're creating a homogenous AppDomain, and in that
// case we control the ApplicationTrust object end-to-end, and know that the permission set will not
// change after the flags are calculated.
[NonSerialized]
private int m_grantSetSpecialFlags;
#if FEATURE_CLICKONCE
public ApplicationTrust (ApplicationIdentity applicationIdentity) : this () {
ApplicationIdentity = applicationIdentity;
}
#endif
public ApplicationTrust () : this (new PermissionSet(PermissionState.None))
{
}
internal ApplicationTrust (PermissionSet defaultGrantSet)
{
InitDefaultGrantSet(defaultGrantSet);
m_fullTrustAssemblies = new List<StrongName>().AsReadOnly();
}
public ApplicationTrust(PermissionSet defaultGrantSet, IEnumerable<StrongName> fullTrustAssemblies) {
if (fullTrustAssemblies == null) {
throw new ArgumentNullException("fullTrustAssemblies");
}
InitDefaultGrantSet(defaultGrantSet);
List<StrongName> fullTrustList = new List<StrongName>();
foreach (StrongName strongName in fullTrustAssemblies) {
if (strongName == null) {
throw new ArgumentException(Environment.GetResourceString("Argument_NullFullTrustAssembly"));
}
fullTrustList.Add(new StrongName(strongName.PublicKey, strongName.Name, strongName.Version));
}
m_fullTrustAssemblies = fullTrustList.AsReadOnly();
}
// Sets up the default grant set for all constructors. Extracted to avoid the cost of
// IEnumerable virtual dispatches on startup when there are no fullTrustAssemblies (CoreCLR)
private void InitDefaultGrantSet(PermissionSet defaultGrantSet) {
if (defaultGrantSet == null) {
throw new ArgumentNullException("defaultGrantSet");
}
// Creating a PolicyStatement copies the incoming permission set, so we don't have to worry
// about the PermissionSet parameter changing underneath us after we've calculated the
// permisison flags in the DefaultGrantSet setter.
DefaultGrantSet = new PolicyStatement(defaultGrantSet);
}
#if FEATURE_CLICKONCE
public ApplicationIdentity ApplicationIdentity {
get {
return m_appId;
}
set {
if (value == null)
throw new ArgumentNullException(Environment.GetResourceString("Argument_InvalidAppId"));
Contract.EndContractBlock();
m_appId = value;
}
}
#endif
public PolicyStatement DefaultGrantSet {
get {
if (m_psDefaultGrant == null)
return new PolicyStatement(new PermissionSet(PermissionState.None));
return m_psDefaultGrant;
}
set {
if (value == null) {
m_psDefaultGrant = null;
m_grantSetSpecialFlags = 0;
}
else {
m_psDefaultGrant = value;
m_grantSetSpecialFlags = SecurityManager.GetSpecialFlags(m_psDefaultGrant.PermissionSet, null);
}
}
}
public IList<StrongName> FullTrustAssemblies {
get {
return m_fullTrustAssemblies;
}
}
#if FEATURE_CLICKONCE
public bool IsApplicationTrustedToRun {
get {
return m_appTrustedToRun;
}
set {
m_appTrustedToRun = value;
}
}
public bool Persist {
get {
return m_persist;
}
set {
m_persist = value;
}
}
public object ExtraInfo {
get {
if (m_elExtraInfo != null) {
m_extraInfo = ObjectFromXml(m_elExtraInfo);
m_elExtraInfo = null;
}
return m_extraInfo;
}
set {
m_elExtraInfo = null;
m_extraInfo = value;
}
}
#endif //FEATURE_CLICKONCE
#if FEATURE_CAS_POLICY
public SecurityElement ToXml () {
SecurityElement elRoot = new SecurityElement("ApplicationTrust");
elRoot.AddAttribute("version", "1");
#if FEATURE_CLICKONCE
if (m_appId != null) {
elRoot.AddAttribute("FullName", SecurityElement.Escape(m_appId.FullName));
}
if (m_appTrustedToRun) {
elRoot.AddAttribute("TrustedToRun", "true");
}
if (m_persist) {
elRoot.AddAttribute("Persist", "true");
}
#endif // FEATURE_CLICKONCE
if (m_psDefaultGrant != null) {
SecurityElement elDefaultGrant = new SecurityElement("DefaultGrant");
elDefaultGrant.AddChild(m_psDefaultGrant.ToXml());
elRoot.AddChild(elDefaultGrant);
}
if (m_fullTrustAssemblies.Count > 0) {
SecurityElement elFullTrustAssemblies = new SecurityElement("FullTrustAssemblies");
foreach (StrongName fullTrustAssembly in m_fullTrustAssemblies) {
elFullTrustAssemblies.AddChild(fullTrustAssembly.ToXml());
}
elRoot.AddChild(elFullTrustAssemblies);
}
#if FEATURE_CLICKONCE
if (ExtraInfo != null) {
elRoot.AddChild(ObjectToXml("ExtraInfo", ExtraInfo));
}
#endif // FEATURE_CLICKONCE
return elRoot;
}
public void FromXml (SecurityElement element) {
if (element == null)
throw new ArgumentNullException("element");
if (String.Compare(element.Tag, "ApplicationTrust", StringComparison.Ordinal) != 0)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML"));
#if FEATURE_CLICKONCE
m_appTrustedToRun = false;
string isAppTrustedToRun = element.Attribute("TrustedToRun");
if (isAppTrustedToRun != null && String.Compare(isAppTrustedToRun, "true", StringComparison.Ordinal) == 0) {
m_appTrustedToRun = true;
}
m_persist = false;
string persist = element.Attribute("Persist");
if (persist != null && String.Compare(persist, "true", StringComparison.Ordinal) == 0) {
m_persist = true;
}
m_appId = null;
string fullName = element.Attribute("FullName");
if (fullName != null && fullName.Length > 0) {
m_appId = new ApplicationIdentity(fullName);
}
#endif // FEATURE_CLICKONCE
m_psDefaultGrant = null;
m_grantSetSpecialFlags = 0;
SecurityElement elDefaultGrant = element.SearchForChildByTag("DefaultGrant");
if (elDefaultGrant != null) {
SecurityElement elDefaultGrantPS = elDefaultGrant.SearchForChildByTag("PolicyStatement");
if (elDefaultGrantPS != null) {
PolicyStatement ps = new PolicyStatement(null);
ps.FromXml(elDefaultGrantPS);
m_psDefaultGrant = ps;
m_grantSetSpecialFlags = SecurityManager.GetSpecialFlags(ps.PermissionSet, null);
}
}
List<StrongName> fullTrustAssemblies = new List<StrongName>();
SecurityElement elFullTrustAssemblies = element.SearchForChildByTag("FullTrustAssemblies");
if (elFullTrustAssemblies != null && elFullTrustAssemblies.InternalChildren != null) {
IEnumerator enumerator = elFullTrustAssemblies.Children.GetEnumerator();
while (enumerator.MoveNext()) {
StrongName fullTrustAssembly = new StrongName();
fullTrustAssembly.FromXml(enumerator.Current as SecurityElement);
fullTrustAssemblies.Add(fullTrustAssembly);
}
}
m_fullTrustAssemblies = fullTrustAssemblies.AsReadOnly();
#if FEATURE_CLICKONCE
m_elExtraInfo = element.SearchForChildByTag("ExtraInfo");
#endif // FEATURE_CLICKONCE
}
#if FEATURE_CLICKONCE
private static SecurityElement ObjectToXml (string tag, Object obj) {
BCLDebug.Assert(obj != null, "You need to pass in an object");
ISecurityEncodable encodableObj = obj as ISecurityEncodable;
SecurityElement elObject;
if (encodableObj != null) {
elObject = encodableObj.ToXml();
if (!elObject.Tag.Equals(tag))
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML"));
}
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
byte[] array = stream.ToArray();
elObject = new SecurityElement(tag);
elObject.AddAttribute("Data", Hex.EncodeHexString(array));
return elObject;
}
private static Object ObjectFromXml (SecurityElement elObject) {
BCLDebug.Assert(elObject != null, "You need to pass in a security element");
if (elObject.Attribute("class") != null) {
ISecurityEncodable encodableObj = XMLUtil.CreateCodeGroup(elObject) as ISecurityEncodable;
if (encodableObj != null) {
encodableObj.FromXml(elObject);
return encodableObj;
}
}
string objectData = elObject.Attribute("Data");
MemoryStream stream = new MemoryStream(Hex.DecodeHexString(objectData));
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream);
}
#endif // FEATURE_CLICKONCE
#endif // FEATURE_CAS_POLICY
#pragma warning disable 618
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
#pragma warning restore 618
[SecuritySafeCritical]
public override EvidenceBase Clone()
{
return base.Clone();
}
}
#if FEATURE_CLICKONCE
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ApplicationTrustCollection : ICollection {
private const string ApplicationTrustProperty = "ApplicationTrust";
private const string InstallerIdentifier = "{60051b8f-4f12-400a-8e50-dd05ebd438d1}";
private static Guid ClrPropertySet = new Guid("c989bb7a-8385-4715-98cf-a741a8edb823");
// The CLR specific constant install reference.
private static object s_installReference = null;
private static StoreApplicationReference InstallReference {
get {
if (s_installReference == null) {
Interlocked.CompareExchange(ref s_installReference,
new StoreApplicationReference(
IsolationInterop.GUID_SXS_INSTALL_REFERENCE_SCHEME_OPAQUESTRING,
InstallerIdentifier,
null),
null);
}
return (StoreApplicationReference) s_installReference;
}
}
private object m_appTrusts = null;
private ArrayList AppTrusts {
[System.Security.SecurityCritical] // auto-generated
get {
if (m_appTrusts == null) {
ArrayList appTrusts = new ArrayList();
if (m_storeBounded) {
RefreshStorePointer();
// enumerate the user store and populate the collection
StoreDeploymentMetadataEnumeration deplEnum = m_pStore.EnumInstallerDeployments(IsolationInterop.GUID_SXS_INSTALL_REFERENCE_SCHEME_OPAQUESTRING, InstallerIdentifier, ApplicationTrustProperty, null);
foreach (IDefinitionAppId defAppId in deplEnum) {
StoreDeploymentMetadataPropertyEnumeration metadataEnum = m_pStore.EnumInstallerDeploymentProperties(IsolationInterop.GUID_SXS_INSTALL_REFERENCE_SCHEME_OPAQUESTRING, InstallerIdentifier, ApplicationTrustProperty, defAppId);
foreach (StoreOperationMetadataProperty appTrustProperty in metadataEnum) {
string appTrustXml = appTrustProperty.Value;
if (appTrustXml != null && appTrustXml.Length > 0) {
SecurityElement seTrust = SecurityElement.FromString(appTrustXml);
ApplicationTrust appTrust = new ApplicationTrust();
appTrust.FromXml(seTrust);
appTrusts.Add(appTrust);
}
}
}
}
Interlocked.CompareExchange(ref m_appTrusts, appTrusts, null);
}
return m_appTrusts as ArrayList;
}
}
private bool m_storeBounded = false;
private Store m_pStore = null; // Component store interface pointer.
// Only internal constructors are exposed.
[System.Security.SecurityCritical] // auto-generated
internal ApplicationTrustCollection () : this(false) {}
internal ApplicationTrustCollection (bool storeBounded) {
m_storeBounded = storeBounded;
}
[System.Security.SecurityCritical] // auto-generated
private void RefreshStorePointer () {
// Refresh store pointer.
if (m_pStore != null)
Marshal.ReleaseComObject(m_pStore.InternalStore);
m_pStore = IsolationInterop.GetUserStore();
}
public int Count
{
[System.Security.SecuritySafeCritical] // overrides public transparent member
get {
return AppTrusts.Count;
}
}
public ApplicationTrust this[int index] {
[System.Security.SecurityCritical] // auto-generated
get {
return AppTrusts[index] as ApplicationTrust;
}
}
public ApplicationTrust this[string appFullName] {
[System.Security.SecurityCritical] // auto-generated
get {
ApplicationIdentity identity = new ApplicationIdentity(appFullName);
ApplicationTrustCollection appTrusts = Find(identity, ApplicationVersionMatch.MatchExactVersion);
if (appTrusts.Count > 0)
return appTrusts[0];
return null;
}
}
[System.Security.SecurityCritical] // auto-generated
private void CommitApplicationTrust(ApplicationIdentity applicationIdentity, string trustXml) {
StoreOperationMetadataProperty[] properties = new StoreOperationMetadataProperty[] {
new StoreOperationMetadataProperty(ClrPropertySet, ApplicationTrustProperty, trustXml)
};
IEnumDefinitionIdentity idenum = applicationIdentity.Identity.EnumAppPath();
IDefinitionIdentity[] asbId = new IDefinitionIdentity[1];
IDefinitionIdentity deplId = null;
if (idenum.Next(1, asbId) == 1)
deplId = asbId[0];
IDefinitionAppId defAppId = IsolationInterop.AppIdAuthority.CreateDefinition();
defAppId.SetAppPath(1, new IDefinitionIdentity[] {deplId});
defAppId.put_Codebase(applicationIdentity.CodeBase);
using (StoreTransaction storeTxn = new StoreTransaction()) {
storeTxn.Add(new StoreOperationSetDeploymentMetadata(defAppId, InstallReference, properties));
RefreshStorePointer();
m_pStore.Transact(storeTxn.Operations);
}
m_appTrusts = null; // reset the app trusts in the collection.
}
[System.Security.SecurityCritical] // auto-generated
public int Add (ApplicationTrust trust) {
if (trust == null)
throw new ArgumentNullException("trust");
if (trust.ApplicationIdentity == null)
throw new ArgumentException(Environment.GetResourceString("Argument_ApplicationTrustShouldHaveIdentity"));
Contract.EndContractBlock();
// Add the trust decision of the application to the fusion store.
if (m_storeBounded) {
CommitApplicationTrust(trust.ApplicationIdentity, trust.ToXml().ToString());
return -1;
} else {
return AppTrusts.Add(trust);
}
}
[System.Security.SecurityCritical] // auto-generated
public void AddRange (ApplicationTrust[] trusts) {
if (trusts == null)
throw new ArgumentNullException("trusts");
Contract.EndContractBlock();
int i=0;
try {
for (; i<trusts.Length; i++) {
Add(trusts[i]);
}
} catch {
for (int j=0; j<i; j++) {
Remove(trusts[j]);
}
throw;
}
}
[System.Security.SecurityCritical] // auto-generated
public void AddRange (ApplicationTrustCollection trusts) {
if (trusts == null)
throw new ArgumentNullException("trusts");
Contract.EndContractBlock();
int i = 0;
try {
foreach (ApplicationTrust trust in trusts) {
Add(trust);
i++;
}
} catch {
for (int j=0; j<i; j++) {
Remove(trusts[j]);
}
throw;
}
}
[System.Security.SecurityCritical] // auto-generated
public ApplicationTrustCollection Find (ApplicationIdentity applicationIdentity, ApplicationVersionMatch versionMatch) {
ApplicationTrustCollection collection = new ApplicationTrustCollection(false);
foreach (ApplicationTrust trust in this) {
if (CmsUtils.CompareIdentities(trust.ApplicationIdentity, applicationIdentity, versionMatch))
collection.Add(trust);
}
return collection;
}
[System.Security.SecurityCritical] // auto-generated
public void Remove (ApplicationIdentity applicationIdentity, ApplicationVersionMatch versionMatch) {
ApplicationTrustCollection collection = Find(applicationIdentity, versionMatch);
RemoveRange(collection);
}
[System.Security.SecurityCritical] // auto-generated
public void Remove (ApplicationTrust trust) {
if (trust == null)
throw new ArgumentNullException("trust");
if (trust.ApplicationIdentity == null)
throw new ArgumentException(Environment.GetResourceString("Argument_ApplicationTrustShouldHaveIdentity"));
Contract.EndContractBlock();
// Remove the trust decision of the application from the fusion store.
if (m_storeBounded) {
CommitApplicationTrust(trust.ApplicationIdentity, null);
} else {
AppTrusts.Remove(trust);
}
}
[System.Security.SecurityCritical] // auto-generated
public void RemoveRange (ApplicationTrust[] trusts) {
if (trusts == null)
throw new ArgumentNullException("trusts");
Contract.EndContractBlock();
int i=0;
try {
for (; i<trusts.Length; i++) {
Remove(trusts[i]);
}
} catch {
for (int j=0; j<i; j++) {
Add(trusts[j]);
}
throw;
}
}
[System.Security.SecurityCritical] // auto-generated
public void RemoveRange (ApplicationTrustCollection trusts) {
if (trusts == null)
throw new ArgumentNullException("trusts");
Contract.EndContractBlock();
int i = 0;
try {
foreach (ApplicationTrust trust in trusts) {
Remove(trust);
i++;
}
} catch {
for (int j=0; j<i; j++) {
Add(trusts[j]);
}
throw;
}
}
[System.Security.SecurityCritical] // auto-generated
public void Clear() {
// remove all trust decisions in the collection.
ArrayList trusts = this.AppTrusts;
if (m_storeBounded) {
foreach (ApplicationTrust trust in trusts) {
if (trust.ApplicationIdentity == null)
throw new ArgumentException(Environment.GetResourceString("Argument_ApplicationTrustShouldHaveIdentity"));
// Remove the trust decision of the application from the fusion store.
CommitApplicationTrust(trust.ApplicationIdentity, null);
}
}
trusts.Clear();
}
public ApplicationTrustEnumerator GetEnumerator() {
return new ApplicationTrustEnumerator(this);
}
/// <internalonly/>
[System.Security.SecuritySafeCritical] // overrides public transparent member
IEnumerator IEnumerable.GetEnumerator()
{
return new ApplicationTrustEnumerator(this);
}
/// <internalonly/>
[System.Security.SecuritySafeCritical] // overrides public transparent member
void ICollection.CopyTo(Array array, int index) {
if (array == null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
if (index < 0 || index >= array.Length)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (array.Length - index < this.Count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
for (int i=0; i < this.Count; i++) {
array.SetValue(this[i], index++);
}
}
public void CopyTo (ApplicationTrust[] array, int index) {
((ICollection)this).CopyTo(array, index);
}
public bool IsSynchronized {
[System.Security.SecuritySafeCritical] // overrides public transparent member
get
{
return false;
}
}
public object SyncRoot {
[System.Security.SecuritySafeCritical] // overrides public transparent member
get
{
return this;
}
}
}
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ApplicationTrustEnumerator : IEnumerator {
[System.Security.SecurityCritical] // auto-generated
private ApplicationTrustCollection m_trusts;
private int m_current;
private ApplicationTrustEnumerator() {}
[System.Security.SecurityCritical] // auto-generated
internal ApplicationTrustEnumerator(ApplicationTrustCollection trusts) {
m_trusts = trusts;
m_current = -1;
}
public ApplicationTrust Current {
[System.Security.SecuritySafeCritical] // auto-generated
get {
return m_trusts[m_current];
}
}
/// <internalonly/>
object IEnumerator.Current {
[System.Security.SecuritySafeCritical] // auto-generated
get {
return (object) m_trusts[m_current];
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public bool MoveNext() {
if (m_current == ((int) m_trusts.Count - 1))
return false;
m_current++;
return true;
}
public void Reset() {
m_current = -1;
}
}
#endif // FEATURE_CLICKONCE
}
| |
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.LogConsistency;
using Orleans.TestingHost;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
using TestExtensions;
using Orleans.EventSourcing.Common;
using Tester;
namespace Tests.GeoClusterTests
{
/// <summary>
/// A fixture that provides a collection of semantic tests for log-consistency providers
/// (concurrent reading and updating, update propagation, conflict resolution)
/// on a multicluster with the desired number of clusters
/// </summary>
public class LogConsistencyTestFixture : IDisposable
{
TestingClusterHost _hostedMultiCluster;
public TestingClusterHost MultiCluster
{
get { return _hostedMultiCluster ?? (_hostedMultiCluster = new TestingClusterHost()); }
}
public void EnsurePreconditionsMet()
{
TestUtils.CheckForAzureStorage();
}
public class ClientWrapper : Tests.GeoClusterTests.TestingClusterHost.ClientWrapperBase
{
public static readonly Func<string, int, string, Action<ClientConfiguration>, Action<IClientBuilder>, ClientWrapper> Factory =
(name, gwPort, clusterId, configUpdater, clientConfigurator) => new ClientWrapper(name, gwPort, clusterId, configUpdater, clientConfigurator);
public ClientWrapper(string name, int gatewayport, string clusterId, Action<ClientConfiguration> customizer, Action<IClientBuilder> clientConfigurator)
: base(name, gatewayport, clusterId, customizer, clientConfigurator)
{
systemManagement = this.GrainFactory.GetGrain<IManagementGrain>(0);
}
public string GetGrainRef(string grainclass, int i)
{
return this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass).ToString();
}
public void SetALocal(string grainclass, int i, int a)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.SetALocal(a).GetResult();
}
public void SetAGlobal(string grainclass, int i, int a)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.SetAGlobal(a).GetResult();
}
public Tuple<int, bool> SetAConditional(string grainclass, int i, int a)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
return grainRef.SetAConditional(a).GetResult();
}
public void IncrementAGlobal(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.IncrementAGlobal().GetResult();
}
public void IncrementALocal(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.IncrementALocal().GetResult();
}
public int GetAGlobal(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
return grainRef.GetAGlobal().GetResult();
}
public int GetALocal(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
return grainRef.GetALocal().GetResult();
}
public void AddReservationLocal(string grainclass, int i, int x)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.AddReservationLocal(x).GetResult();
}
public void RemoveReservationLocal(string grainclass, int i, int x)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.RemoveReservationLocal(x).GetResult();
}
public int[] GetReservationsGlobal(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
return grainRef.GetReservationsGlobal().GetResult();
}
public void Synchronize(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.SynchronizeGlobalState().GetResult();
}
public void InjectClusterConfiguration(params string[] clusters)
{
systemManagement.InjectMultiClusterConfiguration(clusters).GetResult();
}
IManagementGrain systemManagement;
public long GetConfirmedVersion(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
return grainRef.GetConfirmedVersion().GetResult();
}
public IEnumerable<ConnectionIssue> GetUnresolvedConnectionIssues(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
return grainRef.GetUnresolvedConnectionIssues().GetResult();
}
}
public void StartClustersIfNeeded(int numclusters, ITestOutputHelper output)
{
this.output = output;
if (MultiCluster.Clusters.Count != numclusters)
{
if (MultiCluster.Clusters.Count > 0)
MultiCluster.StopAllClientsAndClusters();
output.WriteLine("Creating {0} clusters and clients...", numclusters);
this.numclusters = numclusters;
Assert.True(numclusters >= 2);
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
// use a random global service id for testing purposes
var globalserviceid = Guid.NewGuid();
random = new Random();
System.Threading.ThreadPool.SetMaxThreads(8, 8);
// Create clusters and clients
Cluster = new string[numclusters];
Client = new ClientWrapper[numclusters];
for (int i = 0; i < numclusters; i++)
{
var clustername = Cluster[i] = ((char)('A' + i)).ToString();
MultiCluster.NewGeoCluster(globalserviceid, clustername, 1,
cfg => LogConsistencyProviderConfiguration.ConfigureLogConsistencyProvidersForTesting(TestDefaultConfiguration.DataConnectionString, cfg));
Client[i] = this.MultiCluster.NewClient(clustername, 0, ClientWrapper.Factory);
}
output.WriteLine("Clusters and clients are ready (elapsed = {0})", stopwatch.Elapsed);
// wait for configuration to stabilize
MultiCluster.WaitForLivenessToStabilizeAsync().WaitWithThrow(TimeSpan.FromMinutes(1));
Client[0].InjectClusterConfiguration(Cluster);
MultiCluster.WaitForMultiClusterGossipToStabilizeAsync(false).WaitWithThrow(TimeSpan.FromMinutes(System.Diagnostics.Debugger.IsAttached ? 60 : 1));
stopwatch.Stop();
output.WriteLine("Multicluster is ready (elapsed = {0}).", stopwatch.Elapsed);
}
else
{
output.WriteLine("Reusing existing {0} clusters and clients.", numclusters);
}
}
private ITestOutputHelper output;
public virtual void Dispose()
{
_hostedMultiCluster?.Dispose();
}
protected ClientWrapper[] Client;
protected string[] Cluster;
protected Random random;
protected int numclusters;
private const int Xyz = 333;
private void AssertEqual<T>(T expected, T actual, string grainIdentity)
{
if (! expected.Equals(actual))
{
// need to write grain identity to output so we can search for it in the trace
output.WriteLine($"identity of offending grain: {grainIdentity}");
Assert.Equal(expected, actual);
}
}
public async Task RunChecksOnGrainClass(string grainClass, bool may_update_in_all_clusters, int phases, ITestOutputHelper output)
{
var random = new SafeRandom();
Func<int> GetRandom = () => random.Next();
Func<Task> checker1 = () => Task.Run(() =>
{
int x = GetRandom();
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
// force creation of replicas
for (int i = 0; i < numclusters; i++)
AssertEqual(0, Client[i].GetALocal(grainClass, x), grainIdentity);
// write global on client 0
Client[0].SetAGlobal(grainClass, x, Xyz);
// read global on other clients
for (int i = 1; i < numclusters; i++)
{
int r = Client[i].GetAGlobal(grainClass, x);
AssertEqual(Xyz, r, grainIdentity);
}
// check local stability
for (int i = 0; i < numclusters; i++)
AssertEqual(Xyz, Client[i].GetALocal(grainClass, x), grainIdentity);
// check versions
for (int i = 0; i < numclusters; i++)
AssertEqual(1, Client[i].GetConfirmedVersion(grainClass, x), grainIdentity);
});
Func<Task> checker2 = () => Task.Run(() =>
{
int x = GetRandom();
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
// increment on replica 0
Client[0].IncrementAGlobal(grainClass, x);
// expect on other replicas
for (int i = 1; i < numclusters; i++)
{
int r = Client[i].GetAGlobal(grainClass, x);
AssertEqual(1, r, grainIdentity);
}
// check versions
for (int i = 0; i < numclusters; i++)
AssertEqual(1, Client[i].GetConfirmedVersion(grainClass, x), grainIdentity);
});
Func<Task> checker2b = () => Task.Run(() =>
{
int x = GetRandom();
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
// force first creation on replica 1
AssertEqual(0, Client[1].GetAGlobal(grainClass, x), grainIdentity);
// increment on replica 0
Client[0].IncrementAGlobal(grainClass, x);
// expect on other replicas
for (int i = 1; i < numclusters; i++)
{
int r = Client[i].GetAGlobal(grainClass, x);
AssertEqual(1, r, grainIdentity);
}
// check versions
for (int i = 0; i < numclusters; i++)
AssertEqual(1, Client[i].GetConfirmedVersion(grainClass, x), grainIdentity);
});
Func<int, Task> checker3 = (int numupdates) => Task.Run(() =>
{
int x = GetRandom();
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
// concurrently chaotically increment (numupdates) times
Parallel.For(0, numupdates, i =>
{
var target = may_update_in_all_clusters ? i % numclusters : 0;
Client[target].IncrementALocal(grainClass, x);
});
if (may_update_in_all_clusters)
{
for (int i = 1; i < numclusters; i++)
Client[i].Synchronize(grainClass, x); // push all changes
}
// push & get all
AssertEqual(numupdates, Client[0].GetAGlobal(grainClass, x), grainIdentity);
for (int i = 1; i < numclusters; i++)
AssertEqual(numupdates, Client[i].GetAGlobal(grainClass, x), grainIdentity); // get all
// check versions
for (int i = 0; i < numclusters; i++)
AssertEqual(numupdates, Client[i].GetConfirmedVersion(grainClass, x), grainIdentity);
});
Func<Task> checker4 = () => Task.Run(() =>
{
int x = GetRandom();
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
var t = new List<Task>();
for (int i = 0; i < numclusters; i++)
{
int c = i;
t.Add(Task.Run(() => AssertEqual(true, Client[c].GetALocal(grainClass, x) == 0, grainIdentity)));
}
for (int i = 0; i < numclusters; i++)
{
int c = i;
t.Add(Task.Run(() => AssertEqual(true, Client[c].GetAGlobal(grainClass, x) == 0, grainIdentity)));
}
return Task.WhenAll(t);
});
Func<Task> checker5 = () => Task.Run(() =>
{
var x = GetRandom();
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
Task.WaitAll(
Task.Run(() =>
{
Client[0].AddReservationLocal(grainClass, x, 0);
Client[0].RemoveReservationLocal(grainClass, x, 0);
Client[0].Synchronize(grainClass, x);
}),
Task.Run(() =>
{
Client[1].AddReservationLocal(grainClass, x, 1);
Client[1].RemoveReservationLocal(grainClass, x, 1);
Client[1].AddReservationLocal(grainClass, x, 2);
Client[1].Synchronize(grainClass, x);
})
);
var result = Client[0].GetReservationsGlobal(grainClass, x);
AssertEqual(1, result.Length, grainIdentity);
AssertEqual(2, result[0], grainIdentity);
});
Func<int, Task> checker6 = async (int preload) =>
{
var x = GetRandom();
if (preload % 2 == 0)
Client[1].GetAGlobal(grainClass, x);
if ((preload / 2) % 2 == 0)
Client[0].GetAGlobal(grainClass, x);
bool[] done = new bool[numclusters - 1];
var t = new List<Task>();
// create listener tasks
for (int i = 1; i < numclusters; i++)
{
int c = i;
t.Add(Task.Run(async () =>
{
while (Client[c].GetALocal(grainClass, x) != 1)
await Task.Delay(100);
done[c - 1] = true;
}));
}
// send notification
Client[0].SetALocal(grainClass, x, 1);
await Task.WhenAny(
Task.Delay(20000),
Task.WhenAll(t)
);
Assert.True(done.All(b => b), string.Format("checker6({0}): update did not propagate within 20 sec", preload));
};
Func<int, Task> checker7 = (int variation) => Task.Run(async () =>
{
int x = GetRandom();
if (variation % 2 == 0)
Client[1].GetAGlobal(grainClass, x);
if ((variation / 2) % 2 == 0)
Client[0].GetAGlobal(grainClass, x);
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
// write conditional on client 0, should always succeed
{
var result = Client[0].SetAConditional(grainClass, x, Xyz);
AssertEqual(0, result.Item1, grainIdentity);
AssertEqual(true, result.Item2, grainIdentity);
AssertEqual(1, Client[0].GetConfirmedVersion(grainClass, x), grainIdentity);
}
if ((variation / 4) % 2 == 1)
await Task.Delay(100);
// write conditional on Client[1], may or may not succeed based on timing
{
var result = Client[1].SetAConditional(grainClass, x, 444);
if (result.Item1 == 0) // was stale, thus failed
{
AssertEqual(false, result.Item2, grainIdentity);
// must have updated as a result
AssertEqual(1, Client[1].GetConfirmedVersion(grainClass, x), grainIdentity);
// check stability
AssertEqual(Xyz, Client[0].GetALocal(grainClass, x), grainIdentity);
AssertEqual(Xyz, Client[1].GetALocal(grainClass, x), grainIdentity);
AssertEqual(Xyz, Client[0].GetAGlobal(grainClass, x), grainIdentity);
AssertEqual(Xyz, Client[1].GetAGlobal(grainClass, x), grainIdentity);
}
else // was up-to-date, thus succeeded
{
AssertEqual(true, result.Item2, grainIdentity);
AssertEqual(1, result.Item1, grainIdentity);
// version is now 2
AssertEqual(2, Client[1].GetConfirmedVersion(grainClass, x), grainIdentity);
// check stability
AssertEqual(444, Client[1].GetALocal(grainClass, x), grainIdentity);
AssertEqual(444, Client[0].GetAGlobal(grainClass, x), grainIdentity);
AssertEqual(444, Client[1].GetAGlobal(grainClass, x), grainIdentity);
}
}
});
output.WriteLine("Running individual short tests");
// first, run short ones in sequence
await checker1();
await checker2();
await checker2b();
await checker3(4);
await checker3(20);
await checker4();
if (may_update_in_all_clusters)
await checker5();
await checker6(0);
await checker6(1);
await checker6(2);
await checker6(3);
if (may_update_in_all_clusters)
{
await checker7(0);
await checker7(4);
await checker7(7);
// run tests under blocked notification to force race one way
MultiCluster.SetProtocolMessageFilterForTesting(Cluster[0], msg => ! (msg is INotificationMessage));
await checker7(0);
await checker7(1);
await checker7(2);
await checker7(3);
MultiCluster.SetProtocolMessageFilterForTesting(Cluster[0], _ => true);
}
output.WriteLine("Running individual longer tests");
// then, run slightly longer tests
if (phases != 0)
{
await checker3(20);
await checker3(phases);
}
output.WriteLine("Running many concurrent test instances");
var tasks = new List<Task>();
for (int i = 0; i < phases; i++)
{
tasks.Add(checker1());
tasks.Add(checker2());
tasks.Add(checker2b());
tasks.Add(checker3(4));
tasks.Add(checker4());
if (may_update_in_all_clusters)
tasks.Add(checker5());
tasks.Add(checker6(0));
tasks.Add(checker6(1));
tasks.Add(checker6(2));
tasks.Add(checker6(3));
if (may_update_in_all_clusters)
{
tasks.Add(checker7(0));
tasks.Add(checker7(1));
tasks.Add(checker7(2));
tasks.Add(checker7(3));
tasks.Add(checker7(4));
tasks.Add(checker7(5));
tasks.Add(checker7(6));
tasks.Add(checker7(7));
}
}
await Task.WhenAll(tasks);
}
}
}
| |
//==============================================================================
// TorqueLab ->
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
// Add sequence
//==============================================================================
function ShapeLab::doAddSequence( %this, %seqName, %from, %start, %end ) {
%action = %this.createAction( ActionAddSequence, "Add sequence" );
%action.seqName = %seqName;
%action.origFrom = %from;
%action.from = %from;
%action.start = %start;
%action.end = %end;
%this.doAction( %action );
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionAddSequence::doit( %this ) {
// If adding this sequence from an existing sequence, make a backup copy of
// the existing sequence first, so we can edit the start/end frames later
// without having to worry if the original source sequence has changed.
if ( ShapeLab.shape.getSequenceIndex( %this.from ) >= 0 ) {
%this.from = ShapeLab.getUniqueName( "sequence", "__backup__" @ %this.origFrom @ "_" );
ShapeLab.shape.addSequence( %this.origFrom, %this.from );
}
// Add the sequence
$collada::forceLoadDAE = Lab.forceLoadDAE;
%success = ShapeLab.shape.addSequence( %this.from, %this.seqName, %this.start, %this.end );
$collada::forceLoadDAE = false;
if ( %success ) {
ShapeLabPropWindow.update_onSequenceAdded( %this.seqName, -1 );
return true;
}
return false;
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionAddSequence::undo( %this ) {
Parent::undo( %this );
// Remove the backup sequence if one was created
if ( %this.origFrom !$= %this.from ) {
ShapeLab.shape.removeSequence( %this.from );
%this.from = %this.origFrom;
}
// Remove the actual sequence
if ( ShapeLab.shape.removeSequence( %this.seqName ) )
ShapeLab.update_onSequenceRemoved( %this.seqName );
}
//------------------------------------------------------------------------------
//==============================================================================
// Remove sequence
//==============================================================================
function ShapeLab::doRemoveSequence( %this, %seqName ) {
%action = %this.createAction( ActionRemoveSequence, "Remove sequence" );
%action.seqName = %seqName;
%this.doAction( %action );
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionRemoveSequence::doit( %this ) {
if ( ShapeLab.shape.removeSequence( %this.seqName ) ) {
ShapeLab.update_onSequenceRemoved( %this.seqName );
return true;
}
return false;
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionRemoveSequence::undo( %this ) {
Parent::undo( %this );
}
//------------------------------------------------------------------------------
//==============================================================================
// Rename sequence
//==============================================================================
//==============================================================================
function ShapeLab::doRenameSequence( %this, %oldName, %newName ) {
%action = %this.createAction( ActionRenameSequence, "Rename sequence" );
devLog("doRenameSequence OLD",%oldName,"NEW",%newName);
%action.oldName = %oldName;
%action.newName = %newName;
%this.doAction( %action );
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionRenameSequence::doit( %this ) {
if ( ShapeLab.shape.renameSequence( %this.oldName, %this.newName ) ) {
ShapeLab.update_onSequenceRenamed( %this.oldName, %this.newName );
return true;
}
return false;
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionRenameSequence::undo( %this ) {
Parent::undo( %this );
if ( ShapeLab.shape.renameSequence( %this.newName, %this.oldName ) )
ShapeLab.update_onSequenceRenamed( %this.newName, %this.oldName );
}
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
//Edit sequence source data
//==============================================================================
//==============================================================================
// Edit sequence source data ( parent, start or end )
function ShapeLab::doEditSeqSource( %this, %seqName, %from, %start, %end ) {
%action = %this.createAction( ActionEditSeqSource, "Edit sequence source data" );
%action.seqName = %seqName;
%action.origFrom = %from;
%action.from = %from;
%action.start = %start;
%action.end = %end;
// To support undo, the sequence will be renamed instead of removed (undo just
// removes the added sequence and renames the original back). Generate a unique
// name for the backed up sequence
%action.seqBackup = ShapeLab.getUniqueName( "sequence", "__backup__" @ %action.seqName @ "_" );
// If editing an internal sequence, the source is the renamed backup
if ( %action.from $= %action.seqName )
%action.from = %action.seqBackup;
%this.doAction( %action );
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditSeqSource::doit( %this ) {
// If changing the source to an existing sequence, make a backup copy of
// the existing sequence first, so we can edit the start/end frames later
// without having to worry if the original source sequence has changed.
if ( !startswith( %this.from, "__backup__" ) &&
ShapeLab.shape.getSequenceIndex( %this.from ) >= 0 ) {
%this.from = ShapeLab.getUniqueName( "sequence", "__backup__" @ %this.origFrom @ "_" );
ShapeLab.shape.addSequence( %this.origFrom, %this.from );
}
// Get settings we want to retain
%priority = ShapeLab.shape.getSequencePriority( %this.seqName );
%cyclic = ShapeLab.shape.getSequenceCyclic( %this.seqName );
%blend = ShapeLab.shape.getSequenceBlend( %this.seqName );
// Rename this sequence (instead of removing it) so we can undo this action
ShapeLab.shape.renameSequence( %this.seqName, %this.seqBackup );
// Add the new sequence
if ( ShapeLab.shape.addSequence( %this.from, %this.seqName, %this.start, %this.end ) ) {
// Restore original settings
if ( ShapeLab.shape.getSequencePriority ( %this.seqName ) != %priority )
ShapeLab.shape.setSequencePriority( %this.seqName, %priority );
if ( ShapeLab.shape.getSequenceCyclic( %this.seqName ) != %cyclic )
ShapeLab.shape.setSequenceCyclic( %this.seqName, %cyclic );
%newBlend = ShapeLab.shape.getSequenceBlend( %this.seqName );
if ( %newBlend !$= %blend ) {
// Undo current blend, then apply new one
ShapeLab.shape.setSequenceBlend( %this.seqName, 0, getField( %newBlend, 1 ), getField( %newBlend, 2 ) );
if ( getField( %blend, 0 ) == 1 )
ShapeLab.shape.setSequenceBlend( %this.seqName, getField( %blend, 0 ), getField( %blend, 1 ), getField( %blend, 2 ) );
}
if ( ShapeLab.selectedSequence $= %this.seqName ) {
ShapeLab.update_onSequenceSourceChanged( %this.seqName, %this.start, %this.end );
//ShapeLabSequenceList.editColumn( %this.seqName, 3, %this.end - %this.start + 1 );
ShapeLabThreadViewer.syncPlaybackDetails();
}
return true;
}
return false;
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditSeqSource::undo( %this ) {
Parent::undo( %this );
// Remove the source sequence backup if one was created
if ( ( %this.from !$= %this.origFrom ) && ( %this.from !$= %this.seqBackup ) ) {
ShapeLab.shape.removeSequence( %this.from );
%this.from = %this.origFrom;
}
// Remove the added sequence, and rename the backup back
if ( ShapeLab.shape.removeSequence( %this.seqName ) &&
ShapeLab.shape.renameSequence( %this.seqBackup, %this.seqName ) ) {
if ( ShapeLabSequenceList.getSelectedName() $= %this.seqName ) {
ShapeLab.update_onSequenceSourceChanged( %this.seqName, %this.start, %this.end );
//ShapeLabSequenceList.editColumn( %this.seqName, 3, %this.end - %this.start + 1 );
ShapeLabThreadViewer.syncPlaybackDetails();
}
}
}
//------------------------------------------------------------------------------
//==============================================================================
// Edit cyclic flag
//==============================================================================
//==============================================================================
function ShapeLab::doEditCyclic( %this, %seqName, %cyclic ) {
if (%seqName $= "")
return;
%action = %this.createAction( ActionEditCyclic, "Toggle cyclic flag" );
%action.seqName = %seqName;
%action.cyclic = %cyclic;
%this.doAction( %action );
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditCyclic::doit( %this ) {
if ( ShapeLab.shape.setSequenceCyclic( %this.seqName, %this.cyclic ) ) {
ShapeLab.update_onSequenceCyclicChanged( %this.seqName, %this.cyclic );
return true;
}
return false;
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditCyclic::undo( %this ) {
Parent::undo( %this );
if ( ShapeLab.shape.setSequenceCyclic( %this.seqName, !%this.cyclic ) )
ShapeLab.update_onSequenceCyclicChanged( %this.seqName, !%this.cyclic );
}
//------------------------------------------------------------------------------
//==============================================================================
// Edit blend properties
//==============================================================================
//==============================================================================
function ShapeLab::doEditBlend( %this, %seqName, %blend, %blendSeq, %blendFrame ) {
%action = %this.createAction( ActionEditBlend, "Edit blend properties" );
%action.seqName = %seqName;
%action.blend = %blend;
%action.blendSeq = %blendSeq;
%action.blendFrame = %blendFrame;
// Store the current blend settings
%oldBlend = ShapeLab.shape.getSequenceBlend( %seqName );
%action.oldBlend = getField( %oldBlend, 0 );
%action.oldBlendSeq = getField( %oldBlend, 1 );
%action.oldBlendFrame = getField( %oldBlend, 2 );
// Use new values if the old ones do not exist ( for blend sequences embedded
// in the DTS/DSQ file )
if ( %action.oldBlendSeq $= "" )
%action.oldBlendSeq = %action.blendSeq;
if ( %action.oldBlendFrame $= "" )
%action.oldBlendFrame = %action.blendFrame;
%this.doAction( %action );
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditBlend::doit( %this ) {
// If we are changing the blend reference ( rather than just toggling the flag )
// we need to undo the current blend first.
if ( %this.blend && %this.oldBlend ) {
if ( !ShapeLab.shape.setSequenceBlend( %this.seqName, false, %this.oldBlendSeq, %this.oldBlendFrame ) )
return false;
}
if ( ShapeLab.shape.setSequenceBlend( %this.seqName, %this.blend, %this.blendSeq, %this.blendFrame ) ) {
ShapeLab.update_onSequenceBlendChanged( %this.seqName, %this.blend,
%this.oldBlendSeq, %this.oldBlendFrame, %this.blendSeq, %this.blendFrame );
return true;
}
return false;
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditBlend::undo( %this ) {
Parent::undo( %this );
// If we are changing the blend reference ( rather than just toggling the flag )
// we need to undo the current blend first.
if ( %this.blend && %this.oldBlend ) {
if ( !ShapeLab.shape.setSequenceBlend( %this.seqName, false, %this.blendSeq, %this.blendFrame ) )
return;
}
if ( ShapeLab.shape.setSequenceBlend( %this.seqName, %this.oldBlend, %this.oldBlendSeq, %this.oldBlendFrame ) ) {
ShapeLab.update_onSequenceBlendChanged( %this.seqName, !%this.blend,
%this.blendSeq, %this.blendFrame, %this.oldBlendSeq, %this.oldBlendFrame );
}
}
//------------------------------------------------------------------------------
//==============================================================================
// Edit sequence priority
//==============================================================================
//==============================================================================
function ShapeLab::doEditSequencePriority( %this, %seqName, %newPriority ) {
%action = %this.createAction( ActionEditSequencePriority, "Edit sequence priority" );
%action.seqName = %seqName;
%action.newPriority = %newPriority;
%action.oldPriority = %this.shape.getSequencePriority( %seqName );
%this.doAction( %action );
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditSequencePriority::doit( %this ) {
if ( ShapeLab.shape.setSequencePriority( %this.seqName, %this.newPriority ) ) {
ShapeLab.update_onSequencePriorityChanged( %this.seqName );
return true;
}
return false;
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditSequencePriority::undo( %this ) {
Parent::undo( %this );
if ( ShapeLab.shape.setSequencePriority( %this.seqName, %this.oldPriority ) )
ShapeLab.update_onSequencePriorityChanged( %this.seqName );
}
//------------------------------------------------------------------------------
//==============================================================================
// Edit sequence ground speed
//==============================================================================
//==============================================================================
function ShapeLab::doEditSequenceGroundSpeed( %this, %seqName, %newSpeed ) {
%action = %this.createAction( ActionEditSequenceGroundSpeed, "Edit sequence ground speed" );
%action.seqName = %seqName;
%action.newSpeed = %newSpeed;
%action.oldSpeed = %this.shape.getSequenceGroundSpeed( %seqName );
%this.doAction( %action );
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditSequenceGroundSpeed::doit( %this ) {
if ( ShapeLab.shape.setSequenceGroundSpeed( %this.seqName, %this.newSpeed ) ) {
ShapeLab.update_onSequenceGroundSpeedChanged( %this.seqName );
return true;
}
return false;
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditSequenceGroundSpeed::undo( %this ) {
Parent::undo( %this );
if ( ShapeLab.shape.setSequenceGroundSpeed( %this.seqName, %this.oldSpeed ) )
ShapeLab.update_onSequenceGroundSpeedChanged( %this.seqName );
}
//==============================================================================
// Add Trigger
//==============================================================================
//==============================================================================
// Add trigger
function ShapeLab::doAddTrigger( %this, %seqName, %frame, %state ) {
%action = %this.createAction( ActionAddTrigger, "Add trigger" );
%action.seqName = %seqName;
%action.frame = %frame;
%action.state = %state;
devLog("AddTrigger",%seqName,%frame, %state);
%this.doAction( %action );
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionAddTrigger::doit( %this ) {
if ( ShapeLab.shape.addTrigger( %this.seqName, %this.frame, %this.state ) ) {
ShapeLabPropWindow.update_onTriggerAdded( %this.seqName, %this.frame, %this.state );
return true;
}
return false;
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionAddTrigger::undo( %this ) {
Parent::undo( %this );
if ( ShapeLab.shape.removeTrigger( %this.seqName, %this.frame, %this.state ) )
ShapeLabPropWindow.update_onTriggerRemoved( %this.seqName, %this.frame, %this.state );
}
//------------------------------------------------------------------------------
//==============================================================================
// Remove Trigger
//==============================================================================
//==============================================================================
// Remove trigger
function ShapeLab::doRemoveTrigger( %this, %seqName, %frame, %state ) {
%action = %this.createAction( ActionRemoveTrigger, "Remove trigger" );
%action.seqName = %seqName;
%action.frame = %frame;
%action.state = %state;
%this.doAction( %action );
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionRemoveTrigger::doit( %this ) {
if ( ShapeLab.shape.removeTrigger( %this.seqName, %this.frame, %this.state ) ) {
ShapeLabPropWindow.update_onTriggerRemoved( %this.seqName, %this.frame, %this.state );
return true;
}
return false;
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionRemoveTrigger::undo( %this ) {
Parent::undo( %this );
if ( ShapeLab.shape.addTrigger( %this.seqName, %this.frame, %this.state ) )
ShapeLabPropWindow.update_onTriggerAdded( %this.seqName, %this.frame, %this.state );
}
//------------------------------------------------------------------------------
//==============================================================================
// Edit Trigger
//==============================================================================
//==============================================================================
// Edit trigger
function ShapeLab::doEditTrigger( %this, %seqName, %oldFrame, %oldState, %frame, %state ) {
%action = %this.createAction( ActionEditTrigger, "Edit trigger" );
%action.seqName = %seqName;
%action.oldFrame = %oldFrame;
%action.oldState = %oldState;
%action.frame = %frame;
%action.state = %state;
%this.doAction( %action );
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditTrigger::doit( %this ) {
if ( ShapeLab.shape.addTrigger( %this.seqName, %this.frame, %this.state ) && ShapeLab.shape.removeTrigger( %this.seqName, %this.oldFrame, %this.oldState ) )
{
ShapeLab_TriggerList.updateItem( %this.oldFrame, %this.oldState, %this.frame, %this.state );
return true;
}
return false;
}
//------------------------------------------------------------------------------
//==============================================================================
function ActionEditTrigger::undo( %this ) {
Parent::undo( %this );
if ( ShapeLab.shape.addTrigger( %this.seqName, %this.oldFrame, %this.oldState ) && ShapeLab.shape.removeTrigger( %this.seqName, %this.frame, %this.state ) )
ShapeLab_TriggerList.updateItem( %this.frame, %this.state, %this.oldFrame, %this.oldState );
}
//------------------------------------------------------------------------------
| |
/*
M2Mqtt Project - MQTT Client Library for .Net and GnatMQ MQTT Broker for .NET
Copyright (c) 2014, Paolo Patierno, All rights reserved.
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 3.0 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 SSL && !WINDOWS_PHONE
#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
using Microsoft.SPOT.Net.Security;
#else
using System.Net.Security;
#endif
#endif
using System;
using System.Text;
namespace uPLibrary.Networking.M2Mqtt.Messages
{
/// <summary>
/// Base class for all MQTT messages
/// </summary>
public abstract class MqttMsgBase
{
#region Constants...
// mask, offset and size for fixed header fields
internal const byte MSG_TYPE_MASK = 0xF0;
internal const byte MSG_TYPE_OFFSET = 0x04;
internal const byte MSG_TYPE_SIZE = 0x04;
internal const byte DUP_FLAG_MASK = 0x08;
internal const byte DUP_FLAG_OFFSET = 0x03;
internal const byte DUP_FLAG_SIZE = 0x01;
internal const byte QOS_LEVEL_MASK = 0x06;
internal const byte QOS_LEVEL_OFFSET = 0x01;
internal const byte QOS_LEVEL_SIZE = 0x02;
internal const byte RETAIN_FLAG_MASK = 0x01;
internal const byte RETAIN_FLAG_OFFSET = 0x00;
internal const byte RETAIN_FLAG_SIZE = 0x01;
// MQTT message types
internal const byte MQTT_MSG_CONNECT_TYPE = 0x01;
internal const byte MQTT_MSG_CONNACK_TYPE = 0x02;
internal const byte MQTT_MSG_PUBLISH_TYPE = 0x03;
internal const byte MQTT_MSG_PUBACK_TYPE = 0x04;
internal const byte MQTT_MSG_PUBREC_TYPE = 0x05;
internal const byte MQTT_MSG_PUBREL_TYPE = 0x06;
internal const byte MQTT_MSG_PUBCOMP_TYPE = 0x07;
internal const byte MQTT_MSG_SUBSCRIBE_TYPE = 0x08;
internal const byte MQTT_MSG_SUBACK_TYPE = 0x09;
internal const byte MQTT_MSG_UNSUBSCRIBE_TYPE = 0x0A;
internal const byte MQTT_MSG_UNSUBACK_TYPE = 0x0B;
internal const byte MQTT_MSG_PINGREQ_TYPE = 0x0C;
internal const byte MQTT_MSG_PINGRESP_TYPE = 0x0D;
internal const byte MQTT_MSG_DISCONNECT_TYPE = 0x0E;
// QOS levels
public const byte QOS_LEVEL_AT_MOST_ONCE = 0x00;
public const byte QOS_LEVEL_AT_LEAST_ONCE = 0x01;
public const byte QOS_LEVEL_EXACTLY_ONCE = 0x02;
internal const ushort MAX_TOPIC_LENGTH = 65535;
internal const ushort MIN_TOPIC_LENGTH = 1;
internal const byte MESSAGE_ID_SIZE = 2;
#endregion
#region Properties...
/// <summary>
/// Message type
/// </summary>
public byte Type
{
get { return this.type; }
set { this.type = value; }
}
/// <summary>
/// Duplicate message flag
/// </summary>
public bool DupFlag
{
get { return this.dupFlag; }
set { this.dupFlag = value; }
}
/// <summary>
/// Quality of Service level
/// </summary>
public byte QosLevel
{
get { return this.qosLevel; }
set { this.qosLevel = value; }
}
/// <summary>
/// Retain message flag
/// </summary>
public bool Retain
{
get { return this.retain; }
set { this.retain = value; }
}
#endregion
// message type
protected byte type;
// duplicate delivery
protected bool dupFlag;
// quality of service level
protected byte qosLevel;
// retain flag
protected bool retain;
/// <summary>
/// Returns message bytes rapresentation
/// </summary>
/// <returns>Bytes rapresentation</returns>
public abstract byte[] GetBytes();
/// <summary>
/// Encode remaining length and insert it into message buffer
/// </summary>
/// <param name="remainingLength">Remaining length value to encode</param>
/// <param name="buffer">Message buffer for inserting encoded value</param>
/// <param name="index">Index from which insert encoded value into buffer</param>
/// <returns>Index updated</returns>
protected int encodeRemainingLength(int remainingLength, byte[] buffer, int index)
{
int digit = 0;
do
{
digit = remainingLength % 128;
remainingLength /= 128;
if (remainingLength > 0)
digit = digit | 0x80;
buffer[index++] = (byte)digit;
} while (remainingLength > 0);
return index;
}
/// <summary>
/// Decode remaining length reading bytes from socket
/// </summary>
/// <param name="channel">Channel from reading bytes</param>
/// <returns>Decoded remaining length</returns>
protected static int decodeRemainingLength(IMqttNetworkChannel channel)
{
int multiplier = 1;
int value = 0;
int digit = 0;
byte[] nextByte = new byte[1];
do
{
// next digit from stream
channel.Receive(nextByte);
digit = nextByte[0];
value += ((digit & 127) * multiplier);
multiplier *= 128;
} while ((digit & 128) != 0);
return value;
}
#if DEBUG
/// <summary>
/// Returns a string representation of the message for debugging
/// </summary>
/// <param name="name">Message name</param>
/// <param name="fieldNames">Message fields name</param>
/// <param name="fieldValues">Message fields value</param>
/// <returns>String representation of the message</returns>
protected string GetDebugString(string name, object[] fieldNames, object[] fieldValues)
{
StringBuilder sb = new StringBuilder();
sb.Append(name);
if ((fieldNames != null) && (fieldValues != null))
{
sb.Append("(");
bool addComma = false;
for (int i = 0; i < fieldValues.Length; i++)
{
if (fieldValues[i] != null)
{
if (addComma)
{
sb.Append(",");
}
sb.Append(fieldNames[i]);
sb.Append(":");
sb.Append(GetStringObject(fieldValues[i]));
addComma = true;
}
}
sb.Append(")");
}
return sb.ToString();
}
object GetStringObject(object value)
{
byte[] binary = value as byte[];
if (binary != null)
{
string hexChars = "0123456789ABCDEF";
StringBuilder sb = new StringBuilder(binary.Length * 2);
for (int i = 0; i < binary.Length; ++i)
{
sb.Append(hexChars[binary[i] >> 4]);
sb.Append(hexChars[binary[i] & 0x0F]);
}
return sb.ToString();
}
object[] list = value as object[];
if (list != null)
{
StringBuilder sb = new StringBuilder();
sb.Append('[');
for (int i = 0; i < list.Length; ++i)
{
if (i > 0) sb.Append(',');
sb.Append(list[i]);
}
sb.Append(']');
return sb.ToString();
}
return value;
}
#endif
}
}
| |
using System;
using Stetic.Wrapper;
using Mono.Unix;
namespace Stetic.Editor
{
class ActionToolItem: ActionItem
{
ActionToolbar parentToolbar;
bool motionDrag;
bool showingText;
Gtk.Widget dropButton;
public event EventHandler EditingDone;
internal ActionToolItem (Widget wrapper, ActionToolbar parent, ActionTreeNode node)
: this (wrapper, parent, node, 0)
{
}
internal ActionToolItem (Widget wrapper, ActionToolbar parent, ActionTreeNode node, uint itemSpacing): base (node, parent, itemSpacing)
{
this.parentToolbar = parent;
this.wrapper = wrapper;
CreateControls ();
}
public void StartEditing (bool doClick)
{
if (!editing && node.Action != null) {
// Don't allow efiting global actions
if (wrapper != null && wrapper.Project.ActionGroups.IndexOf (node.Action.ActionGroup) != -1)
return;
editing = true;
Refresh ();
if (doClick && dropButton != null) {
// Make sure the dropButton is properly shown
while (Gtk.Application.EventsPending ())
Gtk.Application.RunIteration ();
OnSelectIcon (null, null);
}
}
}
protected override void EndEditing (Gdk.Key exitKey)
{
if (editing) {
editing = false;
Refresh ();
while (Gtk.Application.EventsPending ())
Gtk.Application.RunIteration ();
GrabFocus ();
if (EditingDone != null)
EditingDone (this, EventArgs.Empty);
}
}
void CreateControls ()
{
Gtk.Widget icon = null;
Gtk.Widget label = null;
dropButton = null;
if (Child != null) {
Gtk.Widget w = Child;
Remove (w);
w.Destroy ();
}
if (node.Type == Gtk.UIManagerItemType.Separator) {
Gtk.Widget sep;
if (parentToolbar.Orientation == Gtk.Orientation.Horizontal) {
sep = new Gtk.VSeparator ();
} else {
sep = new Gtk.HSeparator ();
}
Gtk.HBox box = new Gtk.HBox ();
box.BorderWidth = 6;
box.PackStart (sep, true, true, 0);
Add (box);
return;
}
if (node.Action == null)
return;
Gtk.Action gaction = node.Action.GtkAction;
bool showText = parentToolbar.ToolbarStyle == Gtk.ToolbarStyle.Text;
bool showIcon = parentToolbar.ToolbarStyle == Gtk.ToolbarStyle.Icons;
if (parentToolbar.ToolbarStyle == Gtk.ToolbarStyle.Both) {
showText = showIcon = true;
}
else if (parentToolbar.ToolbarStyle == Gtk.ToolbarStyle.BothHoriz) {
showText = parentToolbar.Orientation == Gtk.Orientation.Vertical || gaction.IsImportant;
showIcon = true;
}
string text = node.Action.ToolLabel;
showingText = showText;
if (showIcon)
{
if (gaction.StockId != null) {
icon = node.Action.CreateIcon (parentToolbar.IconSize);
} else if (!gaction.IsImportant) {
icon = CreateFakeItem ();
}
}
Gtk.Tooltips tooltips = null;
if (editing)
tooltips = new Gtk.Tooltips ();
if (editing) {
Gtk.HBox bbox = new Gtk.HBox ();
bbox.Spacing = 3;
if (icon != null) {
bbox.PackStart (icon, false, false, 0);
}
bbox.PackStart (new Gtk.Arrow (Gtk.ArrowType.Down, Gtk.ShadowType.In), false, false, 0);
Gtk.Button b = new Gtk.Button (bbox);
tooltips.SetTip (b, "Select action type", "");
b.Relief = Gtk.ReliefStyle.None;
b.ButtonPressEvent += OnSelectIcon;
dropButton = b;
icon = b;
if (showText) {
Gtk.Entry entry = new Gtk.Entry ();
entry.Text = text;
entry.Changed += OnLabelChanged;
entry.Activated += OnLabelActivated;
entry.HasFrame = false;
label = entry;
tooltips.SetTip (entry, "Action label", "");
}
} else if (showText && text != null && text.Length > 0) {
label = new Gtk.Label (text);
label.Sensitive = editing || node.Action == null || node.Action.GtkAction.Sensitive;
}
if (icon != null && label != null) {
if (parentToolbar.ToolbarStyle == Gtk.ToolbarStyle.BothHoriz) {
Gtk.HBox box = new Gtk.HBox ();
box.PackStart (icon, false, false, 0);
box.PackStart (label, true, true, 0);
icon = box;
} else if (parentToolbar.ToolbarStyle == Gtk.ToolbarStyle.Both) {
Gtk.VBox box = new Gtk.VBox ();
Gtk.Alignment al = new Gtk.Alignment (0.5f, 0f, 0f, 0f);
al.Add (icon);
box.PackStart (al, false, false, 0);
box.PackStart (label, true, true, 0);
icon = box;
}
} else if (label != null) {
icon = label;
}
if (icon == null) {
icon = CreateFakeItem ();
}
icon.Sensitive = editing || node.Action == null || node.Action.GtkAction.Sensitive;
if (!editing) {
Gtk.Button but = new Gtk.Button (icon);
but.Relief = Gtk.ReliefStyle.None;
but.ButtonPressEvent += OnToolItemPress;
but.ButtonReleaseEvent += OnMemuItemRelease;
but.MotionNotifyEvent += OnMotionNotify;
but.Events |= Gdk.EventMask.PointerMotionMask;
icon = but;
}
Add (icon);
ShowAll ();
}
Gtk.Widget CreateFakeItem ()
{
Gtk.Frame frm = new Gtk.Frame ();
frm.ShadowType = Gtk.ShadowType.Out;
int w, h;
Gtk.Icon.SizeLookup (parentToolbar.IconSize, out w, out h);
frm.WidthRequest = w;
frm.HeightRequest = h;
return frm;
}
void OnLabelChanged (object ob, EventArgs args)
{
localUpdate = true;
Gtk.Entry entry = ob as Gtk.Entry;
if (entry.Text.Length > 0 || node.Action.GtkAction.StockId != null) {
using (node.Action.UndoManager.AtomicChange) {
node.Action.Label = entry.Text;
node.Action.NotifyChanged ();
}
}
localUpdate = false;
}
void OnLabelActivated (object ob, EventArgs args)
{
EndEditing (Gdk.Key.Return);
}
[GLib.ConnectBeforeAttribute]
void OnSelectIcon (object s, Gtk.ButtonPressEventArgs args)
{
Gtk.Menu menu = new Gtk.Menu ();
Gtk.CheckMenuItem item = new Gtk.CheckMenuItem (Catalog.GetString ("Action"));
item.DrawAsRadio = true;
item.Active = (node.Action.Type == Stetic.Wrapper.Action.ActionType.Action);
item.Activated += OnSetActionType;
menu.Insert (item, -1);
item = new Gtk.CheckMenuItem (Catalog.GetString ("Radio Action"));
item.DrawAsRadio = true;
item.Active = (node.Action.Type == Stetic.Wrapper.Action.ActionType.Radio);
item.Activated += OnSetRadioType;
menu.Insert (item, -1);
item = new Gtk.CheckMenuItem (Catalog.GetString ("Toggle Action"));
item.DrawAsRadio = true;
item.Active = (node.Action.Type == Stetic.Wrapper.Action.ActionType.Toggle);
item.Activated += OnSetToggleType;
menu.Insert (item, -1);
menu.Insert (new Gtk.SeparatorMenuItem (), -1);
Gtk.MenuItem itIcons = new Gtk.MenuItem (Catalog.GetString ("Select Icon"));
menu.Insert (itIcons, -1);
IconSelectorMenu menuIcons = new IconSelectorMenu (GetProject ());
menuIcons.IconSelected += OnStockSelected;
itIcons.Submenu = menuIcons;
Gtk.MenuItem it = new Gtk.MenuItem (Catalog.GetString ("Clear Icon"));
it.Sensitive = (node.Action.GtkAction.StockId != null);
it.Activated += OnClearIcon;
menu.Insert (it, -1);
menu.ShowAll ();
uint but = args != null ? args.Event.Button : 1;
menu.Popup (null, null, new Gtk.MenuPositionFunc (OnDropMenuPosition), but, Gtk.Global.CurrentEventTime);
// Make sure we get the focus after closing the menu, so we can keep browsing buttons
// using the keyboard.
menu.Hidden += delegate (object sender, EventArgs a) {
GrabFocus ();
};
if (args != null)
args.RetVal = false;
}
void OnDropMenuPosition (Gtk.Menu menu, out int x, out int y, out bool pushIn)
{
dropButton.ParentWindow.GetOrigin (out x, out y);
x += dropButton.Allocation.X;
y += dropButton.Allocation.Y + dropButton.Allocation.Height;
pushIn = true;
}
void OnSetToggleType (object ob, EventArgs args)
{
using (node.Action.UndoManager.AtomicChange) {
node.Action.Type = Stetic.Wrapper.Action.ActionType.Toggle;
node.Action.NotifyChanged ();
}
}
void OnSetRadioType (object ob, EventArgs args)
{
using (node.Action.UndoManager.AtomicChange) {
node.Action.Type = Stetic.Wrapper.Action.ActionType.Radio;
node.Action.NotifyChanged ();
}
}
void OnSetActionType (object ob, EventArgs args)
{
using (node.Action.UndoManager.AtomicChange) {
node.Action.Type = Stetic.Wrapper.Action.ActionType.Action;
node.Action.NotifyChanged ();
}
}
void OnStockSelected (object s, IconEventArgs args)
{
using (node.Action.UndoManager.AtomicChange) {
node.Action.StockId = args.IconId;
node.Action.NotifyChanged ();
}
}
void OnClearIcon (object on, EventArgs args)
{
using (node.Action.UndoManager.AtomicChange) {
node.Action.StockId = null;
node.Action.NotifyChanged ();
}
}
public override void Refresh ()
{
CreateControls ();
}
[GLib.ConnectBeforeAttribute]
void OnToolItemPress (object ob, Gtk.ButtonPressEventArgs args)
{
if (wrapper != null && wrapper.Project.Selection != wrapper.Wrapped) {
wrapper.Select ();
args.RetVal = true;
return;
}
if (args.Event.Button == 1)
motionDrag = true;
args.RetVal = ProcessButtonPress (args.Event);
}
[GLib.ConnectBeforeAttribute]
void OnMemuItemRelease (object ob, Gtk.ButtonReleaseEventArgs args)
{
args.RetVal = ProcessButtonRelease (args.Event);
motionDrag = false;
}
[GLib.ConnectBeforeAttribute]
void OnMotionNotify (object ob, Gtk.MotionNotifyEventArgs args)
{
if (motionDrag) {
// Looks like drag begin can be intercepted, so the motion notify
// has to be used.
ProcessDragBegin (null, args.Event);
motionDrag = false;
}
}
protected override bool OnButtonReleaseEvent (Gdk.EventButton ev)
{
return ProcessButtonRelease (ev);
}
public bool ProcessButtonRelease (Gdk.EventButton ev)
{
// Clicking a selected item starts the edit mode
if (editOnRelease) {
StartEditing (!showingText);
}
editOnRelease = false;
return true;
}
protected override bool OnKeyPressEvent (Gdk.EventKey e)
{
if (e.Key == Gdk.Key.Return)
EndEditing (Gdk.Key.Return);
else if (e.Key == Gdk.Key.Escape)
EndEditing (Gdk.Key.Escape);
return base.OnKeyPressEvent (e);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Xml;
namespace Microsoft.Web.XmlTransform.Extended
{
internal interface IXmlFormattableAttributes
{
void FormatAttributes(XmlFormatter formatter);
string AttributeIndent { get; }
}
internal class XmlFormatter
{
private readonly XmlFileInfoDocument _document;
private string _originalFileName;
private readonly LinkedList<string> _indents = new LinkedList<string>();
private readonly LinkedList<string> _attributeIndents = new LinkedList<string>();
private string _currentIndent = String.Empty;
private string _currentAttributeIndent;
private string _oneTab;
private string _defaultTab = "\t";
private XmlNode _currentNode;
private XmlNode _previousNode;
public static void Format(XmlDocument document)
{
var errorInfoDocument = document as XmlFileInfoDocument;
if (errorInfoDocument == null) return;
var formatter = new XmlFormatter(errorInfoDocument);
formatter.FormatLoop(errorInfoDocument);
}
private XmlFormatter(XmlFileInfoDocument document)
{
_document = document;
_originalFileName = document.FileName;
}
private XmlNode CurrentNode
{
get
{
return _currentNode;
}
set
{
_previousNode = _currentNode;
_currentNode = value;
}
}
private XmlNode PreviousNode
{
get
{
return _previousNode;
}
}
private string PreviousIndent
{
get
{
Debug.Assert(_indents.Count > 0, "Expected at least one previous indent");
return _indents.Last.Value;
}
}
private string CurrentIndent
{
get { return _currentIndent ?? (_currentIndent = ComputeCurrentIndent()); }
}
public string CurrentAttributeIndent
{
get { return _currentAttributeIndent ?? (_currentAttributeIndent = ComputeCurrentAttributeIndent()); }
}
private string OneTab
{
get { return _oneTab ?? (_oneTab = ComputeOneTab()); }
}
public string DefaultTab
{
get
{
return _defaultTab;
}
set
{
_defaultTab = value;
}
}
private void FormatLoop(XmlNode parentNode)
{
for (int i = 0; i < parentNode.ChildNodes.Count; i++)
{
XmlNode node = parentNode.ChildNodes[i];
CurrentNode = node;
switch (node.NodeType)
{
case XmlNodeType.Element:
i += HandleElement(node);
break;
case XmlNodeType.Whitespace:
i += HandleWhiteSpace(node);
break;
case XmlNodeType.Comment:
case XmlNodeType.Entity:
i += EnsureNodeIndent(node, false);
break;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.CDATA:
case XmlNodeType.Text:
case XmlNodeType.EntityReference:
case XmlNodeType.DocumentType:
case XmlNodeType.XmlDeclaration:
// Do nothing
break;
default:
Debug.Fail(String.Format(CultureInfo.InvariantCulture, "Unexpected element type '{0}' while formatting document", node.NodeType.ToString()));
break;
}
}
}
private void FormatAttributes(XmlNode node)
{
var formattable = node as IXmlFormattableAttributes;
if (formattable != null)
{
formattable.FormatAttributes(this);
}
}
private int HandleElement(XmlNode node)
{
int indexChange = HandleStartElement(node);
ReorderNewItemsAtEnd(node);
// Loop over children
FormatLoop(node);
CurrentNode = node;
indexChange += HandleEndElement(node);
return indexChange;
}
// This is a special case for preserving the whitespace that existed
// before the end tag of this node. If elements were inserted after
// that whitespace, the whitespace needs to be moved back to the
// end of the child list, and new whitespaces should be inserted
// *before* the new nodes.
private void ReorderNewItemsAtEnd(XmlNode node)
{
// If this is a new node, then there couldn't be original
// whitespace before the end tag
if (!IsNewNode(node))
{
// If the last child isn't whitespace, new elements might
// have been added
XmlNode iter = node.LastChild;
if (iter != null && iter.NodeType != XmlNodeType.Whitespace)
{
// The loop continues until we find something that isn't
// a new Element. If it's whitespace, then that will be
// the whitespace we need to move.
XmlNode whitespace = null;
while (iter != null)
{
switch (iter.NodeType)
{
case XmlNodeType.Whitespace:
// Found the whitespace, loop can stop
whitespace = iter;
break;
case XmlNodeType.Element:
// Loop continues over new Elements
if (IsNewNode(iter))
{
iter = iter.PreviousSibling;
continue;
}
break;
// Anything else stops the loop
}
break;
}
if (whitespace != null)
{
// We found whitespace to move. Remove it from where
// it is and add it back to the end
node.RemoveChild(whitespace);
node.AppendChild(whitespace);
}
}
}
}
private int HandleStartElement(XmlNode node)
{
int indexChange = EnsureNodeIndent(node, false);
FormatAttributes(node);
PushIndent();
return indexChange;
}
private int HandleEndElement(XmlNode node)
{
int indexChange = 0;
PopIndent();
if (!((XmlElement)node).IsEmpty)
{
indexChange = EnsureNodeIndent(node, true);
}
return indexChange;
}
private int HandleWhiteSpace(XmlNode node)
{
int indexChange = 0;
// If we find two WhiteSpace nodes in a row, it means some node
// was removed in between. Remove the previous whitespace.
// Dev10 bug 830497 Need to improve Error messages from the publish pipeline
// basically the PreviousNode can be null, it need to be check before use the note.
if (IsWhiteSpace(PreviousNode))
{
// Prefer to keep 'node', but if 'PreviousNode' has a newline
// and 'node' doesn't, keep the whitespace with the newline
XmlNode removeNode = PreviousNode;
if (FindLastNewLine(node.OuterXml) < 0 &&
FindLastNewLine(PreviousNode.OuterXml) >= 0)
{
removeNode = node;
}
removeNode.ParentNode.RemoveChild(removeNode);
indexChange = -1;
}
string indent = GetIndentFromWhiteSpace(node);
if (indent != null)
{
SetIndent(indent);
}
return indexChange;
}
private int EnsureNodeIndent(XmlNode node, bool indentBeforeEnd)
{
int indexChange = 0;
if (NeedsIndent(node, PreviousNode))
{
if (indentBeforeEnd)
{
InsertIndentBeforeEnd(node);
}
else
{
InsertIndentBefore(node);
indexChange = 1;
}
}
return indexChange;
}
private string GetIndentFromWhiteSpace(XmlNode node)
{
var whitespace = node.OuterXml;
var index = FindLastNewLine(whitespace);
return index >= 0 ? whitespace.Substring(index) : null;
// If there's no newline, then this is whitespace in the
// middle of a line, not an indent
}
private int FindLastNewLine(string whitespace)
{
for (int i = whitespace.Length - 1; i >= 0; i--)
{
switch (whitespace[i])
{
case '\r':
return i;
case '\n':
if (i > 0 && whitespace[i - 1] == '\r')
{
return i - 1;
}
return i;
case ' ':
case '\t':
break;
default:
// Non-whitespace character, not legal in indent text
return -1;
}
}
// No newline found
return -1;
}
private void SetIndent(string indent)
{
if (_currentIndent == null || !_currentIndent.Equals(indent))
{
_currentIndent = indent;
// These strings will be determined on demand
_oneTab = null;
_currentAttributeIndent = null;
}
}
private void PushIndent()
{
_indents.AddLast(new LinkedListNode<string>(CurrentIndent));
// The next indent will be determined on demand, assuming
// we don't find one before it's needed
_currentIndent = null;
// Don't use the property accessor to push the attribute
// indent. These aren't always needed, so we don't compute
// them until necessary. Also, we don't walk through this
// stack like we do the indents stack.
_attributeIndents.AddLast(new LinkedListNode<string>(_currentAttributeIndent));
_currentAttributeIndent = null;
}
private void PopIndent()
{
if (_indents.Count > 0)
{
_currentIndent = _indents.Last.Value;
_indents.RemoveLast();
_currentAttributeIndent = _attributeIndents.Last.Value;
_attributeIndents.RemoveLast();
}
else
{
Debug.Fail("Popped too many indents");
throw new InvalidOperationException();
}
}
private bool NeedsIndent(XmlNode node, XmlNode previousNode)
{
return !IsWhiteSpace(previousNode)
&& !IsText(previousNode)
&& (IsNewNode(node) || IsNewNode(previousNode));
}
private bool IsWhiteSpace(XmlNode node)
{
return node != null
&& node.NodeType == XmlNodeType.Whitespace;
}
public bool IsText(XmlNode node)
{
return node != null
&& node.NodeType == XmlNodeType.Text;
}
private bool IsNewNode(XmlNode node)
{
return node != null
&& _document.IsNewNode(node);
}
private void InsertIndentBefore(XmlNode node)
{
node.ParentNode.InsertBefore(_document.CreateWhitespace(CurrentIndent), node);
}
private void InsertIndentBeforeEnd(XmlNode node)
{
node.AppendChild(_document.CreateWhitespace(CurrentIndent));
}
private string ComputeCurrentIndent()
{
return LookAheadForIndent() ?? PreviousIndent + OneTab;
}
private string LookAheadForIndent()
{
if (_currentNode.ParentNode == null)
return null;
foreach (XmlNode siblingNode in _currentNode.ParentNode.ChildNodes)
{
if (!IsWhiteSpace(siblingNode) || siblingNode.NextSibling == null) continue;
var whitespace = siblingNode.OuterXml;
var index = FindLastNewLine(whitespace);
if (index >= 0)
{
return whitespace.Substring(index);
}
}
return null;
}
private string ComputeOneTab()
{
Debug.Assert(_indents.Count > 0, "Expected at least one previous indent");
if (_indents.Count < 0)
{
return DefaultTab;
}
var currentIndentNode = _indents.Last;
var previousIndentNode = currentIndentNode.Previous;
while (previousIndentNode != null)
{
// If we can determine the difference between the current indent
// and the previous one, then that's the value of one tab
if (currentIndentNode.Value.StartsWith(previousIndentNode.Value, StringComparison.Ordinal))
{
return currentIndentNode.Value.Substring(previousIndentNode.Value.Length);
}
currentIndentNode = previousIndentNode;
previousIndentNode = currentIndentNode.Previous;
}
return ConvertIndentToTab(currentIndentNode.Value);
}
private string ConvertIndentToTab(string indent)
{
for (var index = 0; index < indent.Length - 1; index++)
{
switch (indent[index])
{
case '\r':
case '\n':
break;
default:
return indent.Substring(index + 1);
}
}
// There were no characters after the newlines, or the string was
// empty. Fall back on the default value
return DefaultTab;
}
private string ComputeCurrentAttributeIndent()
{
var siblingIndent = LookForSiblingIndent(CurrentNode);
if (siblingIndent != null)
{
return siblingIndent;
}
return CurrentIndent + OneTab;
}
private string LookForSiblingIndent(XmlNode currentNode)
{
var beforeCurrentNode = true;
string foundIndent = null;
foreach (XmlNode node in currentNode.ParentNode.ChildNodes)
{
if (node == currentNode)
{
beforeCurrentNode = false;
}
else
{
var formattable = node as IXmlFormattableAttributes;
if (formattable != null)
{
foundIndent = formattable.AttributeIndent;
}
}
if (!beforeCurrentNode && foundIndent != null)
{
return foundIndent;
}
}
return null;
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityBase.EntityFramework.Entities;
using IdentityBase.EntityFramework.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace IdentityBase.EntityFramework.Extensions
{
/// <summary>
/// Extension methods to define the database schema for the configuration
/// and operational data stores.
/// </summary>
public static class ModelBuilderExtensions
{
private static EntityTypeBuilder<TEntity> ToTable<TEntity>(
this EntityTypeBuilder<TEntity> entityTypeBuilder,
TableConfiguration configuration)
where TEntity : class
{
return string.IsNullOrWhiteSpace(configuration.Schema) ?
entityTypeBuilder.ToTable(configuration.Name) :
entityTypeBuilder
.ToTable(configuration.Name, configuration.Schema);
}
/// <summary>
/// Configures the client context.
/// </summary>
/// <param name="modelBuilder">The model builder.</param>
/// <param name="storeOptions">The store options.</param>
public static void ConfigureClientContext(
this ModelBuilder modelBuilder,
EntityFrameworkOptions storeOptions)
{
if (!string.IsNullOrWhiteSpace(storeOptions.DefaultSchema))
{
modelBuilder.HasDefaultSchema(storeOptions.DefaultSchema);
}
modelBuilder.Entity<Client>(client =>
{
client.ToTable(storeOptions.Client);
client.HasKey(x => x.Id);
client.Property(x => x.ClientId)
.HasMaxLength(200)
.IsRequired();
client.Property(x => x.ProtocolType)
.HasMaxLength(200)
.IsRequired();
client.Property(x => x.ClientName)
.HasMaxLength(200);
client.Property(x => x.ClientUri)
.HasMaxLength(2000);
client.Property(x => x.LogoUri)
.HasMaxLength(2000);
client.Property(x => x.Description)
.HasMaxLength(1000);
client.Property(x => x.FrontChannelLogoutUri)
.HasMaxLength(2000);
client.Property(x => x.BackChannelLogoutUri)
.HasMaxLength(2000);
client.Property(x => x.ClientClaimsPrefix)
.HasMaxLength(200);
client.Property(x => x.PairWiseSubjectSalt)
.HasMaxLength(200);
client.HasIndex(x => x.ClientId).IsUnique();
client.HasMany(x => x.AllowedGrantTypes)
.WithOne(x => x.Client)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
client.HasMany(x => x.RedirectUris)
.WithOne(x => x.Client)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
client.HasMany(x => x.PostLogoutRedirectUris)
.WithOne(x => x.Client)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
client.HasMany(x => x.AllowedScopes)
.WithOne(x => x.Client)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
client.HasMany(x => x.ClientSecrets)
.WithOne(x => x.Client)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
client.HasMany(x => x.Claims)
.WithOne(x => x.Client)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
client.HasMany(x => x.IdentityProviderRestrictions)
.WithOne(x => x.Client)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
client.HasMany(x => x.AllowedCorsOrigins)
.WithOne(x => x.Client)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
client.HasMany(x => x.Properties)
.WithOne(x => x.Client)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<ClientGrantType>(grantType =>
{
grantType.ToTable(storeOptions.ClientGrantType);
grantType.Property(x => x.GrantType)
.HasMaxLength(250)
.IsRequired();
});
modelBuilder.Entity<ClientRedirectUri>(redirectUri =>
{
redirectUri.ToTable(storeOptions.ClientRedirectUri);
redirectUri.Property(x => x.RedirectUri)
.HasMaxLength(2000)
.IsRequired();
});
modelBuilder
.Entity<ClientPostLogoutRedirectUri>(postLogoutRedirectUri =>
{
postLogoutRedirectUri
.ToTable(storeOptions.ClientPostLogoutRedirectUri);
postLogoutRedirectUri
.Property(x => x.PostLogoutRedirectUri)
.HasMaxLength(2000)
.IsRequired();
});
modelBuilder.Entity<ClientScope>(scope =>
{
scope.ToTable(storeOptions.ClientScopes);
scope.Property(x => x.Scope)
.HasMaxLength(200)
.IsRequired();
});
modelBuilder.Entity<ClientSecret>(secret =>
{
secret.ToTable(storeOptions.ClientSecret);
secret.Property(x => x.Value)
.HasMaxLength(2000).IsRequired();
secret.Property(x => x.Type)
.HasMaxLength(250);
secret.Property(x => x.Description)
.HasMaxLength(2000);
});
modelBuilder.Entity<ClientClaim>(claim =>
{
claim.ToTable(storeOptions.ClientClaim);
claim.Property(x => x.Type)
.HasMaxLength(250).IsRequired();
claim.Property(x => x.Value)
.HasMaxLength(250).IsRequired();
});
modelBuilder.Entity<ClientIdPRestriction>(idPRestriction =>
{
idPRestriction.ToTable(storeOptions.ClientIdPRestriction);
idPRestriction.Property(x => x.Provider)
.HasMaxLength(200)
.IsRequired();
});
modelBuilder.Entity<ClientCorsOrigin>(corsOrigin =>
{
corsOrigin.ToTable(storeOptions.ClientCorsOrigin);
corsOrigin.Property(x => x.Origin)
.HasMaxLength(150)
.IsRequired();
});
modelBuilder.Entity<ClientProperty>(property =>
{
property.ToTable(storeOptions.ClientProperty);
property.Property(x => x.Key)
.HasMaxLength(250).IsRequired();
property.Property(x => x.Value)
.HasMaxLength(2000).IsRequired();
});
}
/// <summary>
/// Configures the persisted grant context.
/// </summary>
/// <param name="modelBuilder">The model builder.</param>
/// <param name="storeOptions">The store options.</param>
public static void ConfigurePersistedGrantContext(
this ModelBuilder modelBuilder,
EntityFrameworkOptions storeOptions)
{
if (!string.IsNullOrWhiteSpace(storeOptions.DefaultSchema))
{
modelBuilder.HasDefaultSchema(storeOptions.DefaultSchema);
}
modelBuilder.Entity<PersistedGrant>(grant =>
{
grant.ToTable(storeOptions.PersistedGrants);
grant.Property(x => x.Key)
.HasMaxLength(200)
.ValueGeneratedNever();
grant.Property(x => x.Type)
.HasMaxLength(50)
.IsRequired();
grant.Property(x => x.SubjectId)
.HasMaxLength(200);
grant.Property(x => x.ClientId)
.HasMaxLength(200)
.IsRequired();
grant.Property(x => x.CreationTime)
.IsRequired();
// 50000 chosen to be explicit to allow enough size to avoid
// truncation, yet stay beneath the MySql row size limit of
// ~65K apparently anything over 4K converts to nvarchar(max)
// on SqlServer
grant.Property(x => x.Data)
.HasMaxLength(50000)
.IsRequired();
grant.HasKey(x => x.Key);
grant.HasIndex(x => new { x.SubjectId, x.ClientId, x.Type });
});
}
/// <summary>
/// Configures the resources context.
/// </summary>
/// <param name="modelBuilder">The model builder.</param>
/// <param name="storeOptions">The store options.</param>
public static void ConfigureResourcesContext(
this ModelBuilder modelBuilder,
EntityFrameworkOptions storeOptions)
{
if (!string.IsNullOrWhiteSpace(storeOptions.DefaultSchema))
{
modelBuilder.HasDefaultSchema(storeOptions.DefaultSchema);
}
modelBuilder.Entity<IdentityResource>(identityResource =>
{
identityResource
.ToTable(storeOptions.IdentityResource)
.HasKey(x => x.Id);
identityResource.Property(x => x.Name)
.HasMaxLength(200)
.IsRequired();
identityResource.Property(x => x.DisplayName)
.HasMaxLength(200);
identityResource.Property(x => x.Description)
.HasMaxLength(1000);
identityResource.HasIndex(x => x.Name)
.IsUnique();
identityResource.HasMany(x => x.UserClaims)
.WithOne(x => x.IdentityResource)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<IdentityClaim>(claim =>
{
claim
.ToTable(storeOptions.IdentityClaim)
.HasKey(x => x.Id);
claim.Property(x => x.Type)
.HasMaxLength(200)
.IsRequired();
});
modelBuilder.Entity<ApiResource>(apiResource =>
{
apiResource
.ToTable(storeOptions.ApiResource)
.HasKey(x => x.Id);
apiResource.Property(x => x.Name)
.HasMaxLength(200)
.IsRequired();
apiResource.Property(x => x.DisplayName)
.HasMaxLength(200);
apiResource.Property(x => x.Description)
.HasMaxLength(1000);
apiResource.HasIndex(x => x.Name).IsUnique();
apiResource.HasMany(x => x.Secrets)
.WithOne(x => x.ApiResource)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
apiResource.HasMany(x => x.Scopes)
.WithOne(x => x.ApiResource)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
apiResource.HasMany(x => x.UserClaims)
.WithOne(x => x.ApiResource)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<ApiSecret>(apiSecret =>
{
apiSecret
.ToTable(storeOptions.ApiSecret)
.HasKey(x => x.Id);
apiSecret.Property(x => x.Description)
.HasMaxLength(1000);
apiSecret.Property(x => x.Value)
.HasMaxLength(2000);
apiSecret.Property(x => x.Type)
.HasMaxLength(250);
});
modelBuilder.Entity<ApiResourceClaim>(apiClaim =>
{
apiClaim
.ToTable(storeOptions.ApiClaim)
.HasKey(x => x.Id);
apiClaim.Property(x => x.Type)
.HasMaxLength(200)
.IsRequired();
});
modelBuilder.Entity<ApiScope>(apiScope =>
{
apiScope
.ToTable(storeOptions.ApiScope)
.HasKey(x => x.Id);
apiScope.Property(x => x.Name)
.HasMaxLength(200)
.IsRequired();
apiScope.Property(x => x.DisplayName)
.HasMaxLength(200);
apiScope.Property(x => x.Description)
.HasMaxLength(1000);
apiScope.HasIndex(x => x.Name)
.IsUnique();
apiScope.HasMany(x => x.UserClaims)
.WithOne(x => x.ApiScope)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<ApiScopeClaim>(apiScopeClaim =>
{
apiScopeClaim
.ToTable(storeOptions.ApiScopeClaim)
.HasKey(x => x.Id);
apiScopeClaim.Property(x => x.Type)
.HasMaxLength(200)
.IsRequired();
});
}
/// <summary>
/// Configures the user account context.
/// </summary>
/// <param name="modelBuilder">The model builder.</param>
/// <param name="storeOptions">The store options.</param>
public static void ConfigureUserAccountContext(
this ModelBuilder modelBuilder,
EntityFrameworkOptions storeOptions)
{
if (!string.IsNullOrWhiteSpace(storeOptions.DefaultSchema))
{
modelBuilder.HasDefaultSchema(storeOptions.DefaultSchema);
}
modelBuilder.Entity<UserAccount>(userAccount =>
{
userAccount
.ToTable(storeOptions.UserAccount);
userAccount.HasKey(x => new { x.Id });
userAccount.Property(x => x.Email)
.HasMaxLength(254)
.IsRequired();
userAccount.Property(x => x.IsEmailVerified)
.IsRequired();
userAccount.Property(x => x.EmailVerifiedAt);
userAccount.Property(x => x.IsActive)
.IsRequired();
userAccount.Property(x => x.LastLoginAt);
userAccount.Property(x => x.FailedLoginCount);
userAccount.Property(x => x.PasswordHash)
.HasMaxLength(200);
userAccount.Property(x => x.PasswordChangedAt);
userAccount.Property(x => x.VerificationKey)
.HasMaxLength(100);
userAccount.Property(x => x.VerificationPurpose);
userAccount.Property(x => x.VerificationKeySentAt);
userAccount.Property(x => x.VerificationStorage)
.HasMaxLength(2000);
userAccount.Property(x => x.CreatedAt);
userAccount.Property(x => x.UpdatedAt);
userAccount.Property(x => x.CreatedBy);
userAccount.Property(x => x.CreationKind);
userAccount.HasMany(x => x.Accounts)
.WithOne(x => x.UserAccount)
.HasForeignKey(x => x.UserAccountId)
.IsRequired().OnDelete(DeleteBehavior.Cascade);
userAccount.HasMany(x => x.Claims)
.WithOne(x => x.UserAccount)
.HasForeignKey(x => x.UserAccountId)
.IsRequired().OnDelete(DeleteBehavior.Cascade);
userAccount
.HasIndex(x => x.Email)
.IsUnique();
});
modelBuilder.Entity<ExternalAccount>(externalAccount =>
{
externalAccount
.ToTable(storeOptions.ExternalAccount);
externalAccount.HasKey(x => new
{
x.Provider,
x.Subject
});
externalAccount.Property(x => x.Provider)
.IsRequired();
externalAccount.Property(x => x.Subject)
.IsRequired();
externalAccount.Property(x => x.Email)
.IsRequired().HasMaxLength(254);
externalAccount.Property(x => x.LastLoginAt);
externalAccount.Property(x => x.CreatedAt)
.IsRequired();
externalAccount.Property(x => x.UpdatedAt)
.IsRequired();
externalAccount.Property(x => x.LastLoginAt);
});
modelBuilder.Entity<UserAccountClaim>(claim =>
{
claim
.ToTable(storeOptions.UserAccountClaim);
claim.HasKey(x => new { x.Id });
claim.Property(x => x.Type)
.HasMaxLength(250).IsRequired();
claim.Property(x => x.Value)
.HasMaxLength(250).IsRequired();
claim.Property(x => x.ValueType)
.HasMaxLength(2000);
});
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
namespace Microsoft.Azure.KeyVault.Tests
{
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Azure.KeyVault.WebKey;
using Microsoft.Azure.Services.AppAuthentication;
// Used to compile sample snippets used in MigrationGuide.md documents for track 1.
internal class SampleSnippets
{
private async Task CertificatesMigrationGuide()
{
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_Create
AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
KeyVaultClient client = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback));
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_Create
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateWithOptions
using (HttpClient httpClient = new HttpClient())
{
//@@AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
/*@@*/ provider = new AzureServiceTokenProvider();
//@@KeyVaultClient client = new KeyVaultClient(
/*@@*/ client = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback),
httpClient);
}
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateWithOptions
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateCustomPolicy
CertificatePolicy policy = new CertificatePolicy
{
IssuerParameters = new IssuerParameters("issuer-name"),
SecretProperties = new SecretProperties("application/x-pkcs12"),
KeyProperties = new KeyProperties
{
KeyType = "RSA",
KeySize = 2048,
ReuseKey = true
},
X509CertificateProperties = new X509CertificateProperties("CN=customdomain.com")
{
KeyUsage = new[]
{
KeyUsageType.CRLSign,
KeyUsageType.DataEncipherment,
KeyUsageType.DigitalSignature,
KeyUsageType.KeyEncipherment,
KeyUsageType.KeyAgreement,
KeyUsageType.KeyCertSign
},
ValidityInMonths = 12
},
LifetimeActions = new[]
{
new LifetimeAction(
new Trigger
{
DaysBeforeExpiry = 90
},
new Models.Action(ActionType.AutoRenew))
}
};
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateCustomPolicy
{
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateCertificate
CertificateBundle certificate = null;
// Start certificate creation.
// Depending on the policy and your business process, this could even take days for manual signing.
CertificateOperation createOperation = await client.CreateCertificateAsync("https://myvault.vault.azure.net", "certificate-name", policy);
while (true)
{
if ("InProgress".Equals(createOperation.Status, StringComparison.OrdinalIgnoreCase))
{
await Task.Delay(TimeSpan.FromSeconds(20));
createOperation = await client.GetCertificateOperationAsync("https://myvault.vault.azure.net", "certificate-name");
continue;
}
if ("Completed".Equals(createOperation.Status, StringComparison.OrdinalIgnoreCase))
{
certificate = await client.GetCertificateAsync(createOperation.Id);
break;
}
throw new Exception(string.Format(
CultureInfo.InvariantCulture,
"Polling on pending certificate returned an unexpected result. Error code = {0}, Error message = {1}",
createOperation.Error.Code,
createOperation.Error.Message));
}
// If you need to restart the application you can recreate the operation and continue awaiting.
do
{
createOperation = await client.GetCertificateOperationAsync("https://myvault.vault.azure.net", "certificate-name");
if ("InProgress".Equals(createOperation.Status, StringComparison.OrdinalIgnoreCase))
{
await Task.Delay(TimeSpan.FromSeconds(20));
continue;
}
if ("Completed".Equals(createOperation.Status, StringComparison.OrdinalIgnoreCase))
{
certificate = await client.GetCertificateAsync(createOperation.Id);
break;
}
throw new Exception(string.Format(
CultureInfo.InvariantCulture,
"Polling on pending certificate returned an unexpected result. Error code = {0}, Error message = {1}",
createOperation.Error.Code,
createOperation.Error.Message));
} while (true);
#endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateCertificate
}
{
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_ImportCertificate
byte[] cer = File.ReadAllBytes("certificate.pfx");
string cerBase64 = Convert.ToBase64String(cer);
CertificateBundle certificate = await client.ImportCertificateAsync(
"https://myvault.vault.azure.net",
"certificate-name",
cerBase64,
certificatePolicy: policy);
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_ImportCertificate
}
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateSelfSignedPolicy
//@@CertificatePolicy policy = new CertificatePolicy
/*@@*/
policy = new CertificatePolicy
{
IssuerParameters = new IssuerParameters("Self"),
X509CertificateProperties = new X509CertificateProperties("CN=DefaultPolicy")
};
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateSelfSignedPolicy
// TODO
{
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_ListCertificates
IPage<CertificateItem> page = await client.GetCertificatesAsync("https://myvault.vault.azure.net");
foreach (CertificateItem item in page)
{
CertificateIdentifier certificateId = item.Identifier;
CertificateBundle certificate = await client.GetCertificateAsync(certificateId.Vault, certificateId.Name);
}
while (page.NextPageLink != null)
{
page = await client.GetCertificatesNextAsync(page.NextPageLink);
foreach (CertificateItem item in page)
{
CertificateIdentifier certificateId = item.Identifier;
CertificateBundle certificate = await client.GetCertificateAsync(certificateId.Vault, certificateId.Name);
}
}
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_ListCertificates
}
{
#region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_DeleteCertificate
// Delete the certificate.
DeletedCertificateBundle deletedCertificate = await client.DeleteCertificateAsync("https://myvault.vault.azure.net", "certificate-name");
// Purge or recover the deleted certificate if soft delete is enabled.
if (deletedCertificate.RecoveryId != null)
{
DeletedCertificateIdentifier deletedCertificateId = deletedCertificate.RecoveryIdentifier;
// Deleting a certificate does not happen immediately. Wait a while and check if the deleted certificate exists.
while (true)
{
try
{
await client.GetDeletedCertificateAsync(deletedCertificateId.Vault, deletedCertificateId.Name);
// Finally deleted.
break;
}
catch (KeyVaultErrorException ex) when (ex.Response.StatusCode == HttpStatusCode.NotFound)
{
// Not yet deleted...
}
}
// Purge the deleted certificate.
await client.PurgeDeletedCertificateAsync(deletedCertificateId.Vault, deletedCertificateId.Name);
// You can also recover the deleted certificate using RecoverDeletedCertificateAsync.
}
#endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_DeleteCertificate
}
}
private async Task KeysMigrationGuide()
{
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Create
AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
KeyVaultClient client = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback));
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Create
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions
using (HttpClient httpClient = new HttpClient())
{
//@@AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
/*@@*/ provider = new AzureServiceTokenProvider();
//@@KeyVaultClient client = new KeyVaultClient(
/*@@*/ client = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback),
httpClient);
}
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions
{
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateKey
// Create RSA key.
NewKeyParameters createRsaParameters = new NewKeyParameters
{
Kty = JsonWebKeyType.Rsa,
KeySize = 4096
};
KeyBundle rsaKey = await client.CreateKeyAsync("https://myvault.vault.azure.net", "rsa-key-name", createRsaParameters);
// Create Elliptic-Curve key.
NewKeyParameters createEcParameters = new NewKeyParameters
{
Kty = JsonWebKeyType.EllipticCurve,
CurveName = "P-256"
};
KeyBundle ecKey = await client.CreateKeyAsync("https://myvault.vault.azure.net", "ec-key-name", createEcParameters);
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateKey
}
{
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_ListKeys
IPage<KeyItem> page = await client.GetKeysAsync("https://myvault.vault.azure.net");
foreach (KeyItem item in page)
{
KeyIdentifier keyId = item.Identifier;
KeyBundle key = await client.GetKeyAsync(keyId.Vault, keyId.Name);
}
while (page.NextPageLink != null)
{
page = await client.GetKeysNextAsync(page.NextPageLink);
foreach (KeyItem item in page)
{
KeyIdentifier keyId = item.Identifier;
KeyBundle key = await client.GetKeyAsync(keyId.Vault, keyId.Name);
}
}
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_ListKeys
}
{
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey
// Delete the key.
DeletedKeyBundle deletedKey = await client.DeleteKeyAsync("https://myvault.vault.azure.net", "key-name");
// Purge or recover the deleted key if soft delete is enabled.
if (deletedKey.RecoveryId != null)
{
DeletedKeyIdentifier deletedKeyId = deletedKey.RecoveryIdentifier;
// Deleting a key does not happen immediately. Wait a while and check if the deleted key exists.
while (true)
{
try
{
await client.GetDeletedKeyAsync(deletedKeyId.Vault, deletedKeyId.Name);
// Finally deleted.
break;
}
catch (KeyVaultErrorException ex) when (ex.Response.StatusCode == HttpStatusCode.NotFound)
{
// Not yet deleted...
}
}
// Purge the deleted key.
await client.PurgeDeletedKeyAsync(deletedKeyId.Vault, deletedKeyId.Name);
// You can also recover the deleted key using RecoverDeletedKeyAsync.
}
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey
}
{
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Encrypt
// Encrypt a message. The plaintext must be small enough for the chosen algorithm.
byte[] plaintext = Encoding.UTF8.GetBytes("Small message to encrypt");
KeyOperationResult encrypted = await client.EncryptAsync("rsa-key-name", JsonWebKeyEncryptionAlgorithm.RSAOAEP256, plaintext);
// Decrypt the message.
KeyOperationResult decrypted = await client.DecryptAsync("rsa-key-name", JsonWebKeyEncryptionAlgorithm.RSAOAEP256, encrypted.Result);
string message = Encoding.UTF8.GetString(decrypted.Result);
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Encrypt
}
{
#region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Wrap
using (Aes aes = Aes.Create())
{
// Use a symmetric key to encrypt large amounts of data, possibly streamed...
// Now wrap the key and store the encrypted key and plaintext IV to later decrypt the key to decrypt the data.
KeyOperationResult wrapped = await client.WrapKeyAsync(
"https://myvault.vault.azure.net",
"rsa-key-name",
null,
JsonWebKeyEncryptionAlgorithm.RSAOAEP256,
aes.Key);
// Read the IV and the encrypted key from the payload, then unwrap the key.
KeyOperationResult unwrapped = await client.UnwrapKeyAsync(
"https://myvault.vault.azure.net",
"rsa-key-name",
null,
JsonWebKeyEncryptionAlgorithm.RSAOAEP256,
wrapped.Result);
aes.Key = unwrapped.Result;
// Decrypt the payload with the symmetric key.
}
#endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Wrap
}
}
private async Task SecretsMigrationGuide()
{
#region Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_Create
AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
KeyVaultClient client = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback));
#endregion Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_Create
#region Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_CreateWithOptions
using (HttpClient httpClient = new HttpClient())
{
//@@AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
/*@@*/ provider = new AzureServiceTokenProvider();
//@@KeyVaultClient client = new KeyVaultClient(
/*@@*/ client = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback),
httpClient);
}
#endregion Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_CreateWithOptions
{
#region Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_SetSecret
SecretBundle secret = await client.SetSecretAsync("https://myvault.vault.azure.net", "secret-name", "secret-value");
#endregion Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_SetSecret
}
{
#region Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_GetSecret
// Get the latest secret value.
SecretBundle secret = await client.GetSecretAsync("https://myvault.vault.azure.net", "secret-name", null);
// Get a specific secret value.
SecretBundle secretVersion = await client.GetSecretAsync("https://myvault.vault.azure.net", "secret-name", "e43af03a7cbc47d4a4e9f11540186048");
#endregion Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_GetSecret
}
{
#region Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_ListSecrets
IPage<SecretItem> page = await client.GetSecretsAsync("https://myvault.vault.azure.net");
foreach (SecretItem item in page)
{
SecretIdentifier secretId = item.Identifier;
SecretBundle secret = await client.GetSecretAsync(secretId.Vault, secretId.Name);
}
while (page.NextPageLink != null)
{
page = await client.GetSecretsNextAsync(page.NextPageLink);
foreach (SecretItem item in page)
{
SecretIdentifier secretId = item.Identifier;
SecretBundle secret = await client.GetSecretAsync(secretId.Vault, secretId.Name);
}
}
#endregion Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_ListSecrets
}
{
#region Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_DeleteSecret
// Delete the secret.
DeletedSecretBundle deletedSecret = await client.DeleteSecretAsync("https://myvault.vault.azure.net", "secret-name");
// Purge or recover the deleted secret if soft delete is enabled.
if (deletedSecret.RecoveryId != null)
{
DeletedSecretIdentifier deletedSecretId = deletedSecret.RecoveryIdentifier;
// Deleting a secret does not happen immediately. Wait a while and check if the deleted secret exists.
while (true)
{
try
{
await client.GetDeletedSecretAsync(deletedSecretId.Vault, deletedSecretId.Name);
// Finally deleted.
break;
}
catch (KeyVaultErrorException ex) when (ex.Response.StatusCode == HttpStatusCode.NotFound)
{
// Not yet deleted...
}
}
// Purge the deleted secret.
await client.PurgeDeletedSecretAsync(deletedSecretId.Vault, deletedSecretId.Name);
// You can also recover the deleted secret using RecoverDeletedSecretAsync.
}
#endregion Snippet:Microsoft_Azure_KeyVault_Secrets_Snippets_MigrationGuide_DeleteSecret
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Storages.Algo
File: StorageMessageAdapter.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Storages
{
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Common;
using MoreLinq;
using StockSharp.Algo.Candles;
using StockSharp.BusinessEntities;
using StockSharp.Localization;
using StockSharp.Logging;
using StockSharp.Messages;
/// <summary>
/// Storage based message adapter.
/// </summary>
public class StorageMessageAdapter : BufferMessageAdapter
{
private readonly IStorageRegistry _storageRegistry;
private readonly IEntityRegistry _entityRegistry;
/// <summary>
/// Initializes a new instance of the <see cref="StorageMessageAdapter"/>.
/// </summary>
/// <param name="innerAdapter">The adapter, to which messages will be directed.</param>
/// <param name="entityRegistry">The storage of trade objects.</param>
/// <param name="storageRegistry">The storage of market data.</param>
public StorageMessageAdapter(IMessageAdapter innerAdapter, IEntityRegistry entityRegistry, IStorageRegistry storageRegistry)
: base(innerAdapter)
{
if (entityRegistry == null)
throw new ArgumentNullException(nameof(entityRegistry));
if (storageRegistry == null)
throw new ArgumentNullException(nameof(storageRegistry));
_entityRegistry = entityRegistry;
_storageRegistry = storageRegistry;
Drive = _storageRegistry.DefaultDrive;
var isProcessing = false;
var sync = new SyncObject();
ThreadingHelper.Timer(() =>
{
lock (sync)
{
if (isProcessing)
return;
isProcessing = true;
}
try
{
foreach (var pair in GetTicks())
{
GetStorage<ExecutionMessage>(pair.Key, ExecutionTypes.Tick).Save(pair.Value);
}
foreach (var pair in GetOrderLog())
{
GetStorage<ExecutionMessage>(pair.Key, ExecutionTypes.OrderLog).Save(pair.Value);
}
foreach (var pair in GetTransactions())
{
GetStorage<ExecutionMessage>(pair.Key, ExecutionTypes.Transaction).Save(pair.Value);
}
foreach (var pair in GetOrderBooks())
{
GetStorage(pair.Key, typeof(QuoteChangeMessage), null).Save(pair.Value);
}
foreach (var pair in GetLevel1())
{
GetStorage(pair.Key, typeof(Level1ChangeMessage), null).Save(pair.Value);
}
foreach (var pair in GetCandles())
{
GetStorage(pair.Key.Item1, pair.Key.Item2, pair.Key.Item3).Save(pair.Value);
}
var news = GetNews().ToArray();
if (news.Length > 0)
{
_storageRegistry.GetNewsMessageStorage(Drive, Format).Save(news);
}
}
catch (Exception excp)
{
excp.LogError();
}
finally
{
lock (sync)
isProcessing = false;
}
}).Interval(TimeSpan.FromSeconds(10));
}
private IMarketDataDrive _drive;
/// <summary>
/// The storage (database, file etc.).
/// </summary>
public IMarketDataDrive Drive
{
get { return _drive; }
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_drive = value;
}
}
/// <summary>
/// Format.
/// </summary>
public StorageFormats Format { get; set; }
private TimeSpan _daysLoad;
/// <summary>
/// Max days to load stored data.
/// </summary>
public TimeSpan DaysLoad
{
get { return _daysLoad; }
set
{
if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(value));
_daysLoad = value;
}
}
/// <summary>
/// Use timeframe candles instead of trades.
/// </summary>
public bool UseCandlesInsteadTrades { get; set; }
/// <summary>
/// Use candles with specified timeframe.
/// </summary>
public TimeSpan CandlesTimeFrame { get; set; }
private IMarketDataStorage<TMessage> GetStorage<TMessage>(SecurityId securityId, object arg)
where TMessage : Message
{
return (IMarketDataStorage<TMessage>)GetStorage(securityId, typeof(TMessage), arg);
}
private IMarketDataStorage GetStorage(SecurityId securityId, Type messageType, object arg)
{
var security = _entityRegistry.Securities.ReadBySecurityId(securityId) ?? TryCreateSecurity(securityId);
if (security == null)
throw new InvalidOperationException(LocalizedStrings.Str704Params.Put(securityId));
return _storageRegistry.GetStorage(security, messageType, arg, Drive, Format);
}
/// <summary>
/// Load save data from storage.
/// </summary>
public void Load()
{
var requiredSecurities = new List<SecurityId>();
var availableSecurities = Drive.AvailableSecurities.ToHashSet();
foreach (var board in _entityRegistry.ExchangeBoards)
RaiseStorageMessage(board.ToMessage());
foreach (var security in _entityRegistry.Securities)
{
var msg = security.ToMessage();
if (availableSecurities.Remove(msg.SecurityId))
{
requiredSecurities.Add(msg.SecurityId);
}
RaiseStorageMessage(msg);
}
foreach (var portfolio in _entityRegistry.Portfolios)
{
RaiseStorageMessage(portfolio.ToMessage());
RaiseStorageMessage(portfolio.ToChangeMessage());
}
foreach (var position in _entityRegistry.Positions)
{
RaiseStorageMessage(position.ToMessage());
RaiseStorageMessage(position.ToChangeMessage());
}
if (DaysLoad == TimeSpan.Zero)
return;
var today = DateTime.UtcNow.Date;
var from = (DateTimeOffset)(today - DaysLoad);
var to = DateTimeOffset.Now;
foreach (var secId in requiredSecurities)
{
GetStorage<ExecutionMessage>(secId, ExecutionTypes.Transaction)
.Load(from, to)
.ForEach(RaiseStorageMessage);
}
}
/// <summary>
/// Send message.
/// </summary>
/// <param name="message">Message.</param>
public override void SendInMessage(Message message)
{
if (message.Type == MessageTypes.MarketData)
ProcessMarketDataMessage((MarketDataMessage)message);
base.SendInMessage(message);
}
private void ProcessMarketDataMessage(MarketDataMessage msg)
{
if (msg.IsBack || !msg.IsSubscribe || DaysLoad == TimeSpan.Zero)
return;
var today = DateTime.UtcNow.Date;
var from = (DateTimeOffset)(today - DaysLoad);
var to = DateTimeOffset.Now;
switch (msg.DataType)
{
case MarketDataTypes.Level1:
LoadMessages(GetStorage<Level1ChangeMessage>(msg.SecurityId, null), from, to);
break;
case MarketDataTypes.MarketDepth:
LoadMessages(GetStorage<QuoteChangeMessage>(msg.SecurityId, null), from, to);
break;
case MarketDataTypes.Trades:
if (!UseCandlesInsteadTrades)
LoadMessages(GetStorage<ExecutionMessage>(msg.SecurityId, ExecutionTypes.Tick), from, to);
else
LoadMessages(msg.SecurityId, ExecutionTypes.Tick, from, to);
break;
case MarketDataTypes.OrderLog:
LoadMessages(GetStorage<ExecutionMessage>(msg.SecurityId, ExecutionTypes.OrderLog), from, to);
break;
case MarketDataTypes.News:
LoadMessages(_storageRegistry.GetNewsMessageStorage(Drive, Format), from, to);
break;
case MarketDataTypes.CandleTimeFrame:
LoadMessages(GetStorage<TimeFrameCandleMessage>(msg.SecurityId, msg.Arg), from, to);
break;
case MarketDataTypes.CandlePnF:
LoadMessages(GetStorage<PnFCandleMessage>(msg.SecurityId, msg.Arg), from, to);
break;
case MarketDataTypes.CandleRange:
LoadMessages(GetStorage<RangeCandleMessage>(msg.SecurityId, msg.Arg), from, to);
break;
case MarketDataTypes.CandleRenko:
LoadMessages(GetStorage<RenkoCandleMessage>(msg.SecurityId, msg.Arg), from, to);
break;
case MarketDataTypes.CandleTick:
LoadMessages(GetStorage<TickCandleMessage>(msg.SecurityId, msg.Arg), from, to);
break;
case MarketDataTypes.CandleVolume:
LoadMessages(GetStorage<VolumeCandleMessage>(msg.SecurityId, msg.Arg), from, to);
break;
default:
throw new ArgumentOutOfRangeException(nameof(msg), msg.DataType, LocalizedStrings.Str721);
}
}
private void LoadMessages<TMessage>(IMarketDataStorage<TMessage> storage, DateTimeOffset from, DateTimeOffset to)
where TMessage : Message
{
storage
.Load(from, to)
.ForEach(RaiseStorageMessage);
}
private void LoadMessages(SecurityId securityId, object arg, DateTimeOffset from, DateTimeOffset to)
{
var tickStorage = GetStorage<ExecutionMessage>(securityId, arg);
var tickDates = tickStorage.GetDates(from.DateTime, to.DateTime).ToArray();
var candleStorage = GetStorage<TimeFrameCandleMessage>(securityId, CandlesTimeFrame);
for (var date = from.Date; date <= to.Date; date = date.AddDays(1))
{
if (tickDates.Contains(date))
{
tickStorage.Load(date).ForEach(RaiseStorageMessage);
}
else
{
candleStorage.Load(date).ToTrades(0.001m).ForEach(RaiseStorageMessage);
}
}
RaiseStorageMessage(new HistoryInitializedMessage(securityId));
}
/// <summary>
/// Process <see cref="MessageAdapterWrapper.InnerAdapter"/> output message.
/// </summary>
/// <param name="message">The message.</param>
protected override void OnInnerAdapterNewOutMessage(Message message)
{
switch (message.Type)
{
case MessageTypes.Security:
{
var secMsg = (SecurityMessage)message;
var security = _entityRegistry.Securities.ReadBySecurityId(secMsg.SecurityId);
if (security == null)
security = secMsg.ToSecurity(_storageRegistry.ExchangeInfoProvider);
else
security.ApplyChanges(secMsg, _storageRegistry.ExchangeInfoProvider);
_entityRegistry.Securities.Save(security);
break;
}
case MessageTypes.Board:
{
var boardMsg = (BoardMessage)message;
var board = _entityRegistry.ExchangeBoards.ReadById(boardMsg.Code);
if (board == null)
{
board = _storageRegistry.ExchangeInfoProvider.GetOrCreateBoard(boardMsg.Code, code =>
{
var exchange = boardMsg.ToExchange(new Exchange { Name = boardMsg.ExchangeCode });
return boardMsg.ToBoard(new ExchangeBoard { Code = code, Exchange = exchange });
});
}
else
{
// TODO apply changes
}
_entityRegistry.Exchanges.Save(board.Exchange);
_entityRegistry.ExchangeBoards.Save(board);
break;
}
case MessageTypes.Portfolio:
{
var portfolioMsg = (PortfolioMessage)message;
var portfolio = _entityRegistry.Portfolios.ReadById(portfolioMsg.PortfolioName)
?? new Portfolio { Name = portfolioMsg.PortfolioName };
portfolioMsg.ToPortfolio(portfolio, _storageRegistry.ExchangeInfoProvider);
_entityRegistry.Portfolios.Save(portfolio);
break;
}
case MessageTypes.PortfolioChange:
{
var portfolioMsg = (PortfolioChangeMessage)message;
var portfolio = _entityRegistry.Portfolios.ReadById(portfolioMsg.PortfolioName)
?? new Portfolio { Name = portfolioMsg.PortfolioName };
portfolio.ApplyChanges(portfolioMsg, _storageRegistry.ExchangeInfoProvider);
_entityRegistry.Portfolios.Save(portfolio);
break;
}
case MessageTypes.Position:
{
var positionMsg = (PositionMessage)message;
var position = GetPosition(positionMsg.SecurityId, positionMsg.PortfolioName);
if (position == null)
break;
if (!positionMsg.DepoName.IsEmpty())
position.DepoName = positionMsg.DepoName;
if (positionMsg.LimitType != null)
position.LimitType = positionMsg.LimitType;
if (!positionMsg.Description.IsEmpty())
position.Description = positionMsg.Description;
_entityRegistry.Positions.Save(position);
break;
}
case MessageTypes.PositionChange:
{
var positionMsg = (PositionChangeMessage)message;
var position = GetPosition(positionMsg.SecurityId, positionMsg.PortfolioName);
if (position == null)
break;
position.ApplyChanges(positionMsg);
_entityRegistry.Positions.Save(position);
break;
}
}
base.OnInnerAdapterNewOutMessage(message);
}
private Position GetPosition(SecurityId securityId, string portfolioName)
{
var security = !securityId.SecurityCode.IsEmpty() && !securityId.BoardCode.IsEmpty()
? _entityRegistry.Securities.ReadBySecurityId(securityId)
: _entityRegistry.Securities.Lookup(new Security { Code = securityId.SecurityCode, Type = securityId.SecurityType }).FirstOrDefault();
if (security == null)
security = TryCreateSecurity(securityId);
if (security == null)
return null;
var portfolio = _entityRegistry.Portfolios.ReadById(portfolioName);
if (portfolio == null)
{
portfolio = new Portfolio
{
Name = portfolioName
};
_entityRegistry.Portfolios.Add(portfolio);
}
return _entityRegistry.Positions.ReadBySecurityAndPortfolio(security, portfolio)
?? new Position { Security = security, Portfolio = portfolio };
}
private Security TryCreateSecurity(SecurityId securityId)
{
if (securityId.SecurityCode.IsEmpty() || securityId.BoardCode.IsEmpty())
return null;
var security = new Security
{
Id = securityId.ToStringId(),
Code = securityId.SecurityCode,
Board = _storageRegistry.ExchangeInfoProvider.GetOrCreateBoard(securityId.BoardCode),
//ExtensionInfo = new Dictionary<object, object>()
};
_entityRegistry.Securities.Add(security);
return security;
}
private void RaiseStorageMessage(Message message)
{
if (message.LocalTime.IsDefault())
message.LocalTime = InnerAdapter.CurrentTime;
RaiseNewOutMessage(message);
}
/// <summary>
/// Create a copy of <see cref="StorageMessageAdapter"/>.
/// </summary>
/// <returns>Copy.</returns>
public override IMessageChannel Clone()
{
return new StorageMessageAdapter(InnerAdapter, _entityRegistry, _storageRegistry);
}
}
/// <summary>
/// Indicate history initialized message.
/// </summary>
public class HistoryInitializedMessage : Message
{
/// <summary>
/// Security identifier.
/// </summary>
public SecurityId SecurityId { get; }
/// <summary>
/// Message type.
/// </summary>
public static MessageTypes MessageType => ExtendedMessageTypes.HistoryInitialized;
/// <summary>
/// Initializes a new instance of the <see cref="HistoryInitializedMessage"/>.
/// </summary>
public HistoryInitializedMessage(SecurityId securityId)
: base(MessageType)
{
SecurityId = securityId;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using ASC.Common.Logging;
using ASC.Common.Notify.Patterns;
using ASC.Notify.Channels;
using ASC.Notify.Cron;
using ASC.Notify.Messages;
using ASC.Notify.Patterns;
using ASC.Notify.Recipients;
namespace ASC.Notify.Engine
{
public class NotifyEngine : INotifyEngine
{
private static readonly ILog log = LogManager.GetLogger("ASC.Notify");
private readonly Context context;
private readonly List<SendMethodWrapper> sendMethods = new List<SendMethodWrapper>();
private readonly Queue<NotifyRequest> requests = new Queue<NotifyRequest>(1000);
private readonly Thread notifyScheduler;
private readonly Thread notifySender;
private readonly AutoResetEvent requestsEvent = new AutoResetEvent(false);
private readonly AutoResetEvent methodsEvent = new AutoResetEvent(false);
private readonly Dictionary<string, IPatternStyler> stylers = new Dictionary<string, IPatternStyler>();
private readonly IPatternFormatter sysTagFormatter = new ReplacePatternFormatter(@"_#(?<tagName>[A-Z0-9_\-.]+)#_", true);
private readonly TimeSpan defaultSleep = TimeSpan.FromSeconds(10);
public event Action<NotifyEngine, NotifyRequest> BeforeTransferRequest;
public event Action<NotifyEngine, NotifyRequest> AfterTransferRequest;
public NotifyEngine(Context context)
{
if (context == null) throw new ArgumentNullException("context");
this.context = context;
notifyScheduler = new Thread(NotifyScheduler) { IsBackground = true, Name = "NotifyScheduler" };
notifySender = new Thread(NotifySender) { IsBackground = true, Name = "NotifySender" };
}
public virtual void QueueRequest(NotifyRequest request)
{
if (BeforeTransferRequest != null)
{
BeforeTransferRequest(this, request);
}
lock (requests)
{
if (!notifySender.IsAlive)
{
notifySender.Start();
}
requests.Enqueue(request);
}
requestsEvent.Set();
}
internal void RegisterSendMethod(Action<DateTime> method, string cron)
{
if (method == null) throw new ArgumentNullException("method");
if (string.IsNullOrEmpty(cron)) throw new ArgumentNullException("cron");
var w = new SendMethodWrapper(method, cron);
lock (sendMethods)
{
if (!notifyScheduler.IsAlive)
{
notifyScheduler.Start();
}
sendMethods.Remove(w);
sendMethods.Add(w);
}
methodsEvent.Set();
}
internal void UnregisterSendMethod(Action<DateTime> method)
{
if (method == null) throw new ArgumentNullException("method");
lock (sendMethods)
{
sendMethods.Remove(new SendMethodWrapper(method, null));
}
}
private void NotifyScheduler(object state)
{
try
{
while (true)
{
var min = DateTime.MaxValue;
var now = DateTime.UtcNow;
List<SendMethodWrapper> copy;
lock (sendMethods)
{
copy = sendMethods.ToList();
}
foreach (var w in copy)
{
if (!w.ScheduleDate.HasValue)
{
lock (sendMethods)
{
sendMethods.Remove(w);
}
}
if (w.ScheduleDate.Value <= now)
{
try
{
w.InvokeSendMethod(now);
}
catch (Exception error)
{
log.Error(error);
}
w.UpdateScheduleDate(now);
}
if (w.ScheduleDate.Value > now && w.ScheduleDate.Value < min)
{
min = w.ScheduleDate.Value;
}
}
var wait = min != DateTime.MaxValue ? min - DateTime.UtcNow : defaultSleep;
if (wait < defaultSleep)
{
wait = defaultSleep;
}
else if (wait.Ticks > Int32.MaxValue)
{
wait = TimeSpan.FromTicks(Int32.MaxValue);
}
methodsEvent.WaitOne(wait, false);
}
}
catch (ThreadAbortException)
{
return;
}
catch (Exception e)
{
log.Error(e);
}
}
private void NotifySender(object state)
{
try
{
while (true)
{
NotifyRequest request = null;
lock (requests)
{
if (requests.Any())
{
request = requests.Dequeue();
}
}
if (request != null)
{
if (AfterTransferRequest != null)
{
AfterTransferRequest(this, request);
}
try
{
SendNotify(request);
}
catch (Exception e)
{
log.Error(e);
}
}
else
{
requestsEvent.WaitOne();
}
}
}
catch (ThreadAbortException)
{
return;
}
catch (Exception e)
{
log.Error(e);
}
}
private NotifyResult SendNotify(NotifyRequest request)
{
var sendResponces = new List<SendResponse>();
var response = CheckPreventInterceptors(request, InterceptorPlace.Prepare, null);
if (response != null)
{
sendResponces.Add(response);
}
else
{
sendResponces.AddRange(SendGroupNotify(request));
}
NotifyResult result = null;
if (sendResponces == null || sendResponces.Count == 0)
{
result = new NotifyResult(SendResult.OK, sendResponces);
}
else
{
result = new NotifyResult(sendResponces.Aggregate((SendResult)0, (s, r) => s |= r.Result), sendResponces);
}
log.Debug(result);
return result;
}
private SendResponse CheckPreventInterceptors(NotifyRequest request, InterceptorPlace place, string sender)
{
return request.Intercept(place) ? new SendResponse(request.NotifyAction, sender, request.Recipient, SendResult.Prevented) : null;
}
private List<SendResponse> SendGroupNotify(NotifyRequest request)
{
var responces = new List<SendResponse>();
SendGroupNotify(request, responces);
return responces;
}
private void SendGroupNotify(NotifyRequest request, List<SendResponse> responces)
{
if (request.Recipient is IDirectRecipient)
{
var subscriptionSource = request.NotifySource.GetSubscriptionProvider();
if (!request.IsNeedCheckSubscriptions || !subscriptionSource.IsUnsubscribe(request.Recipient as IDirectRecipient, request.NotifyAction, request.ObjectID))
{
var directresponses = new List<SendResponse>(1);
try
{
directresponses = SendDirectNotify(request);
}
catch (Exception exc)
{
directresponses.Add(new SendResponse(request.NotifyAction, request.Recipient, exc));
}
responces.AddRange(directresponses);
}
}
else
{
if (request.Recipient is IRecipientsGroup)
{
var checkresp = CheckPreventInterceptors(request, InterceptorPlace.GroupSend, null);
if (checkresp != null)
{
responces.Add(checkresp);
}
else
{
var recipientProvider = request.NotifySource.GetRecipientsProvider();
try
{
var recipients = recipientProvider.GetGroupEntries(request.Recipient as IRecipientsGroup, request.ObjectID) ?? new IRecipient[0];
foreach (var recipient in recipients)
{
try
{
var newRequest = request.Split(recipient);
SendGroupNotify(newRequest, responces);
}
catch (Exception exc)
{
responces.Add(new SendResponse(request.NotifyAction, request.Recipient, exc));
}
}
}
catch (Exception exc)
{
responces.Add(new SendResponse(request.NotifyAction, request.Recipient, exc) { Result = SendResult.IncorrectRecipient });
}
}
}
else
{
responces.Add(new SendResponse(request.NotifyAction, request.Recipient, null)
{
Result = SendResult.IncorrectRecipient,
Exception = new NotifyException("recipient may be IRecipientsGroup or IDirectRecipient")
});
}
}
}
private List<SendResponse> SendDirectNotify(NotifyRequest request)
{
if (!(request.Recipient is IDirectRecipient)) throw new ArgumentException("request.Recipient not IDirectRecipient", "request");
var responses = new List<SendResponse>();
var response = CheckPreventInterceptors(request, InterceptorPlace.DirectSend, null);
if (response != null)
{
responses.Add(response);
return responses;
}
try
{
PrepareRequestFillSenders(request);
PrepareRequestFillPatterns(request);
PrepareRequestFillTags(request);
}
catch (Exception)
{
responses.Add(new SendResponse(request.NotifyAction, null, request.Recipient, SendResult.Impossible));
}
if (request.SenderNames != null && request.SenderNames.Length > 0)
{
foreach (var sendertag in request.SenderNames)
{
var channel = context.NotifyService.GetSender(sendertag);
if (channel != null)
{
try
{
response = SendDirectNotify(request, channel);
}
catch (Exception exc)
{
response = new SendResponse(request.NotifyAction, channel.SenderName, request.Recipient, exc);
}
}
else
{
response = new SendResponse(request.NotifyAction, sendertag, request.Recipient, new NotifyException(String.Format("Not registered sender \"{0}\".", sendertag)));
}
responses.Add(response);
}
}
else
{
response = new SendResponse(request.NotifyAction, request.Recipient, new NotifyException("Notice hasn't any senders."));
responses.Add(response);
}
return responses;
}
private SendResponse SendDirectNotify(NotifyRequest request, ISenderChannel channel)
{
var recipient = request.Recipient as IDirectRecipient;
if (recipient == null) throw new ArgumentException("request.Recipient not IDirectRecipient", "request");
request.CurrentSender = channel.SenderName;
NoticeMessage noticeMessage;
var oops = CreateNoticeMessageFromNotifyRequest(request, channel.SenderName, out noticeMessage);
if (oops != null) return oops;
request.CurrentMessage = noticeMessage;
var preventresponse = CheckPreventInterceptors(request, InterceptorPlace.MessageSend, channel.SenderName);
if (preventresponse != null) return preventresponse;
channel.SendAsync(noticeMessage);
return new SendResponse(noticeMessage, channel.SenderName, SendResult.Inprogress);
}
private SendResponse CreateNoticeMessageFromNotifyRequest(NotifyRequest request, string sender, out NoticeMessage noticeMessage)
{
if (request == null) throw new ArgumentNullException("request");
var recipientProvider = request.NotifySource.GetRecipientsProvider();
var recipient = request.Recipient as IDirectRecipient;
var addresses = recipient.Addresses;
if (addresses == null || !addresses.Any())
{
addresses = recipientProvider.GetRecipientAddresses(request.Recipient as IDirectRecipient, sender, request.ObjectID);
recipient = new DirectRecipient(request.Recipient.ID, request.Recipient.Name, addresses);
}
recipient = recipientProvider.FilterRecipientAddresses(recipient);
noticeMessage = request.CreateMessage(recipient);
addresses = recipient.Addresses;
if (addresses == null || !addresses.Any(a => !string.IsNullOrEmpty(a)))
{
//checking addresses
return new SendResponse(request.NotifyAction, sender, recipient, new NotifyException(string.Format("For recipient {0} by sender {1} no one addresses getted.", recipient, sender)));
}
var pattern = request.GetSenderPattern(sender);
if (pattern == null)
{
return new SendResponse(request.NotifyAction, sender, recipient, new NotifyException(String.Format("For action \"{0}\" by sender \"{1}\" no one patterns getted.", request.NotifyAction, sender)));
}
noticeMessage.Pattern = pattern;
noticeMessage.ContentType = pattern.ContentType;
noticeMessage.AddArgument(request.Arguments.ToArray());
var patternProvider = request.NotifySource.GetPatternProvider();
var formatter = patternProvider.GetFormatter(pattern);
try
{
if (formatter != null)
{
formatter.FormatMessage(noticeMessage, noticeMessage.Arguments);
}
sysTagFormatter.FormatMessage(
noticeMessage, new[]
{
new TagValue(Context._SYS_RECIPIENT_ID, request.Recipient.ID),
new TagValue(Context._SYS_RECIPIENT_NAME, request.Recipient.Name),
new TagValue(Context._SYS_RECIPIENT_ADDRESS, addresses != null && addresses.Length > 0 ? addresses[0] : null)
}
);
//Do styling here
if (!string.IsNullOrEmpty(pattern.Styler))
{
//We need to run through styler before templating
StyleMessage(noticeMessage);
}
}
catch (Exception exc)
{
return new SendResponse(request.NotifyAction, sender, recipient, exc);
}
return null;
}
private void StyleMessage(NoticeMessage message)
{
try
{
if (!stylers.ContainsKey(message.Pattern.Styler))
{
var styler = Activator.CreateInstance(Type.GetType(message.Pattern.Styler, true)) as IPatternStyler;
if (styler != null)
{
stylers.Add(message.Pattern.Styler, styler);
}
}
stylers[message.Pattern.Styler].ApplyFormating(message);
}
catch (Exception exc)
{
log.Warn("error styling message", exc);
}
}
private void PrepareRequestFillSenders(NotifyRequest request)
{
if (request.SenderNames == null)
{
var subscriptionProvider = request.NotifySource.GetSubscriptionProvider();
var senderNames = new List<string>();
senderNames.AddRange(subscriptionProvider.GetSubscriptionMethod(request.NotifyAction, request.Recipient) ?? new string[0]);
senderNames.AddRange(request.Arguments.OfType<AdditionalSenderTag>().Select(tag => (string)tag.Value));
request.SenderNames = senderNames.ToArray();
}
}
private void PrepareRequestFillPatterns(NotifyRequest request)
{
if (request.Patterns == null)
{
request.Patterns = new IPattern[request.SenderNames.Length];
if (request.Patterns.Length == 0) return;
var apProvider = request.NotifySource.GetPatternProvider();
for (var i = 0; i < request.SenderNames.Length; i++)
{
var senderName = request.SenderNames[i];
IPattern pattern = null;
if (apProvider.GetPatternMethod != null)
{
pattern = apProvider.GetPatternMethod(request.NotifyAction, senderName, request);
}
if (pattern == null)
{
pattern = apProvider.GetPattern(request.NotifyAction, senderName);
}
if (pattern == null)
{
throw new NotifyException(string.Format("For action \"{0}\" by sender \"{1}\" no one patterns getted.", request.NotifyAction.Name, senderName));
}
request.Patterns[i] = pattern;
}
}
}
private void PrepareRequestFillTags(NotifyRequest request)
{
var patternProvider = request.NotifySource.GetPatternProvider();
foreach (var pattern in request.Patterns)
{
IPatternFormatter formatter;
try
{
formatter = patternProvider.GetFormatter(pattern);
}
catch (Exception exc)
{
throw new NotifyException(string.Format("For pattern \"{0}\" formatter not instanced.", pattern), exc);
}
var tags = new string[0];
try
{
if (formatter != null)
{
tags = formatter.GetTags(pattern) ?? new string[0];
}
}
catch (Exception exc)
{
throw new NotifyException(string.Format("Get tags from formatter of pattern \"{0}\" failed.", pattern), exc);
}
foreach (var tag in tags.Where(tag => !request.Arguments.Exists(tagValue => Equals(tagValue.Tag, tag)) && !request.RequaredTags.Exists(rtag => Equals(rtag, tag))))
{
request.RequaredTags.Add(tag);
}
}
}
private class SendMethodWrapper
{
private readonly object locker = new object();
private readonly CronExpression cronExpression;
private readonly Action<DateTime> method;
private volatile bool invoke;
public DateTime? ScheduleDate { get; private set; }
public SendMethodWrapper(Action<DateTime> method, string cron)
{
this.method = method;
if (!string.IsNullOrEmpty(cron))
{
this.cronExpression = new CronExpression(cron);
}
UpdateScheduleDate(DateTime.UtcNow);
}
public void UpdateScheduleDate(DateTime d)
{
try
{
if (cronExpression != null)
{
ScheduleDate = cronExpression.GetTimeAfter(d);
}
}
catch (Exception e)
{
log.Error(e);
}
}
public void InvokeSendMethod(DateTime d)
{
lock (locker)
{
if (!invoke)
{
method.BeginInvoke(d, InvokeSendCallback, method);
invoke = true;
}
else
{
log.WarnFormat("InvokeSendMethod: {0} at {1} send but previus call not finished.", method.Method.Name, d);
}
}
}
private void InvokeSendCallback(IAsyncResult ar)
{
lock (locker)
{
try
{
var m = (Action<DateTime>)ar.AsyncState;
m.EndInvoke(ar);
}
catch (Exception error)
{
log.Error(error);
}
finally
{
invoke = false;
}
}
}
public override bool Equals(object obj)
{
var w = obj as SendMethodWrapper;
return w != null && method.Equals(w.method);
}
public override int GetHashCode()
{
return method.GetHashCode();
}
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// 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.IO;
using System.Net;
using System.Collections;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Common.DataStructures;
namespace Alachisoft.NCache.Client
{
abstract class CommandBase
{
private byte[] _value = null;
protected byte[] _commandBytes = null;
private long requestId = -1;
private string[] bulkKeys;
private CommandResponse _result = null;
internal string _cacheId;
internal static string NC_NULL_VAL = "NLV";
internal protected string name;
internal protected long clientLastViewId = -1;
internal protected string intendedRecipient;
internal protected string key;
internal protected bool isAsync = false;
internal protected bool asyncCallbackSpecified = false;
internal protected string ipAddress = string.Empty;
protected internal bool inquiryEnabled;
protected Alachisoft.NCache.Common.Protobuf.Command _command;
protected int _commandID = 0;
public int CommandID
{
get { return _commandID; }
set { _commandID = value; }
}
internal byte[] Serialized { get; set; }
private Address _finalDestinationAddress;
/// <summary>
/// Final address where this command has been sent. Set after response for that command has been initialized
/// </summary>
public Address FinalDestinationAddress
{
get { return _finalDestinationAddress; }
set { _finalDestinationAddress = value; }
}
public virtual bool SupportsSurrogation { get { return false; } }
private bool _isRetry;
/// <summary>
/// Indicates wehter the command is a retry command (if first attempt has been failed)
/// </summary>
public bool IsRetry
{
get { return _isRetry; }
set { _isRetry = value; }
}
private Request _parent;
internal Request Parent
{
get { return _parent; }
set { _parent = value; }
}
internal bool IsInternalCommand
{
get { return CommandRequestType == RequestType.InternalCommand; }
}
internal abstract RequestType CommandRequestType
{
get;
}
internal abstract CommandType CommandType
{
get;
}
internal Alachisoft.NCache.Common.Protobuf.Command.Type Type
{
get { return _command.type; }
}
internal protected virtual long RequestId
{
get { return requestId; }
set { requestId = value; }
}
internal virtual bool SupportsAacknowledgement { get { return true; } }
internal protected long ClientLastViewId
{
get { return this.clientLastViewId; }
set { this.clientLastViewId = value; }
}
internal protected string IntendedRecipient
{
get { return this.intendedRecipient; }
set { this.intendedRecipient = value; }
}
internal protected CommandResponse Response
{
get { return _result; }
set { _result = value; }
}
internal protected string Key
{
get { return key; }
}
internal protected string[] BulkKeys
{
get { return bulkKeys; }
set { bulkKeys = value; }
}
internal protected byte[] Value
{
get { return _value; }
set { this._value = value; }
}
internal protected string CommandName
{
get { return name; }
}
/// <summary>
/// Indicates of command is safe to reexecute if failed while executing.
/// Safe commands return same result if reexecuted with same parameters
/// </summary>
internal virtual bool IsSafe { get { return true; } }
/// <summary>
/// Indicades if the command is a key-based operation.
/// This flags helps in sending command to appropriate server if more than one servers are available.
/// </summary>
internal virtual bool IsKeyBased { get { return true; } }
public long AcknowledgmentId { get; internal set; }
public bool PulseOnSend { get; internal set; }
public bool SentOverWire { get; internal set; }
public SendError SendError { get; internal set; }
internal protected void ConstructCommand(string cmdString, byte[] data)
{
byte[] command = HelperFxn.ToBytes(cmdString);
_commandBytes = new byte[2 * (Connection.CmdSizeHolderBytesCount + Connection.ValSizeHolderBytesCount) + command.Length + data.Length];
byte[] commandSize = HelperFxn.ToBytes(command.Length.ToString());
byte[] dataSize = HelperFxn.ToBytes(data.Length.ToString());
commandSize.CopyTo(_commandBytes, 0);
dataSize.CopyTo(_commandBytes, Connection.CmdSizeHolderBytesCount);
//we copy the command size two times to avoid if an corruption occurs.
commandSize.CopyTo(_commandBytes, Connection.TotSizeHolderBytesCount);
dataSize.CopyTo(_commandBytes, Connection.TotSizeHolderBytesCount + Connection.CmdSizeHolderBytesCount);
command.CopyTo(_commandBytes, 2 * Connection.TotSizeHolderBytesCount);
data.CopyTo(_commandBytes, (2 * Connection.TotSizeHolderBytesCount) + command.Length);
}
protected abstract void CreateCommand();
internal virtual byte[] ToByte(long acknowledgement, bool inquiryEnabledOnConnection)
{
if (_commandBytes == null || inquiryEnabled != inquiryEnabledOnConnection)
{
inquiryEnabled = inquiryEnabledOnConnection;
this.CreateCommand();
if (_command != null) _command.commandID = this._commandID;
this.SerializeCommand();
}
if (SupportsAacknowledgement && inquiryEnabled)
{
byte[] acknowledgementBuffer = HelperFxn.ToBytes(acknowledgement.ToString());
MemoryStream stream = new MemoryStream(_commandBytes, 0, _commandBytes.Length, true, true);
stream.Seek(0, SeekOrigin.Begin);
stream.Write(acknowledgementBuffer, 0, acknowledgementBuffer.Length);
_commandBytes = stream.GetBuffer();
}
return _commandBytes;
}
protected virtual void SerializeCommandInternal(Stream stream)
{
ProtoBuf.Serializer.Serialize(stream, _command);
}
protected virtual short GetCommandHandle()
{
return 0;
}
protected virtual void SerializeCommand()
{
using (MemoryStream stream = new MemoryStream())
{
//Writes a section for acknowledgment buffer.
byte[] acknowledgementBuffer = (SupportsAacknowledgement && inquiryEnabled) ? new byte[20] : new byte[0];
stream.Write(acknowledgementBuffer, 0, acknowledgementBuffer.Length);
// Write command type, write 0 for base Command.
byte[] commandType = HelperFxn.WriteShort(GetCommandHandle());
stream.Write(commandType, 0, commandType.Length);
// Writes a section for the command size.
byte[] size = new byte[Connection.CmdSizeHolderBytesCount];
stream.Write(size, 0, size.Length);
//Writes the command.
SerializeCommandInternal(stream);
int messageLen = (int)stream.Length - (size.Length + acknowledgementBuffer.Length + commandType.Length);
//Int32.Max.String() = 10 chars long...
size = HelperFxn.ToBytes(messageLen.ToString());
stream.Position = 0;
stream.Position += acknowledgementBuffer.Length;
stream.Position += commandType.Length;
stream.Write(size, 0, size.Length);
this._commandBytes = stream.ToArray();
stream.Close();
}
}
/// <summary>
/// Resets command by resetting command bytes and assigns a new commandID
/// </summary>
public void ResetCommand()
{
if (_parent != null)
{
this._commandBytes = null;
this._commandID = this._parent.GetNextCommandID();
}
}
/// <summary>
/// Create a dedicated command by merging all commands provided to the function
/// </summary>
/// <param name="commands">Commands needed to be merged to create dedicated command</param>
/// <returns>Dedicated command</returns>
public static CommandBase GetDedicatedCommand(IEnumerable<CommandBase> commands)
{
/*
* usama@30092014
* This function will be called only for bulk commands
* If commands are non-key commands, each command in passed commands will be the same,
* If commands are key based bulk command, each command will have seperate set of keys. Need to merge all keys to create a dedicated command.
*/
CommandBase dedicatedCommand = null;
List<CommandBase> commandsList = new List<CommandBase>(commands);
dedicatedCommand = commandsList[0].GetMergedCommand(commandsList);
dedicatedCommand._commandBytes = null;
dedicatedCommand.ClientLastViewId = Broker.ForcedViewId;
dedicatedCommand.Parent.Commands.Clear();
dedicatedCommand.Parent.AddCommand(new Address(IPAddress.Any, 9800), dedicatedCommand);
return dedicatedCommand;
}
public byte[] GetSerializedSurrogateCommand()
{
byte[] serializedbytes = null;
using (MemoryStream stream = new MemoryStream())
{
this.CreateCommand();
if(_command != null)
{
ProtoBuf.Serializer.Serialize<Alachisoft.NCache.Common.Protobuf.Command>(stream, _command);
}
serializedbytes = stream.ToArray();
}
return serializedbytes;
}
protected virtual CommandBase GetMergedCommand(List<CommandBase> commands)
{
return commands != null && commands.Count > 0 ? commands[0] : null;
}
protected string RebuildCommandWithTagInfo(Hashtable tagInfo)
{
System.Text.StringBuilder cmdString = new System.Text.StringBuilder();
cmdString.AppendFormat("{0}\"", tagInfo["type"] as string);
ArrayList tagsList = tagInfo["tags-list"] as ArrayList;
cmdString.AppendFormat("{0}\"", tagsList.Count);
IEnumerator tagsEnum = tagsList.GetEnumerator();
while (tagsEnum.MoveNext())
{
if (tagsEnum.Current != null)
{
cmdString.AppendFormat("{0}\"", tagsEnum.Current);
}
else
{
cmdString.AppendFormat("{0}\"", NC_NULL_VAL);
}
}
return cmdString.ToString();
}
protected string RebuildCommandWithQueryInfo(Hashtable queryInfo)
{
System.Text.StringBuilder cmdString = new System.Text.StringBuilder();
IDictionaryEnumerator queryInfoDic = queryInfo.GetEnumerator();
while (queryInfoDic.MoveNext())
{
cmdString.AppendFormat("{0}\"", queryInfoDic.Key);
ArrayList values = (ArrayList)queryInfoDic.Value;
cmdString.AppendFormat("{0}\"", values.Count);
IEnumerator valuesEnum = values.GetEnumerator();
while (valuesEnum.MoveNext())
{
if (valuesEnum.Current != null) //(Remove confusion between a null value and empty value
{
if (valuesEnum.Current is System.DateTime)
{
System.Globalization.CultureInfo enUs = new System.Globalization.CultureInfo("en-US");
cmdString.AppendFormat("{0}\"", ((DateTime)valuesEnum.Current).ToString(enUs));
}
else
cmdString.AppendFormat("{0}\"", valuesEnum.Current);
}
else
{
cmdString.AppendFormat("{0}\"", NC_NULL_VAL);
}
}
}
return cmdString.ToString();
}
}
}
| |
// 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.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// CustomImagesOperations operations.
/// </summary>
internal partial class CustomImagesOperations : IServiceOperations<DevTestLabsClient>, ICustomImagesOperations
{
/// <summary>
/// Initializes a new instance of the CustomImagesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal CustomImagesOperations(DevTestLabsClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DevTestLabsClient
/// </summary>
public DevTestLabsClient Client { get; private set; }
/// <summary>
/// List custom images in a given lab.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<CustomImage>>> ListWithHttpMessagesAsync(string labName, ODataQuery<CustomImage> odataQuery = default(ODataQuery<CustomImage>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("labName", labName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<CustomImage>>();
_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<Page<CustomImage>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get custom image.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the custom image.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example: 'properties($select=vm)'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<CustomImage>> GetWithHttpMessagesAsync(string labName, string name, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<CustomImage>();
_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<CustomImage>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or replace an existing custom image. This operation can take a
/// while to complete.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the custom image.
/// </param>
/// <param name='customImage'>
/// A custom image.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<CustomImage>> CreateOrUpdateWithHttpMessagesAsync(string labName, string name, CustomImage customImage, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<CustomImage> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(
labName, name, customImage, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Create or replace an existing custom image. This operation can take a
/// while to complete.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the custom image.
/// </param>
/// <param name='customImage'>
/// A custom image.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<CustomImage>> BeginCreateOrUpdateWithHttpMessagesAsync(string labName, string name, CustomImage customImage, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (customImage == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "customImage");
}
if (customImage != null)
{
customImage.Validate();
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("customImage", customImage);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(customImage != null)
{
_requestContent = SafeJsonConvert.SerializeObject(customImage, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<CustomImage>();
_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<CustomImage>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<CustomImage>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete custom image. This operation can take a while to complete.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the custom image.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(
labName, name, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// Delete custom image. This operation can take a while to complete.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the custom image.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// List custom images in a given lab.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<CustomImage>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<CustomImage>>();
_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<Page<CustomImage>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading;
namespace System.ComponentModel
{
/// <summary>
/// This type description provider provides type information through
/// reflection. Unless someone has provided a custom type description
/// provider for a type or instance, or unless an instance implements
/// ICustomTypeDescriptor, any query for type information will go through
/// this class. There should be a single instance of this class associated
/// with "object", as it can provide all type information for any type.
/// </summary>
internal sealed partial class ReflectTypeDescriptionProvider : TypeDescriptionProvider
{
// Hastable of Type -> ReflectedTypeData. ReflectedTypeData contains all
// of the type information we have gathered for a given type.
//
private Hashtable _typeData;
// This is the signature we look for when creating types that are generic, but
// want to know what type they are dealing with. Enums are a good example of this;
// there is one enum converter that can work with all enums, but it needs to know
// the type of enum it is dealing with.
//
private static Type[] s_typeConstructor = new Type[] { typeof(Type) };
// This is where we store the various converters, etc for the intrinsic types.
//
private static Hashtable s_editorTables;
private static Hashtable s_intrinsicTypeConverters;
// For converters, etc that are bound to class attribute data, rather than a class
// type, we have special key sentinel values that we put into the hash table.
//
private static object s_intrinsicReferenceKey = new object();
private static object s_intrinsicNullableKey = new object();
// The key we put into IDictionaryService to store our cache dictionary.
//
private static object s_dictionaryKey = new object();
// This is a cache on top of core reflection. The cache
// builds itself recursively, so if you ask for the properties
// on Control, Component and object are also automatically filled
// in. The keys to the property and event caches are types.
// The keys to the attribute cache are either MemberInfos or types.
//
private static Hashtable s_propertyCache;
private static Hashtable s_eventCache;
private static Hashtable s_attributeCache;
private static Hashtable s_extendedPropertyCache;
// These are keys we stuff into our object cache. We use this
// cache data to store extender provider info for an object.
//
private static readonly Guid s_extenderPropertiesKey = Guid.NewGuid();
private static readonly Guid s_extenderProviderPropertiesKey = Guid.NewGuid();
// These are attributes that, when we discover them on interfaces, we do
// not merge them into the attribute set for a class.
private static readonly Type[] s_skipInterfaceAttributeList = new Type[]
{
#if FEATURE_SKIP_INTERFACE
typeof(System.Runtime.InteropServices.GuidAttribute),
typeof(System.Runtime.InteropServices.InterfaceTypeAttribute)
#endif
typeof(System.Runtime.InteropServices.ComVisibleAttribute),
};
internal static Guid ExtenderProviderKey { get; } = Guid.NewGuid();
private static readonly object s_internalSyncObject = new object();
/// <summary>
/// Creates a new ReflectTypeDescriptionProvider. The type is the
/// type we will obtain type information for.
/// </summary>
internal ReflectTypeDescriptionProvider()
{
}
private static Hashtable EditorTables => LazyInitializer.EnsureInitialized(ref s_editorTables, () => new Hashtable(4));
/// <summary>
/// This is a table we create for intrinsic types.
/// There should be entries here ONLY for intrinsic
/// types, as all other types we should be able to
/// add attributes directly as metadata.
/// </summary>
private static Hashtable IntrinsicTypeConverters => LazyInitializer.EnsureInitialized(ref s_intrinsicTypeConverters, () => new Hashtable
{
// Add the intrinsics
//
[typeof(bool)] = typeof(BooleanConverter),
[typeof(byte)] = typeof(ByteConverter),
[typeof(sbyte)] = typeof(SByteConverter),
[typeof(char)] = typeof(CharConverter),
[typeof(double)] = typeof(DoubleConverter),
[typeof(string)] = typeof(StringConverter),
[typeof(int)] = typeof(Int32Converter),
[typeof(short)] = typeof(Int16Converter),
[typeof(long)] = typeof(Int64Converter),
[typeof(float)] = typeof(SingleConverter),
[typeof(ushort)] = typeof(UInt16Converter),
[typeof(uint)] = typeof(UInt32Converter),
[typeof(ulong)] = typeof(UInt64Converter),
[typeof(object)] = typeof(TypeConverter),
[typeof(void)] = typeof(TypeConverter),
[typeof(CultureInfo)] = typeof(CultureInfoConverter),
[typeof(DateTime)] = typeof(DateTimeConverter),
[typeof(DateTimeOffset)] = typeof(DateTimeOffsetConverter),
[typeof(decimal)] = typeof(DecimalConverter),
[typeof(TimeSpan)] = typeof(TimeSpanConverter),
[typeof(Guid)] = typeof(GuidConverter),
[typeof(Uri)] = typeof(UriTypeConverter),
[typeof(Version)] = typeof(VersionConverter),
[typeof(Color)] = typeof(ColorConverter),
[typeof(Point)] = typeof(PointConverter),
[typeof(Rectangle)] = typeof(RectangleConverter),
[typeof(Size)] = typeof(SizeConverter),
[typeof(SizeF)] = typeof(SizeFConverter),
// Special cases for things that are not bound to a specific type
//
[typeof(Array)] = typeof(ArrayConverter),
[typeof(ICollection)] = typeof(CollectionConverter),
[typeof(Enum)] = typeof(EnumConverter),
[s_intrinsicNullableKey] = typeof(NullableConverter),
});
private static Hashtable PropertyCache => LazyInitializer.EnsureInitialized(ref s_propertyCache, () => new Hashtable());
private static Hashtable EventCache => LazyInitializer.EnsureInitialized(ref s_eventCache, () => new Hashtable());
private static Hashtable AttributeCache => LazyInitializer.EnsureInitialized(ref s_attributeCache, () => new Hashtable());
private static Hashtable ExtendedPropertyCache => LazyInitializer.EnsureInitialized(ref s_extendedPropertyCache, () => new Hashtable());
/// <summary>
/// Adds an editor table for the given editor base type.
/// Typically, editors are specified as metadata on an object. If no metadata for a
/// requested editor base type can be found on an object, however, the
/// TypeDescriptor will search an editor
/// table for the editor type, if one can be found.
/// </summary>
internal static void AddEditorTable(Type editorBaseType, Hashtable table)
{
if (editorBaseType == null)
{
throw new ArgumentNullException(nameof(editorBaseType));
}
if (table == null)
{
Debug.Fail("COMPAT: Editor table should not be null");
// don't throw; RTM didn't so we can't do it either.
}
lock (s_internalSyncObject)
{
Hashtable editorTables = EditorTables;
if (!editorTables.ContainsKey(editorBaseType))
{
editorTables[editorBaseType] = table;
}
}
}
/// <summary>
/// CreateInstance implementation. We delegate to Activator.
/// </summary>
public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args)
{
Debug.Assert(objectType != null, "Should have arg-checked before coming in here");
object obj = null;
if (argTypes != null)
{
obj = objectType.GetConstructor(argTypes)?.Invoke(args);
}
else
{
if (args != null)
{
argTypes = new Type[args.Length];
for (int idx = 0; idx < args.Length; idx++)
{
if (args[idx] != null)
{
argTypes[idx] = args[idx].GetType();
}
else
{
argTypes[idx] = typeof(object);
}
}
}
else
{
argTypes = Array.Empty<Type>();
}
obj = objectType.GetConstructor(argTypes)?.Invoke(args);
}
return obj ?? Activator.CreateInstance(objectType, args);
}
/// <summary>
/// Helper method to create editors and type converters. This checks to see if the
/// type implements a Type constructor, and if it does it invokes that ctor.
/// Otherwise, it just tries to create the type.
/// </summary>
private static object CreateInstance(Type objectType, Type callingType)
{
return objectType.GetConstructor(s_typeConstructor)?.Invoke(new object[] { callingType })
?? Activator.CreateInstance(objectType);
}
/// <summary>
/// Retrieves custom attributes.
/// </summary>
internal AttributeCollection GetAttributes(Type type)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetAttributes();
}
/// <summary>
/// Our implementation of GetCache sits on top of IDictionaryService.
/// </summary>
public override IDictionary GetCache(object instance)
{
IComponent comp = instance as IComponent;
if (comp != null && comp.Site != null)
{
IDictionaryService ds = comp.Site.GetService(typeof(IDictionaryService)) as IDictionaryService;
if (ds != null)
{
IDictionary dict = ds.GetValue(s_dictionaryKey) as IDictionary;
if (dict == null)
{
dict = new Hashtable();
ds.SetValue(s_dictionaryKey, dict);
}
return dict;
}
}
return null;
}
/// <summary>
/// Retrieves the class name for our type.
/// </summary>
internal string GetClassName(Type type)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetClassName(null);
}
/// <summary>
/// Retrieves the component name from the site.
/// </summary>
internal string GetComponentName(Type type, object instance)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetComponentName(instance);
}
/// <summary>
/// Retrieves the type converter. If instance is non-null,
/// it will be used to retrieve attributes. Otherwise, _type
/// will be used.
/// </summary>
internal TypeConverter GetConverter(Type type, object instance)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetConverter(instance);
}
/// <summary>
/// Return the default event. The default event is determined by the
/// presence of a DefaultEventAttribute on the class.
/// </summary>
internal EventDescriptor GetDefaultEvent(Type type, object instance)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetDefaultEvent(instance);
}
/// <summary>
/// Return the default property.
/// </summary>
internal PropertyDescriptor GetDefaultProperty(Type type, object instance)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetDefaultProperty(instance);
}
/// <summary>
/// Retrieves the editor for the given base type.
/// </summary>
internal object GetEditor(Type type, object instance, Type editorBaseType)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetEditor(instance, editorBaseType);
}
/// <summary>
/// Retrieves a default editor table for the given editor base type.
/// </summary>
private static Hashtable GetEditorTable(Type editorBaseType)
{
Hashtable editorTables = EditorTables;
object table = editorTables[editorBaseType];
if (table == null)
{
// Before we give up, it is possible that the
// class initializer for editorBaseType hasn't
// actually run.
//
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(editorBaseType.TypeHandle);
table = editorTables[editorBaseType];
// If the table is still null, then throw a
// sentinel in there so we don't
// go through this again.
//
if (table == null)
{
lock (s_internalSyncObject)
{
table = editorTables[editorBaseType];
if (table == null)
{
editorTables[editorBaseType] = editorTables;
}
}
}
}
// Look for our sentinel value that indicates
// we have already tried and failed to get
// a table.
//
if (table == editorTables)
{
table = null;
}
return (Hashtable)table;
}
/// <summary>
/// Retrieves the events for this type.
/// </summary>
internal EventDescriptorCollection GetEvents(Type type)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetEvents();
}
/// <summary>
/// Retrieves custom extender attributes. We don't support
/// extender attributes, so we always return an empty collection.
/// </summary>
internal AttributeCollection GetExtendedAttributes(object instance)
{
return AttributeCollection.Empty;
}
/// <summary>
/// Retrieves the class name for our type.
/// </summary>
internal string GetExtendedClassName(object instance)
{
return GetClassName(instance.GetType());
}
/// <summary>
/// Retrieves the component name from the site.
/// </summary>
internal string GetExtendedComponentName(object instance)
{
return GetComponentName(instance.GetType(), instance);
}
/// <summary>
/// Retrieves the type converter. If instance is non-null,
/// it will be used to retrieve attributes. Otherwise, _type
/// will be used.
/// </summary>
internal TypeConverter GetExtendedConverter(object instance)
{
return GetConverter(instance.GetType(), instance);
}
/// <summary>
/// Return the default event. The default event is determined by the
/// presence of a DefaultEventAttribute on the class.
/// </summary>
internal EventDescriptor GetExtendedDefaultEvent(object instance)
{
return null; // we don't support extended events.
}
/// <summary>
/// Return the default property.
/// </summary>
internal PropertyDescriptor GetExtendedDefaultProperty(object instance)
{
return null; // extender properties are never the default.
}
/// <summary>
/// Retrieves the editor for the given base type.
/// </summary>
internal object GetExtendedEditor(object instance, Type editorBaseType)
{
return GetEditor(instance.GetType(), instance, editorBaseType);
}
/// <summary>
/// Retrieves the events for this type.
/// </summary>
internal EventDescriptorCollection GetExtendedEvents(object instance)
{
return EventDescriptorCollection.Empty;
}
/// <summary>
/// Retrieves the properties for this type.
/// </summary>
internal PropertyDescriptorCollection GetExtendedProperties(object instance)
{
// Is this object a sited component? If not, then it
// doesn't have any extender properties.
//
Type componentType = instance.GetType();
// Check the component for extender providers. We prefer
// IExtenderListService, but will use the container if that's
// all we have. In either case, we check the list of extenders
// against previously stored data in the object cache. If
// the cache is up to date, we just return the extenders in the
// cache.
//
IExtenderProvider[] extenders = GetExtenderProviders(instance);
IDictionary cache = TypeDescriptor.GetCache(instance);
if (extenders.Length == 0)
{
return PropertyDescriptorCollection.Empty;
}
// Ok, we have a set of extenders. Now, check to see if there
// are properties already in our object cache. If there aren't,
// then we will need to create them.
//
PropertyDescriptorCollection properties = null;
if (cache != null)
{
properties = cache[s_extenderPropertiesKey] as PropertyDescriptorCollection;
}
if (properties != null)
{
return properties;
}
// Unlike normal properties, it is fine for there to be properties with
// duplicate names here.
//
List<PropertyDescriptor> propertyList = null;
for (int idx = 0; idx < extenders.Length; idx++)
{
PropertyDescriptor[] propertyArray = ReflectGetExtendedProperties(extenders[idx]);
if (propertyList == null)
{
propertyList = new List<PropertyDescriptor>(propertyArray.Length * extenders.Length);
}
for (int propIdx = 0; propIdx < propertyArray.Length; propIdx++)
{
PropertyDescriptor prop = propertyArray[propIdx];
ExtenderProvidedPropertyAttribute eppa = prop.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute;
Debug.Assert(eppa != null, $"Extender property {prop.Name} has no provider attribute. We will skip it.");
if (eppa != null)
{
Type receiverType = eppa.ReceiverType;
if (receiverType != null)
{
if (receiverType.IsAssignableFrom(componentType))
{
propertyList.Add(prop);
}
}
}
}
}
// propertyHash now contains ExtendedPropertyDescriptor objects
// for each extended property.
//
if (propertyList != null)
{
PropertyDescriptor[] fullArray = new PropertyDescriptor[propertyList.Count];
propertyList.CopyTo(fullArray, 0);
properties = new PropertyDescriptorCollection(fullArray, true);
}
else
{
properties = PropertyDescriptorCollection.Empty;
}
if (cache != null)
{
cache[s_extenderPropertiesKey] = properties;
}
return properties;
}
protected internal override IExtenderProvider[] GetExtenderProviders(object instance)
{
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
IComponent component = instance as IComponent;
if (component != null && component.Site != null)
{
IExtenderListService extenderList = component.Site.GetService(typeof(IExtenderListService)) as IExtenderListService;
IDictionary cache = TypeDescriptor.GetCache(instance);
if (extenderList != null)
{
return GetExtenders(extenderList.GetExtenderProviders(), instance, cache);
}
#if FEATURE_COMPONENT_COLLECTION
else
{
IContainer cont = component.Site.Container;
if (cont != null)
{
return GetExtenders(cont.Components, instance, cache);
}
}
#endif
}
return Array.Empty<IExtenderProvider>();
}
/// <summary>
/// GetExtenders builds a list of extender providers from
/// a collection of components. It validates the extenders
/// against any cached collection of extenders in the
/// cache. If there is a discrepancy, this will erase
/// any cached extender properties from the cache and
/// save the updated extender list. If there is no
/// discrepancy this will simply return the cached list.
/// </summary>
private static IExtenderProvider[] GetExtenders(ICollection components, object instance, IDictionary cache)
{
bool newExtenders = false;
int extenderCount = 0;
IExtenderProvider[] existingExtenders = null;
//CanExtend is expensive. We will remember results of CanExtend for the first 64 extenders and using "long canExtend" as a bit vector.
// we want to avoid memory allocation as well so we don't use some more sophisticated data structure like an array of booleans
ulong canExtend = 0;
int maxCanExtendResults = 64;
// currentExtenders is what we intend to return. If the caller passed us
// the return value from IExtenderListService, components will already be
// an IExtenderProvider[]. If not, then we must treat components as an
// opaque collection. We spend a great deal of energy here to avoid
// copying or allocating memory because this method is called every
// time a component is asked for its properties.
IExtenderProvider[] currentExtenders = components as IExtenderProvider[];
if (cache != null)
{
existingExtenders = cache[ExtenderProviderKey] as IExtenderProvider[];
}
if (existingExtenders == null)
{
newExtenders = true;
}
int curIdx = 0;
int idx = 0;
if (currentExtenders != null)
{
for (curIdx = 0; curIdx < currentExtenders.Length; curIdx++)
{
if (currentExtenders[curIdx].CanExtend(instance))
{
extenderCount++;
// Performance:We would like to call CanExtend as little as possible therefore we remember its result
if (curIdx < maxCanExtendResults)
canExtend |= (ulong)1 << curIdx;
if (!newExtenders && (idx >= existingExtenders.Length || currentExtenders[curIdx] != existingExtenders[idx++]))
{
newExtenders = true;
}
}
}
}
else if (components != null)
{
foreach (object obj in components)
{
IExtenderProvider prov = obj as IExtenderProvider;
if (prov != null && prov.CanExtend(instance))
{
extenderCount++;
if (curIdx < maxCanExtendResults)
canExtend |= (ulong)1 << curIdx;
if (!newExtenders && (idx >= existingExtenders.Length || prov != existingExtenders[idx++]))
{
newExtenders = true;
}
}
curIdx++;
}
}
if (existingExtenders != null && extenderCount != existingExtenders.Length)
{
newExtenders = true;
}
if (newExtenders)
{
if (currentExtenders == null || extenderCount != currentExtenders.Length)
{
IExtenderProvider[] newExtenderArray = new IExtenderProvider[extenderCount];
curIdx = 0;
idx = 0;
if (currentExtenders != null && extenderCount > 0)
{
while (curIdx < currentExtenders.Length)
{
if ((curIdx < maxCanExtendResults && (canExtend & ((ulong)1 << curIdx)) != 0) ||
(curIdx >= maxCanExtendResults && currentExtenders[curIdx].CanExtend(instance)))
{
Debug.Assert(idx < extenderCount, "There are more extenders than we expect");
newExtenderArray[idx++] = currentExtenders[curIdx];
}
curIdx++;
}
Debug.Assert(idx == extenderCount, "Wrong number of extenders");
}
else if (extenderCount > 0)
{
foreach (var component in components)
{
IExtenderProvider p = component as IExtenderProvider;
if (p != null && ((curIdx < maxCanExtendResults && (canExtend & ((ulong)1 << curIdx)) != 0) ||
(curIdx >= maxCanExtendResults && p.CanExtend(instance))))
{
Debug.Assert(idx < extenderCount, "There are more extenders than we expect");
newExtenderArray[idx++] = p;
}
curIdx++;
}
Debug.Assert(idx == extenderCount, "Wrong number of extenders");
}
currentExtenders = newExtenderArray;
}
if (cache != null)
{
cache[ExtenderProviderKey] = currentExtenders;
cache.Remove(s_extenderPropertiesKey);
}
}
else
{
currentExtenders = existingExtenders;
}
return currentExtenders;
}
/// <summary>
/// Retrieves the owner for a property.
/// </summary>
internal object GetExtendedPropertyOwner(object instance, PropertyDescriptor pd)
{
return GetPropertyOwner(instance.GetType(), instance, pd);
}
//////////////////////////////////////////////////////////
/// <summary>
/// Provides a type descriptor for the given object. We only support this
/// if the object is a component that
/// </summary>
public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance)
{
Debug.Fail("This should never be invoked. TypeDescriptionNode should wrap for us.");
return null;
}
/// <summary>
/// The name of the specified component, or null if the component has no name.
/// In many cases this will return the same value as GetComponentName. If the
/// component resides in a nested container or has other nested semantics, it may
/// return a different fully qualified name.
///
/// If not overridden, the default implementation of this method will call
/// GetComponentName.
/// </summary>
public override string GetFullComponentName(object component)
{
IComponent comp = component as IComponent;
INestedSite ns = comp?.Site as INestedSite;
if (ns != null)
{
return ns.FullName;
}
return TypeDescriptor.GetComponentName(component);
}
/// <summary>
/// Returns an array of types we have populated metadata for that live
/// in the current module.
/// </summary>
internal Type[] GetPopulatedTypes(Module module)
{
List<Type> typeList = new List<Type>();
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator e = _typeData.GetEnumerator();
while (e.MoveNext())
{
DictionaryEntry de = e.Entry;
Type type = (Type)de.Key;
ReflectedTypeData typeData = (ReflectedTypeData)de.Value;
if (type.Module == module && typeData.IsPopulated)
{
typeList.Add(type);
}
}
return typeList.ToArray();
}
/// <summary>
/// Retrieves the properties for this type.
/// </summary>
internal PropertyDescriptorCollection GetProperties(Type type)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetProperties();
}
/// <summary>
/// Retrieves the owner for a property.
/// </summary>
internal object GetPropertyOwner(Type type, object instance, PropertyDescriptor pd)
{
return TypeDescriptor.GetAssociation(type, instance);
}
/// <summary>
/// Returns an Type for the given type. Since type implements IReflect,
/// we just return objectType.
/// </summary>
public override Type GetReflectionType(Type objectType, object instance)
{
Debug.Assert(objectType != null, "Should have arg-checked before coming in here");
return objectType;
}
/// <summary>
/// Returns the type data for the given type, or
/// null if there is no type data for the type yet and
/// createIfNeeded is false.
/// </summary>
private ReflectedTypeData GetTypeData(Type type, bool createIfNeeded)
{
ReflectedTypeData td = null;
if (_typeData != null)
{
td = (ReflectedTypeData)_typeData[type];
if (td != null)
{
return td;
}
}
lock (s_internalSyncObject)
{
if (_typeData != null)
{
td = (ReflectedTypeData)_typeData[type];
}
if (td == null && createIfNeeded)
{
td = new ReflectedTypeData(type);
if (_typeData == null)
{
_typeData = new Hashtable();
}
_typeData[type] = td;
}
}
return td;
}
/// <summary>
/// This method returns a custom type descriptor for the given type / object.
/// The objectType parameter is always valid, but the instance parameter may
/// be null if no instance was passed to TypeDescriptor. The method should
/// return a custom type descriptor for the object. If the method is not
/// interested in providing type information for the object it should
/// return null.
/// </summary>
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
Debug.Fail("This should never be invoked. TypeDescriptionNode should wrap for us.");
return null;
}
/// <summary>
/// Retrieves a type from a name.
/// </summary>
private static Type GetTypeFromName(string typeName)
{
Type t = Type.GetType(typeName);
if (t == null)
{
int commaIndex = typeName.IndexOf(',');
if (commaIndex != -1)
{
// At design time, it's possible for us to reuse
// an assembly but add new types. The app domain
// will cache the assembly based on identity, however,
// so it could be looking in the previous version
// of the assembly and not finding the type. We work
// around this by looking for the non-assembly qualified
// name, which causes the domain to raise a type
// resolve event.
//
t = Type.GetType(typeName.Substring(0, commaIndex));
}
}
return t;
}
/// <summary>
/// This method returns true if the data cache in this reflection
/// type descriptor has data in it.
/// </summary>
internal bool IsPopulated(Type type)
{
ReflectedTypeData td = GetTypeData(type, false);
if (td != null)
{
return td.IsPopulated;
}
return false;
}
/// <summary>
/// Static helper API around reflection to get and cache
/// custom attributes. This does not recurse, but it will
/// walk interfaces on the type. Interfaces are added
/// to the end, so merging should be done from length - 1
/// to 0.
/// </summary>
internal static Attribute[] ReflectGetAttributes(Type type)
{
Hashtable attributeCache = AttributeCache;
Attribute[] attrs = (Attribute[])attributeCache[type];
if (attrs != null)
{
return attrs;
}
lock (s_internalSyncObject)
{
attrs = (Attribute[])attributeCache[type];
if (attrs == null)
{
// Get the type's attributes.
//
attrs = type.GetCustomAttributes(typeof(Attribute), false).OfType<Attribute>().ToArray();
attributeCache[type] = attrs;
}
}
return attrs;
}
/// <summary>
/// Static helper API around reflection to get and cache
/// custom attributes. This does not recurse to the base class.
/// </summary>
internal static Attribute[] ReflectGetAttributes(MemberInfo member)
{
Hashtable attributeCache = AttributeCache;
Attribute[] attrs = (Attribute[])attributeCache[member];
if (attrs != null)
{
return attrs;
}
lock (s_internalSyncObject)
{
attrs = (Attribute[])attributeCache[member];
if (attrs == null)
{
// Get the member's attributes.
//
attrs = member.GetCustomAttributes(typeof(Attribute), false).OfType<Attribute>().ToArray();
attributeCache[member] = attrs;
}
}
return attrs;
}
/// <summary>
/// Static helper API around reflection to get and cache
/// events. This does not recurse to the base class.
/// </summary>
private static EventDescriptor[] ReflectGetEvents(Type type)
{
Hashtable eventCache = EventCache;
EventDescriptor[] events = (EventDescriptor[])eventCache[type];
if (events != null)
{
return events;
}
lock (s_internalSyncObject)
{
events = (EventDescriptor[])eventCache[type];
if (events == null)
{
BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
// Get the type's events. Events may have their add and
// remove methods individually overridden in a derived
// class, but at some point in the base class chain both
// methods must exist. If we find an event that doesn't
// have both add and remove, we skip it here, because it
// will be picked up in our base class scan.
//
EventInfo[] eventInfos = type.GetEvents(bindingFlags);
events = new EventDescriptor[eventInfos.Length];
int eventCount = 0;
for (int idx = 0; idx < eventInfos.Length; idx++)
{
EventInfo eventInfo = eventInfos[idx];
// GetEvents returns events that are on nonpublic types
// if those types are from our assembly. Screen these.
//
if ((!(eventInfo.DeclaringType.IsPublic || eventInfo.DeclaringType.IsNestedPublic)) && (eventInfo.DeclaringType.Assembly == typeof(ReflectTypeDescriptionProvider).Assembly))
{
Debug.Fail("Hey, assumption holds true. Rip this assert.");
continue;
}
if (eventInfo.AddMethod != null && eventInfo.RemoveMethod != null)
{
events[eventCount++] = new ReflectEventDescriptor(type, eventInfo);
}
}
if (eventCount != events.Length)
{
EventDescriptor[] newEvents = new EventDescriptor[eventCount];
Array.Copy(events, 0, newEvents, 0, eventCount);
events = newEvents;
}
#if DEBUG
foreach (EventDescriptor dbgEvent in events)
{
Debug.Assert(dbgEvent != null, "Holes in event array for type " + type);
}
#endif
eventCache[type] = events;
}
}
return events;
}
/// <summary>
/// This performs the actual reflection needed to discover
/// extender properties. If object caching is supported this
/// will maintain a cache of property descriptors on the
/// extender provider. Extender properties are actually two
/// property descriptors in one. There is a chunk of per-class
/// data in a ReflectPropertyDescriptor that defines the
/// parameter types and get and set methods of the extended property,
/// and there is an ExtendedPropertyDescriptor that combines this
/// with an extender provider object to create what looks like a
/// normal property. ReflectGetExtendedProperties maintains two
/// separate caches for these two sets: a static one for the
/// ReflectPropertyDescriptor values that don't change for each
/// provider instance, and a per-provider cache that contains
/// the ExtendedPropertyDescriptors.
/// </summary>
private static PropertyDescriptor[] ReflectGetExtendedProperties(IExtenderProvider provider)
{
IDictionary cache = TypeDescriptor.GetCache(provider);
PropertyDescriptor[] properties;
if (cache != null)
{
properties = cache[s_extenderProviderPropertiesKey] as PropertyDescriptor[];
if (properties != null)
{
return properties;
}
}
// Our per-instance cache missed. We have never seen this instance of the
// extender provider before. See if we can find our class-based
// property store.
//
Type providerType = provider.GetType();
Hashtable extendedPropertyCache = ExtendedPropertyCache;
ReflectPropertyDescriptor[] extendedProperties = (ReflectPropertyDescriptor[])extendedPropertyCache[providerType];
if (extendedProperties == null)
{
lock (s_internalSyncObject)
{
extendedProperties = (ReflectPropertyDescriptor[])extendedPropertyCache[providerType];
// Our class-based property store failed as well, so we need to build up the set of
// extended properties here.
//
if (extendedProperties == null)
{
AttributeCollection attributes = TypeDescriptor.GetAttributes(providerType);
List<ReflectPropertyDescriptor> extendedList = new List<ReflectPropertyDescriptor>(attributes.Count);
foreach (Attribute attr in attributes)
{
ProvidePropertyAttribute provideAttr = attr as ProvidePropertyAttribute;
if (provideAttr != null)
{
Type receiverType = GetTypeFromName(provideAttr.ReceiverTypeName);
if (receiverType != null)
{
MethodInfo getMethod = providerType.GetMethod("Get" + provideAttr.PropertyName, new Type[] { receiverType });
if (getMethod != null && !getMethod.IsStatic && getMethod.IsPublic)
{
MethodInfo setMethod = providerType.GetMethod("Set" + provideAttr.PropertyName, new Type[] { receiverType, getMethod.ReturnType });
if (setMethod != null && (setMethod.IsStatic || !setMethod.IsPublic))
{
setMethod = null;
}
extendedList.Add(new ReflectPropertyDescriptor(providerType, provideAttr.PropertyName, getMethod.ReturnType, receiverType, getMethod, setMethod, null));
}
}
}
}
extendedProperties = new ReflectPropertyDescriptor[extendedList.Count];
extendedList.CopyTo(extendedProperties, 0);
extendedPropertyCache[providerType] = extendedProperties;
}
}
}
// Now that we have our extended properties we can build up a list of callable properties. These can be
// returned to the user.
//
properties = new PropertyDescriptor[extendedProperties.Length];
for (int idx = 0; idx < extendedProperties.Length; idx++)
{
ReflectPropertyDescriptor rpd = extendedProperties[idx];
properties[idx] = new ExtendedPropertyDescriptor(rpd, rpd.ExtenderGetReceiverType(), provider, null);
}
if (cache != null)
{
cache[s_extenderProviderPropertiesKey] = properties;
}
return properties;
}
/// <summary>
/// Static helper API around reflection to get and cache
/// properties. This does not recurse to the base class.
/// </summary>
private static PropertyDescriptor[] ReflectGetProperties(Type type)
{
Hashtable propertyCache = PropertyCache;
PropertyDescriptor[] properties = (PropertyDescriptor[])propertyCache[type];
if (properties != null)
{
return properties;
}
lock (s_internalSyncObject)
{
properties = (PropertyDescriptor[])propertyCache[type];
if (properties == null)
{
BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
// Get the type's properties. Properties may have their
// get and set methods individually overridden in a derived
// class, so if we find a missing method we need to walk
// down the base class chain to find it. We actually merge
// "new" properties of the same name, so we must preserve
// the member info for each method individually.
//
PropertyInfo[] propertyInfos = type.GetProperties(bindingFlags);
properties = new PropertyDescriptor[propertyInfos.Length];
int propertyCount = 0;
for (int idx = 0; idx < propertyInfos.Length; idx++)
{
PropertyInfo propertyInfo = propertyInfos[idx];
// Today we do not support parameterized properties.
//
if (propertyInfo.GetIndexParameters().Length > 0)
{
continue;
}
MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: false);
MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: false);
string name = propertyInfo.Name;
// If the property only overrode "set", then we don't
// pick it up here. Rather, we just merge it in from
// the base class list.
// If a property had at least a get method, we consider it. We don't
// consider write-only properties.
//
if (getMethod != null)
{
properties[propertyCount++] = new ReflectPropertyDescriptor(type, name,
propertyInfo.PropertyType,
propertyInfo, getMethod,
setMethod, null);
}
}
if (propertyCount != properties.Length)
{
PropertyDescriptor[] newProperties = new PropertyDescriptor[propertyCount];
Array.Copy(properties, 0, newProperties, 0, propertyCount);
properties = newProperties;
}
Debug.Assert(!properties.Any(dbgProp => dbgProp == null), $"Holes in property array for type {type}");
propertyCache[type] = properties;
}
}
return properties;
}
/// <summary>
/// Refreshes the contents of this type descriptor. This does not
/// actually requery, but it will clear our state so the next
/// query re-populates.
/// </summary>
internal void Refresh(Type type)
{
ReflectedTypeData td = GetTypeData(type, false);
td?.Refresh();
}
/// <summary>
/// Searches the provided intrinsic hashtable for a match with the object type.
/// At the beginning, the hashtable contains types for the various converters.
/// As this table is searched, the types for these objects
/// are replaced with instances, so we only create as needed. This method
/// does the search up the base class hierarchy and will create instances
/// for types as needed. These instances are stored back into the table
/// for the base type, and for the original component type, for fast access.
/// </summary>
private static object SearchIntrinsicTable(Hashtable table, Type callingType)
{
object hashEntry = null;
// We take a lock on this table. Nothing in this code calls out to
// other methods that lock, so it should be fairly safe to grab this
// lock. Also, this allows multiple intrinsic tables to be searched
// at once.
//
lock (table)
{
Type baseType = callingType;
while (baseType != null && baseType != typeof(object))
{
hashEntry = table[baseType];
// If the entry is a late-bound type, then try to
// resolve it.
//
string typeString = hashEntry as string;
if (typeString != null)
{
hashEntry = Type.GetType(typeString);
if (hashEntry != null)
{
table[baseType] = hashEntry;
}
}
if (hashEntry != null)
{
break;
}
baseType = baseType.BaseType;
}
// Now make a scan through each value in the table, looking for interfaces.
// If we find one, see if the object implements the interface.
//
if (hashEntry == null)
{
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator e = table.GetEnumerator();
while (e.MoveNext())
{
DictionaryEntry de = e.Entry;
Type keyType = de.Key as Type;
if (keyType != null && keyType.IsInterface && keyType.IsAssignableFrom(callingType))
{
hashEntry = de.Value;
string typeString = hashEntry as string;
if (typeString != null)
{
hashEntry = Type.GetType(typeString);
if (hashEntry != null)
{
table[callingType] = hashEntry;
}
}
if (hashEntry != null)
{
break;
}
}
}
}
// Special case converters
//
if (hashEntry == null)
{
if (callingType.IsGenericType && callingType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// Check if it is a nullable value
hashEntry = table[s_intrinsicNullableKey];
}
else if (callingType.IsInterface)
{
// Finally, check to see if the component type is some unknown interface.
// We have a custom converter for that.
hashEntry = table[s_intrinsicReferenceKey];
}
}
// Interfaces do not derive from object, so we
// must handle the case of no hash entry here.
//
if (hashEntry == null)
{
hashEntry = table[typeof(object)];
}
// If the entry is a type, create an instance of it and then
// replace the entry. This way we only need to create once.
// We can only do this if the object doesn't want a type
// in its constructor.
//
Type type = hashEntry as Type;
if (type != null)
{
hashEntry = CreateInstance(type, callingType);
if (type.GetConstructor(s_typeConstructor) == null)
{
table[callingType] = hashEntry;
}
}
}
return hashEntry;
}
}
}
| |
/*
Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.
The MIT License(MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
namespace Shield.Services
{
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Shield.Core;
using Shield.Core.Models;
using Windows.Graphics.Display;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Shapes;
public class Screen
{
public static readonly DependencyProperty RemoteIdProperty = DependencyProperty.RegisterAttached(
"RemoteId",
typeof(int),
typeof(FrameworkElement),
new PropertyMetadata(0));
private readonly int DefaultFontSize = 22;
private readonly FontFamily fixedFont = new FontFamily("Courier New");
private readonly SolidColorBrush foreground = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF));
private readonly SolidColorBrush gray = new SolidColorBrush(Color.FromArgb(0xFF, 0x80, 0x80, 0x80));
private readonly MainPage mainPage;
private readonly SolidColorBrush textForgroundBrush = new SolidColorBrush(Colors.White);
private SolidColorBrush background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
private int lastY = -1;
public Screen(MainPage mainPage)
{
this.mainPage = mainPage;
}
public async Task LogPrint(ScreenMessage lcdt)
{
if (lcdt.Action != null && lcdt.Action.ToUpperInvariant().Equals("CLEAR"))
{
this.mainPage.text.Text = string.Empty;
}
await
this.mainPage.dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
() => { this.mainPage.text.Text += lcdt.Message + "\r\n"; });
}
public async void LcdPrint(ScreenMessage lcdt)
{
var isText = lcdt.Service.Equals("LCDT");
FrameworkElement element = null;
var expandToEdge = false;
SolidColorBrush backgroundBrush = null;
if (lcdt.Action != null)
{
if (!string.IsNullOrWhiteSpace(lcdt.ARGB))
{
if (lcdt.ARGB[0] == '#')
{
var hex = lcdt.ARGB.ToByteArray();
if (hex.Length > 3)
{
backgroundBrush =
new SolidColorBrush(
Color.FromArgb(hex[0] == 0 ? (byte)255 : hex[0], hex[1], hex[2], hex[3]));
}
}
else
{
uint color;
if (uint.TryParse(lcdt.ARGB, out color))
{
var argb = new ArgbUnion { Value = color };
backgroundBrush =
new SolidColorBrush(
Color.FromArgb(argb.A == 0 ? (byte)255 : argb.A, argb.R, argb.G, argb.B));
}
}
}
var action = lcdt.Action.ToUpperInvariant();
switch (action)
{
case "ORIENTATION":
{
var current = DisplayInformation.AutoRotationPreferences;
if (lcdt.Value.HasValue)
{
DisplayInformation.AutoRotationPreferences = (DisplayOrientations)lcdt.Value.Value;
}
await this.mainPage.SendResult(new ScreenResultMessage(lcdt) { ResultId = (int)current });
break;
}
case "ENABLE":
{
this.mainPage.sensors[lcdt.Service + ":" + lcdt.Message] = 1;
return;
}
case "DISABLE":
{
if (this.mainPage.sensors.ContainsKey(lcdt.Service + ":" + lcdt.Message))
{
this.mainPage.sensors.Remove(lcdt.Service + ":" + lcdt.Message);
}
return;
}
case "CLEAR":
{
if (lcdt.Y.HasValue)
{
this.RemoveLine(lcdt.Y.Value);
}
else if (lcdt.Pid.HasValue)
{
this.RemoveId(lcdt.Pid.Value);
}
else
{
this.mainPage.canvas.Children.Clear();
if (backgroundBrush != null)
{
this.mainPage.canvas.Background = backgroundBrush;
}
this.lastY = -1;
this.mainPage.player.Stop();
this.mainPage.player.Source = null;
}
break;
}
case "BUTTON":
{
element = new Button
{
Content = lcdt.Message,
FontSize = lcdt.Size ?? this.DefaultFontSize,
Tag = lcdt.Tag,
Foreground = this.textForgroundBrush,
Background = new SolidColorBrush(Colors.Gray)
};
element.Tapped += async (s, a) => await this.mainPage.SendEvent(s, a, "tapped");
((Button)element).Click += async (s, a) => await this.mainPage.SendEvent(s, a, "click");
element.PointerPressed += async (s, a) => await this.mainPage.SendEvent(s, a, "pressed");
element.PointerReleased += async (s, a) => await this.mainPage.SendEvent(s, a, "released");
break;
}
case "IMAGE":
{
var imageBitmap = new BitmapImage(new Uri(lcdt.Path, UriKind.Absolute));
// imageBitmap.CreateOptions = Windows.UI.Xaml.Media.Imaging.BitmapCreateOptions.IgnoreImageCache;
if (lcdt.Width.HasValue)
{
imageBitmap.DecodePixelWidth = lcdt.Width.Value;
}
if (lcdt.Height.HasValue)
{
imageBitmap.DecodePixelHeight = lcdt.Height.Value;
}
element = new Image { Tag = lcdt.Tag };
((Image)element).Source = imageBitmap;
element.Tapped += async (s, a) => await this.mainPage.SendEvent(s, a, "tapped");
break;
}
case "LINE":
{
var line = new Line
{
X1 = lcdt.X.Value,
Y1 = lcdt.Y.Value,
X2 = lcdt.X2.Value,
Y2 = lcdt.Y2.Value,
StrokeThickness = lcdt.Width ?? 1,
Stroke = this.foreground
};
element = line;
break;
}
case "INPUT":
{
element = new TextBox
{
Text = lcdt.Message ?? string.Empty,
FontSize = lcdt.Size ?? this.DefaultFontSize,
TextWrapping = TextWrapping.Wrap,
Foreground = this.textForgroundBrush,
AcceptsReturn = lcdt.Multi ?? false
};
expandToEdge = true;
element.SetValue(Canvas.LeftProperty, lcdt.X);
element.SetValue(Canvas.TopProperty, lcdt.Y);
element.LostFocus +=
async (s, a) =>
await this.mainPage.SendEvent(s, a, "lostfocus", lcdt, ((TextBox)s).Text);
((TextBox)element).TextChanged +=
async (s, a) => await this.mainPage.SendEvent(s, a, "changed", lcdt, ((TextBox)s).Text);
break;
}
case "RECTANGLE":
{
var rect = new Rectangle { Tag = lcdt.Tag, Fill = backgroundBrush ?? this.gray };
if (lcdt.Width.HasValue)
{
rect.Width = lcdt.Width.Value;
}
if (lcdt.Height.HasValue)
{
rect.Height = lcdt.Height.Value;
}
element = rect;
element.Tapped += async (s, a) => await this.mainPage.SendEvent(s, a, "tapped", lcdt);
rect.PointerEntered += async (s, a) => await this.mainPage.SendEvent(s, a, "entered", lcdt);
rect.PointerExited += async (s, a) => await this.mainPage.SendEvent(s, a, "exited", lcdt);
break;
}
case "TEXT":
{
var textBlock = new TextBlock
{
Text = lcdt.Message,
FontSize = lcdt.Size ?? this.DefaultFontSize,
TextWrapping = TextWrapping.Wrap,
Tag = lcdt.Tag,
Foreground = this.textForgroundBrush
};
expandToEdge = true;
element = textBlock;
element.SetValue(Canvas.LeftProperty, lcdt.X);
element.SetValue(Canvas.TopProperty, lcdt.Y);
break;
}
default:
break;
}
}
if (element == null && isText && lcdt.Message != null)
{
var x = lcdt.X ?? 0;
var y = lcdt.Y ?? this.lastY + 1;
expandToEdge = true;
element = new TextBlock
{
Text = lcdt.Message,
FontSize = lcdt.Size ?? this.DefaultFontSize,
TextWrapping = TextWrapping.Wrap,
Tag = y.ToString(),
Foreground = this.textForgroundBrush
};
var textblock = (TextBlock)element;
textblock.FontFamily = this.fixedFont;
if (lcdt.Foreground != null)
{
textblock.Foreground = HexColorToBrush(lcdt.Foreground);
}
if (lcdt.HorizontalAlignment != null)
{
if (lcdt.HorizontalAlignment.Equals("Center"))
{
textblock.TextAlignment = TextAlignment.Center;
}
}
element.SetValue(Canvas.LeftProperty, isText ? x * textblock.FontSize : x);
element.SetValue(Canvas.TopProperty, isText ? y * textblock.FontSize : y);
}
else if (element != null && element.GetType() != typeof(Line))
{
element.SetValue(Canvas.LeftProperty, lcdt.X);
element.SetValue(Canvas.TopProperty, lcdt.Y);
}
if (element != null)
{
var x = lcdt.X ?? 0;
var y = lcdt.Y ?? this.lastY + 1;
if (lcdt.HorizontalAlignment != null)
{
if (lcdt.HorizontalAlignment.Equals("Center"))
{
element.HorizontalAlignment = HorizontalAlignment.Center;
element.Width = this.mainPage.canvas.Width;
}
}
if (lcdt.FlowDirection != null)
{
if (lcdt.FlowDirection.Equals("RightToLeft"))
{
element.FlowDirection = FlowDirection.RightToLeft;
}
else if (lcdt.FlowDirection.Equals("LeftToRight"))
{
element.FlowDirection = FlowDirection.LeftToRight;
}
}
if (lcdt.Width.HasValue)
{
element.Width = lcdt.Width.Value;
}
else if (expandToEdge)
{
element.Width = this.mainPage.canvas.ActualWidth;
}
if (lcdt.Height.HasValue)
{
element.Height = lcdt.Height.Value;
}
// TODO: add optional/extra properties in a later version here.
if (isText && x == 0)
{
this.RemoveLine(y);
}
element.SetValue(RemoteIdProperty, lcdt.Id);
this.mainPage.canvas.Children.Add(element);
if (isText)
{
this.lastY = y;
}
}
}
public static Brush HexColorToBrush(string color)
{
color = color.Replace("#", string.Empty);
if (color.Length > 5)
{
return
new SolidColorBrush(
ColorHelper.FromArgb(
color.Length > 7
? byte.Parse(color.Substring(color.Length - 8, 2), NumberStyles.HexNumber)
: (byte)255,
byte.Parse(color.Substring(color.Length - 6, 2), NumberStyles.HexNumber),
byte.Parse(color.Substring(color.Length - 4, 2), NumberStyles.HexNumber),
byte.Parse(color.Substring(color.Length - 2, 2), NumberStyles.HexNumber)));
}
return null;
}
private void RemoveLine(int y)
{
var lines =
this.mainPage.canvas.Children.Where(
t => t is TextBlock && ((TextBlock)t).Tag != null && ((TextBlock)t).Tag.Equals(y.ToString()));
foreach (var line in lines)
{
this.mainPage.canvas.Children.Remove(line);
}
}
private UIElement GetId(int id)
{
return this.mainPage.canvas.Children.FirstOrDefault(e => ((int)e.GetValue(RemoteIdProperty)) == id);
}
private void RemoveId(int id)
{
var items = this.mainPage.canvas.Children.Where(e => ((int)e.GetValue(RemoteIdProperty)) == id);
foreach (var item in items)
{
this.mainPage.canvas.Children.Remove(item);
}
}
[StructLayout(LayoutKind.Explicit)]
public struct ArgbUnion
{
[FieldOffset(0)]
public byte B;
[FieldOffset(1)]
public byte G;
[FieldOffset(2)]
public byte R;
[FieldOffset(3)]
public byte A;
[FieldOffset(0)]
public uint Value;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
#define LLVM
namespace Microsoft.Zelig.Runtime
{
using System;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
[ExtendClass(typeof(System.Buffer), NoConstructors=true, ProcessAfter=typeof(ArrayImpl))]
public static class BufferImpl
{
//
// Helper Methods
//
public unsafe static void BlockCopy( ArrayImpl src ,
int srcOffset ,
ArrayImpl dst ,
int dstOffset ,
int count )
{
TS.VTable vtSrc = TS.VTable.Get( src );
TS.VTable vtDst = TS.VTable.Get( dst );
if((vtSrc.TypeInfo.ContainedType is TS.ScalarTypeRepresentation) == false)
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( "Not a scalar" );
#else
throw new NotSupportedException();
#endif
}
if((vtDst.TypeInfo.ContainedType is TS.ScalarTypeRepresentation) == false)
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( "Not a scalar" );
#else
throw new NotSupportedException();
#endif
}
if(count < 0)
{
#if EXCEPTION_STRINGS
throw new IndexOutOfRangeException( "count" );
#else
throw new IndexOutOfRangeException();
#endif
}
if(srcOffset < 0 || (uint)(srcOffset + count) > src.Size)
{
#if EXCEPTION_STRINGS
throw new IndexOutOfRangeException( "src" );
#else
throw new IndexOutOfRangeException();
#endif
}
if(dstOffset < 0 || (uint)(dstOffset + count) > dst.Size)
{
#if EXCEPTION_STRINGS
throw new IndexOutOfRangeException( "dst" );
#else
throw new IndexOutOfRangeException();
#endif
}
byte* srcPtr = (byte*)src.GetDataPointer();
byte* dstPtr = (byte*)dst.GetDataPointer();
InternalMemoryMove( &srcPtr[srcOffset], &dstPtr[dstOffset], count );
}
internal unsafe static void InternalBlockCopy( ArrayImpl src ,
int srcOffset ,
ArrayImpl dst ,
int dstOffset ,
int count )
{
BugCheck.Assert( TS.VTable.Get( src ) == TS.VTable.Get( dst ), BugCheck.StopCode.IncorrectArgument );
if(count < 0)
{
#if EXCEPTION_STRINGS
throw new IndexOutOfRangeException( "count" );
#else
throw new IndexOutOfRangeException();
#endif
}
if(srcOffset < 0 || (uint)(srcOffset + count) > src.Size)
{
#if EXCEPTION_STRINGS
throw new IndexOutOfRangeException( "src" );
#else
throw new IndexOutOfRangeException();
#endif
}
if(dstOffset < 0 || (uint)(dstOffset + count) > dst.Size)
{
#if EXCEPTION_STRINGS
throw new IndexOutOfRangeException( "dst" );
#else
throw new IndexOutOfRangeException();
#endif
}
byte* srcPtr = (byte*)src.GetDataPointer();
byte* dstPtr = (byte*)dst.GetDataPointer();
InternalMemoryMove( &srcPtr[srcOffset], &dstPtr[dstOffset], count );
}
//--//--//
[DisableNullChecks]
#if LLVM
[NoInline] // Disable inlining so we always have a chance to replace the method.
#endif // LLVM
[TS.WellKnownMethod("System_Buffer_InternalMemoryCopy")]
internal unsafe static void InternalMemoryCopy( byte* src ,
byte* dst ,
int count )
{
BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex );
if(AddressMath.IsAlignedTo32bits( src ) &&
AddressMath.IsAlignedTo32bits( dst ) )
{
int count32 = count / 4;
InternalMemoryCopy( (uint*)src, (uint*)dst, count32 );
int count2 = count32 * 4;
src += count2;
dst += count2;
count -= count2;
}
else if(AddressMath.IsAlignedTo16bits( src ) &&
AddressMath.IsAlignedTo16bits( dst ) )
{
int count16 = count / 2;
InternalMemoryCopy( (ushort*)src, (ushort*)dst, count16 );
int count2 = count16 * 2;
src += count2;
dst += count2;
count -= count2;
}
if(count > 0)
{
while(count >= 4)
{
var v0 = src[0];
var v1 = src[1];
var v2 = src[2];
var v3 = src[3];
dst[0] = v0;
dst[1] = v1;
dst[2] = v2;
dst[3] = v3;
dst += 4;
src += 4;
count -= 4;
}
if((count & 2) != 0)
{
var v0 = src[0];
var v1 = src[1];
dst[0] = v0;
dst[1] = v1;
dst += 2;
src += 2;
}
if((count & 1) != 0)
{
dst[0] = src[0];
}
}
}
[Inline]
internal unsafe static void InternalMemoryCopy( sbyte* src ,
sbyte* dst ,
int count )
{
InternalMemoryCopy( (byte*)src, (byte*)dst, count );
}
//--//
[DisableNullChecks]
internal unsafe static void InternalMemoryCopy( ushort* src ,
ushort* dst ,
int count )
{
#if LLVM
InternalMemoryCopy((byte*)src, (byte*)dst, count * sizeof(ushort));
#else // LLVM
BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex );
if(AddressMath.IsAlignedTo32bits( src ) &&
AddressMath.IsAlignedTo32bits( dst ) )
{
int count32 = count / 2;
InternalMemoryCopy( (uint*)src, (uint*)dst, count32 );
int count2 = count32 * 2;
src += count2;
dst += count2;
count -= count2;
}
if(count > 0)
{
while(count >= 4)
{
var v0 = src[0];
var v1 = src[1];
var v2 = src[2];
var v3 = src[3];
dst[0] = v0;
dst[1] = v1;
dst[2] = v2;
dst[3] = v3;
dst += 4;
src += 4;
count -= 4;
}
if((count & 2) != 0)
{
var v0 = src[0];
var v1 = src[1];
dst[0] = v0;
dst[1] = v1;
dst += 2;
src += 2;
}
if((count & 1) != 0)
{
dst[0] = src[0];
}
}
#endif // LLVM
}
[Inline]
internal unsafe static void InternalMemoryCopy( short* src ,
short* dst ,
int count )
{
InternalMemoryCopy( (ushort*)src, (ushort*)dst, count );
}
[Inline]
internal unsafe static void InternalMemoryCopy( char* src ,
char* dst ,
int count )
{
InternalMemoryCopy( (ushort*)src, (ushort*)dst, count );
}
//--//
[DisableNullChecks]
internal unsafe static void InternalMemoryCopy( uint* src ,
uint* dst ,
int count )
{
#if LLVM
InternalMemoryCopy((byte*)src, (byte*)dst, count * sizeof(uint));
#else // LLVM
BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex );
if(count > 0)
{
while(count >= 4)
{
var v0 = src[0];
var v1 = src[1];
var v2 = src[2];
var v3 = src[3];
dst[0] = v0;
dst[1] = v1;
dst[2] = v2;
dst[3] = v3;
dst += 4;
src += 4;
count -= 4;
}
if((count & 2) != 0)
{
var v0 = src[0];
var v1 = src[1];
dst[0] = v0;
dst[1] = v1;
dst += 2;
src += 2;
}
if((count & 1) != 0)
{
dst[0] = src[0];
}
}
#endif // LLVM
}
[Inline]
internal unsafe static void InternalMemoryCopy( int* src ,
int* dst ,
int count )
{
InternalMemoryCopy( (uint*)src, (uint*)dst, count );
}
//--//--//
[DisableNullChecks]
#if LLVM
[NoInline] // Disable inlining so we always have a chance to replace the method.
#endif // LLVM
[TS.WellKnownMethod( "System_Buffer_InternalBackwardMemoryCopy" )]
internal unsafe static void InternalBackwardMemoryCopy( byte* src ,
byte* dst ,
int count )
{
BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex );
src += count;
dst += count;
if(AddressMath.IsAlignedTo32bits( src ) &&
AddressMath.IsAlignedTo32bits( dst ) )
{
uint* src2 = (uint*)src;
uint* dst2 = (uint*)dst;
int count32 = count / 4;
src2 -= count32;
dst2 -= count32;
InternalBackwardMemoryCopy( src2, dst2, count32 );
int count2 = count32 * 4;
src = (byte*)src2;
dst = (byte*)dst2;
count -= count2;
}
else if(AddressMath.IsAlignedTo16bits( src ) &&
AddressMath.IsAlignedTo16bits( dst ) )
{
ushort* src2 = (ushort*)src;
ushort* dst2 = (ushort*)dst;
int count16 = count / 2;
src2 -= count16;
dst2 -= count16;
InternalBackwardMemoryCopy( src2, dst2, count16 );
int count2 = count16 * 2;
src = (byte*)src2;
dst = (byte*)dst2;
count -= count2;
}
if(count > 0)
{
while(count >= 4)
{
dst -= 4;
src -= 4;
count -= 4;
var v0 = src[0];
var v1 = src[1];
var v2 = src[2];
var v3 = src[3];
dst[0] = v0;
dst[1] = v1;
dst[2] = v2;
dst[3] = v3;
}
if((count & 2) != 0)
{
dst -= 2;
src -= 2;
var v0 = src[0];
var v1 = src[1];
dst[0] = v0;
dst[1] = v1;
}
if((count & 1) != 0)
{
dst -= 1;
src -= 1;
dst[0] = src[0];
}
}
}
[Inline]
internal unsafe static void InternalBackwardMemoryCopy( sbyte* src ,
sbyte* dst ,
int count )
{
InternalBackwardMemoryCopy( (byte*)src, (byte*)dst, count );
}
//--//
[DisableNullChecks]
internal unsafe static void InternalBackwardMemoryCopy( ushort* src ,
ushort* dst ,
int count )
{
#if LLVM
InternalBackwardMemoryCopy( (byte*)src, (byte*)dst, count * sizeof( ushort ) );
#else // LLVM
BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex );
src += count;
dst += count;
if(AddressMath.IsAlignedTo32bits( src ) &&
AddressMath.IsAlignedTo32bits( dst ) )
{
uint* src2 = (uint*)src;
uint* dst2 = (uint*)dst;
int count32 = count / 2;
src2 -= count32;
dst2 -= count32;
InternalBackwardMemoryCopy( src2, dst2, count32 );
int count2 = count32 * 2;
src = (ushort*)src2;
dst = (ushort*)dst2;
count -= count2;
}
if(count > 0)
{
while(count >= 4)
{
dst -= 4;
src -= 4;
count -= 4;
var v0 = src[0];
var v1 = src[1];
var v2 = src[2];
var v3 = src[3];
dst[0] = v0;
dst[1] = v1;
dst[2] = v2;
dst[3] = v3;
}
if((count & 2) != 0)
{
dst -= 2;
src -= 2;
var v0 = src[0];
var v1 = src[1];
dst[0] = v0;
dst[1] = v1;
}
if((count & 1) != 0)
{
dst -= 1;
src -= 1;
dst[0] = src[0];
}
}
#endif // LLVM
}
[Inline]
internal unsafe static void InternalBackwardMemoryCopy( short* src ,
short* dst ,
int count )
{
InternalBackwardMemoryCopy( (ushort*)src, (ushort*)dst, count );
}
[Inline]
internal unsafe static void InternalBackwardMemoryCopy( char* src ,
char* dst ,
int count )
{
InternalBackwardMemoryCopy( (ushort*)src, (ushort*)dst, count );
}
//--//
[DisableNullChecks]
internal unsafe static void InternalBackwardMemoryCopy( uint* src ,
uint* dst ,
int count )
{
#if LLVM
InternalBackwardMemoryCopy( (byte*)src, (byte*)dst, count * sizeof( uint ) );
#else // LLVM
BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex );
if(count > 0)
{
src += count;
dst += count;
while(count >= 4)
{
dst -= 4;
src -= 4;
count -= 4;
var v0 = src[0];
var v1 = src[1];
var v2 = src[2];
var v3 = src[3];
dst[0] = v0;
dst[1] = v1;
dst[2] = v2;
dst[3] = v3;
}
if((count & 2) != 0)
{
dst -= 2;
src -= 2;
var v0 = src[0];
var v1 = src[1];
dst[0] = v0;
dst[1] = v1;
}
if((count & 1) != 0)
{
dst -= 1;
src -= 1;
dst[0] = src[0];
}
}
#endif // LLVM
}
[Inline]
internal unsafe static void InternalBackwardMemoryCopy( int* src ,
int* dst ,
int count )
{
InternalBackwardMemoryCopy( (uint*)src, (uint*)dst, count );
}
//--//--//
internal unsafe static void InternalMemoryMove( byte* src ,
byte* dst ,
int count )
{
BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex );
if(src <= dst && dst < &src[count])
{
InternalBackwardMemoryCopy( src, dst, count );
}
else
{
InternalMemoryCopy( src, dst, count );
}
}
[Inline]
internal unsafe static void InternalMemoryMove( sbyte* src ,
sbyte* dst ,
int count )
{
InternalMemoryMove( (byte*)src, (byte*)dst, count );
}
//--//
internal unsafe static void InternalMemoryMove( ushort* src ,
ushort* dst ,
int count )
{
BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex );
if(src <= dst && dst < &src[count])
{
InternalBackwardMemoryCopy( src, dst, count );
}
else
{
InternalMemoryCopy( src, dst, count );
}
}
[Inline]
internal unsafe static void InternalMemoryMove( short* src ,
short* dst ,
int count )
{
InternalMemoryMove( (ushort*)src, (ushort*)dst, count );
}
[Inline]
internal unsafe static void InternalMemoryMove( char* src ,
char* dst ,
int count )
{
InternalMemoryMove( (ushort*)src, (ushort*)dst, count );
}
//--//
internal unsafe static void InternalMemoryMove( uint* src ,
uint* dst ,
int count )
{
BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex );
if(src <= dst && dst < &src[count])
{
InternalBackwardMemoryCopy( src, dst, count );
}
else
{
InternalMemoryCopy( src, dst, count );
}
}
[Inline]
internal unsafe static void InternalMemoryMove( int* src ,
int* dst ,
int count )
{
InternalMemoryMove( (uint*)src, (uint*)dst, count );
}
}
}
| |
using System.Collections.Generic;
using Docu.Documentation;
using Docu.Output;
using Docu.IO;
using Example;
using NUnit.Framework;
using Rhino.Mocks;
namespace Docu.Tests.Output
{
[TestFixture]
public class TemplateTransformerTests : BaseFixture
{
[Test]
public void GeneratesOutputFromTemplate()
{
var generator = MockRepository.GenerateMock<IOutputGenerator>();
var writer = MockRepository.GenerateStub<IOutputWriter>();
var resolver = MockRepository.GenerateStub<IPatternTemplateResolver>();
var transformer = new PageWriter(generator, writer, resolver);
var namespaces = new Namespace[0];
resolver.Stub(x => x.Resolve(null, null))
.IgnoreArguments()
.Return(new List<TemplateMatch> { new TemplateMatch("simple.htm", "simple.spark", new ViewData()) });
transformer.CreatePages("simple.spark", "", namespaces);
generator.AssertWasCalled(
x => x.Convert(Arg.Is("simple.spark"), Arg<ViewData>.Is.Anything, Arg<string>.Is.Anything));
}
[Test]
public void WritesOutputToFile()
{
var generator = MockRepository.GenerateStub<IOutputGenerator>();
var writer = MockRepository.GenerateMock<IOutputWriter>();
var resolver = MockRepository.GenerateStub<IPatternTemplateResolver>();
var transformer = new PageWriter(generator, writer, resolver);
var namespaces = new Namespace[0];
resolver.Stub(x => x.Resolve(null, null))
.IgnoreArguments()
.Return(new List<TemplateMatch> { new TemplateMatch("simple.htm", "simple.spark", new ViewData()) });
generator.Stub(x => x.Convert(null, null, null))
.IgnoreArguments()
.Return("content");
transformer.CreatePages("simple.spark", "", namespaces);
writer.AssertWasCalled(x => x.WriteFile("simple.htm", "content"));
}
[Test]
public void GeneratesOutputForEachNamespaceFromTemplateWhenPatternUsed()
{
var generator = MockRepository.GenerateMock<IOutputGenerator>();
var writer = MockRepository.GenerateStub<IOutputWriter>();
var resolver = MockRepository.GenerateStub<IPatternTemplateResolver>();
var transformer = new PageWriter(generator, writer, resolver);
var namespaces = Namespaces("One", "Two");
resolver.Stub(x => x.Resolve(null, null))
.IgnoreArguments()
.Return(new List<TemplateMatch>
{
new TemplateMatch("One.htm", "!namespace.spark", new ViewData()),
new TemplateMatch("Two.htm", "!namespace.spark", new ViewData())
});
transformer.CreatePages("!namespace.spark", "", namespaces);
generator.AssertWasCalled(
x => x.Convert(Arg.Is("!namespace.spark"), Arg<ViewData>.Is.Anything, Arg<string>.Is.Anything),
x => x.Repeat.Twice());
}
[Test]
public void WritesOutputForEachNamespaceToFileWhenPatternUsed()
{
var generator = MockRepository.GenerateStub<IOutputGenerator>();
var writer = MockRepository.GenerateMock<IOutputWriter>();
var resolver = MockRepository.GenerateStub<IPatternTemplateResolver>();
var transformer = new PageWriter(generator, writer, resolver);
var namespaces = Namespaces("One", "Two");
resolver.Stub(x => x.Resolve(null, null))
.IgnoreArguments()
.Return(new List<TemplateMatch>
{
new TemplateMatch("One.htm", "!namespace.spark", new ViewData()),
new TemplateMatch("Two.htm", "!namespace.spark", new ViewData())
});
generator.Stub(x => x.Convert(null, null, null))
.IgnoreArguments()
.Return("content");
transformer.CreatePages("!namespace.spark", "", namespaces);
writer.AssertWasCalled(x => x.WriteFile("One.htm", "content"));
writer.AssertWasCalled(x => x.WriteFile("Two.htm", "content"));
}
[Test]
public void GeneratesOutputForEachTypeFromTemplateWhenPatternUsed()
{
var generator = MockRepository.GenerateMock<IOutputGenerator>();
var writer = MockRepository.GenerateStub<IOutputWriter>();
var resolver = MockRepository.GenerateStub<IPatternTemplateResolver>();
var transformer = new PageWriter(generator, writer, resolver);
var namespaces = Namespaces("One", "Two");
Type<First>(namespaces[0]);
Type<Second>(namespaces[1]);
resolver.Stub(x => x.Resolve(null, null))
.IgnoreArguments()
.Return(new List<TemplateMatch>
{
new TemplateMatch("One.First.htm", "!type.spark", new ViewData()),
new TemplateMatch("Two.Second.htm", "!type.spark", new ViewData())
});
transformer.CreatePages("!type.spark", "", namespaces);
generator.AssertWasCalled(
x => x.Convert(Arg.Is("!type.spark"), Arg<ViewData>.Is.Anything, Arg<string>.Is.Anything),
x => x.Repeat.Twice());
}
[Test]
public void WritesOutputForEachTypeToFileWhenPatternUsed()
{
var generator = MockRepository.GenerateStub<IOutputGenerator>();
var writer = MockRepository.GenerateMock<IOutputWriter>();
var resolver = MockRepository.GenerateStub<IPatternTemplateResolver>();
var transformer = new PageWriter(generator, writer, resolver);
var namespaces = Namespaces("One", "Two");
Type<First>(namespaces[0]);
Type<Second>(namespaces[1]);
resolver.Stub(x => x.Resolve(null, null))
.IgnoreArguments()
.Return(new List<TemplateMatch>
{
new TemplateMatch("One.First.htm", "!type.spark", new ViewData()),
new TemplateMatch("Two.Second.htm", "!type.spark", new ViewData())
});
generator.Stub(x => x.Convert(null, null, null))
.IgnoreArguments()
.Return("content");
transformer.CreatePages("!type.spark", "", namespaces);
writer.AssertWasCalled(x => x.WriteFile("One.First.htm", "content"));
writer.AssertWasCalled(x => x.WriteFile("Two.Second.htm", "content"));
}
[Test]
public void TransformsTemplateInDirectoriesWithNamespacePattern()
{
var generator = MockRepository.GenerateStub<IOutputGenerator>();
var writer = MockRepository.GenerateMock<IOutputWriter>();
var resolver = MockRepository.GenerateStub<IPatternTemplateResolver>();
var transformer = new PageWriter(generator, writer, resolver);
var namespaces = Namespaces("One", "Two");
resolver.Stub(x => x.Resolve(null, null))
.IgnoreArguments()
.Return(new List<TemplateMatch>
{
new TemplateMatch("One\\template.htm", "!namespace\\template.spark", new ViewData()),
new TemplateMatch("Two\\template.htm", "!namespace\\template.spark", new ViewData())
});
writer.Stub(x => x.Exists(null))
.IgnoreArguments()
.Return(false);
generator.Stub(x => x.Convert(null, null, null))
.IgnoreArguments()
.Return("content");
transformer.CreatePages("!namespace\\template.spark", "", namespaces);
writer.AssertWasCalled(x => x.CreateDirectory("One"));
writer.AssertWasCalled(x => x.WriteFile("One\\template.htm", "content"));
writer.AssertWasCalled(x => x.CreateDirectory("Two"));
writer.AssertWasCalled(x => x.WriteFile("Two\\template.htm", "content"));
}
[Test]
public void TransformsTemplatesInDirectoriesWithTypePattern()
{
var generator = MockRepository.GenerateStub<IOutputGenerator>();
var writer = MockRepository.GenerateMock<IOutputWriter>();
var resolver = MockRepository.GenerateStub<IPatternTemplateResolver>();
var transformer = new PageWriter(generator, writer, resolver);
var namespaces = Namespaces("One", "Two");
Type<First>(namespaces[0]);
Type<Second>(namespaces[1]);
resolver.Stub(x => x.Resolve(null, null))
.IgnoreArguments()
.Return(new List<TemplateMatch>
{
new TemplateMatch("One.First\\template.htm", "!type\\template.spark", new ViewData()),
new TemplateMatch("Two.Second\\template.htm", "!type\\template.spark", new ViewData()),
});
writer.Stub(x => x.Exists(null))
.IgnoreArguments()
.Return(false);
generator.Stub(x => x.Convert(null, null, null))
.IgnoreArguments()
.Return("content");
transformer.CreatePages("!type\\template.spark", "", namespaces);
writer.AssertWasCalled(x => x.CreateDirectory("One.First"));
writer.AssertWasCalled(x => x.WriteFile("One.First\\template.htm", "content"));
writer.AssertWasCalled(x => x.CreateDirectory("Two.Second"));
writer.AssertWasCalled(x => x.WriteFile("Two.Second\\template.htm", "content"));
}
[Test]
public void TransformsTemplatesWithinPatternDirectories()
{
var generator = MockRepository.GenerateStub<IOutputGenerator>();
var writer = MockRepository.GenerateMock<IOutputWriter>();
var resolver = MockRepository.GenerateStub<IPatternTemplateResolver>();
var transformer = new PageWriter(generator, writer, resolver);
var namespaces = Namespaces("One", "Two");
resolver.Stub(x => x.Resolve(null, null))
.IgnoreArguments()
.Return(new List<TemplateMatch>
{
new TemplateMatch("One\\test.htm", "", new ViewData()),
new TemplateMatch("Two\\test.htm", "", new ViewData()),
});
generator.Stub(x => x.Convert(null, null, null))
.IgnoreArguments()
.Return("content");
transformer.CreatePages("!namespace\\test.spark", "", namespaces);
writer.AssertWasCalled(x => x.WriteFile("One\\test.htm", "content"));
writer.AssertWasCalled(x => x.WriteFile("Two\\test.htm", "content"));
}
[Test]
public void TransformsTemplatesInDirectories()
{
var generator = MockRepository.GenerateStub<IOutputGenerator>();
var writer = MockRepository.GenerateMock<IOutputWriter>();
var resolver = MockRepository.GenerateStub<IPatternTemplateResolver>();
var transformer = new PageWriter(generator, writer, resolver);
var namespaces = new Namespace[0];
resolver.Stub(x => x.Resolve(null, null))
.IgnoreArguments()
.Return(new List<TemplateMatch> { new TemplateMatch("directory\\test.htm", "", new ViewData()) });
generator.Stub(x => x.Convert(null, null, null))
.IgnoreArguments()
.Return("content");
transformer.CreatePages("directory\\test.spark", "", namespaces);
writer.AssertWasCalled(x => x.WriteFile("directory\\test.htm", "content"));
}
}
}
| |
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_ANDROID
using System;
using System.Runtime.InteropServices;
namespace Cloo.Bindings
{
[System.Security.SuppressUnmanagedCodeSecurity]
public class CL10 : ICL10
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
protected const string libName = "OpenCL.dll";
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
protected const string libName = "/System/Library/Frameworks/OpenCL.framework/Versions/Current/OpenCL";
#elif UNITY_STANDALONE_LINUX || UNITY_ANDROID
protected const string libName = "OpenCL";
#endif
#region External
[DllImport(libName, EntryPoint = "clGetPlatformIDs")]
extern static ComputeErrorCode GetPlatformIDs(
Int32 num_entries,
[Out, MarshalAs(UnmanagedType.LPArray)] CLPlatformHandle[] platforms,
out Int32 num_platforms);
[DllImport(libName, EntryPoint = "clGetPlatformInfo")]
extern static ComputeErrorCode GetPlatformInfo(
CLPlatformHandle platform,
ComputePlatformInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clGetDeviceIDs")]
extern static ComputeErrorCode GetDeviceIDs(
CLPlatformHandle platform,
ComputeDeviceTypes device_type,
Int32 num_entries,
[Out, MarshalAs(UnmanagedType.LPArray)] CLDeviceHandle[] devices,
out Int32 num_devices);
[DllImport(libName, EntryPoint = "clGetDeviceInfo")]
extern static ComputeErrorCode GetDeviceInfo(
CLDeviceHandle device,
ComputeDeviceInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clCreateContext")]
extern static CLContextHandle CreateContext(
[MarshalAs(UnmanagedType.LPArray)] IntPtr[] properties,
Int32 num_devices,
[MarshalAs(UnmanagedType.LPArray)] CLDeviceHandle[] devices,
ComputeContextNotifier pfn_notify,
IntPtr user_data,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clCreateContextFromType")]
extern static CLContextHandle CreateContextFromType(
[MarshalAs(UnmanagedType.LPArray)] IntPtr[] properties,
ComputeDeviceTypes device_type,
ComputeContextNotifier pfn_notify,
IntPtr user_data,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clRetainContext")]
extern static ComputeErrorCode RetainContext(
CLContextHandle context);
[DllImport(libName, EntryPoint = "clReleaseContext")]
extern static ComputeErrorCode ReleaseContext(
CLContextHandle context);
[DllImport(libName, EntryPoint = "clGetContextInfo")]
extern static ComputeErrorCode GetContextInfo(
CLContextHandle context,
ComputeContextInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clCreateCommandQueue")]
extern static CLCommandQueueHandle CreateCommandQueue(
CLContextHandle context,
CLDeviceHandle device,
ComputeCommandQueueFlags properties,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clRetainCommandQueue")]
extern static ComputeErrorCode RetainCommandQueue(
CLCommandQueueHandle command_queue);
[DllImport(libName, EntryPoint = "clReleaseCommandQueue")]
extern static ComputeErrorCode
ReleaseCommandQueue(
CLCommandQueueHandle command_queue);
[DllImport(libName, EntryPoint = "clGetCommandQueueInfo")]
extern static ComputeErrorCode GetCommandQueueInfo(
CLCommandQueueHandle command_queue,
ComputeCommandQueueInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clSetCommandQueueProperty")]
extern static ComputeErrorCode SetCommandQueueProperty(
CLCommandQueueHandle command_queue,
ComputeCommandQueueFlags properties,
[MarshalAs(UnmanagedType.Bool)] bool enable,
out ComputeCommandQueueFlags old_properties);
[DllImport(libName, EntryPoint = "clCreateBuffer")]
extern static CLMemoryHandle CreateBuffer(
CLContextHandle context,
ComputeMemoryFlags flags,
IntPtr size,
IntPtr host_ptr,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clCreateImage2D")]
extern static CLMemoryHandle CreateImage2D(
CLContextHandle context,
ComputeMemoryFlags flags,
ref ComputeImageFormat image_format,
IntPtr image_width,
IntPtr image_height,
IntPtr image_row_pitch,
IntPtr host_ptr,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clCreateImage3D")]
extern static CLMemoryHandle CreateImage3D(
CLContextHandle context,
ComputeMemoryFlags flags,
ref ComputeImageFormat image_format,
IntPtr image_width,
IntPtr image_height,
IntPtr image_depth,
IntPtr image_row_pitch,
IntPtr image_slice_pitch,
IntPtr host_ptr,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clRetainMemObject")]
extern static ComputeErrorCode RetainMemObject(
CLMemoryHandle memobj);
[DllImport(libName, EntryPoint = "clReleaseMemObject")]
extern static ComputeErrorCode ReleaseMemObject(
CLMemoryHandle memobj);
[DllImport(libName, EntryPoint = "clGetSupportedImageFormats")]
extern static ComputeErrorCode GetSupportedImageFormats(
CLContextHandle context,
ComputeMemoryFlags flags,
ComputeMemoryType image_type,
Int32 num_entries,
[Out, MarshalAs(UnmanagedType.LPArray)] ComputeImageFormat[] image_formats,
out Int32 num_image_formats);
[DllImport(libName, EntryPoint = "clGetMemObjectInfo")]
extern static ComputeErrorCode GetMemObjectInfo(
CLMemoryHandle memobj,
ComputeMemoryInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clGetImageInfo")]
extern static ComputeErrorCode GetImageInfo(
CLMemoryHandle image,
ComputeImageInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clCreateSampler")]
extern static CLSamplerHandle CreateSampler(
CLContextHandle context,
[MarshalAs(UnmanagedType.Bool)] bool normalized_coords,
ComputeImageAddressing addressing_mode,
ComputeImageFiltering filter_mode,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clRetainSampler")]
extern static ComputeErrorCode RetainSampler(
CLSamplerHandle sample);
[DllImport(libName, EntryPoint = "clReleaseSampler")]
extern static ComputeErrorCode ReleaseSampler(
CLSamplerHandle sample);
[DllImport(libName, EntryPoint = "clGetSamplerInfo")]
extern static ComputeErrorCode GetSamplerInfo(
CLSamplerHandle sample,
ComputeSamplerInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clCreateProgramWithSource")]
extern static CLProgramHandle CreateProgramWithSource(
CLContextHandle context,
Int32 count,
String[] strings,
[MarshalAs(UnmanagedType.LPArray)] IntPtr[] lengths,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clCreateProgramWithBinary")]
extern static CLProgramHandle CreateProgramWithBinary(
CLContextHandle context,
Int32 num_devices,
[MarshalAs(UnmanagedType.LPArray)] CLDeviceHandle[] device_list,
[MarshalAs(UnmanagedType.LPArray)] IntPtr[] lengths,
[MarshalAs(UnmanagedType.LPArray)] IntPtr[] binaries,
[MarshalAs(UnmanagedType.LPArray)] Int32[] binary_status,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clRetainProgram")]
extern static ComputeErrorCode RetainProgram(
CLProgramHandle program);
[DllImport(libName, EntryPoint = "clReleaseProgram")]
extern static ComputeErrorCode ReleaseProgram(
CLProgramHandle program);
[DllImport(libName, EntryPoint = "clBuildProgram")]
extern static ComputeErrorCode BuildProgram(
CLProgramHandle program,
Int32 num_devices,
[MarshalAs(UnmanagedType.LPArray)] CLDeviceHandle[] device_list,
String options,
ComputeProgramBuildNotifier pfn_notify,
IntPtr user_data);
[DllImport(libName, EntryPoint = "clUnloadCompiler")]
extern static ComputeErrorCode UnloadCompiler();
[DllImport(libName, EntryPoint = "clGetProgramInfo")]
extern static ComputeErrorCode GetProgramInfo(
CLProgramHandle program,
ComputeProgramInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clGetProgramBuildInfo")]
extern static ComputeErrorCode GetProgramBuildInfo(
CLProgramHandle program,
CLDeviceHandle device,
ComputeProgramBuildInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clCreateKernel")]
extern static CLKernelHandle CreateKernel(
CLProgramHandle program,
String kernel_name,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clCreateKernelsInProgram")]
extern static ComputeErrorCode CreateKernelsInProgram(
CLProgramHandle program,
Int32 num_kernels,
[Out, MarshalAs(UnmanagedType.LPArray)] CLKernelHandle[] kernels,
out Int32 num_kernels_ret);
[DllImport(libName, EntryPoint = "clRetainKernel")]
extern static ComputeErrorCode RetainKernel(
CLKernelHandle kernel);
[DllImport(libName, EntryPoint = "clReleaseKernel")]
extern static ComputeErrorCode ReleaseKernel(
CLKernelHandle kernel);
[DllImport(libName, EntryPoint = "clSetKernelArg")]
extern static ComputeErrorCode SetKernelArg(
CLKernelHandle kernel,
Int32 arg_index,
IntPtr arg_size,
IntPtr arg_value);
[DllImport(libName, EntryPoint = "clGetKernelInfo")]
extern static ComputeErrorCode GetKernelInfo(
CLKernelHandle kernel,
ComputeKernelInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clGetKernelWorkGroupInfo")]
extern static ComputeErrorCode GetKernelWorkGroupInfo(
CLKernelHandle kernel,
CLDeviceHandle device,
ComputeKernelWorkGroupInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clWaitForEvents")]
extern static ComputeErrorCode WaitForEvents(
Int32 num_events,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_list);
[DllImport(libName, EntryPoint = "clGetEventInfo")]
extern static ComputeErrorCode GetEventInfo(
CLEventHandle @event,
ComputeEventInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clRetainEvent")]
extern static ComputeErrorCode RetainEvent(
CLEventHandle @event);
[DllImport(libName, EntryPoint = "clReleaseEvent")]
extern static ComputeErrorCode ReleaseEvent(
CLEventHandle @event);
[DllImport(libName, EntryPoint = "clGetEventProfilingInfo")]
extern static ComputeErrorCode GetEventProfilingInfo(
CLEventHandle @event,
ComputeCommandProfilingInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clFlush")]
extern static ComputeErrorCode Flush(
CLCommandQueueHandle command_queue);
[DllImport(libName, EntryPoint = "clFinish")]
extern static ComputeErrorCode Finish(
CLCommandQueueHandle command_queue);
[DllImport(libName, EntryPoint = "clEnqueueReadBuffer")]
extern static ComputeErrorCode EnqueueReadBuffer(
CLCommandQueueHandle command_queue,
CLMemoryHandle buffer,
[MarshalAs(UnmanagedType.Bool)] bool blocking_read,
IntPtr offset,
IntPtr cb,
IntPtr ptr,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueWriteBuffer")]
extern static ComputeErrorCode EnqueueWriteBuffer(
CLCommandQueueHandle command_queue,
CLMemoryHandle buffer,
[MarshalAs(UnmanagedType.Bool)] bool blocking_write,
IntPtr offset,
IntPtr cb,
IntPtr ptr,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueCopyBuffer")]
extern static ComputeErrorCode EnqueueCopyBuffer(
CLCommandQueueHandle command_queue,
CLMemoryHandle src_buffer,
CLMemoryHandle dst_buffer,
IntPtr src_offset,
IntPtr dst_offset,
IntPtr cb,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueReadImage")]
extern static ComputeErrorCode EnqueueReadImage(
CLCommandQueueHandle command_queue,
CLMemoryHandle image,
[MarshalAs(UnmanagedType.Bool)] bool blocking_read,
ref SysIntX3 origin,
ref SysIntX3 region,
IntPtr row_pitch,
IntPtr slice_pitch,
IntPtr ptr,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueWriteImage")]
extern static ComputeErrorCode EnqueueWriteImage(
CLCommandQueueHandle command_queue,
CLMemoryHandle image,
[MarshalAs(UnmanagedType.Bool)] bool blocking_write,
ref SysIntX3 origin,
ref SysIntX3 region,
IntPtr input_row_pitch,
IntPtr input_slice_pitch,
IntPtr ptr,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueCopyImage")]
extern static ComputeErrorCode EnqueueCopyImage(
CLCommandQueueHandle command_queue,
CLMemoryHandle src_image,
CLMemoryHandle dst_image,
ref SysIntX3 src_origin,
ref SysIntX3 dst_origin,
ref SysIntX3 region,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueCopyImageToBuffer")]
extern static ComputeErrorCode EnqueueCopyImageToBuffer(
CLCommandQueueHandle command_queue,
CLMemoryHandle src_image,
CLMemoryHandle dst_buffer,
ref SysIntX3 src_origin,
ref SysIntX3 region,
IntPtr dst_offset,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueCopyBufferToImage")]
extern static ComputeErrorCode EnqueueCopyBufferToImage(
CLCommandQueueHandle command_queue,
CLMemoryHandle src_buffer,
CLMemoryHandle dst_image,
IntPtr src_offset,
ref SysIntX3 dst_origin,
ref SysIntX3 region,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueMapBuffer")]
extern static IntPtr EnqueueMapBuffer(
CLCommandQueueHandle command_queue,
CLMemoryHandle buffer,
[MarshalAs(UnmanagedType.Bool)] bool blocking_map,
ComputeMemoryMappingFlags map_flags,
IntPtr offset,
IntPtr cb,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clEnqueueMapImage")]
extern static IntPtr EnqueueMapImage(
CLCommandQueueHandle command_queue,
CLMemoryHandle image,
[MarshalAs(UnmanagedType.Bool)] bool blocking_map,
ComputeMemoryMappingFlags map_flags,
ref SysIntX3 origin,
ref SysIntX3 region,
out IntPtr image_row_pitch,
out IntPtr image_slice_pitch,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clEnqueueUnmapMemObject")]
extern static ComputeErrorCode EnqueueUnmapMemObject(
CLCommandQueueHandle command_queue,
CLMemoryHandle memobj,
IntPtr mapped_ptr,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueNDRangeKernel")]
extern static ComputeErrorCode EnqueueNDRangeKernel(
CLCommandQueueHandle command_queue,
CLKernelHandle kernel,
Int32 work_dim,
[MarshalAs(UnmanagedType.LPArray)] IntPtr[] global_work_offset,
[MarshalAs(UnmanagedType.LPArray)] IntPtr[] global_work_size,
[MarshalAs(UnmanagedType.LPArray)] IntPtr[] local_work_size,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueTask")]
extern static ComputeErrorCode EnqueueTask(
CLCommandQueueHandle command_queue,
CLKernelHandle kernel,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
/*
[DllImport(libName, EntryPoint = "clEnqueueNativeKernel")]
extern static ComputeErrorCode EnqueueNativeKernel(
CLCommandQueueHandle command_queue,
IntPtr user_func,
IntPtr args,
IntPtr cb_args,
Int32 num_mem_objects,
IntPtr* mem_list,
IntPtr* args_mem_loc,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst=1)] CLEventHandle[] new_event);
*/
[DllImport(libName, EntryPoint = "clEnqueueMarker")]
extern static ComputeErrorCode EnqueueMarker(
CLCommandQueueHandle command_queue,
out CLEventHandle new_event);
[DllImport(libName, EntryPoint = "clEnqueueWaitForEvents")]
extern static ComputeErrorCode EnqueueWaitForEvents(
CLCommandQueueHandle command_queue,
Int32 num_events,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_list);
[DllImport(libName, EntryPoint = "clEnqueueBarrier")]
extern static ComputeErrorCode EnqueueBarrier(
CLCommandQueueHandle command_queue);
[DllImport(libName, EntryPoint = "clGetExtensionFunctionAddress")]
extern static IntPtr GetExtensionFunctionAddress(
String func_name);
[DllImport(libName, EntryPoint = "clCreateFromGLBuffer")]
extern static CLMemoryHandle CreateFromGLBuffer(
CLContextHandle context,
ComputeMemoryFlags flags,
Int32 bufobj,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clCreateFromGLTexture2D")]
extern static CLMemoryHandle CreateFromGLTexture2D(
CLContextHandle context,
ComputeMemoryFlags flags,
Int32 target,
Int32 miplevel,
Int32 texture,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clCreateFromGLTexture3D")]
extern static CLMemoryHandle CreateFromGLTexture3D(
CLContextHandle context,
ComputeMemoryFlags flags,
Int32 target,
Int32 miplevel,
Int32 texture,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clCreateFromGLRenderbuffer")]
extern static CLMemoryHandle CreateFromGLRenderbuffer(
CLContextHandle context,
ComputeMemoryFlags flags,
Int32 renderbuffer,
out ComputeErrorCode errcode_ret);
[DllImport(libName, EntryPoint = "clGetGLObjectInfo")]
extern static ComputeErrorCode GetGLObjectInfo(
CLMemoryHandle memobj,
out ComputeGLObjectType gl_object_type,
out Int32 gl_object_name);
[DllImport(libName, EntryPoint = "clGetGLTextureInfo")]
extern static ComputeErrorCode GetGLTextureInfo(
CLMemoryHandle memobj,
ComputeGLTextureInfo param_name,
IntPtr param_value_size,
IntPtr param_value,
out IntPtr param_value_size_ret);
[DllImport(libName, EntryPoint = "clEnqueueAcquireGLObjects")]
extern static ComputeErrorCode EnqueueAcquireGLObjects(
CLCommandQueueHandle command_queue,
Int32 num_objects,
[MarshalAs(UnmanagedType.LPArray)] CLMemoryHandle[] mem_objects,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
[DllImport(libName, EntryPoint = "clEnqueueReleaseGLObjects")]
extern static ComputeErrorCode EnqueueReleaseGLObjects(
CLCommandQueueHandle command_queue,
Int32 num_objects,
[MarshalAs(UnmanagedType.LPArray)] CLMemoryHandle[] mem_objects,
Int32 num_events_in_wait_list,
[MarshalAs(UnmanagedType.LPArray)] CLEventHandle[] event_wait_list,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] CLEventHandle[] new_event);
#endregion
#region ICL10 implementation
ComputeErrorCode ICL10.GetPlatformInfo(CLPlatformHandle platform, ComputePlatformInfo param_name, IntPtr param_value_size,
IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetPlatformInfo(platform, param_name, param_value_size, param_value, out param_value_size_ret);
}
ComputeErrorCode ICL10.GetDeviceIDs(CLPlatformHandle platform, ComputeDeviceTypes device_type, int num_entries,
CLDeviceHandle[] devices, out int num_devices)
{
return GetDeviceIDs(platform, device_type, num_entries, devices, out num_devices);
}
ComputeErrorCode ICL10.GetDeviceInfo(CLDeviceHandle device, ComputeDeviceInfo param_name, IntPtr param_value_size,
IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetDeviceInfo(device, param_name, param_value_size, param_value, out param_value_size_ret);
}
CLContextHandle ICL10.CreateContext(IntPtr[] properties, int num_devices, CLDeviceHandle[] devices,
ComputeContextNotifier pfn_notify, IntPtr user_data, out ComputeErrorCode errcode_ret)
{
return CreateContext(properties, num_devices, devices, pfn_notify, user_data, out errcode_ret);
}
CLContextHandle ICL10.CreateContextFromType(IntPtr[] properties, ComputeDeviceTypes device_type,
ComputeContextNotifier pfn_notify, IntPtr user_data,
out ComputeErrorCode errcode_ret)
{
return CreateContextFromType(properties, device_type, pfn_notify, user_data, out errcode_ret);
}
ComputeErrorCode ICL10.RetainContext(CLContextHandle context)
{
return RetainContext(context);
}
ComputeErrorCode ICL10.ReleaseContext(CLContextHandle context)
{
return ReleaseContext(context);
}
ComputeErrorCode ICL10.GetContextInfo(CLContextHandle context, ComputeContextInfo param_name, IntPtr param_value_size,
IntPtr param_value, out IntPtr param_value_size_ret)
{
param_value_size_ret = IntPtr.Zero;
return GetContextInfo(context, param_name, param_value_size, param_value, out param_value_size_ret);
}
CLCommandQueueHandle ICL10.CreateCommandQueue(CLContextHandle context, CLDeviceHandle device,
ComputeCommandQueueFlags properties, out ComputeErrorCode errcode_ret)
{
return CreateCommandQueue(context, device, properties, out errcode_ret);
}
ComputeErrorCode ICL10.RetainCommandQueue(CLCommandQueueHandle command_queue)
{
return RetainCommandQueue(command_queue);
}
ComputeErrorCode ICL10.ReleaseCommandQueue(CLCommandQueueHandle command_queue)
{
return ReleaseCommandQueue(command_queue);
}
ComputeErrorCode ICL10.GetCommandQueueInfo(CLCommandQueueHandle command_queue, ComputeCommandQueueInfo param_name,
IntPtr param_value_size, IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetCommandQueueInfo(command_queue, param_name, param_value_size, param_value, out param_value_size_ret);
}
ComputeErrorCode ICL10.SetCommandQueueProperty(CLCommandQueueHandle command_queue, ComputeCommandQueueFlags properties,
bool enable, out ComputeCommandQueueFlags old_properties)
{
return SetCommandQueueProperty(command_queue, properties, enable, out old_properties);
}
CLMemoryHandle ICL10.CreateBuffer(CLContextHandle context, ComputeMemoryFlags flags, IntPtr size, IntPtr host_ptr,
out ComputeErrorCode errcode_ret)
{
return CreateBuffer(context, flags, size, host_ptr, out errcode_ret);
}
CLMemoryHandle ICL10.CreateImage2D(CLContextHandle context, ComputeMemoryFlags flags, ref ComputeImageFormat image_format,
IntPtr image_width, IntPtr image_height, IntPtr image_row_pitch, IntPtr host_ptr,
out ComputeErrorCode errcode_ret)
{
return CreateImage2D(context, flags, ref image_format, image_width, image_height, image_row_pitch, host_ptr, out errcode_ret);
}
CLMemoryHandle ICL10.CreateImage3D(CLContextHandle context, ComputeMemoryFlags flags, ref ComputeImageFormat image_format,
IntPtr image_width, IntPtr image_height, IntPtr image_depth, IntPtr image_row_pitch,
IntPtr image_slice_pitch, IntPtr host_ptr, out ComputeErrorCode errcode_ret)
{
return CreateImage3D(context, flags, ref image_format, image_width, image_height, image_depth, image_row_pitch, image_slice_pitch, host_ptr, out errcode_ret);
}
ComputeErrorCode ICL10.RetainMemObject(CLMemoryHandle memobj)
{
return RetainMemObject(memobj);
}
ComputeErrorCode ICL10.ReleaseMemObject(CLMemoryHandle memobj)
{
return ReleaseMemObject(memobj);
}
ComputeErrorCode ICL10.GetSupportedImageFormats(CLContextHandle context, ComputeMemoryFlags flags,
ComputeMemoryType image_type, int num_entries,
ComputeImageFormat[] image_formats, out int num_image_formats)
{
return GetSupportedImageFormats(context, flags, image_type, num_entries, image_formats, out num_image_formats);
}
ComputeErrorCode ICL10.GetMemObjectInfo(CLMemoryHandle memobj, ComputeMemoryInfo param_name, IntPtr param_value_size,
IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetMemObjectInfo(memobj, param_name, param_value_size, param_value, out param_value_size_ret);
}
ComputeErrorCode ICL10.GetImageInfo(CLMemoryHandle image, ComputeImageInfo param_name, IntPtr param_value_size,
IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetImageInfo(image, param_name, param_value_size, param_value, out param_value_size_ret);
}
CLSamplerHandle ICL10.CreateSampler(CLContextHandle context, bool normalized_coords, ComputeImageAddressing addressing_mode,
ComputeImageFiltering filter_mode, out ComputeErrorCode errcode_ret)
{
return CreateSampler(context, normalized_coords, addressing_mode, filter_mode, out errcode_ret);
}
ComputeErrorCode ICL10.RetainSampler(CLSamplerHandle sample)
{
return RetainSampler(sample);
}
ComputeErrorCode ICL10.ReleaseSampler(CLSamplerHandle sample)
{
return ReleaseSampler(sample);
}
ComputeErrorCode ICL10.GetSamplerInfo(CLSamplerHandle sample, ComputeSamplerInfo param_name, IntPtr param_value_size,
IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetSamplerInfo(sample, param_name, param_value_size, param_value, out param_value_size_ret);
}
CLProgramHandle ICL10.CreateProgramWithSource(CLContextHandle context, int count, string[] strings, IntPtr[] lengths,
out ComputeErrorCode errcode_ret)
{
return CreateProgramWithSource(context, count, strings, lengths, out errcode_ret);
}
CLProgramHandle ICL10.CreateProgramWithBinary(CLContextHandle context, int num_devices, CLDeviceHandle[] device_list,
IntPtr[] lengths, IntPtr[] binaries, int[] binary_status,
out ComputeErrorCode errcode_ret)
{
return CreateProgramWithBinary(context, num_devices, device_list, lengths, binaries, binary_status, out errcode_ret);
}
ComputeErrorCode ICL10.RetainProgram(CLProgramHandle program)
{
return RetainProgram(program);
}
ComputeErrorCode ICL10.ReleaseProgram(CLProgramHandle program)
{
return ReleaseProgram(program);
}
ComputeErrorCode ICL10.BuildProgram(CLProgramHandle program, int num_devices, CLDeviceHandle[] device_list, string options,
ComputeProgramBuildNotifier pfn_notify, IntPtr user_data)
{
return BuildProgram(program, num_devices, device_list, options, pfn_notify, user_data);
}
ComputeErrorCode ICL10.UnloadCompiler()
{
return UnloadCompiler();
}
ComputeErrorCode ICL10.GetProgramInfo(CLProgramHandle program, ComputeProgramInfo param_name, IntPtr param_value_size,
IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetProgramInfo(program, param_name, param_value_size, param_value, out param_value_size_ret);
}
ComputeErrorCode ICL10.GetProgramBuildInfo(CLProgramHandle program, CLDeviceHandle device, ComputeProgramBuildInfo param_name,
IntPtr param_value_size, IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetProgramBuildInfo(program, device, param_name, param_value_size, param_value, out param_value_size_ret);
}
CLKernelHandle ICL10.CreateKernel(CLProgramHandle program, string kernel_name, out ComputeErrorCode errcode_ret)
{
return CreateKernel(program, kernel_name, out errcode_ret);
}
ComputeErrorCode ICL10.CreateKernelsInProgram(CLProgramHandle program, int num_kernels, CLKernelHandle[] kernels,
out int num_kernels_ret)
{
return CreateKernelsInProgram(program, num_kernels, kernels, out num_kernels_ret);
}
ComputeErrorCode ICL10.RetainKernel(CLKernelHandle kernel)
{
return RetainKernel(kernel);
}
ComputeErrorCode ICL10.ReleaseKernel(CLKernelHandle kernel)
{
return ReleaseKernel(kernel);
}
ComputeErrorCode ICL10.SetKernelArg(CLKernelHandle kernel, int arg_index, IntPtr arg_size, IntPtr arg_value)
{
return SetKernelArg(kernel, arg_index, arg_size, arg_value);
}
ComputeErrorCode ICL10.GetKernelInfo(CLKernelHandle kernel, ComputeKernelInfo param_name, IntPtr param_value_size,
IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetKernelInfo(kernel, param_name, param_value_size, param_value, out param_value_size_ret);
}
ComputeErrorCode ICL10.GetKernelWorkGroupInfo(CLKernelHandle kernel, CLDeviceHandle device,
ComputeKernelWorkGroupInfo param_name, IntPtr param_value_size,
IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetKernelWorkGroupInfo(kernel, device, param_name, param_value_size, param_value, out param_value_size_ret);
}
ComputeErrorCode ICL10.WaitForEvents(int num_events, CLEventHandle[] event_list)
{
return WaitForEvents(num_events, event_list);
}
ComputeErrorCode ICL10.GetEventInfo(CLEventHandle @event, ComputeEventInfo param_name, IntPtr param_value_size,
IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetEventInfo(@event, param_name, param_value_size, param_value, out param_value_size_ret);
}
ComputeErrorCode ICL10.RetainEvent(CLEventHandle @event)
{
return RetainEvent(@event);
}
ComputeErrorCode ICL10.ReleaseEvent(CLEventHandle @event)
{
return ReleaseEvent(@event);
}
ComputeErrorCode ICL10.GetEventProfilingInfo(CLEventHandle @event, ComputeCommandProfilingInfo param_name,
IntPtr param_value_size, IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetEventProfilingInfo(@event, param_name, param_value_size, param_value, out param_value_size_ret);
}
ComputeErrorCode ICL10.Flush(CLCommandQueueHandle command_queue)
{
return Flush(command_queue);
}
ComputeErrorCode ICL10.Finish(CLCommandQueueHandle command_queue)
{
return Finish(command_queue);
}
ComputeErrorCode ICL10.EnqueueReadBuffer(CLCommandQueueHandle command_queue, CLMemoryHandle buffer, bool blocking_read,
IntPtr offset, IntPtr cb, IntPtr ptr, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event)
{
return EnqueueReadBuffer(command_queue, buffer, blocking_read, offset, cb, ptr, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL10.EnqueueWriteBuffer(CLCommandQueueHandle command_queue, CLMemoryHandle buffer, bool blocking_write,
IntPtr offset, IntPtr cb, IntPtr ptr, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event)
{
return EnqueueWriteBuffer(command_queue, buffer, blocking_write, offset, cb, ptr, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL10.EnqueueCopyBuffer(CLCommandQueueHandle command_queue, CLMemoryHandle src_buffer,
CLMemoryHandle dst_buffer, IntPtr src_offset, IntPtr dst_offset, IntPtr cb,
int num_events_in_wait_list, CLEventHandle[] event_wait_list,
CLEventHandle[] new_event)
{
return EnqueueCopyBuffer(command_queue, src_buffer, dst_buffer, src_offset, dst_offset, cb, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL10.EnqueueReadImage(CLCommandQueueHandle command_queue, CLMemoryHandle image, bool blocking_read,
ref SysIntX3 origin, ref SysIntX3 region, IntPtr row_pitch, IntPtr slice_pitch,
IntPtr ptr, int num_events_in_wait_list, CLEventHandle[] event_wait_list,
CLEventHandle[] new_event)
{
return EnqueueReadImage(command_queue, image, blocking_read, ref origin, ref region, row_pitch, slice_pitch, ptr, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL10.EnqueueWriteImage(CLCommandQueueHandle command_queue, CLMemoryHandle image, bool blocking_write,
ref SysIntX3 origin, ref SysIntX3 region, IntPtr input_row_pitch,
IntPtr input_slice_pitch, IntPtr ptr, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event)
{
return EnqueueWriteImage(command_queue, image, blocking_write, ref origin, ref region, input_row_pitch, input_slice_pitch, ptr, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL10.EnqueueCopyImage(CLCommandQueueHandle command_queue, CLMemoryHandle src_image, CLMemoryHandle dst_image,
ref SysIntX3 src_origin, ref SysIntX3 dst_origin, ref SysIntX3 region,
int num_events_in_wait_list, CLEventHandle[] event_wait_list,
CLEventHandle[] new_event)
{
return EnqueueCopyImage(command_queue, src_image, dst_image, ref src_origin, ref dst_origin, ref region, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL10.EnqueueCopyImageToBuffer(CLCommandQueueHandle command_queue, CLMemoryHandle src_image,
CLMemoryHandle dst_buffer, ref SysIntX3 src_origin, ref SysIntX3 region,
IntPtr dst_offset, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event)
{
return EnqueueCopyImageToBuffer(command_queue, src_image, dst_buffer, ref src_origin, ref region, dst_offset, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL10.EnqueueCopyBufferToImage(CLCommandQueueHandle command_queue, CLMemoryHandle src_buffer,
CLMemoryHandle dst_image, IntPtr src_offset, ref SysIntX3 dst_origin,
ref SysIntX3 region, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event)
{
return EnqueueCopyBufferToImage(command_queue, src_buffer, dst_image, src_offset, ref dst_origin, ref region, num_events_in_wait_list, event_wait_list, new_event);
}
IntPtr ICL10.EnqueueMapBuffer(CLCommandQueueHandle command_queue, CLMemoryHandle buffer, bool blocking_map,
ComputeMemoryMappingFlags map_flags, IntPtr offset, IntPtr cb, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event, out ComputeErrorCode errcode_ret)
{
return EnqueueMapBuffer(command_queue, buffer, blocking_map, map_flags, offset, cb, num_events_in_wait_list, event_wait_list, new_event, out errcode_ret);
}
IntPtr ICL10.EnqueueMapImage(CLCommandQueueHandle command_queue, CLMemoryHandle image, bool blocking_map,
ComputeMemoryMappingFlags map_flags, ref SysIntX3 origin, ref SysIntX3 region,
out IntPtr image_row_pitch, out IntPtr image_slice_pitch, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event, out ComputeErrorCode errcode_ret)
{
return EnqueueMapImage(command_queue, image, blocking_map, map_flags, ref origin, ref region, out image_row_pitch, out image_slice_pitch, num_events_in_wait_list, event_wait_list, new_event, out errcode_ret);
}
ComputeErrorCode ICL10.EnqueueUnmapMemObject(CLCommandQueueHandle command_queue, CLMemoryHandle memobj, IntPtr mapped_ptr,
int num_events_in_wait_list, CLEventHandle[] event_wait_list,
CLEventHandle[] new_event)
{
return EnqueueUnmapMemObject(command_queue, memobj, mapped_ptr, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL10.EnqueueNDRangeKernel(CLCommandQueueHandle command_queue, CLKernelHandle kernel, int work_dim,
IntPtr[] global_work_offset, IntPtr[] global_work_size, IntPtr[] local_work_size,
int num_events_in_wait_list, CLEventHandle[] event_wait_list,
CLEventHandle[] new_event)
{
return EnqueueNDRangeKernel(command_queue, kernel, work_dim, global_work_offset, global_work_size, local_work_size, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL10.EnqueueTask(CLCommandQueueHandle command_queue, CLKernelHandle kernel, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event)
{
return EnqueueTask(command_queue, kernel, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL10.EnqueueMarker(CLCommandQueueHandle command_queue, out CLEventHandle new_event)
{
return EnqueueMarker(command_queue, out new_event);
}
ComputeErrorCode ICL10.EnqueueWaitForEvents(CLCommandQueueHandle command_queue, int num_events, CLEventHandle[] event_list)
{
return EnqueueWaitForEvents(command_queue, num_events, event_list);
}
ComputeErrorCode ICL10.EnqueueBarrier(CLCommandQueueHandle command_queue)
{
return EnqueueBarrier(command_queue);
}
IntPtr ICL10.GetExtensionFunctionAddress(string func_name)
{
return GetExtensionFunctionAddress(func_name);
}
CLMemoryHandle ICL10.CreateFromGLBuffer(CLContextHandle context, ComputeMemoryFlags flags, int bufobj,
out ComputeErrorCode errcode_ret)
{
return CreateFromGLBuffer(context, flags, bufobj, out errcode_ret);
}
CLMemoryHandle ICL10.CreateFromGLTexture2D(CLContextHandle context, ComputeMemoryFlags flags, int target, int miplevel,
int texture, out ComputeErrorCode errcode_ret)
{
return CreateFromGLTexture2D(context, flags, target, miplevel, texture, out errcode_ret);
}
CLMemoryHandle ICL10.CreateFromGLTexture3D(CLContextHandle context, ComputeMemoryFlags flags, int target, int miplevel,
int texture, out ComputeErrorCode errcode_ret)
{
return CreateFromGLTexture3D(context, flags, target, miplevel, texture, out errcode_ret);
}
CLMemoryHandle ICL10.CreateFromGLRenderbuffer(CLContextHandle context, ComputeMemoryFlags flags, int renderbuffer,
out ComputeErrorCode errcode_ret)
{
return CreateFromGLRenderbuffer(context, flags, renderbuffer, out errcode_ret);
}
ComputeErrorCode ICL10.GetGLObjectInfo(CLMemoryHandle memobj, out ComputeGLObjectType gl_object_type, out int gl_object_name)
{
return GetGLObjectInfo(memobj, out gl_object_type, out gl_object_name);
}
ComputeErrorCode ICL10.GetGLTextureInfo(CLMemoryHandle memobj, ComputeGLTextureInfo param_name, IntPtr param_value_size,
IntPtr param_value, out IntPtr param_value_size_ret)
{
return GetGLTextureInfo(memobj, param_name, param_value_size, param_value, out param_value_size_ret);
}
ComputeErrorCode ICL10.EnqueueAcquireGLObjects(CLCommandQueueHandle command_queue, int num_objects,
CLMemoryHandle[] mem_objects, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event)
{
return EnqueueAcquireGLObjects(command_queue, num_objects, mem_objects, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL10.EnqueueReleaseGLObjects(CLCommandQueueHandle command_queue, int num_objects,
CLMemoryHandle[] mem_objects, int num_events_in_wait_list,
CLEventHandle[] event_wait_list, CLEventHandle[] new_event)
{
return EnqueueReleaseGLObjects(command_queue, num_objects, mem_objects, num_events_in_wait_list, event_wait_list, new_event);
}
ComputeErrorCode ICL10.GetPlatformIDs(int num_entries, CLPlatformHandle[] platforms, out int num_platforms)
{
return GetPlatformIDs(num_entries, platforms, out num_platforms);
}
#endregion
}
}
#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.Generic;
using System.Linq;
using System.Xml.Linq;
using CoreXml.Test.XLinq;
using Microsoft.Test.ModuleCore;
namespace XLinqTests
{
public class AddNodeAfter : AddNodeBeforeAfterBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+AddNodeAfter
// Test Case
#region Public Methods and Operators
public override void AddChildren()
{
AddChild(new TestVariation(AddingMultipleNodesIntoElement) { Attribute = new VariationAttribute("Adding multiple (4) objects into XElement - connected") { Params = new object[] { true, 4 }, Priority = 1 } });
AddChild(new TestVariation(AddingMultipleNodesIntoElement) { Attribute = new VariationAttribute("Adding single object into XElement - not connected") { Params = new object[] { false, 1 }, Priority = 1 } });
AddChild(new TestVariation(AddingMultipleNodesIntoElement) { Attribute = new VariationAttribute("Adding multiple (4) objects into XElement - not connected") { Params = new object[] { false, 4 }, Priority = 1 } });
AddChild(new TestVariation(AddingMultipleNodesIntoElement) { Attribute = new VariationAttribute("Adding single object into XElement - connected") { Params = new object[] { true, 1 }, Priority = 1 } });
AddChild(new TestVariation(InvalidNodeTypes) { Attribute = new VariationAttribute("Invalid node types - single object") { Priority = 2 } });
AddChild(new TestVariation(ValidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument valid add - not connected (multiple)") { Params = new object[] { false, 3 }, Priority = 1 } });
AddChild(new TestVariation(ValidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument valid add - connected (single)") { Params = new object[] { true, 1 }, Priority = 0 } });
AddChild(new TestVariation(ValidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument valid add - not connected (single)") { Params = new object[] { false, 1 }, Priority = 0 } });
AddChild(new TestVariation(ValidAddIntoXDocument) { Attribute = new VariationAttribute("XDocument valid add - connected (multiple)") { Params = new object[] { true, 3 }, Priority = 1 } });
AddChild(new TestVariation(InvalidAddIntoXDocument1) { Attribute = new VariationAttribute("XDocument invalid add - double DTD") { Priority = 1 } });
AddChild(new TestVariation(InvalidAddIntoXDocument2) { Attribute = new VariationAttribute("XDocument invalid add - DTD after element") { Priority = 1 } });
AddChild(new TestVariation(InvalidAddIntoXDocument4) { Attribute = new VariationAttribute("XDocument invalid add - multiple root elements") { Priority = 1 } });
AddChild(new TestVariation(InvalidAddIntoXDocument5) { Attribute = new VariationAttribute("XDocument invalid add - CData, attribute, text (no whitespace)") { Priority = 1 } });
AddChild(new TestVariation(WorkOnTextNodes1) { Attribute = new VariationAttribute("Working on the text nodes 1.") { Priority = 1 } });
AddChild(new TestVariation(WorkOnTextNodes2) { Attribute = new VariationAttribute("Working on the text nodes 2.") { Priority = 1 } });
}
// - order
// - parent, document property
// - query
// - value
// - assigning/cloning nodes (connected, not connected)
// ----
// add valid:
// - first, in the middle, last
// - elem, text/XText (concatenation), PI, Comment - for XE
// - elem (just root), PI, Comment, XDecl/XDocType (order!)
// - on other node types
//[Variation(Priority = 1, Desc = "Adding multiple (4) objects into XElement - not connected", Params = new object[] { false, 4 })]
//[Variation(Priority = 1, Desc = "Adding multiple (4) objects into XElement - connected", Params = new object[] { true, 4 })]
//[Variation(Priority = 1, Desc = "Adding single object into XElement - not connected", Params = new object[] { false, 1 })]
//[Variation(Priority = 1, Desc = "Adding single object into XElement - connected", Params = new object[] { true, 1 })]
public void AddingMultipleNodesIntoElement()
{
AddingMultipleNodesIntoElement(delegate(XNode n, object[] content) { n.AddAfterSelf(content); }, CalculateExpectedValuesAddAfter);
}
public IEnumerable<ExpectedValue> CalculateExpectedValuesAddAfter(XContainer orig, int startPos, IEnumerable<object> newNodes)
{
int counter = 0;
for (XNode node = orig.FirstNode; node != null; node = node.NextNode, counter++)
{
yield return new ExpectedValue(!(node is XText), node); // Don't build on the text node identity
if (counter == startPos)
{
foreach (object o in newNodes)
{
yield return new ExpectedValue(o is XNode && (o as XNode).Parent == null && (o as XNode).Document == null, o);
}
}
}
}
//[Variation(Priority = 2, Desc = "Invalid node types - single object")]
// XDocument constraints:
// - only one DTD, DTD is first (before elem)
// - only one root element
// - no CDATA,
// - no Attribute
// - no no text (except whitespace)
//[Variation(Priority = 1, Desc = "XDocument invalid add - double DTD")]
public void InvalidAddIntoXDocument1()
{
runWithEvents = (bool)Params[0];
try
{
var doc = new XDocument(new XDocumentType("root", null, null, null), new XElement("A"));
var o = new XDocumentType("D", null, null, null);
if (runWithEvents)
{
eHelper = new EventsHelper(doc);
}
doc.FirstNode.AddAfterSelf(o);
if (runWithEvents)
{
eHelper.Verify(XObjectChange.Add, o);
}
TestLog.Compare(false, "Exception expected");
}
catch (InvalidOperationException)
{
}
}
//[Variation(Priority = 1, Desc = "XDocument invalid add - DTD after element")]
public void InvalidAddIntoXDocument2()
{
runWithEvents = (bool)Params[0];
try
{
var doc = new XDocument(new XElement("A"));
var o = new XDocumentType("D", null, null, null);
if (runWithEvents)
{
eHelper = new EventsHelper(doc);
}
doc.FirstNode.AddAfterSelf(o);
if (runWithEvents)
{
eHelper.Verify(XObjectChange.Add, o);
}
TestLog.Compare(false, "Exception expected");
}
catch (InvalidOperationException)
{
}
}
//[Variation(Priority = 1, Desc = "XDocument invalid add - multiple root elements")]
public void InvalidAddIntoXDocument4()
{
runWithEvents = (bool)Params[0];
try
{
var doc = new XDocument(new XElement("A"));
var o = new XElement("C");
if (runWithEvents)
{
eHelper = new EventsHelper(doc);
}
doc.FirstNode.AddAfterSelf(o);
if (runWithEvents)
{
eHelper.Verify(XObjectChange.Add, o);
}
TestLog.Compare(false, "Exception expected");
}
catch (InvalidOperationException)
{
}
}
//[Variation(Priority = 1, Desc = "XDocument invalid add - CData, attribute, text (no whitespace)")]
public void InvalidAddIntoXDocument5()
{
runWithEvents = (bool)Params[0];
foreach (object o in new object[] { new XCData("CD"), new XAttribute("a1", "avalue"), "text1", new XText("text2"), new XDocument() })
{
try
{
var doc = new XDocument(new XElement("A"));
if (runWithEvents)
{
eHelper = new EventsHelper(doc);
}
doc.FirstNode.AddAfterSelf(o);
if (runWithEvents)
{
eHelper.Verify(XObjectChange.Add, o);
}
TestLog.Compare(false, "Exception expected");
}
catch (ArgumentException)
{
}
}
}
public void InvalidNodeTypes()
{
runWithEvents = (bool)Params[0];
var root = new XElement("root", new XAttribute("a", "b"), new XElement("here"), "tests");
var rootCopy = new XElement(root);
XElement elem = root.Element("here");
object[] nodes = { new XAttribute("xx", "yy"), new XDocument(),
new XDocumentType("root", null, null, null) };
if (runWithEvents)
{
eHelper = new EventsHelper(elem);
}
foreach (object o in nodes)
{
try
{
elem.AddAfterSelf(o);
if (runWithEvents)
{
eHelper.Verify(XObjectChange.Add, o);
}
TestLog.Compare(false, "Should fail!");
}
catch (Exception)
{
TestLog.Compare(XNode.DeepEquals(root, rootCopy), "root.Equals(rootCopy)");
}
}
}
//[Variation(Priority = 0, Desc = "XDocument valid add - connected (single)", Params = new object[] { true, 1 })]
//[Variation(Priority = 0, Desc = "XDocument valid add - not connected (single)", Params = new object[] { false, 1 })]
//[Variation(Priority = 1, Desc = "XDocument valid add - connected (multiple)", Params = new object[] { true, 3 })]
//[Variation(Priority = 1, Desc = "XDocument valid add - not connected (multiple)", Params = new object[] { false, 3 })]
public void ValidAddIntoXDocument()
{
ValidAddIntoXDocument(delegate(XNode n, object[] content) { n.AddAfterSelf(content); }, CalculateExpectedValuesAddAfter);
}
//[Variation(Priority = 1, Desc = "Working on the text nodes 1.")]
public void WorkOnTextNodes1()
{
runWithEvents = (bool)Params[0];
var elem = new XElement("A", new XElement("B"), "text0", new XElement("C"));
XNode n = elem.FirstNode.NextNode;
if (runWithEvents)
{
eHelper = new EventsHelper(elem);
}
n.AddAfterSelf("text1");
n.AddAfterSelf("text2");
if (runWithEvents)
{
eHelper.Verify(new[] { XObjectChange.Value, XObjectChange.Value });
}
TestLog.Compare(elem.Nodes().Count(), 3, "elem.Nodes().Count(), 3");
TestLog.Compare((n as XText).Value, "text0text1text2", "(n as XText).Value, text0text1text2");
}
//[Variation(Priority = 1, Desc = "Working on the text nodes 2.")]
public void WorkOnTextNodes2()
{
runWithEvents = (bool)Params[0];
var elem = new XElement("A", new XElement("B"), "text0", new XElement("C"));
XNode n = elem.FirstNode.NextNode;
if (runWithEvents)
{
eHelper = new EventsHelper(elem);
}
n.AddAfterSelf("text1", "text2");
if (runWithEvents)
{
eHelper.Verify(XObjectChange.Value);
}
TestLog.Compare(elem.Nodes().Count(), 3, "elem.Nodes().Count(), 3");
TestLog.Compare((n as XText).Value, "text0text1text2", "(n as XText).Value, text0text1text2");
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Xml;
using Nini.Config;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Data;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Hypergrid;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
namespace OpenSim.Services.GridService
{
public class HypergridLinker
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private static uint m_autoMappingX = 0;
private static uint m_autoMappingY = 0;
private static bool m_enableAutoMapping = false;
protected IRegionData m_Database;
protected GridService m_GridService;
protected IAssetService m_AssetService;
protected GatekeeperServiceConnector m_GatekeeperConnector;
protected UUID m_ScopeID = UUID.Zero;
// protected bool m_Check4096 = true;
protected string m_MapTileDirectory = string.Empty;
protected string m_ThisGatekeeper = string.Empty;
protected Uri m_ThisGatekeeperURI = null;
protected GridRegion m_DefaultRegion;
protected GridRegion DefaultRegion
{
get
{
if (m_DefaultRegion == null)
{
List<GridRegion> defs = m_GridService.GetDefaultHypergridRegions(m_ScopeID);
if (defs != null && defs.Count > 0)
m_DefaultRegion = defs[0];
else
{
// Get any region
defs = m_GridService.GetRegionsByName(m_ScopeID, "", 1);
if (defs != null && defs.Count > 0)
m_DefaultRegion = defs[0];
else
{
// This shouldn't happen
m_DefaultRegion = new GridRegion(1000, 1000);
m_log.Error("[HYPERGRID LINKER]: Something is wrong with this grid. It has no regions?");
}
}
}
return m_DefaultRegion;
}
}
public HypergridLinker(IConfigSource config, GridService gridService, IRegionData db)
{
IConfig gridConfig = config.Configs["GridService"];
if (gridConfig == null)
return;
if (!gridConfig.GetBoolean("HypergridLinker", false))
return;
m_Database = db;
m_GridService = gridService;
m_log.DebugFormat("[HYPERGRID LINKER]: Starting with db {0}", db.GetType());
string assetService = gridConfig.GetString("AssetService", string.Empty);
Object[] args = new Object[] { config };
if (assetService != string.Empty)
m_AssetService = ServerUtils.LoadPlugin<IAssetService>(assetService, args);
string scope = gridConfig.GetString("ScopeID", string.Empty);
if (scope != string.Empty)
UUID.TryParse(scope, out m_ScopeID);
// m_Check4096 = gridConfig.GetBoolean("Check4096", true);
m_MapTileDirectory = gridConfig.GetString("MapTileDirectory", "maptiles");
m_ThisGatekeeper = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI",
new string[] { "Startup", "Hypergrid", "GridService" }, String.Empty);
// Legacy. Remove soon!
m_ThisGatekeeper = gridConfig.GetString("Gatekeeper", m_ThisGatekeeper);
try
{
m_ThisGatekeeperURI = new Uri(m_ThisGatekeeper);
}
catch
{
m_log.WarnFormat("[HYPERGRID LINKER]: Malformed URL in [GridService], variable Gatekeeper = {0}", m_ThisGatekeeper);
}
m_GatekeeperConnector = new GatekeeperServiceConnector(m_AssetService);
m_log.Debug("[HYPERGRID LINKER]: Loaded all services...");
if (!string.IsNullOrEmpty(m_MapTileDirectory))
{
try
{
Directory.CreateDirectory(m_MapTileDirectory);
}
catch (Exception e)
{
m_log.WarnFormat("[HYPERGRID LINKER]: Could not create map tile storage directory {0}: {1}", m_MapTileDirectory, e);
m_MapTileDirectory = string.Empty;
}
}
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "link-region",
"link-region <Xloc> <Yloc> <ServerURI> [<RemoteRegionName>]",
"Link a HyperGrid Region. Examples for <ServerURI>: http://grid.net:8002/ or http://example.org/path/foo.php", RunCommand);
MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "link-region",
"link-region <Xloc> <Yloc> <RegionIP> <RegionPort> [<RemoteRegionName>]",
"Link a hypergrid region (deprecated)", RunCommand);
MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "unlink-region",
"unlink-region <local name>",
"Unlink a hypergrid region", RunCommand);
MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "link-mapping", "link-mapping [<x> <y>]",
"Set local coordinate to map HG regions to", RunCommand);
MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "show hyperlinks", "show hyperlinks",
"List the HG regions", HandleShow);
}
}
#region Link Region
// from map search
public GridRegion LinkRegion(UUID scopeID, string regionDescriptor)
{
string reason = string.Empty;
uint xloc = Util.RegionToWorldLoc((uint)random.Next(0, Int16.MaxValue));
return TryLinkRegionToCoords(scopeID, regionDescriptor, (int)xloc, 0, out reason);
}
private static Random random = new Random();
// From the command line link-region (obsolete) and the map
public GridRegion TryLinkRegionToCoords(UUID scopeID, string mapName, int xloc, int yloc, out string reason)
{
return TryLinkRegionToCoords(scopeID, mapName, xloc, yloc, UUID.Zero, out reason);
}
public GridRegion TryLinkRegionToCoords(UUID scopeID, string mapName, int xloc, int yloc, UUID ownerID, out string reason)
{
reason = string.Empty;
GridRegion regInfo = null;
mapName = mapName.Trim();
if (!mapName.StartsWith("http"))
{
// Formats: grid.example.com:8002:region name
// grid.example.com:region name
// grid.example.com:8002
// grid.example.com
string host;
uint port = 80;
string regionName = "";
string[] parts = mapName.Split(new char[] { ':' });
if (parts.Length == 0)
{
reason = "Wrong format for link-region";
return null;
}
host = parts[0];
if (parts.Length >= 2)
{
// If it's a number then assume it's a port. Otherwise, it's a region name.
if (!UInt32.TryParse(parts[1], out port))
regionName = parts[1];
}
// always take the last one
if (parts.Length >= 3)
{
regionName = parts[2];
}
bool success = TryCreateLink(scopeID, xloc, yloc, regionName, port, host, ownerID, out regInfo, out reason);
if (success)
{
regInfo.RegionName = mapName;
return regInfo;
}
}
else
{
// Formats: http://grid.example.com region name
// http://grid.example.com "region name"
// http://grid.example.com
string serverURI;
string regionName = "";
string[] parts = mapName.Split(new char[] { ' ' });
if (parts.Length == 0)
{
reason = "Wrong format for link-region";
return null;
}
serverURI = parts[0];
if (parts.Length >= 2)
{
regionName = mapName.Substring(serverURI.Length);
regionName = regionName.Trim(new char[] { '"', ' ' });
}
if (TryCreateLink(scopeID, xloc, yloc, regionName, 0, null, serverURI, ownerID, out regInfo, out reason))
{
regInfo.RegionName = mapName;
return regInfo;
}
}
return null;
}
public bool TryCreateLink(UUID scopeID, int xloc, int yloc, string remoteRegionName, uint externalPort, string externalHostName, UUID ownerID, out GridRegion regInfo, out string reason)
{
return TryCreateLink(scopeID, xloc, yloc, remoteRegionName, externalPort, externalHostName, null, ownerID, out regInfo, out reason);
}
public bool TryCreateLink(UUID scopeID, int xloc, int yloc, string remoteRegionName, uint externalPort, string externalHostName, string serverURI, UUID ownerID, out GridRegion regInfo, out string reason)
{
m_log.InfoFormat("[HYPERGRID LINKER]: Link to {0} {1}, in {2}-{3}",
((serverURI == null) ? (externalHostName + ":" + externalPort) : serverURI),
remoteRegionName, Util.WorldToRegionLoc((uint)xloc), Util.WorldToRegionLoc((uint)yloc));
reason = string.Empty;
Uri uri = null;
regInfo = new GridRegion();
if (externalPort > 0)
regInfo.HttpPort = externalPort;
else
regInfo.HttpPort = 80;
if (externalHostName != null)
regInfo.ExternalHostName = externalHostName;
else
regInfo.ExternalHostName = "0.0.0.0";
if (serverURI != null)
{
regInfo.ServerURI = serverURI;
try
{
uri = new Uri(serverURI);
regInfo.ExternalHostName = uri.Host;
regInfo.HttpPort = (uint)uri.Port;
}
catch {}
}
if (remoteRegionName != string.Empty)
regInfo.RegionName = remoteRegionName;
regInfo.RegionLocX = xloc;
regInfo.RegionLocY = yloc;
regInfo.ScopeID = scopeID;
regInfo.EstateOwner = ownerID;
// Make sure we're not hyperlinking to regions on this grid!
if (m_ThisGatekeeperURI != null)
{
if (regInfo.ExternalHostName == m_ThisGatekeeperURI.Host && regInfo.HttpPort == m_ThisGatekeeperURI.Port)
{
m_log.InfoFormat("[HYPERGRID LINKER]: Cannot hyperlink to regions on the same grid");
reason = "Cannot hyperlink to regions on the same grid";
return false;
}
}
else
m_log.WarnFormat("[HYPERGRID LINKER]: Please set this grid's Gatekeeper's address in [GridService]!");
// Check for free coordinates
GridRegion region = m_GridService.GetRegionByPosition(regInfo.ScopeID, regInfo.RegionLocX, regInfo.RegionLocY);
if (region != null)
{
m_log.WarnFormat("[HYPERGRID LINKER]: Coordinates {0}-{1} are already occupied by region {2} with uuid {3}",
Util.WorldToRegionLoc((uint)regInfo.RegionLocX), Util.WorldToRegionLoc((uint)regInfo.RegionLocY),
region.RegionName, region.RegionID);
reason = "Coordinates are already in use";
return false;
}
try
{
regInfo.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), (int)0);
}
catch (Exception e)
{
m_log.Warn("[HYPERGRID LINKER]: Wrong format for link-region: " + e.Message);
reason = "Internal error";
return false;
}
// Finally, link it
ulong handle = 0;
UUID regionID = UUID.Zero;
string externalName = string.Empty;
string imageURL = string.Empty;
if (!m_GatekeeperConnector.LinkRegion(regInfo, out regionID, out handle, out externalName, out imageURL, out reason))
return false;
if (regionID == UUID.Zero)
{
m_log.Warn("[HYPERGRID LINKER]: Unable to link region");
reason = "Remote region could not be found";
return false;
}
region = m_GridService.GetRegionByUUID(scopeID, regionID);
if (region != null)
{
m_log.DebugFormat("[HYPERGRID LINKER]: Region already exists in coordinates {0} {1}",
Util.WorldToRegionLoc((uint)regInfo.RegionLocX), Util.WorldToRegionLoc((uint)regInfo.RegionLocY));
regInfo = region;
return true;
}
// We are now performing this check for each individual teleport in the EntityTransferModule instead. This
// allows us to give better feedback when teleports fail because of the distance reason (which can't be
// done here) and it also hypergrid teleports that are within range (possibly because the source grid
// itself has regions that are very far apart).
// uint x, y;
// if (m_Check4096 && !Check4096(handle, out x, out y))
// {
// //RemoveHyperlinkRegion(regInfo.RegionID);
// reason = "Region is too far (" + x + ", " + y + ")";
// m_log.Info("[HYPERGRID LINKER]: Unable to link, region is too far (" + x + ", " + y + ")");
// //return false;
// }
regInfo.RegionID = regionID;
if (externalName == string.Empty)
regInfo.RegionName = regInfo.ServerURI;
else
regInfo.RegionName = externalName;
m_log.DebugFormat("[HYPERGRID LINKER]: naming linked region {0}, handle {1}", regInfo.RegionName, handle.ToString());
// Get the map image
regInfo.TerrainImage = GetMapImage(regionID, imageURL);
// Store the origin's coordinates somewhere
regInfo.RegionSecret = handle.ToString();
AddHyperlinkRegion(regInfo, handle);
m_log.InfoFormat("[HYPERGRID LINKER]: Successfully linked to region {0} with image {1}", regInfo.RegionName, regInfo.TerrainImage);
return true;
}
public bool TryUnlinkRegion(string mapName)
{
m_log.DebugFormat("[HYPERGRID LINKER]: Request to unlink {0}", mapName);
GridRegion regInfo = null;
List<RegionData> regions = m_Database.Get(Util.EscapeForLike(mapName), m_ScopeID);
if (regions != null && regions.Count > 0)
{
OpenSim.Framework.RegionFlags rflags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(regions[0].Data["flags"]);
if ((rflags & OpenSim.Framework.RegionFlags.Hyperlink) != 0)
{
regInfo = new GridRegion();
regInfo.RegionID = regions[0].RegionID;
regInfo.ScopeID = m_ScopeID;
}
}
if (regInfo != null)
{
RemoveHyperlinkRegion(regInfo.RegionID);
return true;
}
else
{
m_log.InfoFormat("[HYPERGRID LINKER]: Region {0} not found", mapName);
return false;
}
}
// Not currently used
// /// <summary>
// /// Cope with this viewer limitation.
// /// </summary>
// /// <param name="regInfo"></param>
// /// <returns></returns>
// public bool Check4096(ulong realHandle, out uint x, out uint y)
// {
// uint ux = 0, uy = 0;
// Utils.LongToUInts(realHandle, out ux, out uy);
// x = Util.WorldToRegionLoc(ux);
// y = Util.WorldToRegionLoc(uy);
//
// const uint limit = Util.RegionToWorldLoc(4096 - 1);
// uint xmin = ux - limit;
// uint xmax = ux + limit;
// uint ymin = uy - limit;
// uint ymax = uy + limit;
// // World map boundary checks
// if (xmin < 0 || xmin > ux)
// xmin = 0;
// if (xmax > int.MaxValue || xmax < ux)
// xmax = int.MaxValue;
// if (ymin < 0 || ymin > uy)
// ymin = 0;
// if (ymax > int.MaxValue || ymax < uy)
// ymax = int.MaxValue;
//
// // Check for any regions that are within the possible teleport range to the linked region
// List<GridRegion> regions = m_GridService.GetRegionRange(m_ScopeID, (int)xmin, (int)xmax, (int)ymin, (int)ymax);
// if (regions.Count == 0)
// {
// return false;
// }
// else
// {
// // Check for regions which are not linked regions
// List<GridRegion> hyperlinks = m_GridService.GetHyperlinks(m_ScopeID);
// IEnumerable<GridRegion> availableRegions = regions.Except(hyperlinks);
// if (availableRegions.Count() == 0)
// return false;
// }
//
// return true;
// }
private void AddHyperlinkRegion(GridRegion regionInfo, ulong regionHandle)
{
RegionData rdata = m_GridService.RegionInfo2RegionData(regionInfo);
int flags = (int)OpenSim.Framework.RegionFlags.Hyperlink + (int)OpenSim.Framework.RegionFlags.NoDirectLogin + (int)OpenSim.Framework.RegionFlags.RegionOnline;
rdata.Data["flags"] = flags.ToString();
m_Database.Store(rdata);
}
private void RemoveHyperlinkRegion(UUID regionID)
{
m_Database.Delete(regionID);
}
public UUID GetMapImage(UUID regionID, string imageURL)
{
return m_GatekeeperConnector.GetMapImage(regionID, imageURL, m_MapTileDirectory);
}
#endregion
#region Console Commands
public void HandleShow(string module, string[] cmd)
{
if (cmd.Length != 2)
{
MainConsole.Instance.Output("Syntax: show hyperlinks");
return;
}
List<RegionData> regions = m_Database.GetHyperlinks(UUID.Zero);
if (regions == null || regions.Count < 1)
{
MainConsole.Instance.Output("No hyperlinks");
return;
}
MainConsole.Instance.Output("Region Name");
MainConsole.Instance.Output("Location Region UUID");
MainConsole.Instance.Output(new string('-', 72));
foreach (RegionData r in regions)
{
MainConsole.Instance.Output(
String.Format("{0}\n{2,-32} {1}\n",
r.RegionName, r.RegionID,
String.Format("{0},{1} ({2},{3})", r.posX, r.posY,
Util.WorldToRegionLoc((uint)r.posX), Util.WorldToRegionLoc((uint)r.posY)
)
)
);
}
return;
}
public void RunCommand(string module, string[] cmdparams)
{
List<string> args = new List<string>(cmdparams);
if (args.Count < 1)
return;
string command = args[0];
args.RemoveAt(0);
cmdparams = args.ToArray();
RunHGCommand(command, cmdparams);
}
private void RunLinkRegionCommand(string[] cmdparams)
{
int xloc, yloc;
string serverURI;
string remoteName = null;
xloc = (int)Util.RegionToWorldLoc((uint)Convert.ToInt32(cmdparams[0]));
yloc = (int)Util.RegionToWorldLoc((uint)Convert.ToInt32(cmdparams[1]));
serverURI = cmdparams[2];
if (cmdparams.Length > 3)
remoteName = string.Join(" ", cmdparams, 3, cmdparams.Length - 3);
string reason = string.Empty;
GridRegion regInfo;
if (TryCreateLink(UUID.Zero, xloc, yloc, remoteName, 0, null, serverURI, UUID.Zero, out regInfo, out reason))
MainConsole.Instance.Output("Hyperlink established");
else
MainConsole.Instance.Output("Failed to link region: " + reason);
}
private void RunHGCommand(string command, string[] cmdparams)
{
if (command.Equals("link-mapping"))
{
if (cmdparams.Length == 2)
{
try
{
m_autoMappingX = Convert.ToUInt32(cmdparams[0]);
m_autoMappingY = Convert.ToUInt32(cmdparams[1]);
m_enableAutoMapping = true;
}
catch (Exception)
{
m_autoMappingX = 0;
m_autoMappingY = 0;
m_enableAutoMapping = false;
}
}
}
else if (command.Equals("link-region"))
{
if (cmdparams.Length < 3)
{
if ((cmdparams.Length == 1) || (cmdparams.Length == 2))
{
LoadXmlLinkFile(cmdparams);
}
else
{
LinkRegionCmdUsage();
}
return;
}
//this should be the prefererred way of setting up hg links now
if (cmdparams[2].StartsWith("http"))
{
RunLinkRegionCommand(cmdparams);
}
else if (cmdparams[2].Contains(":"))
{
// New format
string[] parts = cmdparams[2].Split(':');
if (parts.Length > 2)
{
// Insert remote region name
ArrayList parameters = new ArrayList(cmdparams);
parameters.Insert(3, parts[2]);
cmdparams = (string[])parameters.ToArray(typeof(string));
}
cmdparams[2] = "http://" + parts[0] + ':' + parts[1];
RunLinkRegionCommand(cmdparams);
}
else
{
// old format
GridRegion regInfo;
uint xloc, yloc;
uint externalPort;
string externalHostName;
try
{
xloc = Convert.ToUInt32(cmdparams[0]);
yloc = Convert.ToUInt32(cmdparams[1]);
externalPort = Convert.ToUInt32(cmdparams[3]);
externalHostName = cmdparams[2];
//internalPort = Convert.ToUInt32(cmdparams[4]);
//remotingPort = Convert.ToUInt32(cmdparams[5]);
}
catch (Exception e)
{
MainConsole.Instance.Output("[HGrid] Wrong format for link-region command: " + e.Message);
LinkRegionCmdUsage();
return;
}
// Convert cell coordinates given by the user to meters
xloc = Util.RegionToWorldLoc(xloc);
yloc = Util.RegionToWorldLoc(yloc);
string reason = string.Empty;
if (TryCreateLink(UUID.Zero, (int)xloc, (int)yloc,
string.Empty, externalPort, externalHostName, UUID.Zero, out regInfo, out reason))
{
// What is this? The GridRegion instance will be discarded anyway,
// which effectively ignores any local name given with the command.
//if (cmdparams.Length >= 5)
//{
// regInfo.RegionName = "";
// for (int i = 4; i < cmdparams.Length; i++)
// regInfo.RegionName += cmdparams[i] + " ";
//}
}
}
return;
}
else if (command.Equals("unlink-region"))
{
if (cmdparams.Length < 1)
{
UnlinkRegionCmdUsage();
return;
}
string region = string.Join(" ", cmdparams);
if (TryUnlinkRegion(region))
MainConsole.Instance.Output("Successfully unlinked " + region);
else
MainConsole.Instance.Output("Unable to unlink " + region + ", region not found.");
}
}
private void LoadXmlLinkFile(string[] cmdparams)
{
//use http://www.hgurl.com/hypergrid.xml for test
try
{
XmlReader r = XmlReader.Create(cmdparams[0]);
XmlConfigSource cs = new XmlConfigSource(r);
string[] excludeSections = null;
if (cmdparams.Length == 2)
{
if (cmdparams[1].ToLower().StartsWith("excludelist:"))
{
string excludeString = cmdparams[1].ToLower();
excludeString = excludeString.Remove(0, 12);
char[] splitter = { ';' };
excludeSections = excludeString.Split(splitter);
}
}
for (int i = 0; i < cs.Configs.Count; i++)
{
bool skip = false;
if ((excludeSections != null) && (excludeSections.Length > 0))
{
for (int n = 0; n < excludeSections.Length; n++)
{
if (excludeSections[n] == cs.Configs[i].Name.ToLower())
{
skip = true;
break;
}
}
}
if (!skip)
{
ReadLinkFromConfig(cs.Configs[i]);
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
private void ReadLinkFromConfig(IConfig config)
{
GridRegion regInfo;
uint xloc, yloc;
uint externalPort;
string externalHostName;
uint realXLoc, realYLoc;
xloc = Convert.ToUInt32(config.GetString("xloc", "0"));
yloc = Convert.ToUInt32(config.GetString("yloc", "0"));
externalPort = Convert.ToUInt32(config.GetString("externalPort", "0"));
externalHostName = config.GetString("externalHostName", "");
realXLoc = Convert.ToUInt32(config.GetString("real-xloc", "0"));
realYLoc = Convert.ToUInt32(config.GetString("real-yloc", "0"));
if (m_enableAutoMapping)
{
xloc = (xloc % 100) + m_autoMappingX;
yloc = (yloc % 100) + m_autoMappingY;
}
if (((realXLoc == 0) && (realYLoc == 0)) ||
(((realXLoc - xloc < 3896) || (xloc - realXLoc < 3896)) &&
((realYLoc - yloc < 3896) || (yloc - realYLoc < 3896))))
{
xloc = Util.RegionToWorldLoc(xloc);
yloc = Util.RegionToWorldLoc(yloc);
string reason = string.Empty;
if (TryCreateLink(UUID.Zero, (int)xloc, (int)yloc,
string.Empty, externalPort, externalHostName, UUID.Zero, out regInfo, out reason))
{
regInfo.RegionName = config.GetString("localName", "");
}
else
MainConsole.Instance.Output("Unable to link " + externalHostName + ": " + reason);
}
}
private void LinkRegionCmdUsage()
{
MainConsole.Instance.Output("Usage: link-region <Xloc> <Yloc> <ServerURI> [<RemoteRegionName>]");
MainConsole.Instance.Output("Usage (deprecated): link-region <Xloc> <Yloc> <HostName>:<HttpPort>[:<RemoteRegionName>]");
MainConsole.Instance.Output("Usage (deprecated): link-region <Xloc> <Yloc> <HostName> <HttpPort> [<LocalName>]");
MainConsole.Instance.Output("Usage: link-region <URI_of_xml> [<exclude>]");
}
private void UnlinkRegionCmdUsage()
{
MainConsole.Instance.Output("Usage: unlink-region <LocalName>");
}
#endregion
}
}
| |
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using EasyNetQ.Logging;
using EasyNetQ.SystemMessages;
using RabbitMQ.Client;
using RabbitMQ.Client.Exceptions;
using System.Threading;
using System.Threading.Tasks;
namespace EasyNetQ.Consumer;
/// <summary>
/// A strategy for dealing with failed messages. When a message consumer throws, HandleConsumerError is invoked.
///
/// The general principle is to put all failed messages in a dedicated error queue so that they can be
/// examined and retried (or ignored).
///
/// Each failed message is wrapped in a special system message, 'Error' and routed by a special exchange
/// named after the original message's routing key. This is so that ad-hoc queues can be attached for
/// errors on specific message types.
///
/// Each exchange is bound to the central EasyNetQ error queue.
/// </summary>
public class DefaultConsumerErrorStrategy : IConsumerErrorStrategy
{
private readonly ILogger<DefaultConsumerErrorStrategy> logger;
private readonly IConsumerConnection connection;
private readonly IConventions conventions;
private readonly IErrorMessageSerializer errorMessageSerializer;
private readonly ConcurrentDictionary<string, object> existingErrorExchangesWithQueues = new();
private readonly ISerializer serializer;
private readonly ITypeNameSerializer typeNameSerializer;
private readonly ConnectionConfiguration configuration;
private volatile bool disposed;
/// <summary>
/// Creates DefaultConsumerErrorStrategy
/// </summary>
public DefaultConsumerErrorStrategy(
ILogger<DefaultConsumerErrorStrategy> logger,
IConsumerConnection connection,
ISerializer serializer,
IConventions conventions,
ITypeNameSerializer typeNameSerializer,
IErrorMessageSerializer errorMessageSerializer,
ConnectionConfiguration configuration
)
{
Preconditions.CheckNotNull(connection, nameof(connection));
Preconditions.CheckNotNull(serializer, nameof(serializer));
Preconditions.CheckNotNull(conventions, nameof(conventions));
Preconditions.CheckNotNull(typeNameSerializer, nameof(typeNameSerializer));
Preconditions.CheckNotNull(errorMessageSerializer, nameof(errorMessageSerializer));
Preconditions.CheckNotNull(configuration, nameof(configuration));
this.logger = logger;
this.connection = connection;
this.serializer = serializer;
this.conventions = conventions;
this.typeNameSerializer = typeNameSerializer;
this.errorMessageSerializer = errorMessageSerializer;
this.configuration = configuration;
}
/// <inheritdoc />
public virtual Task<AckStrategy> HandleConsumerErrorAsync(ConsumerExecutionContext context, Exception exception, CancellationToken cancellationToken)
{
Preconditions.CheckNotNull(context, nameof(context));
Preconditions.CheckNotNull(exception, nameof(exception));
if (disposed)
throw new ObjectDisposedException(nameof(DefaultConsumerErrorStrategy));
var receivedInfo = context.ReceivedInfo;
var properties = context.Properties;
var body = context.Body.ToArray();
logger.Error(
exception,
"Exception thrown by subscription callback, receivedInfo={receivedInfo}, properties={properties}, message={message}",
receivedInfo,
properties,
Convert.ToBase64String(body)
);
try
{
using var model = connection.CreateModel();
if (configuration.PublisherConfirms) model.ConfirmSelect();
var errorExchange = DeclareErrorExchangeWithQueue(model, receivedInfo);
using var message = CreateErrorMessage(receivedInfo, properties, body, exception);
var errorProperties = model.CreateBasicProperties();
errorProperties.Persistent = true;
errorProperties.Type = typeNameSerializer.Serialize(typeof(Error));
model.BasicPublish(errorExchange, receivedInfo.RoutingKey, errorProperties, message.Memory);
if (!configuration.PublisherConfirms) return Task.FromResult(AckStrategies.Ack);
return Task.FromResult(model.WaitForConfirms(configuration.Timeout) ? AckStrategies.Ack : AckStrategies.NackWithRequeue);
}
catch (BrokerUnreachableException unreachableException)
{
// thrown if the broker is unreachable during initial creation.
logger.Error(
unreachableException,
"Cannot connect to broker while attempting to publish error message"
);
}
catch (OperationInterruptedException interruptedException)
{
// thrown if the broker connection is broken during declare or publish.
logger.Error(
interruptedException,
"Broker connection was closed while attempting to publish error message"
);
}
catch (Exception unexpectedException)
{
// Something else unexpected has gone wrong :(
logger.Error(unexpectedException, "Failed to publish error message");
}
return Task.FromResult(AckStrategies.NackWithRequeue);
}
/// <inheritdoc />
public virtual Task<AckStrategy> HandleConsumerCancelledAsync(ConsumerExecutionContext context, CancellationToken cancellationToken)
{
return Task.FromResult(AckStrategies.NackWithRequeue);
}
/// <inheritdoc />
public virtual void Dispose()
{
if (disposed) return;
disposed = true;
}
private static void DeclareAndBindErrorExchangeWithErrorQueue(IModel model, string exchangeName, string queueName, string routingKey)
{
model.QueueDeclare(queueName, true, false, false, null);
model.ExchangeDeclare(exchangeName, ExchangeType.Direct, true);
model.QueueBind(queueName, exchangeName, routingKey);
}
private string DeclareErrorExchangeWithQueue(IModel model, MessageReceivedInfo receivedInfo)
{
var errorExchangeName = conventions.ErrorExchangeNamingConvention(receivedInfo);
var errorQueueName = conventions.ErrorQueueNamingConvention(receivedInfo);
var routingKey = receivedInfo.RoutingKey;
var errorTopologyIdentifier = $"{errorExchangeName}-{errorQueueName}-{routingKey}";
existingErrorExchangesWithQueues.GetOrAdd(errorTopologyIdentifier, _ =>
{
DeclareAndBindErrorExchangeWithErrorQueue(model, errorExchangeName, errorQueueName, routingKey);
return null;
});
return errorExchangeName;
}
private IMemoryOwner<byte> CreateErrorMessage(
MessageReceivedInfo receivedInfo, MessageProperties properties, byte[] body, Exception exception
)
{
var messageAsString = errorMessageSerializer.Serialize(body);
var error = new Error
{
RoutingKey = receivedInfo.RoutingKey,
Exchange = receivedInfo.Exchange,
Queue = receivedInfo.Queue,
Exception = exception.ToString(),
Message = messageAsString,
DateTime = DateTime.UtcNow
};
if (properties.Headers == null)
{
error.BasicProperties = properties;
}
else
{
// we'll need to clone context.Properties as we are mutating the headers dictionary
error.BasicProperties = (MessageProperties)properties.Clone();
// the RabbitMQClient implicitly converts strings to byte[] on sending, but reads them back as byte[]
// we're making the assumption here that any byte[] values in the headers are strings
// and all others are basic types. RabbitMq client generally throws a nasty exception if you try
// to store anything other than basic types in headers anyway.
//see http://hg.rabbitmq.com/rabbitmq-dotnet-client/file/tip/projects/client/RabbitMQ.Client/src/client/impl/WireFormatting.cs
error.BasicProperties.Headers = properties.Headers.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value is byte[] bytes ? Encoding.UTF8.GetString(bytes) : kvp.Value
);
}
return serializer.MessageToBytes(typeof(Error), error);
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using DiscUtils.Internal;
using DiscUtils.Streams;
namespace DiscUtils.Partitions
{
/// <summary>
/// Represents a GUID Partition Table.
/// </summary>
public sealed class GuidPartitionTable : PartitionTable
{
private Stream _diskData;
private Geometry _diskGeometry;
private byte[] _entryBuffer;
private GptHeader _primaryHeader;
private GptHeader _secondaryHeader;
/// <summary>
/// Initializes a new instance of the GuidPartitionTable class.
/// </summary>
/// <param name="disk">The disk containing the partition table.</param>
public GuidPartitionTable(VirtualDisk disk)
{
Init(disk.Content, disk.Geometry);
}
/// <summary>
/// Initializes a new instance of the GuidPartitionTable class.
/// </summary>
/// <param name="disk">The stream containing the disk data.</param>
/// <param name="diskGeometry">The geometry of the disk.</param>
public GuidPartitionTable(Stream disk, Geometry diskGeometry)
{
Init(disk, diskGeometry);
}
/// <summary>
/// Gets the unique GPT identifier for this disk.
/// </summary>
public override Guid DiskGuid
{
get { return _primaryHeader.DiskGuid; }
}
/// <summary>
/// Gets the first sector of the disk available to hold partitions.
/// </summary>
public long FirstUsableSector
{
get { return _primaryHeader.FirstUsable; }
}
/// <summary>
/// Gets the last sector of the disk available to hold partitions.
/// </summary>
public long LastUsableSector
{
get { return _primaryHeader.LastUsable; }
}
/// <summary>
/// Gets a collection of the partitions for storing Operating System file-systems.
/// </summary>
public override ReadOnlyCollection<PartitionInfo> Partitions
{
get
{
return
new ReadOnlyCollection<PartitionInfo>(Utilities.Map(GetAllEntries(),
e => new GuidPartitionInfo(this, e)));
}
}
/// <summary>
/// Creates a new partition table on a disk.
/// </summary>
/// <param name="disk">The disk to initialize.</param>
/// <returns>An object to access the newly created partition table.</returns>
public static GuidPartitionTable Initialize(VirtualDisk disk)
{
return Initialize(disk.Content, disk.Geometry);
}
/// <summary>
/// Creates a new partition table on a disk.
/// </summary>
/// <param name="disk">The stream containing the disk data.</param>
/// <param name="diskGeometry">The geometry of the disk.</param>
/// <returns>An object to access the newly created partition table.</returns>
public static GuidPartitionTable Initialize(Stream disk, Geometry diskGeometry)
{
// Create the protective MBR partition record.
BiosPartitionTable pt = BiosPartitionTable.Initialize(disk, diskGeometry);
pt.CreatePrimaryByCylinder(0, diskGeometry.Cylinders - 1, BiosPartitionTypes.GptProtective, false);
// Create the GPT headers, and blank-out the entry areas
const int EntryCount = 128;
const int EntrySize = 128;
int entrySectors = (EntryCount * EntrySize + diskGeometry.BytesPerSector - 1) / diskGeometry.BytesPerSector;
byte[] entriesBuffer = new byte[EntryCount * EntrySize];
// Prepare primary header
GptHeader header = new GptHeader(diskGeometry.BytesPerSector);
header.HeaderLba = 1;
header.AlternateHeaderLba = disk.Length / diskGeometry.BytesPerSector - 1;
header.FirstUsable = header.HeaderLba + entrySectors + 1;
header.LastUsable = header.AlternateHeaderLba - entrySectors - 1;
header.DiskGuid = Guid.NewGuid();
header.PartitionEntriesLba = 2;
header.PartitionEntryCount = EntryCount;
header.PartitionEntrySize = EntrySize;
header.EntriesCrc = CalcEntriesCrc(entriesBuffer);
// Write the primary header
byte[] headerBuffer = new byte[diskGeometry.BytesPerSector];
header.WriteTo(headerBuffer, 0);
disk.Position = header.HeaderLba * diskGeometry.BytesPerSector;
disk.Write(headerBuffer, 0, headerBuffer.Length);
// Calc alternate header
header.HeaderLba = header.AlternateHeaderLba;
header.AlternateHeaderLba = 1;
header.PartitionEntriesLba = header.HeaderLba - entrySectors;
// Write the alternate header
header.WriteTo(headerBuffer, 0);
disk.Position = header.HeaderLba * diskGeometry.BytesPerSector;
disk.Write(headerBuffer, 0, headerBuffer.Length);
return new GuidPartitionTable(disk, diskGeometry);
}
/// <summary>
/// Creates a new partition table on a disk containing a single partition.
/// </summary>
/// <param name="disk">The disk to initialize.</param>
/// <param name="type">The partition type for the single partition.</param>
/// <returns>An object to access the newly created partition table.</returns>
public static GuidPartitionTable Initialize(VirtualDisk disk, WellKnownPartitionType type)
{
GuidPartitionTable pt = Initialize(disk);
pt.Create(type, true);
return pt;
}
/// <summary>
/// Creates a new partition that encompasses the entire disk.
/// </summary>
/// <param name="type">The partition type.</param>
/// <param name="active">Whether the partition is active (bootable).</param>
/// <returns>The index of the partition.</returns>
/// <remarks>The partition table must be empty before this method is called,
/// otherwise IOException is thrown.</remarks>
public override int Create(WellKnownPartitionType type, bool active)
{
List<GptEntry> allEntries = new List<GptEntry>(GetAllEntries());
EstablishReservedPartition(allEntries);
// Fill the rest of the disk with the requested partition
long start = FirstAvailableSector(allEntries);
long end = FindLastFreeSector(start, allEntries);
return Create(start, end, GuidPartitionTypes.Convert(type), 0, "Data Partition");
}
/// <summary>
/// Creates a new primary partition with a target size.
/// </summary>
/// <param name="size">The target size (in bytes).</param>
/// <param name="type">The partition type.</param>
/// <param name="active">Whether the partition is active (bootable).</param>
/// <returns>The index of the new partition.</returns>
public override int Create(long size, WellKnownPartitionType type, bool active)
{
if (size < _diskGeometry.BytesPerSector)
{
throw new ArgumentOutOfRangeException(nameof(size), size, "size must be at least one sector");
}
long sectorLength = size / _diskGeometry.BytesPerSector;
long start = FindGap(size / _diskGeometry.BytesPerSector, 1);
return Create(start, start + sectorLength - 1, GuidPartitionTypes.Convert(type), 0, "Data Partition");
}
/// <summary>
/// Creates a new aligned partition that encompasses the entire disk.
/// </summary>
/// <param name="type">The partition type.</param>
/// <param name="active">Whether the partition is active (bootable).</param>
/// <param name="alignment">The alignment (in bytes).</param>
/// <returns>The index of the partition.</returns>
/// <remarks>The partition table must be empty before this method is called,
/// otherwise IOException is thrown.</remarks>
/// <remarks>
/// Traditionally partitions were aligned to the physical structure of the underlying disk,
/// however with modern storage greater efficiency is acheived by aligning partitions on
/// large values that are a power of two.
/// </remarks>
public override int CreateAligned(WellKnownPartitionType type, bool active, int alignment)
{
if (alignment % _diskGeometry.BytesPerSector != 0)
{
throw new ArgumentException("Alignment is not a multiple of the sector size");
}
List<GptEntry> allEntries = new List<GptEntry>(GetAllEntries());
EstablishReservedPartition(allEntries);
// Fill the rest of the disk with the requested partition
long start = MathUtilities.RoundUp(FirstAvailableSector(allEntries), alignment / _diskGeometry.BytesPerSector);
long end = MathUtilities.RoundDown(FindLastFreeSector(start, allEntries) + 1,
alignment / _diskGeometry.BytesPerSector);
if (end <= start)
{
throw new IOException("No available space");
}
return Create(start, end - 1, GuidPartitionTypes.Convert(type), 0, "Data Partition");
}
/// <summary>
/// Creates a new aligned partition with a target size.
/// </summary>
/// <param name="size">The target size (in bytes).</param>
/// <param name="type">The partition type.</param>
/// <param name="active">Whether the partition is active (bootable).</param>
/// <param name="alignment">The alignment (in bytes).</param>
/// <returns>The index of the new partition.</returns>
/// <remarks>
/// Traditionally partitions were aligned to the physical structure of the underlying disk,
/// however with modern storage greater efficiency is achieved by aligning partitions on
/// large values that are a power of two.
/// </remarks>
public override int CreateAligned(long size, WellKnownPartitionType type, bool active, int alignment)
{
if (size < _diskGeometry.BytesPerSector)
{
throw new ArgumentOutOfRangeException(nameof(size), size, "size must be at least one sector");
}
if (alignment % _diskGeometry.BytesPerSector != 0)
{
throw new ArgumentException("Alignment is not a multiple of the sector size");
}
if (size % alignment != 0)
{
throw new ArgumentException("Size is not a multiple of the alignment");
}
long sectorLength = size / _diskGeometry.BytesPerSector;
long start = FindGap(size / _diskGeometry.BytesPerSector, alignment / _diskGeometry.BytesPerSector);
return Create(start, start + sectorLength - 1, GuidPartitionTypes.Convert(type), 0, "Data Partition");
}
/// <summary>
/// Creates a new GUID partition on the disk.
/// </summary>
/// <param name="startSector">The first sector of the partition.</param>
/// <param name="endSector">The last sector of the partition.</param>
/// <param name="type">The partition type.</param>
/// <param name="attributes">The partition attributes.</param>
/// <param name="name">The name of the partition.</param>
/// <returns>The index of the new partition.</returns>
/// <remarks>No checking is performed on the parameters, the caller is
/// responsible for ensuring that the partition does not overlap other partitions.</remarks>
public int Create(long startSector, long endSector, Guid type, long attributes, string name)
{
GptEntry newEntry = CreateEntry(startSector, endSector, type, attributes, name);
return GetEntryIndex(newEntry.Identity);
}
/// <summary>
/// Deletes a partition at a given index.
/// </summary>
/// <param name="index">The index of the partition.</param>
public override void Delete(int index)
{
int offset = GetPartitionOffset(index);
Array.Clear(_entryBuffer, offset, _primaryHeader.PartitionEntrySize);
Write();
}
internal SparseStream Open(GptEntry entry)
{
long start = entry.FirstUsedLogicalBlock * _diskGeometry.BytesPerSector;
long end = (entry.LastUsedLogicalBlock + 1) * _diskGeometry.BytesPerSector;
return new SubStream(_diskData, start, end - start);
}
private static uint CalcEntriesCrc(byte[] buffer)
{
return Crc32LittleEndian.Compute(Crc32Algorithm.Common, buffer, 0, buffer.Length);
}
private static int CountEntries<T>(ICollection<T> values, Func<T, bool> pred)
{
int count = 0;
foreach (T val in values)
{
if (pred(val))
{
++count;
}
}
return count;
}
private void Init(Stream disk, Geometry diskGeometry)
{
BiosPartitionTable bpt;
try
{
bpt = new BiosPartitionTable(disk, diskGeometry);
}
catch (IOException ioe)
{
throw new IOException("Invalid GPT disk, protective MBR table not present or invalid", ioe);
}
if (bpt.Count != 1 || bpt[0].BiosType != BiosPartitionTypes.GptProtective)
{
throw new IOException("Invalid GPT disk, protective MBR table is not valid");
}
_diskData = disk;
_diskGeometry = diskGeometry;
disk.Position = diskGeometry.BytesPerSector;
byte[] sector = StreamUtilities.ReadExact(disk, diskGeometry.BytesPerSector);
_primaryHeader = new GptHeader(diskGeometry.BytesPerSector);
if (!_primaryHeader.ReadFrom(sector, 0) || !ReadEntries(_primaryHeader))
{
disk.Position = disk.Length - diskGeometry.BytesPerSector;
disk.Read(sector, 0, sector.Length);
_secondaryHeader = new GptHeader(diskGeometry.BytesPerSector);
if (!_secondaryHeader.ReadFrom(sector, 0) || !ReadEntries(_secondaryHeader))
{
throw new IOException("No valid GUID Partition Table found");
}
// Generate from the primary table from the secondary one
_primaryHeader = new GptHeader(_secondaryHeader);
_primaryHeader.HeaderLba = _secondaryHeader.AlternateHeaderLba;
_primaryHeader.AlternateHeaderLba = _secondaryHeader.HeaderLba;
_primaryHeader.PartitionEntriesLba = 2;
// If the disk is writeable, fix up the primary partition table based on the
// (valid) secondary table.
if (disk.CanWrite)
{
WritePrimaryHeader();
}
}
if (_secondaryHeader == null)
{
_secondaryHeader = new GptHeader(diskGeometry.BytesPerSector);
disk.Position = disk.Length - diskGeometry.BytesPerSector;
disk.Read(sector, 0, sector.Length);
if (!_secondaryHeader.ReadFrom(sector, 0) || !ReadEntries(_secondaryHeader))
{
// Generate from the secondary table from the primary one
_secondaryHeader = new GptHeader(_primaryHeader);
_secondaryHeader.HeaderLba = _secondaryHeader.AlternateHeaderLba;
_secondaryHeader.AlternateHeaderLba = _secondaryHeader.HeaderLba;
_secondaryHeader.PartitionEntriesLba = _secondaryHeader.HeaderLba -
MathUtilities.RoundUp(
_secondaryHeader.PartitionEntryCount *
_secondaryHeader.PartitionEntrySize,
diskGeometry.BytesPerSector);
// If the disk is writeable, fix up the secondary partition table based on the
// (valid) primary table.
if (disk.CanWrite)
{
WriteSecondaryHeader();
}
}
}
}
private void EstablishReservedPartition(List<GptEntry> allEntries)
{
// If no MicrosoftReserved partition, and no Microsoft Data partitions, and the disk
// has a 'reasonable' size free, create a Microsoft Reserved partition.
if (CountEntries(allEntries, e => e.PartitionType == GuidPartitionTypes.MicrosoftReserved) == 0
&& CountEntries(allEntries, e => e.PartitionType == GuidPartitionTypes.WindowsBasicData) == 0
&& _diskGeometry.Capacity > 512 * 1024 * 1024)
{
long reservedStart = FirstAvailableSector(allEntries);
long reservedEnd = FindLastFreeSector(reservedStart, allEntries);
if ((reservedEnd - reservedStart + 1) * _diskGeometry.BytesPerSector > 512 * 1024 * 1024)
{
long size = (_diskGeometry.Capacity < 16 * 1024L * 1024 * 1024 ? 32 : 128) * 1024 * 1024;
reservedEnd = reservedStart + size / _diskGeometry.BytesPerSector - 1;
int reservedOffset = GetFreeEntryOffset();
GptEntry newReservedEntry = new GptEntry();
newReservedEntry.PartitionType = GuidPartitionTypes.MicrosoftReserved;
newReservedEntry.Identity = Guid.NewGuid();
newReservedEntry.FirstUsedLogicalBlock = reservedStart;
newReservedEntry.LastUsedLogicalBlock = reservedEnd;
newReservedEntry.Attributes = 0;
newReservedEntry.Name = "Microsoft reserved partition";
newReservedEntry.WriteTo(_entryBuffer, reservedOffset);
allEntries.Add(newReservedEntry);
}
}
}
private GptEntry CreateEntry(long startSector, long endSector, Guid type, long attributes, string name)
{
if (endSector < startSector)
{
throw new ArgumentException("The end sector is before the start sector");
}
int offset = GetFreeEntryOffset();
GptEntry newEntry = new GptEntry();
newEntry.PartitionType = type;
newEntry.Identity = Guid.NewGuid();
newEntry.FirstUsedLogicalBlock = startSector;
newEntry.LastUsedLogicalBlock = endSector;
newEntry.Attributes = (ulong)attributes;
newEntry.Name = name;
newEntry.WriteTo(_entryBuffer, offset);
// Commit changes to disk
Write();
return newEntry;
}
private long FindGap(long numSectors, long alignmentSectors)
{
List<GptEntry> list = new List<GptEntry>(GetAllEntries());
list.Sort();
long startSector = MathUtilities.RoundUp(_primaryHeader.FirstUsable, alignmentSectors);
foreach (GptEntry entry in list)
{
if (
!Utilities.RangesOverlap(startSector, startSector + numSectors - 1, entry.FirstUsedLogicalBlock,
entry.LastUsedLogicalBlock))
{
break;
}
startSector = MathUtilities.RoundUp(entry.LastUsedLogicalBlock + 1, alignmentSectors);
}
if (_diskGeometry.TotalSectorsLong - startSector < numSectors)
{
throw new IOException(string.Format(CultureInfo.InvariantCulture,
"Unable to find free space of {0} sectors", numSectors));
}
return startSector;
}
private long FirstAvailableSector(List<GptEntry> allEntries)
{
long start = _primaryHeader.FirstUsable;
foreach (GptEntry entry in allEntries)
{
if (entry.LastUsedLogicalBlock >= start)
{
start = entry.LastUsedLogicalBlock + 1;
}
}
return start;
}
private long FindLastFreeSector(long start, List<GptEntry> allEntries)
{
long end = _primaryHeader.LastUsable;
foreach (GptEntry entry in allEntries)
{
if (entry.LastUsedLogicalBlock > start && entry.FirstUsedLogicalBlock <= end)
{
end = entry.FirstUsedLogicalBlock - 1;
}
}
return end;
}
private void Write()
{
WritePrimaryHeader();
WriteSecondaryHeader();
}
private void WritePrimaryHeader()
{
byte[] buffer = new byte[_diskGeometry.BytesPerSector];
_primaryHeader.EntriesCrc = CalcEntriesCrc();
_primaryHeader.WriteTo(buffer, 0);
_diskData.Position = _diskGeometry.BytesPerSector;
_diskData.Write(buffer, 0, buffer.Length);
_diskData.Position = 2 * _diskGeometry.BytesPerSector;
_diskData.Write(_entryBuffer, 0, _entryBuffer.Length);
}
private void WriteSecondaryHeader()
{
byte[] buffer = new byte[_diskGeometry.BytesPerSector];
_secondaryHeader.EntriesCrc = CalcEntriesCrc();
_secondaryHeader.WriteTo(buffer, 0);
_diskData.Position = _diskData.Length - _diskGeometry.BytesPerSector;
_diskData.Write(buffer, 0, buffer.Length);
_diskData.Position = _secondaryHeader.PartitionEntriesLba * _diskGeometry.BytesPerSector;
_diskData.Write(_entryBuffer, 0, _entryBuffer.Length);
}
private bool ReadEntries(GptHeader header)
{
_diskData.Position = header.PartitionEntriesLba * _diskGeometry.BytesPerSector;
_entryBuffer = StreamUtilities.ReadExact(_diskData, (int)(header.PartitionEntrySize * header.PartitionEntryCount));
if (header.EntriesCrc != CalcEntriesCrc())
{
return false;
}
return true;
}
private uint CalcEntriesCrc()
{
return Crc32LittleEndian.Compute(Crc32Algorithm.Common, _entryBuffer, 0, _entryBuffer.Length);
}
private IEnumerable<GptEntry> GetAllEntries()
{
for (int i = 0; i < _primaryHeader.PartitionEntryCount; ++i)
{
GptEntry entry = new GptEntry();
entry.ReadFrom(_entryBuffer, i * _primaryHeader.PartitionEntrySize);
if (entry.PartitionType != Guid.Empty)
{
yield return entry;
}
}
}
private int GetPartitionOffset(int index)
{
bool found = false;
int entriesSoFar = 0;
int position = 0;
while (!found && position < _primaryHeader.PartitionEntryCount)
{
GptEntry entry = new GptEntry();
entry.ReadFrom(_entryBuffer, position * _primaryHeader.PartitionEntrySize);
if (entry.PartitionType != Guid.Empty)
{
if (index == entriesSoFar)
{
found = true;
break;
}
entriesSoFar++;
}
position++;
}
if (found)
{
return position * _primaryHeader.PartitionEntrySize;
}
throw new IOException(string.Format(CultureInfo.InvariantCulture, "No such partition: {0}", index));
}
private int GetEntryIndex(Guid identity)
{
int index = 0;
for (int i = 0; i < _primaryHeader.PartitionEntryCount; ++i)
{
GptEntry entry = new GptEntry();
entry.ReadFrom(_entryBuffer, i * _primaryHeader.PartitionEntrySize);
if (entry.Identity == identity)
{
return index;
}
if (entry.PartitionType != Guid.Empty)
{
index++;
}
}
throw new IOException("No such partition");
}
private int GetFreeEntryOffset()
{
for (int i = 0; i < _primaryHeader.PartitionEntryCount; ++i)
{
GptEntry entry = new GptEntry();
entry.ReadFrom(_entryBuffer, i * _primaryHeader.PartitionEntrySize);
if (entry.PartitionType == Guid.Empty)
{
return i * _primaryHeader.PartitionEntrySize;
}
}
throw new IOException("No free partition entries available");
}
}
}
| |
/*
* Copyright (c) 2009, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Net;
using System.Net.Security;
using System.IO;
using System.Text;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
namespace OpenMetaverse.Http
{
public class TrustAllCertificatePolicy : ICertificatePolicy
{
public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem)
{
return true;
}
public static bool TrustAllCertificateHandler(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
public static class CapsBase
{
public delegate void OpenWriteEventHandler(HttpWebRequest request);
public delegate void DownloadProgressEventHandler(HttpWebRequest request, HttpWebResponse response, int bytesReceived, int totalBytesToReceive);
public delegate void RequestCompletedEventHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error);
static CapsBase()
{
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
// Even though this will compile on Mono 2.4, it throws a runtime exception
//ServicePointManager.ServerCertificateValidationCallback = TrustAllCertificatePolicy.TrustAllCertificateHandler;
}
private class RequestState
{
public HttpWebRequest Request;
public byte[] UploadData;
public int MillisecondsTimeout;
public OpenWriteEventHandler OpenWriteCallback;
public DownloadProgressEventHandler DownloadProgressCallback;
public RequestCompletedEventHandler CompletedCallback;
public RequestState(HttpWebRequest request, byte[] uploadData, int millisecondsTimeout, OpenWriteEventHandler openWriteCallback,
DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
{
Request = request;
UploadData = uploadData;
MillisecondsTimeout = millisecondsTimeout;
OpenWriteCallback = openWriteCallback;
DownloadProgressCallback = downloadProgressCallback;
CompletedCallback = completedCallback;
}
}
public static HttpWebRequest UploadDataAsync(Uri address, X509Certificate2 clientCert, string contentType, byte[] data,
int millisecondsTimeout, OpenWriteEventHandler openWriteCallback, DownloadProgressEventHandler downloadProgressCallback,
RequestCompletedEventHandler completedCallback)
{
// Create the request
HttpWebRequest request = SetupRequest(address, clientCert);
request.ContentLength = data.Length;
if (!String.IsNullOrEmpty(contentType))
request.ContentType = contentType;
request.Method = "POST";
// Create an object to hold all of the state for this request
RequestState state = new RequestState(request, data, millisecondsTimeout, openWriteCallback,
downloadProgressCallback, completedCallback);
// Start the request for a stream to upload to
IAsyncResult result = request.BeginGetRequestStream(OpenWrite, state);
// Register a timeout for the request
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true);
return request;
}
public static HttpWebRequest DownloadStringAsync(Uri address, X509Certificate2 clientCert, int millisecondsTimeout,
DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
{
// Create the request
HttpWebRequest request = SetupRequest(address, clientCert);
request.Method = "GET";
DownloadDataAsync(request, millisecondsTimeout, downloadProgressCallback, completedCallback);
return request;
}
public static void DownloadDataAsync(HttpWebRequest request, int millisecondsTimeout,
DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
{
// Create an object to hold all of the state for this request
RequestState state = new RequestState(request, null, millisecondsTimeout, null, downloadProgressCallback,
completedCallback);
// Start the request for the remote server response
IAsyncResult result = request.BeginGetResponse(GetResponse, state);
// Register a timeout for the request
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true);
}
static HttpWebRequest SetupRequest(Uri address, X509Certificate2 clientCert)
{
if (address == null)
throw new ArgumentNullException("address");
// Create the request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(address);
// Add the client certificate to the request if one was given
if (clientCert != null)
request.ClientCertificates.Add(clientCert);
// Leave idle connections to this endpoint open for up to 60 seconds
request.ServicePoint.MaxIdleTime = 1000 * 60;
// Disable stupid Expect-100: Continue header
request.ServicePoint.Expect100Continue = false;
// Crank up the max number of connections per endpoint (default is 2!)
request.ServicePoint.ConnectionLimit = 20;
// Caps requests are never sent as trickles of data, so Nagle's
// coalescing algorithm won't help us
request.ServicePoint.UseNagleAlgorithm = false;
return request;
}
static void OpenWrite(IAsyncResult ar)
{
RequestState state = (RequestState)ar.AsyncState;
try
{
// Get the stream to write our upload to
using (Stream uploadStream = state.Request.EndGetRequestStream(ar))
{
// Fire the callback for successfully opening the stream
if (state.OpenWriteCallback != null)
state.OpenWriteCallback(state.Request);
// Write our data to the upload stream
uploadStream.Write(state.UploadData, 0, state.UploadData.Length);
}
// Start the request for the remote server response
IAsyncResult result = state.Request.BeginGetResponse(GetResponse, state);
// Register a timeout for the request
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state,
state.MillisecondsTimeout, true);
}
catch (Exception ex)
{
//Logger.Log.Debug("CapsBase.OpenWrite(): " + ex.Message);
if (state.CompletedCallback != null)
state.CompletedCallback(state.Request, null, null, ex);
}
}
static void GetResponse(IAsyncResult ar)
{
RequestState state = (RequestState)ar.AsyncState;
HttpWebResponse response = null;
byte[] responseData = null;
Exception error = null;
try
{
response = (HttpWebResponse)state.Request.EndGetResponse(ar);
// Get the stream for downloading the response
using (Stream responseStream = response.GetResponseStream())
{
#region Read the response
// If Content-Length is set we create a buffer of the exact size, otherwise
// a MemoryStream is used to receive the response
bool nolength = (response.ContentLength <= 0);
int size = (nolength) ? 8192 : (int)response.ContentLength;
MemoryStream ms = (nolength) ? new MemoryStream() : null;
byte[] buffer = new byte[size];
int bytesRead = 0;
int offset = 0;
while ((bytesRead = responseStream.Read(buffer, offset, size)) != 0)
{
if (nolength)
{
ms.Write(buffer, 0, bytesRead);
}
else
{
offset += bytesRead;
size -= bytesRead;
}
// Fire the download progress callback for each chunk of received data
if (state.DownloadProgressCallback != null)
state.DownloadProgressCallback(state.Request, response, bytesRead, size);
}
if (nolength)
{
responseData = ms.ToArray();
ms.Close();
ms.Dispose();
}
else
{
responseData = buffer;
}
#endregion Read the response
responseStream.Close();
}
}
catch (Exception ex)
{
// Logger.DebugLog("CapsBase.GetResponse(): " + ex.Message);
error = ex;
}
if (state.CompletedCallback != null)
state.CompletedCallback(state.Request, response, responseData, error);
}
static void TimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
RequestState requestState = state as RequestState;
//Logger.Log.Debug("CapsBase.TimeoutCallback(): Request to " + requestState.Request.RequestUri +
// " timed out after " + requestState.MillisecondsTimeout + " milliseconds");
if (requestState != null && requestState.Request != null)
requestState.Request.Abort();
}
}
}
}
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
using System;
using IronScheme.Editor.Controls;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using IronScheme.Editor.Runtime;
using System.Diagnostics;
using System.Text;
using System.Configuration;
using System.Collections.Generic;
namespace IronScheme.Editor.ComponentModel
{
/// <summary>
/// Provides service for scripting
/// </summary>
public interface IShellService : IService
{
/// <summary>
/// Inits the command.
/// </summary>
void InitCommand();
void RunCurrentFile();
void RunCommand(string p);
}
[Menu("Scheme")]
sealed class ShellService : ServiceBase, IShellService
{
ShellTextBox atb;
internal IDockContent tbp;
List<string> history = new List<string>();
class ShellTextBox : AdvancedTextBox
{
internal ShellService svc;
internal int last = 0;
public override void NavigateUp()
{
if (Buffer.CaretIndex == TextLength - 1)
{
if (svc.history.Count > 0)
{
last--;
if (last == -1)
{
last = svc.history.Count - 1;
}
string line = Buffer[Buffer.CurrentLine];
if (line == "> ")
{
AppendText(svc.history[last]);
}
else
{
Buffer.SetLine(Buffer.CurrentLine, "> " + svc.history[last]);
}
Invalidate();
}
}
else
{
base.NavigateUp();
}
}
public override void NavigateDown()
{
if (Buffer.CaretIndex == TextLength - 1)
{
if (svc.history.Count > 0)
{
last++;
if (last == svc.history.Count)
{
Buffer.SetLine(Buffer.CurrentLine, "> ");
}
else
{
if (last >= svc.history.Count)
{
last = 0;
}
string line = Buffer[Buffer.CurrentLine];
if (line == "> ")
{
AppendText(svc.history[last]);
}
else
{
Buffer.SetLine(Buffer.CurrentLine, "> " + svc.history[last]);
}
}
Invalidate();
}
}
else
{
base.NavigateDown();
}
}
}
public void InitCommand()
{
if (SettingsService.idemode)
{
atb = ServiceHost.File.Open <ShellTextBox>(Application.StartupPath + "/shell", DockState.DockBottom);
atb.svc = this;
atb.Clear();
ServiceHost.File.Closing += delegate (object sender, FileEventArgs e)
{
e.Cancel |= (StringComparer.InvariantCultureIgnoreCase.Compare(e.FileName, Application.StartupPath + "\\shell") == 0);
};
atb.LineInserted += new AdvancedTextBox.LineInsertNotify(atb_LineInserted);
atb.AutoSave = true;
tbp = atb.Parent as IDockContent;
tbp.Text = "Scheme Shell ";
tbp.HideOnClose = true;
tbp.Hide();
InitializeShell();
}
}
[MenuItem("Run current file", Index = 0, Image = "IronScheme.png")]
public void RunCurrentFile()
{
if (Array.IndexOf(ServiceHost.File.DirtyFiles, ServiceHost.File.Current) >= 0)
{
ServiceHost.File.Save(ServiceHost.File.Current);
}
RunFile(ServiceHost.File.Current);
}
void RunFile(string filename)
{
if (In != null)
{
string ext = Path.GetExtension(filename);
switch (ext)
{
case ".ss":
case ".sls":
case ".scm":
string cmd = string.Format("(load \"{0}\")\n", filename.Replace("\\", "/"));
atb.AppendText(cmd);
atb.Invalidate();
AddCommand(cmd.TrimEnd('\n'));
In.Write(cmd);
In.Flush();
break;
}
}
}
void atb_LineInserted(string line)
{
if (In != null)
{
int i = line.IndexOf("> ");
if (i < 0)
{
i = line.IndexOf(". ");
}
if (i >= 0)
{
atb.ReadOnly = true;
string cmd = line.Substring(i + 2);
AddCommand(cmd);
In.WriteLine(cmd);
In.Flush();
}
}
}
void AddCommand(string cmd)
{
if (history.Count == 0 || cmd != history[history.Count - 1])
{
if ("" != cmd.Trim())
{
history.Add(cmd);
}
}
atb.last = 0;
}
public void RunCommand(string p)
{
string cmd = p + "\n";
atb.AppendText(cmd);
atb.Invalidate();
AddCommand(cmd.TrimEnd('\n'));
In.Write(cmd);
In.Flush();
}
[MenuItem("Restart shell", Index=1)]
void RestartShell()
{
StopShell();
InitializeShell();
}
[MenuItem("Stop shell", Index=2)]
void StopShell()
{
StopShell(true);
}
ManualResetEvent stopshell;
void StopShell(bool print)
{
if (p != null)
{
stopshell = new ManualResetEvent(false);
p.Kill();
reading = false;
stopshell.WaitOne();
if (print)
{
atb.Text = "Shell stopped\n";
}
}
}
protected override void Dispose(bool disposing)
{
StopShell(false);
base.Dispose(disposing);
}
StreamReader Out, Error;
StreamWriter In;
Thread readthread, errorthread;
void Read()
{
StringBuilder sb = new StringBuilder();
while (reading)
{
while (printingerror)
{
Thread.Sleep(10);
}
int c = Out.Read();
if (c >= 0 && c != '\r')
{
sb.Append((char)c);
if (sb.Length > 1)
{
char prev = sb[sb.Length - 2];
if ((c == ' ' && (prev == '>' || prev == '.')) || c == '\n')
{
atb.Invoke(new U(UpdateText), sb.ToString());
sb.Length = 0;
}
}
}
}
}
bool printingerror = false;
void ReadError()
{
StringBuilder sb = new StringBuilder();
while (reading)
{
printingerror = false;
int c = Error.Read();
printingerror = true;
if (c >= 0 && c != '\r')
{
sb.Append((char)c);
if (sb.Length > 1)
{
char prev = sb[sb.Length - 2];
if ((c == ' ' && (prev == '>' || prev == '.')) || c == '\n')
{
atb.Invoke(new U(UpdateText), sb.ToString());
sb.Length = 0;
}
}
}
}
}
Process p;
void InitializeShell()
{
string path = ConfigurationManager.AppSettings["ShellDirectory"];
if (path == null)
{
ShellExeNotFound(path);
return;
}
string filename = ConfigurationManager.AppSettings["ShellExecutable"];
string fn = Path.Combine(path, filename);
if (!File.Exists(fn))
{
ShellExeNotFound(fn);
return;
}
p = new Process();
readthread = new Thread(Read);
errorthread = new Thread(ReadError);
string args = ConfigurationManager.AppSettings["ShellArguments"];
ProcessStartInfo psi = new ProcessStartInfo(fn);
psi.Arguments = args ?? "";
psi.WorkingDirectory = path;
psi.CreateNoWindow = true;
psi.RedirectStandardError = psi.RedirectStandardInput = psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
p.StartInfo = psi;
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(p_Exited);
p.Start();
Error = p.StandardError;
Out = p.StandardOutput;
In = p.StandardInput;
reading = true;
errorthread.Start();
readthread.Start();
}
private void ShellExeNotFound(string filepath)
{
atb.ReadOnly = true;
atb.AppendText(filepath + " not found");
}
bool reading = false;
delegate void U(string t);
void UpdateText(string text)
{
atb.AppendText(text);
atb.ScrollToCaret();
atb.ReadOnly = false;
}
void p_Exited(object sender, EventArgs e)
{
readthread.Abort();
errorthread.Abort();
In = null;
Out = null;
Error = null;
p = null;
stopshell.Set();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using System.Threading;
namespace System.Net.Security
{
//
// This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context.
//
internal class SslStreamInternal
{
private const int PinnableReadBufferSize = 4096 * 4 + 32; // We read in 16K chunks + headers.
private static PinnableBufferCache s_PinnableReadBufferCache = new PinnableBufferCache("System.Net.SslStream", PinnableReadBufferSize);
private const int PinnableWriteBufferSize = 4096 + 1024; // We write in 4K chunks + encryption overhead.
private static PinnableBufferCache s_PinnableWriteBufferCache = new PinnableBufferCache("System.Net.SslStream", PinnableWriteBufferSize);
private SslState _SslState;
private int _NestedWrite;
private int _NestedRead;
// Never updated directly, special properties are used. This is the read buffer.
private byte[] _InternalBuffer;
private bool _InternalBufferFromPinnableCache;
private byte[] _PinnableOutputBuffer; // Used for writes when we can do it.
private byte[] _PinnableOutputBufferInUse; // Remembers what UNENCRYPTED buffer is using _PinnableOutputBuffer.
private int _InternalOffset;
private int _InternalBufferCount;
private FixedSizeReader _Reader;
internal SslStreamInternal(SslState sslState)
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage1("CTOR: In System.Net._SslStream.SslStream", this.GetHashCode());
}
_SslState = sslState;
_Reader = new FixedSizeReader(_SslState.InnerStream);
}
// If we have a read buffer from the pinnable cache, return it.
private void FreeReadBuffer()
{
if (_InternalBufferFromPinnableCache)
{
s_PinnableReadBufferCache.FreeBuffer(_InternalBuffer);
_InternalBufferFromPinnableCache = false;
}
_InternalBuffer = null;
}
~SslStreamInternal()
{
if (_InternalBufferFromPinnableCache)
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage2("DTOR: In System.Net._SslStream.~SslStream Freeing Read Buffer", this.GetHashCode(), PinnableBufferCacheEventSource.AddressOfByteArray(_InternalBuffer));
}
FreeReadBuffer();
}
if (_PinnableOutputBuffer != null)
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage2("DTOR: In System.Net._SslStream.~SslStream Freeing Write Buffer", this.GetHashCode(), PinnableBufferCacheEventSource.AddressOfByteArray(_PinnableOutputBuffer));
}
s_PinnableWriteBufferCache.FreeBuffer(_PinnableOutputBuffer);
}
}
internal int Read(byte[] buffer, int offset, int count)
{
return ProcessRead(buffer, offset, count);
}
internal void Write(byte[] buffer, int offset, int count)
{
ProcessWrite(buffer, offset, count);
}
internal bool DataAvailable
{
get { return InternalBufferCount != 0; }
}
private byte[] InternalBuffer
{
get
{
return _InternalBuffer;
}
}
private int InternalOffset
{
get
{
return _InternalOffset;
}
}
private int InternalBufferCount
{
get
{
return _InternalBufferCount;
}
}
private void SkipBytes(int decrCount)
{
_InternalOffset += decrCount;
_InternalBufferCount -= decrCount;
}
//
// This will set the internal offset to "curOffset" and ensure internal buffer.
// If not enough, reallocate and copy up to "curOffset".
//
private void EnsureInternalBufferSize(int curOffset, int addSize)
{
if (_InternalBuffer == null || _InternalBuffer.Length < addSize + curOffset)
{
bool wasPinnable = _InternalBufferFromPinnableCache;
byte[] saved = _InternalBuffer;
int newSize = addSize + curOffset;
if (newSize <= PinnableReadBufferSize)
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.EnsureInternalBufferSize IS pinnable", this.GetHashCode(), newSize);
}
_InternalBufferFromPinnableCache = true;
_InternalBuffer = s_PinnableReadBufferCache.AllocateBuffer();
}
else
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.EnsureInternalBufferSize NOT pinnable", this.GetHashCode(), newSize);
}
_InternalBufferFromPinnableCache = false;
_InternalBuffer = new byte[newSize];
}
if (saved != null && curOffset != 0)
{
Buffer.BlockCopy(saved, 0, _InternalBuffer, 0, curOffset);
}
if (wasPinnable)
{
s_PinnableReadBufferCache.FreeBuffer(saved);
}
}
_InternalOffset = curOffset;
_InternalBufferCount = curOffset + addSize;
}
//
// Validates user parameteres for all Read/Write methods.
//
private void ValidateParameters(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (count > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException("count", SR.net_offset_plus_count);
}
}
//
// Sync write method.
//
private void ProcessWrite(byte[] buffer, int offset, int count)
{
ValidateParameters(buffer, offset, count);
if (Interlocked.Exchange(ref _NestedWrite, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "Write", "write"));
}
try
{
StartWriting(buffer, offset, count);
}
catch (Exception e)
{
_SslState.FinishWrite();
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_write, e);
}
finally
{
_NestedWrite = 0;
}
}
private void StartWriting(byte[] buffer, int offset, int count)
{
// We loop to this method from the callback.
// If the last chunk was just completed from async callback (count < 0), we complete user request.
if (count >= 0)
{
byte[] outBuffer = null;
if (_PinnableOutputBufferInUse == null)
{
if (_PinnableOutputBuffer == null)
{
_PinnableOutputBuffer = s_PinnableWriteBufferCache.AllocateBuffer();
}
_PinnableOutputBufferInUse = buffer;
outBuffer = _PinnableOutputBuffer;
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Trying Pinnable", this.GetHashCode(), count, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer));
}
}
else
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.StartWriting BufferInUse", this.GetHashCode(), count);
}
}
do
{
// Request a write IO slot.
if (_SslState.CheckEnqueueWrite(null))
{
// Operation is async and has been queued, return.
return;
}
int chunkBytes = Math.Min(count, _SslState.MaxDataSize);
int encryptedBytes;
SecurityStatusPal errorCode = _SslState.EncryptData(buffer, offset, chunkBytes, ref outBuffer, out encryptedBytes);
if (errorCode != SecurityStatusPal.OK)
{
ProtocolToken message = new ProtocolToken(null, errorCode);
throw new IOException(SR.net_io_encrypt, message.GetException());
}
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Got Encrypted Buffer",
this.GetHashCode(), encryptedBytes, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer));
}
_SslState.InnerStream.Write(outBuffer, 0, encryptedBytes);
offset += chunkBytes;
count -= chunkBytes;
// Release write IO slot.
_SslState.FinishWrite();
} while (count != 0);
}
if (buffer == _PinnableOutputBufferInUse)
{
_PinnableOutputBufferInUse = null;
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage1("In System.Net._SslStream.StartWriting Freeing buffer.", this.GetHashCode());
}
}
}
//
// Sync read method.
//
private int ProcessRead(byte[] buffer, int offset, int count)
{
ValidateParameters(buffer, offset, count);
if (Interlocked.Exchange(ref _NestedRead, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "Read", "read"));
}
try
{
int copyBytes;
if (InternalBufferCount != 0)
{
copyBytes = InternalBufferCount > count ? count : InternalBufferCount;
if (copyBytes != 0)
{
Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, copyBytes);
SkipBytes(copyBytes);
}
return copyBytes;
}
return StartReading(buffer, offset, count);
}
catch (Exception e)
{
_SslState.FinishRead(null);
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_read, e);
}
finally
{
_NestedRead = 0;
}
}
//
// To avoid recursion when decrypted 0 bytes this method will loop until a decrypted result at least 1 byte.
//
private int StartReading(byte[] buffer, int offset, int count)
{
int result = 0;
if (GlobalLog.IsEnabled && InternalBufferCount != 0)
{
GlobalLog.AssertFormat("SslStream::StartReading()|Previous frame was not consumed. InternalBufferCount:{0}", InternalBufferCount);
}
do
{
int copyBytes = _SslState.CheckEnqueueRead(buffer, offset, count, null);
if (copyBytes == 0)
{
//Queued but not completed!
return 0;
}
if (copyBytes != -1)
{
return copyBytes;
}
}
// When we read -1 bytes means we have decrypted 0 bytes or rehandshaking, need looping.
while ((result = StartFrameHeader(buffer, offset, count)) == -1);
return result;
}
//
// Need read frame size first
//
private int StartFrameHeader(byte[] buffer, int offset, int count)
{
int readBytes = 0;
//
// Always pass InternalBuffer for SSPI "in place" decryption.
// A user buffer can be shared by many threads in that case decryption/integrity check may fail cause of data corruption.
//
// Reset internal buffer for a new frame.
EnsureInternalBufferSize(0, SecureChannel.ReadHeaderSize);
readBytes = _Reader.ReadPacket(InternalBuffer, 0, SecureChannel.ReadHeaderSize);
return StartFrameBody(readBytes, buffer, offset, count);
}
private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count)
{
if (readBytes == 0)
{
//EOF : Reset the buffer as we did not read anything into it.
SkipBytes(InternalBufferCount);
return 0;
}
// Now readBytes is a payload size.
readBytes = _SslState.GetRemainingFrameSize(InternalBuffer, readBytes);
if (readBytes < 0)
{
throw new IOException(SR.net_frame_read_size);
}
EnsureInternalBufferSize(SecureChannel.ReadHeaderSize, readBytes);
readBytes = _Reader.ReadPacket(InternalBuffer, SecureChannel.ReadHeaderSize, readBytes);
return ProcessFrameBody(readBytes, buffer, offset, count);
}
//
// readBytes == SSL Data Payload size on input or 0 on EOF
//
private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count)
{
if (readBytes == 0)
{
// EOF
throw new IOException(SR.net_io_eof);
}
// Set readBytes to total number of received bytes.
readBytes += SecureChannel.ReadHeaderSize;
// Decrypt into internal buffer, change "readBytes" to count now _Decrypted Bytes_.
int data_offset = 0;
SecurityStatusPal errorCode = _SslState.DecryptData(InternalBuffer, ref data_offset, ref readBytes);
if (errorCode != SecurityStatusPal.OK)
{
byte[] extraBuffer = null;
if (readBytes != 0)
{
extraBuffer = new byte[readBytes];
Buffer.BlockCopy(InternalBuffer, data_offset, extraBuffer, 0, readBytes);
}
// Reset internal buffer count.
SkipBytes(InternalBufferCount);
return ProcessReadErrorCode(errorCode, buffer, offset, count, extraBuffer);
}
if (readBytes == 0 && count != 0)
{
// Read again since remote side has sent encrypted 0 bytes.
SkipBytes(InternalBufferCount);
return -1;
}
// Decrypted data start from "data_offset" offset, the total count can be shrunk after decryption.
EnsureInternalBufferSize(0, data_offset + readBytes);
SkipBytes(data_offset);
if (readBytes > count)
{
readBytes = count;
}
Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, readBytes);
// This will adjust both the remaining internal buffer count and the offset.
SkipBytes(readBytes);
_SslState.FinishRead(null);
return readBytes;
}
//
// Only processing SEC_I_RENEGOTIATE.
//
private int ProcessReadErrorCode(SecurityStatusPal errorCode, byte[] buffer, int offset, int count, byte[] extraBuffer)
{
// ERROR - examine what kind
ProtocolToken message = new ProtocolToken(null, errorCode);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::***Processing an error Status = " + message.Status.ToString());
}
if (message.Renegotiate)
{
_SslState.ReplyOnReAuthentication(extraBuffer);
// Loop on read.
return -1;
}
if (message.CloseConnection)
{
_SslState.FinishRead(null);
return 0;
}
throw new IOException(SR.net_io_decrypt, message.GetException());
}
}
}
| |
/*
* Velcro Physics:
* Copyright (c) 2017 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System.Diagnostics;
using Microsoft.Xna.Framework;
using VelcroPhysics.Collision.RayCast;
using VelcroPhysics.Shared;
namespace VelcroPhysics.Collision.Shapes
{
/// <summary>
/// A chain shape is a free form sequence of line segments.
/// The chain has two-sided collision, so you can use inside and outside collision.
/// Therefore, you may use any winding order.
/// Connectivity information is used to create smooth collisions.
/// WARNING: The chain will not collide properly if there are self-intersections.
/// </summary>
public class ChainShape : Shape
{
private bool _hasPrevVertex, _hasNextVertex;
private Vector2 _prevVertex, _nextVertex;
/// <summary>
/// Create a new ChainShape from the vertices.
/// </summary>
/// <param name="vertices">The vertices to use. Must contain 2 or more vertices.</param>
/// <param name="createLoop">
/// Set to true to create a closed loop. It connects the first vertex to the last, and
/// automatically adjusts connectivity to create smooth collisions along the chain.
/// </param>
public ChainShape(Vertices vertices, bool createLoop = false) : base(ShapeType.Chain, Settings.PolygonRadius)
{
Debug.Assert(vertices != null && vertices.Count >= 3);
Debug.Assert(vertices[0] != vertices[vertices.Count - 1]); //Velcro. See http://www.box2d.org/forum/viewtopic.php?f=4&t=7973&p=35363
for (int i = 1; i < vertices.Count; ++i)
{
// If the code crashes here, it means your vertices are too close together.
Debug.Assert(Vector2.DistanceSquared(vertices[i - 1], vertices[i]) > Settings.LinearSlop * Settings.LinearSlop);
}
Vertices = new Vertices(vertices);
//Velcro: I merged CreateLoop() and CreateChain() to this
if (createLoop)
{
Vertices.Add(vertices[0]);
PrevVertex = Vertices[Vertices.Count - 2]; //Velcro: We use the properties instead of the private fields here to set _hasPrevVertex
NextVertex = Vertices[1]; //Velcro: We use the properties instead of the private fields here to set _hasNextVertex
}
ComputeProperties();
}
internal ChainShape() : base(ShapeType.Chain, Settings.PolygonRadius) { }
/// <summary>
/// The vertices. These are not owned/freed by the chain Shape.
/// </summary>
public Vertices Vertices { get; set; }
/// <summary>
/// Edge count = vertex count - 1
/// </summary>
public override int ChildCount => Vertices.Count - 1;
/// <summary>
/// Establish connectivity to a vertex that precedes the first vertex.
/// Don't call this for loops.
/// </summary>
public Vector2 PrevVertex
{
get { return _prevVertex; }
set
{
_prevVertex = value;
_hasPrevVertex = true;
}
}
/// <summary>
/// Establish connectivity to a vertex that follows the last vertex.
/// Don't call this for loops.
/// </summary>
public Vector2 NextVertex
{
get { return _nextVertex; }
set
{
_nextVertex = value;
_hasNextVertex = true;
}
}
internal void GetChildEdge(EdgeShape edge, int index)
{
Debug.Assert(0 <= index && index < Vertices.Count - 1);
Debug.Assert(edge != null);
edge.ShapeType = ShapeType.Edge;
edge._radius = _radius;
edge.Vertex1 = Vertices[index + 0];
edge.Vertex2 = Vertices[index + 1];
if (index > 0)
{
edge.Vertex0 = Vertices[index - 1];
edge.HasVertex0 = true;
}
else
{
edge.Vertex0 = _prevVertex;
edge.HasVertex0 = _hasPrevVertex;
}
if (index < Vertices.Count - 2)
{
edge.Vertex3 = Vertices[index + 2];
edge.HasVertex3 = true;
}
else
{
edge.Vertex3 = _nextVertex;
edge.HasVertex3 = _hasNextVertex;
}
}
public EdgeShape GetChildEdge(int index)
{
EdgeShape edgeShape = new EdgeShape();
GetChildEdge(edgeShape, index);
return edgeShape;
}
public override bool TestPoint(ref Transform transform, ref Vector2 point)
{
return false;
}
public override bool RayCast(ref RayCastInput input, ref Transform transform, int childIndex, out RayCastOutput output)
{
Debug.Assert(childIndex < Vertices.Count);
int i1 = childIndex;
int i2 = childIndex + 1;
if (i2 == Vertices.Count)
i2 = 0;
Vector2 v1 = Vertices[i1];
Vector2 v2 = Vertices[i2];
return RayCastHelper.RayCastEdge(ref v1, ref v2, ref input, ref transform, out output);
}
public override void ComputeAABB(ref Transform transform, int childIndex, out AABB aabb)
{
Debug.Assert(childIndex < Vertices.Count);
int i1 = childIndex;
int i2 = childIndex + 1;
if (i2 == Vertices.Count)
i2 = 0;
Vector2 v1 = Vertices[i1];
Vector2 v2 = Vertices[i2];
AABBHelper.ComputeEdgeAABB(ref v1, ref v2, ref transform, out aabb);
}
protected sealed override void ComputeProperties()
{
//Does nothing. Chain shapes don't have properties.
}
/// <summary>
/// Compare the chain to another chain
/// </summary>
/// <param name="shape">The other chain</param>
/// <returns>True if the two chain shapes are the same</returns>
public bool CompareTo(ChainShape shape)
{
if (Vertices.Count != shape.Vertices.Count)
return false;
for (int i = 0; i < Vertices.Count; i++)
{
if (Vertices[i] != shape.Vertices[i])
return false;
}
return PrevVertex == shape.PrevVertex && NextVertex == shape.NextVertex;
}
public override Shape Clone()
{
ChainShape clone = new ChainShape();
clone.ShapeType = ShapeType;
clone._density = _density;
clone._radius = _radius;
clone.PrevVertex = _prevVertex;
clone.NextVertex = _nextVertex;
clone._hasNextVertex = _hasNextVertex;
clone._hasPrevVertex = _hasPrevVertex;
clone.Vertices = new Vertices(Vertices);
return clone;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Index
{
/*
* This class keeps track of each SegmentInfos instance that
* is still "live", either because it corresponds to a
* segments_N file in the Directory (a "commit", i.e. a
* committed SegmentInfos) or because it's an in-memory
* SegmentInfos that a writer is actively updating but has
* not yet committed. This class uses simple reference
* counting to map the live SegmentInfos instances to
* individual files in the Directory.
*
* When autoCommit=true, IndexWriter currently commits only
* on completion of a merge (though this may change with
* time: it is not a guarantee). When autoCommit=false,
* IndexWriter only commits when it is closed. Regardless
* of autoCommit, the user may call IndexWriter.commit() to
* force a blocking commit.
*
* The same directory file may be referenced by more than
* one IndexCommit, i.e. more than one SegmentInfos.
* Therefore we count how many commits reference each file.
* When all the commits referencing a certain file have been
* deleted, the refcount for that file becomes zero, and the
* file is deleted.
*
* A separate deletion policy interface
* (IndexDeletionPolicy) is consulted on creation (onInit)
* and once per commit (onCommit), to decide when a commit
* should be removed.
*
* It is the business of the IndexDeletionPolicy to choose
* when to delete commit points. The actual mechanics of
* file deletion, retrying, etc, derived from the deletion
* of commit points is the business of the IndexFileDeleter.
*
* The current default deletion policy is {@link
* KeepOnlyLastCommitDeletionPolicy}, which removes all
* prior commits when a new commit has completed. This
* matches the behavior before 2.2.
*
* Note that you must hold the write.lock before
* instantiating this class. It opens segments_N file(s)
* directly with no retry logic.
*/
sealed public class IndexFileDeleter
{
/* Files that we tried to delete but failed (likely
* because they are open and we are running on Windows),
* so we will retry them again later: */
private List<string> deletable;
/* Reference count for all files in the index.
* Counts how many existing commits reference a file.
* Maps string to RefCount (class below) instances: */
private Dictionary<string,RefCount> refCounts = new Dictionary<string,RefCount>();
/* Holds all commits (segments_N) currently in the index.
* This will have just 1 commit if you are using the
* default delete policy (KeepOnlyLastCommitDeletionPolicy).
* Other policies may leave commit points live for longer
* in which case this list would be longer than 1: */
private List<IndexCommitPoint> commits = new List<IndexCommitPoint>();
/* Holds files we had incref'd from the previous
* non-commit checkpoint: */
private List<string> lastFiles = new List<string>();
/* Commits that the IndexDeletionPolicy have decided to delete: */
private List<IndexCommitPoint> commitsToDelete = new List<IndexCommitPoint>();
private System.IO.TextWriter infoStream;
private Directory directory;
private IndexDeletionPolicy policy;
private DocumentsWriter docWriter;
/// <summary>Change to true to see details of reference counts when
/// infoStream != null
/// </summary>
public static bool VERBOSE_REF_COUNTS = false;
internal void SetInfoStream(System.IO.TextWriter infoStream)
{
this.infoStream = infoStream;
if (infoStream != null)
{
Message("setInfoStream deletionPolicy=" + policy);
}
}
private void Message(string message)
{
infoStream.WriteLine("IFD [" + SupportClass.ThreadClass.Current().Name + "]: " + message);
}
/// <summary> Initialize the deleter: find all previous commits in
/// the Directory, incref the files they reference, call
/// the policy to let it delete commits. The incoming
/// segmentInfos must have been loaded from a commit point
/// and not yet modified. This will remove any files not
/// referenced by any of the commits.
/// </summary>
/// <throws> CorruptIndexException if the index is corrupt </throws>
/// <throws> IOException if there is a low-level IO error </throws>
public IndexFileDeleter(Directory directory, IndexDeletionPolicy policy, SegmentInfos segmentInfos, System.IO.TextWriter infoStream, DocumentsWriter docWriter)
{
this.docWriter = docWriter;
this.infoStream = infoStream;
if (infoStream != null)
{
Message("init: current segments file is \"" + segmentInfos.GetCurrentSegmentFileName() + "\"; deletionPolicy=" + policy);
}
this.policy = policy;
this.directory = directory;
// First pass: walk the files and initialize our ref
// counts:
long currentGen = segmentInfos.GetGeneration();
IndexFileNameFilter filter = IndexFileNameFilter.GetFilter();
string[] files = directory.List();
if (files == null)
{
throw new System.IO.IOException("cannot read directory " + directory + ": list() returned null");
}
CommitPoint currentCommitPoint = null;
for (int i = 0; i < files.Length; i++)
{
string fileName = files[i];
if (filter.Accept(null, fileName) && !fileName.Equals(IndexFileNames.SEGMENTS_GEN))
{
// Add this file to refCounts with initial count 0:
GetRefCount(fileName);
if (fileName.StartsWith(IndexFileNames.SEGMENTS))
{
// This is a commit (segments or segments_N), and
// it's valid (<= the max gen). Load it, then
// incref all files it refers to:
if (SegmentInfos.GenerationFromSegmentsFileName(fileName) <= currentGen)
{
if (infoStream != null)
{
Message("init: load commit \"" + fileName + "\"");
}
SegmentInfos sis = new SegmentInfos();
try
{
sis.Read(directory, fileName);
}
catch (System.IO.FileNotFoundException)
{
// LUCENE-948: on NFS (and maybe others), if
// you have writers switching back and forth
// between machines, it's very likely that the
// dir listing will be stale and will claim a
// file segments_X exists when in fact it
// doesn't. So, we catch this and handle it
// as if the file does not exist
if (infoStream != null)
{
Message("init: hit FileNotFoundException when loading commit \"" + fileName + "\"; skipping this commit point");
}
sis = null;
}
if (sis != null)
{
CommitPoint commitPoint = new CommitPoint(this, commitsToDelete, directory, sis);
if (sis.GetGeneration() == segmentInfos.GetGeneration())
{
currentCommitPoint = commitPoint;
}
commits.Add(commitPoint);
IncRef(sis, true);
}
}
}
}
}
if (currentCommitPoint == null)
{
// We did not in fact see the segments_N file
// corresponding to the segmentInfos that was passed
// in. Yet, it must exist, because our caller holds
// the write lock. This can happen when the directory
// listing was stale (eg when index accessed via NFS
// client with stale directory listing cache). So we
// try now to explicitly open this commit point:
SegmentInfos sis = new SegmentInfos();
try
{
sis.Read(directory, segmentInfos.GetCurrentSegmentFileName());
}
catch (System.IO.IOException)
{
throw new CorruptIndexException("failed to locate current segments_N file");
}
if (infoStream != null)
Message("forced open of current segments file " + segmentInfos.GetCurrentSegmentFileName());
currentCommitPoint = new CommitPoint(this, commitsToDelete, directory, sis);
commits.Add(currentCommitPoint);
IncRef(sis, true);
}
// We keep commits list in sorted order (oldest to newest):
commits.Sort();
// Now delete anything with ref count at 0. These are
// presumably abandoned files eg due to crash of
// IndexWriter.
IEnumerator<KeyValuePair<string,RefCount>> it = refCounts.GetEnumerator();
while (it.MoveNext())
{
string fileName = it.Current.Key;
RefCount rc = it.Current.Value;
if (0 == rc.count)
{
if (infoStream != null)
{
Message("init: removing unreferenced file \"" + fileName + "\"");
}
DeleteFile(fileName);
}
}
// Finally, give policy a chance to remove things on
// startup:
policy.OnInit(commits);
// It's OK for the onInit to remove the current commit
// point; we just have to checkpoint our in-memory
// SegmentInfos to protect those files that it uses:
if (currentCommitPoint.deleted)
{
Checkpoint(segmentInfos, false);
}
DeleteCommits();
}
/// <summary> Remove the CommitPoints in the commitsToDelete List by
/// DecRef'ing all files from each SegmentInfos.
/// </summary>
private void DeleteCommits()
{
int size = commitsToDelete.Count;
if (size > 0)
{
// First decref all files that had been referred to by
// the now-deleted commits:
for (int i = 0; i < size; i++)
{
CommitPoint commit = (CommitPoint)commitsToDelete[i];
if (infoStream != null)
{
Message("deleteCommits: now decRef commit \"" + commit.GetSegmentsFileName() + "\"");
}
int size2 = commit.files.Count;
for (int j = 0; j < size2; j++)
{
DecRef((string)commit.files[j]);
}
}
commitsToDelete.Clear();
// Now compact commits to remove deleted ones (preserving the sort):
size = commits.Count;
int readFrom = 0;
int writeTo = 0;
while (readFrom < size)
{
CommitPoint commit = (CommitPoint) commits[readFrom];
if (!commit.deleted)
{
if (writeTo != readFrom)
{
commits[writeTo] = commits[readFrom];
}
writeTo++;
}
readFrom++;
}
while (size > writeTo)
{
commits.RemoveAt(size - 1);
size--;
}
}
}
/// <summary> Writer calls this when it has hit an error and had to
/// roll back, to tell us that there may now be
/// unreferenced files in the filesystem. So we re-list
/// the filesystem and delete such files. If segmentName
/// is non-null, we will only delete files corresponding to
/// that segment.
/// </summary>
public void Refresh(string segmentName)
{
string[] files = directory.List();
if (files == null)
{
throw new System.IO.IOException("cannot read directory " + directory + ": list() returned null");
}
IndexFileNameFilter filter = IndexFileNameFilter.GetFilter();
string segmentPrefix1;
string segmentPrefix2;
if (segmentName != null)
{
segmentPrefix1 = segmentName + ".";
segmentPrefix2 = segmentName + "_";
}
else
{
segmentPrefix1 = null;
segmentPrefix2 = null;
}
for (int i = 0; i < files.Length; i++)
{
string fileName = files[i];
if (filter.Accept(null, fileName) && (segmentName == null || fileName.StartsWith(segmentPrefix1) || fileName.StartsWith(segmentPrefix2)) && !refCounts.ContainsKey(fileName) && !fileName.Equals(IndexFileNames.SEGMENTS_GEN))
{
// Unreferenced file, so remove it
if (infoStream != null)
{
Message("refresh [prefix=" + segmentName + "]: removing newly created unreferenced file \"" + fileName + "\"");
}
DeleteFile(fileName);
}
}
}
public void Refresh()
{
Refresh(null);
}
public void Close()
{
DeletePendingFiles();
}
private void DeletePendingFiles()
{
if (deletable != null)
{
System.Collections.IList oldDeletable = deletable;
deletable = null;
int size = oldDeletable.Count;
for (int i = 0; i < size; i++)
{
if (infoStream != null)
{
Message("delete pending file " + oldDeletable[i]);
}
DeleteFile((string)oldDeletable[i]);
}
}
}
/// <summary> For definition of "check point" see IndexWriter comments:
/// "Clarification: Check Points (and commits)".
///
/// Writer calls this when it has made a "consistent
/// change" to the index, meaning new files are written to
/// the index and the in-memory SegmentInfos have been
/// modified to point to those files.
///
/// This may or may not be a commit (segments_N may or may
/// not have been written).
///
/// We simply incref the files referenced by the new
/// SegmentInfos and decref the files we had previously
/// seen (if any).
///
/// If this is a commit, we also call the policy to give it
/// a chance to remove other commits. If any commits are
/// removed, we decref their files as well.
/// </summary>
public void Checkpoint(SegmentInfos segmentInfos, bool isCommit)
{
if (infoStream != null)
{
Message("now checkpoint \"" + segmentInfos.GetCurrentSegmentFileName() + "\" [" + segmentInfos.Count + " segments " + "; isCommit = " + isCommit + "]");
}
// Try again now to delete any previously un-deletable
// files (because they were in use, on Windows):
DeletePendingFiles();
// Incref the files:
IncRef(segmentInfos, isCommit);
if (isCommit)
{
// append to our commits list
commits.Add(new CommitPoint(this, commitsToDelete, directory, segmentInfos));
// tell policy so it can remove commits
policy.OnCommit(commits);
// decref files for commits that were deleted by the policy
DeleteCommits();
}
else
{
List<string> docWriterFiles;
if (docWriter != null)
{
docWriterFiles = docWriter.OpenFiles();
if (docWriterFiles != null)
// we must incRef these files before decRef'ing
// last files to make sure we don't accidentally
// delete them
IncRef(docWriterFiles);
}
else
docWriterFiles = null;
// DecRef old files from the last checkpoint, if any:
int size = lastFiles.Count;
if (size > 0)
{
for (int i = 0; i < size; i++)
DecRef(lastFiles[i]);
lastFiles.Clear();
}
// Save files so we can decr on next checkpoint/commit:
size = segmentInfos.Count;
for (int i = 0; i < size; i++)
{
SegmentInfo segmentInfo = segmentInfos.Info(i);
if (segmentInfo.dir == directory)
{
SupportClass.CollectionsSupport.AddAll(segmentInfo.Files(), lastFiles);
}
}
if (docWriterFiles != null)
SupportClass.CollectionsSupport.AddAll(docWriterFiles, lastFiles);
}
}
internal void IncRef(SegmentInfos segmentInfos, bool isCommit)
{
int size = segmentInfos.Count;
for (int i = 0; i < size; i++)
{
SegmentInfo segmentInfo = segmentInfos.Info(i);
if (segmentInfo.dir == directory)
{
IncRef(segmentInfo.Files());
}
}
if (isCommit)
{
// Since this is a commit point, also incref its
// segments_N file:
GetRefCount(segmentInfos.GetCurrentSegmentFileName()).IncRef();
}
}
internal void IncRef(System.Collections.Generic.IList<string> files)
{
int size = files.Count;
for (int i = 0; i < size; i++)
{
string fileName = files[i];
RefCount rc = GetRefCount(fileName);
if (infoStream != null && VERBOSE_REF_COUNTS)
{
Message(" IncRef \"" + fileName + "\": pre-incr count is " + rc.count);
}
rc.IncRef();
}
}
internal void DecRef(System.Collections.Generic.IList<string> files)
{
int size = files.Count;
for (int i = 0; i < size; i++)
{
DecRef(files[i]);
}
}
internal void DecRef(string fileName)
{
RefCount rc = GetRefCount(fileName);
if (infoStream != null && VERBOSE_REF_COUNTS)
{
Message(" DecRef \"" + fileName + "\": pre-decr count is " + rc.count);
}
if (0 == rc.DecRef())
{
// This file is no longer referenced by any past
// commit points nor by the in-memory SegmentInfos:
DeleteFile(fileName);
refCounts.Remove(fileName);
}
}
internal void DecRef(SegmentInfos segmentInfos)
{
int size = segmentInfos.Count;
for (int i = 0; i < size; i++)
{
SegmentInfo segmentInfo = segmentInfos.Info(i);
if (segmentInfo.dir == directory)
{
DecRef(segmentInfo.Files());
}
}
}
private RefCount GetRefCount(string fileName)
{
RefCount rc;
if (!refCounts.ContainsKey(fileName))
{
rc = new RefCount();
refCounts[fileName] = rc;
}
else
{
rc = refCounts[fileName];
}
return rc;
}
internal void DeleteFiles(List<string> files)
{
int size = files.Count;
for (int i = 0; i < size; i++)
DeleteFile(files[i]);
}
/// <summary>Delets the specified files, but only if they are new
/// (have not yet been incref'd).
/// </summary>
internal void DeleteNewFiles(ICollection<string> files)
{
IEnumerator<string> enumerator = files.GetEnumerator();
while (enumerator.MoveNext())
{
string fileName = enumerator.Current;
if (!refCounts.ContainsKey(fileName))
DeleteFile(fileName);
}
}
internal void DeleteFile(string fileName)
{
try
{
if (infoStream != null)
{
Message("delete \"" + fileName + "\"");
}
directory.DeleteFile(fileName);
}
catch (System.IO.IOException e)
{
// if delete fails
if (directory.FileExists(fileName))
{
// Some operating systems (e.g. Windows) don't
// permit a file to be deleted while it is opened
// for read (e.g. by another process or thread). So
// we assume that when a delete fails it is because
// the file is open in another process, and queue
// the file for subsequent deletion.
if (infoStream != null)
{
Message("IndexFileDeleter: unable to remove file \"" + fileName + "\": " + e.ToString() + "; Will re-try later.");
}
if (deletable == null)
{
deletable = new List<string>();
}
deletable.Add(fileName); // add to deletable
}
}
}
/// <summary> Tracks the reference count for a single index file:</summary>
sealed private class RefCount
{
internal int count;
public int IncRef()
{
return ++count;
}
public int DecRef()
{
System.Diagnostics.Debug.Assert(count > 0);
return --count;
}
}
/// <summary> Holds details for each commit point. This class is
/// also passed to the deletion policy. Note: this class
/// has a natural ordering that is inconsistent with
/// equals.
/// </summary>
sealed private class CommitPoint : IndexCommit, System.IComparable
{
private void InitBlock(IndexFileDeleter enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private IndexFileDeleter enclosingInstance;
public IndexFileDeleter Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal long gen;
internal List<string> files;
internal string segmentsFileName;
internal bool deleted;
internal Directory directory;
internal ICollection<IndexCommitPoint> commitsToDelete;
internal long version;
internal long generation;
internal readonly bool isOptimized;
public CommitPoint(IndexFileDeleter enclosingInstance, ICollection<IndexCommitPoint> commitsToDelete, Directory directory, SegmentInfos segmentInfos)
{
InitBlock(enclosingInstance);
this.directory = directory;
this.commitsToDelete = commitsToDelete;
segmentsFileName = segmentInfos.GetCurrentSegmentFileName();
version = segmentInfos.GetVersion();
generation = segmentInfos.GetGeneration();
int size = segmentInfos.Count;
files = new List<string>(size);
files.Add(segmentsFileName);
gen = segmentInfos.GetGeneration();
for (int i = 0; i < size; i++)
{
SegmentInfo segmentInfo = segmentInfos.Info(i);
if (segmentInfo.dir == Enclosing_Instance.directory)
{
SupportClass.CollectionsSupport.AddAll(segmentInfo.Files(), files);
}
}
isOptimized = segmentInfos.Count == 1 && !segmentInfos.Info(0).HasDeletions();
}
public override bool IsOptimized()
{
return isOptimized;
}
public override string GetSegmentsFileName()
{
return segmentsFileName;
}
public override ICollection<string> GetFileNames()
{
return files.AsReadOnly();
}
public override Directory GetDirectory()
{
return directory;
}
public override long GetVersion()
{
return version;
}
public override long GetGeneration()
{
return generation;
}
/// <summary> Called only be the deletion policy, to remove this
/// commit point from the index.
/// </summary>
public override void Delete()
{
if (!deleted)
{
deleted = true;
Enclosing_Instance.commitsToDelete.Add(this);
}
}
public override bool IsDeleted()
{
return deleted;
}
public int CompareTo(object obj)
{
CommitPoint commit = (CommitPoint)obj;
if (gen < commit.gen)
{
return -1;
}
else if (gen > commit.gen)
{
return 1;
}
else
{
return 0;
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Class providing an algorithm for automatic resizing
/// of table columns.
/// </summary>
internal sealed class ColumnWidthManager
{
/// <summary>
/// Class providing an algorithm for automatic resizing.
/// </summary>
/// <param name="tableWidth">Overall width of the table in characters.</param>
/// <param name="minimumColumnWidth">Minimum usable column width.</param>
/// <param name="separatorWidth">Number of separator characters.</param>
internal ColumnWidthManager(int tableWidth, int minimumColumnWidth, int separatorWidth)
{
_tableWidth = tableWidth;
_minimumColumnWidth = minimumColumnWidth;
_separatorWidth = separatorWidth;
}
/// <summary>
/// Calculate the widths by applying some heuristics to get them to fit on the
/// allotted table width. It first assigns widths to the columns that do not have a specified
/// width, then it checks if the total width exceeds the screen widths. If so, it proceeds
/// with column elimination, starting from the right most column.
/// </summary>
/// <param name="columnWidths">Array of column widths to appropriately size.</param>
internal void CalculateColumnWidths(Span<int> columnWidths)
{
if (AssignColumnWidths(columnWidths))
{
// we do not have any trimming to do, we are done
return;
}
// total width exceeds screen width, go on with trimming
TrimToFit(columnWidths);
}
/// <summary>
/// Do not remove columns, just assign widths to columns that have a zero width
/// (meaning unassigned)
/// </summary>
/// <param name="columnWidths">Columns to process.</param>
/// <returns>True if there was a fit, false if there is need for trimming.</returns>
private bool AssignColumnWidths(Span<int> columnWidths)
{
// run a quick check to see if all the columns have a specified width,
// if so, we are done
bool allSpecified = true;
int maxInitialWidthSum = 0;
for (int k = 0; k < columnWidths.Length; k++)
{
if (columnWidths[k] <= 0)
{
allSpecified = false;
break;
}
maxInitialWidthSum += columnWidths[k];
}
if (allSpecified)
{
// compute the total table width (columns and separators)
maxInitialWidthSum += _separatorWidth * (columnWidths.Length - 1);
if (maxInitialWidthSum <= _tableWidth)
{
// we fit with all the columns specified
return true;
}
// we do not fit, we will have to trim
return false;
}
// we have columns with no width assigned
// remember the columns we are trying to size
// assign them the minimum column size
bool[] fixedColumn = new bool[columnWidths.Length];
for (int k = 0; k < columnWidths.Length; k++)
{
fixedColumn[k] = columnWidths[k] > 0;
if (columnWidths[k] == 0)
columnWidths[k] = _minimumColumnWidth;
}
// see if we fit
int currentTableWidth = CurrentTableWidth(columnWidths);
int availableWidth = _tableWidth - currentTableWidth;
if (availableWidth < 0)
{
// if the total width is too much, we will have to remove some columns
return false;
}
else if (availableWidth == 0)
{
// we just fit
return true;
}
// we still have room and we want to add more width
while (availableWidth > 0)
{
for (int k = 0; k < columnWidths.Length; k++)
{
if (fixedColumn[k])
continue;
columnWidths[k]++;
availableWidth--;
if (availableWidth == 0)
break;
}
}
return true; // we fit
}
/// <summary>
/// Trim columns if the total column width is too much for the screen.
/// </summary>
/// <param name="columnWidths">Column widths to trim.</param>
private void TrimToFit(Span<int> columnWidths)
{
while (true)
{
int currentTableWidth = CurrentTableWidth(columnWidths);
int widthInExcess = currentTableWidth - _tableWidth;
if (widthInExcess <= 0)
{
return; // we are done, because we fit
}
// we need to remove or shrink the last visible column
int lastVisibleColumn = GetLastVisibleColumn(columnWidths);
if (lastVisibleColumn < 0)
return; // nothing left to hide, because all the columns are hidden
// try to trim the last column to fit
int newLastVisibleColumnWidth = columnWidths[lastVisibleColumn] - widthInExcess;
if (newLastVisibleColumnWidth < _minimumColumnWidth)
{
// cannot fit it in, just hide
columnWidths[lastVisibleColumn] = -1;
continue;
}
else
{
// shrink the column to fit
columnWidths[lastVisibleColumn] = newLastVisibleColumnWidth;
}
}
}
/// <summary>
/// Computes the total table width from the column width array.
/// </summary>
/// <param name="columnWidths">Column widths array.</param>
/// <returns></returns>
private int CurrentTableWidth(Span<int> columnWidths)
{
int sum = 0;
int visibleColumns = 0;
for (int k = 0; k < columnWidths.Length; k++)
{
if (columnWidths[k] > 0)
{
sum += columnWidths[k];
visibleColumns++;
}
}
return sum + _separatorWidth * (visibleColumns - 1);
}
/// <summary>
/// Get the last visible column (i.e. with a width >= 0)
/// </summary>
/// <param name="columnWidths">Column widths array.</param>
/// <returns>Index of the last visible column, -1 if none.</returns>
private static int GetLastVisibleColumn(Span<int> columnWidths)
{
for (int k = 0; k < columnWidths.Length; k++)
{
if (columnWidths[k] < 0)
return k - 1;
}
return columnWidths.Length - 1;
}
private int _tableWidth;
private int _minimumColumnWidth;
private int _separatorWidth;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Amazon.SQS;
using Amazon.SQS.Model;
using JustSaying.Messaging;
using JustSaying.Messaging.Interrogation;
using JustSaying.Messaging.MessageHandling;
using JustSaying.Messaging.MessageProcessingStrategies;
using JustSaying.Messaging.MessageSerialisation;
using JustSaying.Messaging.Monitoring;
using Microsoft.Extensions.Logging;
using Message = JustSaying.Models.Message;
namespace JustSaying.AwsTools.MessageHandling
{
public class SqsNotificationListener : INotificationSubscriber
{
private readonly SqsQueueBase _queue;
private readonly IMessageMonitor _messagingMonitor;
private readonly List<string> _requestMessageAttributeNames = new List<string>();
private readonly MessageDispatcher _messageDispatcher;
private readonly MessageHandlerWrapper _messageHandlerWrapper;
private IMessageProcessingStrategy _messageProcessingStrategy;
private readonly HandlerMap _handlerMap = new HandlerMap();
private CancellationTokenSource _cts = new CancellationTokenSource();
private readonly ILogger _log;
public SqsNotificationListener(
SqsQueueBase queue,
IMessageSerialisationRegister serialisationRegister,
IMessageMonitor messagingMonitor,
ILoggerFactory loggerFactory,
Action<Exception, Amazon.SQS.Model.Message> onError = null,
IMessageLock messageLock = null,
IMessageBackoffStrategy messageBackoffStrategy = null)
{
_queue = queue;
_messagingMonitor = messagingMonitor;
onError = onError ?? ((ex, message) => { });
_log = loggerFactory.CreateLogger("JustSaying");
_messageProcessingStrategy = new DefaultThrottledThroughput(_messagingMonitor);
_messageHandlerWrapper = new MessageHandlerWrapper(messageLock, _messagingMonitor);
_messageDispatcher = new MessageDispatcher(queue, serialisationRegister, messagingMonitor, onError, _handlerMap, loggerFactory, messageBackoffStrategy);
Subscribers = new Collection<ISubscriber>();
if (messageBackoffStrategy != null)
{
_requestMessageAttributeNames.Add(MessageSystemAttributeName.ApproximateReceiveCount);
}
}
public string Queue => _queue.QueueName;
// ToDo: This should not be here.
public SqsNotificationListener WithMaximumConcurrentLimitOnMessagesInFlightOf(int maximumAllowedMesagesInFlight)
{
_messageProcessingStrategy = new Throttled(maximumAllowedMesagesInFlight, _messagingMonitor);
return this;
}
public SqsNotificationListener WithMessageProcessingStrategy(IMessageProcessingStrategy messageProcessingStrategy)
{
_messageProcessingStrategy = messageProcessingStrategy;
return this;
}
public void AddMessageHandler<T>(Func<IHandlerAsync<T>> futureHandler) where T : Message
{
if (_handlerMap.ContainsKey(typeof(T)))
{
throw new NotSupportedException(
$"The handler for '{typeof(T).Name}' messages on this queue has already been registered.");
}
Subscribers.Add(new Subscriber(typeof(T)));
var handlerFunc = _messageHandlerWrapper.WrapMessageHandler(futureHandler);
_handlerMap.Add(typeof(T), handlerFunc);
}
public void Listen()
{
var queue = _queue.QueueName;
var region = _queue.Region.SystemName;
var queueInfo = $"Queue: {queue}, Region: {region}";
_cts = new CancellationTokenSource();
Task.Factory.StartNew(async () =>
{
while (!_cts.IsCancellationRequested)
{
await ListenLoop(_cts.Token).ConfigureAwait(false);
}
})
.Unwrap()
.ContinueWith(t => LogTaskEndState(t, queueInfo, _log));
_log.LogInformation($"Starting Listening - {queueInfo}");
}
private static void LogTaskEndState(Task task, string queueInfo, ILogger log)
{
if (task.IsFaulted)
{
log.LogWarning($"[Faulted] Stopped Listening - {queueInfo}\n{AggregateExceptionDetails(task.Exception)}");
}
else
{
var endState = task.Status.ToString();
log.LogInformation($"[{endState}] Stopped Listening - {queueInfo}");
}
}
private static string AggregateExceptionDetails(AggregateException ex)
{
var flatEx = ex.Flatten();
if (flatEx.InnerExceptions.Count == 0)
{
return "AggregateException containing no inner exceptions\n" + ex;
}
if (flatEx.InnerExceptions.Count == 1)
{
return ex.InnerExceptions[0].ToString();
}
var innerExDetails = new StringBuilder();
innerExDetails.AppendFormat("AggregateException containing {0} inner exceptions", flatEx.InnerExceptions.Count);
foreach (var innerEx in flatEx.InnerExceptions)
{
innerExDetails.AppendLine(innerEx.ToString());
}
return innerExDetails.ToString();
}
public void StopListening()
{
_cts.Cancel();
_log.LogInformation($"Stopping Listening - Queue: {_queue.QueueName}, Region: {_queue.Region.SystemName}");
}
internal async Task ListenLoop(CancellationToken ct)
{
var queueName = _queue.QueueName;
var region = _queue.Region.SystemName;
ReceiveMessageResponse sqsMessageResponse = null;
try
{
sqsMessageResponse = await GetMessagesFromSqsQueue(ct, queueName, region).ConfigureAwait(false);
var messageCount = sqsMessageResponse.Messages.Count;
_log.LogTrace($"Polled for messages - Queue: {queueName}, Region: {region}, MessageCount: {messageCount}");
}
catch (InvalidOperationException ex)
{
_log.LogTrace($"Could not determine number of messages to read from [{queueName}], region: [{region}]. Ex: {ex}");
}
catch (OperationCanceledException ex)
{
_log.LogTrace($"Suspected no message in queue [{queueName}], region: [{region}]. Ex: {ex}");
}
catch (Exception ex)
{
var msg = $"Issue receiving messages for queue {queueName}, region {region}";
_log.LogError(0, ex, msg);
}
try
{
if (sqsMessageResponse != null)
{
foreach (var message in sqsMessageResponse.Messages)
{
HandleMessage(message);
}
}
}
catch (Exception ex)
{
var msg = $"Issue in message handling loop for queue {queueName}, region {region}";
_log.LogError(0, ex, msg);
}
}
private async Task<ReceiveMessageResponse> GetMessagesFromSqsQueue(CancellationToken ct, string queueName, string region)
{
var numberOfMessagesToReadFromSqs = await GetNumberOfMessagesToReadFromSqs()
.ConfigureAwait(false);
var watch = System.Diagnostics.Stopwatch.StartNew();
var request = new ReceiveMessageRequest
{
QueueUrl = _queue.Url,
MaxNumberOfMessages = numberOfMessagesToReadFromSqs,
WaitTimeSeconds = 20,
AttributeNames = _requestMessageAttributeNames
};
var receiveTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(300));
ReceiveMessageResponse sqsMessageResponse;
try
{
using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(ct, receiveTimeout.Token))
{
sqsMessageResponse = await _queue.Client.ReceiveMessageAsync(request, linkedCts.Token)
.ConfigureAwait(false);
}
}
finally
{
if (receiveTimeout.Token.IsCancellationRequested)
{
_log.LogInformation($"Receiving messages from queue {queueName}, region {region}, timed out");
}
}
watch.Stop();
_messagingMonitor.ReceiveMessageTime(watch.ElapsedMilliseconds, queueName, region);
return sqsMessageResponse;
}
private async Task<int> GetNumberOfMessagesToReadFromSqs()
{
var numberOfMessagesToReadFromSqs = Math.Min(_messageProcessingStrategy.AvailableWorkers, MessageConstants.MaxAmazonMessageCap);
if (numberOfMessagesToReadFromSqs == 0)
{
await _messageProcessingStrategy.WaitForAvailableWorkers().ConfigureAwait(false);
numberOfMessagesToReadFromSqs = Math.Min(_messageProcessingStrategy.AvailableWorkers, MessageConstants.MaxAmazonMessageCap);
}
if (numberOfMessagesToReadFromSqs == 0)
{
throw new InvalidOperationException("Cannot determine numberOfMessagesToReadFromSqs");
}
return numberOfMessagesToReadFromSqs;
}
private void HandleMessage(Amazon.SQS.Model.Message message)
{
var action = new Func<Task>(() => _messageDispatcher.DispatchMessage(message));
_messageProcessingStrategy.StartWorker(action);
}
public ICollection<ISubscriber> Subscribers { get; set; }
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Media.Capture;
using Windows.Media.Capture.Frames;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
public sealed partial class Scenario1_DisplayDepthColorIR : Page
{
private MediaCapture _mediaCapture;
private List<MediaFrameReader> _sourceReaders = new List<MediaFrameReader>();
private IReadOnlyDictionary<MediaFrameSourceKind, FrameRenderer> _frameRenderers;
private int _groupSelectionIndex;
private readonly SimpleLogger _logger;
public Scenario1_DisplayDepthColorIR()
{
InitializeComponent();
_logger = new SimpleLogger(outputTextBlock);
// This sample reads three kinds of frames: Color, Depth, and Infrared.
_frameRenderers = new Dictionary<MediaFrameSourceKind, FrameRenderer>()
{
{ MediaFrameSourceKind.Color, new FrameRenderer(colorPreviewImage) },
{ MediaFrameSourceKind.Depth, new FrameRenderer(depthPreviewImage)},
{ MediaFrameSourceKind.Infrared, new FrameRenderer(infraredPreviewImage)},
};
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
await PickNextMediaSourceAsync();
}
protected override async void OnNavigatedFrom(NavigationEventArgs e)
{
await CleanupMediaCaptureAsync();
}
private async void NextButton_Click(object eventSender, RoutedEventArgs eventArgs)
{
await PickNextMediaSourceAsync();
}
/// <summary>
/// Disables the "Next Group" button while we switch to the next camera
/// source and start reading frames.
/// </summary>
private async Task PickNextMediaSourceAsync()
{
try
{
this.NextButton.IsEnabled = false;
await PickNextMediaSourceWorkerAsync();
}
finally
{
this.NextButton.IsEnabled = true;
}
}
/// <summary>
/// Switches to the next camera source and starts reading frames.
/// </summary>
private async Task PickNextMediaSourceWorkerAsync()
{
await CleanupMediaCaptureAsync();
var allGroups = await MediaFrameSourceGroup.FindAllAsync();
if (allGroups.Count == 0)
{
_logger.Log("No source groups found.");
return;
}
// Pick next group in the array after each time the Next button is clicked.
_groupSelectionIndex = (_groupSelectionIndex + 1) % allGroups.Count;
var selectedGroup = allGroups[_groupSelectionIndex];
_logger.Log($"Found {allGroups.Count} groups and selecting index [{_groupSelectionIndex}]: {selectedGroup.DisplayName}");
try
{
// Initialize MediaCapture with selected group.
// This can raise an exception if the source no longer exists,
// or if the source could not be initialized.
await InitializeMediaCaptureAsync(selectedGroup);
}
catch (Exception exception)
{
_logger.Log($"MediaCapture initialization error: {exception.Message}");
await CleanupMediaCaptureAsync();
return;
}
// Set up frame readers, register event handlers and start streaming.
var startedKinds = new HashSet<MediaFrameSourceKind>();
foreach (MediaFrameSource source in _mediaCapture.FrameSources.Values)
{
MediaFrameSourceKind kind = source.Info.SourceKind;
// Ignore this source if we already have a source of this kind.
if (startedKinds.Contains(kind))
{
continue;
}
// Look for a format which the FrameRenderer can render.
string requestedSubtype = null;
foreach (MediaFrameFormat format in source.SupportedFormats)
{
requestedSubtype = FrameRenderer.GetSubtypeForFrameReader(kind, format);
if (requestedSubtype != null)
{
// Tell the source to use the format we can render.
await source.SetFormatAsync(format);
break;
}
}
if (requestedSubtype == null)
{
// No acceptable format was found. Ignore this source.
continue;
}
MediaFrameReader frameReader = await _mediaCapture.CreateFrameReaderAsync(source, requestedSubtype);
frameReader.FrameArrived += FrameReader_FrameArrived;
_sourceReaders.Add(frameReader);
MediaFrameReaderStartStatus status = await frameReader.StartAsync();
if (status == MediaFrameReaderStartStatus.Success)
{
_logger.Log($"Started {kind} reader.");
startedKinds.Add(kind);
}
else
{
_logger.Log($"Unable to start {kind} reader. Error: {status}");
}
}
if (startedKinds.Count == 0)
{
_logger.Log($"No eligible sources in {selectedGroup.DisplayName}.");
}
}
/// <summary>
/// Initializes the MediaCapture object with the given source group.
/// </summary>
/// <param name="sourceGroup">SourceGroup with which to initialize.</param>
private async Task InitializeMediaCaptureAsync(MediaFrameSourceGroup sourceGroup)
{
if (_mediaCapture != null)
{
return;
}
// Initialize mediacapture with the source group.
_mediaCapture = new MediaCapture();
var settings = new MediaCaptureInitializationSettings
{
SourceGroup = sourceGroup,
// This media capture can share streaming with other apps.
SharingMode = MediaCaptureSharingMode.SharedReadOnly,
// Only stream video and don't initialize audio capture devices.
StreamingCaptureMode = StreamingCaptureMode.Video,
// Set to CPU to ensure frames always contain CPU SoftwareBitmap images
// instead of preferring GPU D3DSurface images.
MemoryPreference = MediaCaptureMemoryPreference.Cpu
};
await _mediaCapture.InitializeAsync(settings);
_logger.Log("MediaCapture is successfully initialized in shared mode.");
}
/// <summary>
/// Unregisters FrameArrived event handlers, stops and disposes frame readers
/// and disposes the MediaCapture object.
/// </summary>
private async Task CleanupMediaCaptureAsync()
{
if (_mediaCapture != null)
{
using (var mediaCapture = _mediaCapture)
{
_mediaCapture = null;
foreach (var reader in _sourceReaders)
{
if (reader != null)
{
reader.FrameArrived -= FrameReader_FrameArrived;
await reader.StopAsync();
reader.Dispose();
}
}
_sourceReaders.Clear();
}
}
}
/// <summary>
/// Handles a frame arrived event and renders the frame to the screen.
/// </summary>
private void FrameReader_FrameArrived(MediaFrameReader sender, MediaFrameArrivedEventArgs args)
{
// TryAcquireLatestFrame will return the latest frame that has not yet been acquired.
// This can return null if there is no such frame, or if the reader is not in the
// "Started" state. The latter can occur if a FrameArrived event was in flight
// when the reader was stopped.
using (var frame = sender.TryAcquireLatestFrame())
{
if (frame != null)
{
var renderer = _frameRenderers[frame.SourceKind];
renderer.ProcessFrame(frame);
}
}
}
};
}
| |
//
// Notebook.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.Windows.Markup;
using Xwt.Drawing;
namespace Xwt
{
[BackendType (typeof(INotebookBackend))]
public class Notebook: Widget
{
ChildrenCollection<NotebookTab> tabs;
EventHandler currentTabChanged;
protected new class WidgetBackendHost: Widget.WidgetBackendHost, INotebookEventSink, ICollectionEventSink<NotebookTab>, IContainerEventSink<NotebookTab>
{
public void AddedItem (NotebookTab item, int index)
{
((Notebook)Parent).OnAdd (item);
}
public void RemovedItem (NotebookTab item, int index)
{
((Notebook)Parent).OnRemove (item.Child);
}
public void ChildChanged (NotebookTab child, string hint)
{
((Notebook)Parent).Backend.UpdateLabel (child, hint);
((Notebook)Parent).OnPreferredSizeChanged ();
}
public void ChildReplaced (NotebookTab child, Widget oldWidget, Widget newWidget)
{
((Notebook)Parent).OnReplaceChild (child, oldWidget, newWidget);
}
public void OnCurrentTabChanged ()
{
((Notebook)Parent).OnCurrentTabChanged (EventArgs.Empty);
}
}
static Notebook ()
{
MapEvent (NotebookEvent.CurrentTabChanged, typeof(Notebook), "OnCurrentTabChanged");
}
public Notebook ()
{
tabs = new ChildrenCollection <NotebookTab> ((WidgetBackendHost) BackendHost);
}
protected override BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
INotebookBackend Backend {
get { return (INotebookBackend) BackendHost.Backend; }
}
public void Add (Widget w, string label)
{
NotebookTab t = new NotebookTab ((WidgetBackendHost)BackendHost, w);
t.Label = label;
tabs.Add (t);
}
public void Add (Widget w, string label, Image image)
{
NotebookTab t = new NotebookTab ((WidgetBackendHost)BackendHost, w);
t.Label = label;
t.Image = image.GetImageDescription(BackendHost.ToolkitEngine);
tabs.Add (t);
}
void OnRemove (Widget child)
{
UnregisterChild (child);
Backend.Remove ((IWidgetBackend)GetBackend (child));
OnPreferredSizeChanged ();
}
void OnAdd (NotebookTab tab)
{
RegisterChild (tab.Child);
Backend.Add ((IWidgetBackend)GetBackend (tab.Child), tab);
OnPreferredSizeChanged ();
}
void OnReplaceChild (NotebookTab tab, Widget oldWidget, Widget newWidget)
{
if (oldWidget != null)
OnRemove (oldWidget);
OnAdd (tab);
}
public ChildrenCollection<NotebookTab> Tabs {
get { return tabs; }
}
public NotebookTab CurrentTab {
get {
return tabs [Backend.CurrentTab];
}
set {
for (int n=0; n<tabs.Count; n++) {
if (tabs[n] == value) {
Backend.CurrentTab = n;
return;
}
}
CurrentTabIndex = -1;
}
}
public int CurrentTabIndex {
get { return Backend.CurrentTab; }
set { Backend.CurrentTab = value; }
}
public NotebookTabOrientation TabOrientation {
get { return Backend.TabOrientation; }
set { Backend.TabOrientation = value; }
}
public bool ExpandTabLabels {
get { return Backend.ExpandTabLabels; }
set { Backend.ExpandTabLabels = value; }
}
protected virtual void OnCurrentTabChanged (EventArgs e)
{
if (currentTabChanged != null)
currentTabChanged (this, e);
}
public event EventHandler CurrentTabChanged {
add {
BackendHost.OnBeforeEventAdd (NotebookEvent.CurrentTabChanged, currentTabChanged);
currentTabChanged += value;
}
remove {
currentTabChanged -= value;
BackendHost.OnAfterEventRemove (NotebookEvent.CurrentTabChanged, currentTabChanged);
}
}
}
[ContentProperty("Child")]
public class NotebookTab
{
IContainerEventSink<NotebookTab> parent;
string label;
ImageDescription image;
Widget child;
internal NotebookTab (IContainerEventSink<NotebookTab> parent, Widget child)
{
this.child = child;
this.parent = parent;
}
public string Label {
get {
return label;
}
set {
label = value;
parent.ChildChanged (this, "Label");
}
}
public ImageDescription Image {
get { return image; }
set {
image = value;
parent.ChildChanged (this, "Image");
}
}
public Widget Child {
get {
return child;
}
set {
var oldVal = child;
child = value;
parent.ChildReplaced (this, oldVal, value);
}
}
}
public enum NotebookTabOrientation {
Top,
Left,
Right,
Bottom
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
// Helper class used to manage the lifetime of a connection relative to its pool.
internal abstract class ConnectionPoolHelper
{
private IConnectionInitiator _connectionInitiator;
private ConnectionPool _connectionPool;
private Uri _via;
private bool _closed;
// key for rawConnection in the connection pool
private string _connectionKey;
// did rawConnection originally come from connectionPool?
private bool _isConnectionFromPool;
// the "raw" connection that should be stored in the pool
private IConnection _rawConnection;
// the "upgraded" connection built on top of the "raw" connection to be used for I/O
private IConnection _upgradedConnection;
public ConnectionPoolHelper(ConnectionPool connectionPool, IConnectionInitiator connectionInitiator, Uri via)
{
_connectionInitiator = connectionInitiator;
_connectionPool = connectionPool;
_via = via;
}
private object ThisLock
{
get { return this; }
}
protected abstract IConnection AcceptPooledConnection(IConnection connection, ref TimeoutHelper timeoutHelper);
protected abstract Task<IConnection> AcceptPooledConnectionAsync(IConnection connection, ref TimeoutHelper timeoutHelper);
protected abstract TimeoutException CreateNewConnectionTimeoutException(TimeSpan timeout, TimeoutException innerException);
private IConnection TakeConnection(TimeSpan timeout)
{
return _connectionPool.TakeConnection(null, _via, timeout, out _connectionKey);
}
public async Task<IConnection> EstablishConnectionAsync(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
IConnection localRawConnection = null;
IConnection localUpgradedConnection = null;
bool localIsConnectionFromPool = true;
// first try and use a connection from our pool (and use it if we successfully receive an ACK)
while (localIsConnectionFromPool)
{
localRawConnection = TakeConnection(timeoutHelper.RemainingTime());
if (localRawConnection == null)
{
localIsConnectionFromPool = false;
}
else
{
bool preambleSuccess = false;
try
{
localUpgradedConnection = await AcceptPooledConnectionAsync(localRawConnection, ref timeoutHelper);
preambleSuccess = true;
break;
}
catch (CommunicationException)
{
// CommunicationException is ok since it was a cached connection of unknown state
}
catch (TimeoutException)
{
// ditto for TimeoutException
}
finally
{
if (!preambleSuccess)
{
// This cannot throw TimeoutException since isConnectionStillGood is false (doesn't attempt a Close).
_connectionPool.ReturnConnection(_connectionKey, localRawConnection, false, TimeSpan.Zero);
}
}
}
}
// if there isn't anything in the pool, we need to use a new connection
if (!localIsConnectionFromPool)
{
bool success = false;
TimeSpan connectTimeout = timeoutHelper.RemainingTime();
try
{
try
{
localRawConnection = await _connectionInitiator.ConnectAsync(_via, connectTimeout);
}
catch (TimeoutException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateNewConnectionTimeoutException(
connectTimeout, e));
}
_connectionInitiator = null;
localUpgradedConnection = await AcceptPooledConnectionAsync(localRawConnection, ref timeoutHelper);
success = true;
}
finally
{
if (!success)
{
_connectionKey = null;
if (localRawConnection != null)
{
localRawConnection.Abort();
}
}
}
}
SnapshotConnection(localUpgradedConnection, localRawConnection, localIsConnectionFromPool);
return localUpgradedConnection;
}
public IConnection EstablishConnection(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
IConnection localRawConnection = null;
IConnection localUpgradedConnection = null;
bool localIsConnectionFromPool = true;
// first try and use a connection from our pool (and use it if we successfully receive an ACK)
while (localIsConnectionFromPool)
{
localRawConnection = TakeConnection(timeoutHelper.RemainingTime());
if (localRawConnection == null)
{
localIsConnectionFromPool = false;
}
else
{
bool preambleSuccess = false;
try
{
localUpgradedConnection = AcceptPooledConnection(localRawConnection, ref timeoutHelper);
preambleSuccess = true;
break;
}
catch (CommunicationException /*e*/)
{
// CommunicationException is ok since it was a cached connection of unknown state
}
catch (TimeoutException /*e*/)
{
// ditto for TimeoutException
}
finally
{
if (!preambleSuccess)
{
// This cannot throw TimeoutException since isConnectionStillGood is false (doesn't attempt a Close).
_connectionPool.ReturnConnection(_connectionKey, localRawConnection, false, TimeSpan.Zero);
}
}
}
}
// if there isn't anything in the pool, we need to use a new connection
if (!localIsConnectionFromPool)
{
bool success = false;
TimeSpan connectTimeout = timeoutHelper.RemainingTime();
try
{
try
{
localRawConnection = _connectionInitiator.Connect(_via, connectTimeout);
}
catch (TimeoutException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateNewConnectionTimeoutException(
connectTimeout, e));
}
_connectionInitiator = null;
localUpgradedConnection = AcceptPooledConnection(localRawConnection, ref timeoutHelper);
success = true;
}
finally
{
if (!success)
{
_connectionKey = null;
if (localRawConnection != null)
{
localRawConnection.Abort();
}
}
}
}
SnapshotConnection(localUpgradedConnection, localRawConnection, localIsConnectionFromPool);
return localUpgradedConnection;
}
private void SnapshotConnection(IConnection upgradedConnection, IConnection rawConnection, bool isConnectionFromPool)
{
lock (ThisLock)
{
if (_closed)
{
upgradedConnection.Abort();
// cleanup our pool if necessary
if (isConnectionFromPool)
{
_connectionPool.ReturnConnection(_connectionKey, rawConnection, false, TimeSpan.Zero);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new CommunicationObjectAbortedException(
SR.Format(SR.OperationAbortedDuringConnectionEstablishment, _via)));
}
else
{
_upgradedConnection = upgradedConnection;
_rawConnection = rawConnection;
_isConnectionFromPool = isConnectionFromPool;
}
}
}
public void Abort()
{
ReleaseConnection(true, TimeSpan.Zero);
}
public void Close(TimeSpan timeout)
{
ReleaseConnection(false, timeout);
}
private void ReleaseConnection(bool abort, TimeSpan timeout)
{
string localConnectionKey;
IConnection localUpgradedConnection;
IConnection localRawConnection;
lock (ThisLock)
{
_closed = true;
localConnectionKey = _connectionKey;
localUpgradedConnection = _upgradedConnection;
localRawConnection = _rawConnection;
_upgradedConnection = null;
_rawConnection = null;
}
if (localUpgradedConnection == null)
{
return;
}
try
{
if (_isConnectionFromPool)
{
_connectionPool.ReturnConnection(localConnectionKey, localRawConnection, !abort, timeout);
}
else
{
if (abort)
{
localUpgradedConnection.Abort();
}
else
{
_connectionPool.AddConnection(localConnectionKey, localRawConnection, timeout);
}
}
}
catch (CommunicationException /*e*/)
{
localUpgradedConnection.Abort();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Utils;
namespace DotVVM.Framework.Controls
{
[StructLayout(LayoutKind.Explicit)]
internal struct DotvvmControlProperties : IEnumerable<KeyValuePair<DotvvmProperty, object?>>
{
// There are 3 possible states of this structure:
// 1. keys == values == null --> it is empty
// 2. keys == null & values is Dictionary<DotvvmProperty, object> --> it falls back to traditional mutable property dictionary
// 3. keys is DotvvmProperty[] & values is object[] --> read-only perfect 2-slot hashing
[FieldOffset(0)]
private object? keys;
[FieldOffset(0)]
private DotvvmProperty?[] keysAsArray;
[FieldOffset(8)]
private object? values;
[FieldOffset(8)]
private object?[] valuesAsArray;
[FieldOffset(8)]
private Dictionary<DotvvmProperty, object?> valuesAsDictionary;
[FieldOffset(16)]
private int hashSeed;
public void AssignBulk(DotvvmProperty?[] keys, object?[] values, int hashSeed)
{
// The explicit layout is quite likely to mess with array covariance, just make sure we don't encounter that
Debug.Assert(values.GetType() == typeof(object[]));
Debug.Assert(keys.GetType() == typeof(DotvvmProperty[]));
Debug.Assert(keys.Length == values.Length);
if (this.values == null || this.keys == keys)
{
this.valuesAsArray = values;
this.keysAsArray = keys;
this.hashSeed = hashSeed;
}
else
{
// we can just to check if all current properties are in the proposed set
// if they are not we will have to copy it
if (this.keys == null) // TODO: is this heuristic actually useful?
{
var ok = true;
foreach (var x in (Dictionary<DotvvmProperty, object>)this.values)
{
var e = PropertyImmutableHashtable.FindSlot(keys, hashSeed, x.Key);
if (e < 0 || !Object.Equals(values[e], x.Value))
ok = false;
}
if (ok)
{
this.values = values;
this.keys = keys;
this.hashSeed = hashSeed;
return;
}
}
for (int i = 0; i < keys.Length; i++)
{
if (keys[i] != null)
this.Set(keys[i]!, values[i]);
}
}
}
public void ClearEverything()
{
values = null;
keys = null;
}
public bool Contains(DotvvmProperty p)
{
if (values == null) { return false; }
if (keys == null)
{
Debug.Assert(values is Dictionary<DotvvmProperty, object>);
return valuesAsDictionary.ContainsKey(p);
}
Debug.Assert(values is object[]);
Debug.Assert(keys is DotvvmProperty[]);
return PropertyImmutableHashtable.ContainsKey(this.keysAsArray, this.hashSeed, p);
}
public bool TryGet(DotvvmProperty p, out object? value)
{
value = null;
if (values == null) { return false; }
if (keys == null)
{
Debug.Assert(values is Dictionary<DotvvmProperty, object>);
return valuesAsDictionary.TryGetValue(p, out value);
}
Debug.Assert(values is object[]);
Debug.Assert(keys is DotvvmProperty[]);
var index = PropertyImmutableHashtable.FindSlot(this.keysAsArray, this.hashSeed, p);
if (index != -1)
value = this.valuesAsArray[index & (this.keysAsArray.Length - 1)];
return index != -1;
}
public object? GetOrThrow(DotvvmProperty p)
{
if (this.TryGet(p, out var x)) return x;
throw new KeyNotFoundException();
}
public void Set(DotvvmProperty p, object? value)
{
if (values == null)
{
Debug.Assert(keys == null);
var d = new Dictionary<DotvvmProperty, object?>();
d[p] = value;
this.values = d;
}
else if (keys == null)
{
Debug.Assert(values is Dictionary<DotvvmProperty, object?>);
valuesAsDictionary[p] = value;
}
else
{
Debug.Assert(this.values is object[]);
Debug.Assert(this.keys is DotvvmProperty[]);
var keys = this.keysAsArray;
var values = this.valuesAsArray;
var slot = PropertyImmutableHashtable.FindSlot(keys, this.hashSeed, p);
if (slot >= 0 && Object.Equals(values[slot], value))
{
// no-op, we would be changing it to the same value
}
else
{
var d = new Dictionary<DotvvmProperty, object?>();
for (int i = 0; i < keys.Length; i++)
{
if (keys[i] != null)
d[keys[i]!] = values[i];
}
d[p] = value;
this.valuesAsDictionary = d;
this.keys = null;
}
}
}
/// <summary> Tries to set value into the dictionary without overwriting anything. </summary>
public bool TryAdd(DotvvmProperty p, object? value)
{
if (values == null)
{
Debug.Assert(keys == null);
var d = new Dictionary<DotvvmProperty, object?>();
d[p] = value;
this.values = d;
return true;
}
else if (keys == null)
{
Debug.Assert(values is Dictionary<DotvvmProperty, object?>);
#if CSharp8Polyfill
if (valuesAsDictionary.TryGetValue(p, out var existingValue))
return Object.Equals(existingValue, value);
else
{
valuesAsDictionary.Add(p, value);
return true;
}
#else
if (valuesAsDictionary.TryAdd(p, value))
return true;
else
return Object.Equals(valuesAsDictionary[p], value);
#endif
}
else
{
Debug.Assert(this.values is object[]);
Debug.Assert(this.keys is DotvvmProperty[]);
var keys = this.keysAsArray;
var values = this.valuesAsArray;
var slot = PropertyImmutableHashtable.FindSlot(keys, this.hashSeed, p);
if (slot >= 0)
{
// value already exists
return Object.Equals(values[slot], value);
}
else
{
var d = new Dictionary<DotvvmProperty, object?>();
for (int i = 0; i < keys.Length; i++)
{
if (keys[i] != null)
d[keys[i]!] = values[i];
}
d[p] = value;
this.valuesAsDictionary = d;
this.keys = null;
return true;
}
}
}
public DotvvmControlPropertiesEnumerator GetEnumerator()
{
if (values == null) return EmptyEnumerator;
if (keys == null) return new DotvvmControlPropertiesEnumerator(valuesAsDictionary.GetEnumerator());
return new DotvvmControlPropertiesEnumerator(this.keysAsArray, this.valuesAsArray);
}
IEnumerator<KeyValuePair<DotvvmProperty, object?>> IEnumerable<KeyValuePair<DotvvmProperty, object?>>.GetEnumerator() =>
GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private static DotvvmControlPropertiesEnumerator EmptyEnumerator = new DotvvmControlPropertiesEnumerator(new DotvvmProperty[0], new object[0]);
public bool Remove(DotvvmProperty key)
{
if (!Contains(key)) return false;
if (this.keys == null && valuesAsDictionary != null)
{
return valuesAsDictionary.Remove(key);
}
// move from read-only struct to mutable struct
{
var keysTmp = this.keysAsArray;
var valuesTmp = this.valuesAsArray;
var d = new Dictionary<DotvvmProperty, object?>();
for (int i = 0; i < keysTmp.Length; i++)
{
if (keysTmp[i] != null && keysTmp[i] != key)
d[keysTmp[i]!] = valuesTmp[i];
}
this.valuesAsDictionary = d;
this.keys = null;
return true;
}
}
private static object? CloneValue(object? value)
{
if (value is DotvvmBindableObject bindableObject)
return bindableObject.CloneControl();
return null;
}
public int Count()
{
if (this.values == null) return 0;
if (this.keys == null)
return this.valuesAsDictionary.Count;
int count = 0;
for (int i = 0; i < this.keysAsArray.Length; i++)
{
// get rid of a branch which would be almost always misspredicted
var x = this.keysAsArray[i] is not null;
count += Unsafe.As<bool, byte>(ref x);
}
return count;
}
internal void CloneInto(ref DotvvmControlProperties newDict)
{
if (this.values == null)
{
newDict = default;
return;
}
else if (this.keys == null)
{
var dictionary = this.valuesAsDictionary;
if (dictionary.Count > 30)
{
newDict = this;
newDict.valuesAsDictionary = new Dictionary<DotvvmProperty, object?>(dictionary);
foreach (var (key, value) in dictionary)
if (CloneValue(value) is {} newValue)
newDict.valuesAsDictionary[key] = newValue;
return;
}
// move to immutable version if it's reasonably small. It will be probably cloned multiple times again
var properties = new DotvvmProperty[dictionary.Count];
var values = new object?[properties.Length];
int j = 0;
foreach (var x in this.valuesAsDictionary)
{
(properties[j], values[j]) = x;
j++;
}
Array.Sort(properties, values, PropertyImmutableHashtable.DotvvmPropertyComparer.Instance);
(this.hashSeed, this.keysAsArray, this.valuesAsArray) = PropertyImmutableHashtable.CreateTableWithValues(properties, values);
}
newDict = this;
for (int i = 0; i < newDict.valuesAsArray.Length; i++)
{
if (CloneValue(newDict.valuesAsArray[i]) is {} newValue)
{
// clone the array if we didn't do that already
if (newDict.values == this.values)
newDict.values = this.valuesAsArray.Clone();
newDict.valuesAsArray[i] = newValue;
}
}
}
}
public struct DotvvmControlPropertiesEnumerator : IEnumerator<KeyValuePair<DotvvmProperty, object?>>
{
private DotvvmProperty?[]? keys;
private object?[]? values;
private int index;
private Dictionary<DotvvmProperty, object?>.Enumerator dictEnumerator;
internal DotvvmControlPropertiesEnumerator(DotvvmProperty?[] keys, object?[] values)
{
this.keys = keys;
this.values = values;
this.index = -1;
dictEnumerator = default;
}
internal DotvvmControlPropertiesEnumerator(in Dictionary<DotvvmProperty, object?>.Enumerator e)
{
this.keys = null;
this.values = null;
this.index = 0;
this.dictEnumerator = e;
}
public KeyValuePair<DotvvmProperty, object?> Current => keys == null ? dictEnumerator.Current : new KeyValuePair<DotvvmProperty, object?>(keys[index]!, values![index]);
object IEnumerator.Current => this.Current;
public void Dispose()
{
}
public bool MoveNext()
{
if (keys == null)
return dictEnumerator.MoveNext();
while (++index < keys.Length && keys[index] == null) { }
return index < keys.Length;
}
public void Reset()
{
if (keys == null)
((IEnumerator)dictEnumerator).Reset();
else index = -1;
}
}
public readonly struct DotvvmPropertyDictionary : IDictionary<DotvvmProperty, object?>
{
private readonly DotvvmBindableObject control;
public DotvvmPropertyDictionary(DotvvmBindableObject control)
{
this.control = control;
}
public object? this[DotvvmProperty key] { get => control.properties.GetOrThrow(key); set => control.properties.Set(key, value); }
public ICollection<DotvvmProperty> Keys => throw new NotImplementedException();
public ICollection<object?> Values => throw new NotImplementedException();
public int Count => control.properties.Count();
public bool IsReadOnly => false;
public void Add(DotvvmProperty key, object? value)
{
if (!control.properties.TryAdd(key, value))
throw new System.ArgumentException("An item with the same key has already been added.");
}
public bool TryAdd(DotvvmProperty key, object? value)
{
return control.properties.TryAdd(key, value);
}
public void Add(KeyValuePair<DotvvmProperty, object?> item) => Add(item.Key, item.Value);
public void Clear()
{
control.properties.ClearEverything();
}
public bool Contains(KeyValuePair<DotvvmProperty, object?> item) => control.properties.TryGet(item.Key, out var x) && Object.Equals(x, item.Value);
public bool ContainsKey(DotvvmProperty key) => control.properties.Contains(key);
public void CopyTo(KeyValuePair<DotvvmProperty, object?>[] array, int arrayIndex)
{
foreach (var x in control.properties)
{
array[arrayIndex++] = x;
}
}
public DotvvmControlPropertiesEnumerator GetEnumerator() => control.properties.GetEnumerator();
public bool Remove(DotvvmProperty key)
{
return control.properties.Remove(key);
}
public bool Remove(KeyValuePair<DotvvmProperty, object?> item)
{
throw new NotImplementedException();
}
public bool TryGetValue(DotvvmProperty key, out object? value) =>
control.properties.TryGet(key, out value);
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
IEnumerator<KeyValuePair<DotvvmProperty, object?>> IEnumerable<KeyValuePair<DotvvmProperty, object?>>.GetEnumerator() => this.GetEnumerator();
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
namespace AutoTest.Messages
{
public class TestResult : ICustomBinarySerializable
{
private TestRunner _runner;
private TestRunStatus _status;
private string _name = "";
private string _displayName = null;
private string _message = "";
private IStackLine[] _stackTrace;
private static readonly TestResult _passResult;
public TimeSpan TimeSpent = new TimeSpan();
/// <summary>
/// Factory method to return passed message
/// </summary>
/// <returns>Passed test result with no message</returns>
public static TestResult Pass()
{
return _passResult;
}
/// <summary>
/// Factory method to return failed result
/// </summary>
/// <param name="message">The failure message</param>
/// <returns>A failed result</returns>
public static TestResult Fail(string message)
{
return new TestResult(TestRunner.Any, TestRunStatus.Failed, message);
}
public TestResult(TestRunner runner, TestRunStatus status, string name)
{
_runner = runner;
_name = name;
_status = status;
_stackTrace = new IStackLine[] { };
}
public TestResult(TestRunner runner, TestRunStatus status, string name, string message)
{
_runner = runner;
_status = status;
_name = name;
_message = message;
_stackTrace = new IStackLine[] { };
}
public TestResult(TestRunner runner, TestRunStatus status, string name, string message, IStackLine[] stackTrace)
{
_runner = runner;
_status = status;
_name = name;
_message = message;
_stackTrace = stackTrace;
}
public TestResult(TestRunner runner, TestRunStatus status, string name, string message, IStackLine[] stackTrace, double milliseconds)
{
_runner = runner;
_status = status;
_name = name;
_message = message;
_stackTrace = stackTrace;
TimeSpent = TimeSpan.FromMilliseconds(milliseconds);
}
static TestResult()
{
_passResult = new TestResult(TestRunner.Any, TestRunStatus.Passed, string.Empty);
}
public TestRunner Runner
{
get { return _runner; }
}
public TestRunStatus Status
{
get { return _status; }
}
public string Name
{
get { return _name; }
}
public string DisplayName
{
get
{
if (_displayName == null)
return _name;
return _displayName;
}
}
public string Message
{
get { return _message; } set { _message = value; }
}
public IStackLine[] StackTrace
{
get { return _stackTrace; } set { _stackTrace = value; }
}
public TestResult SetDisplayName(string name)
{
_displayName = name;
return this;
}
public override bool Equals(object obj)
{
var other = (TestResult) obj;
return GetHashCode().Equals(other.GetHashCode());
}
public override int GetHashCode()
{
// Overflow is fine, just wrap
unchecked
{
int hash = 17;
hash = hash * 23 + _runner.GetHashCode();
hash = hash * 23 + (_name == null ? 0 : _name.GetHashCode());
hash = hash * 23 + (_message == null ? 0 : _message.GetHashCode());
foreach (var line in _stackTrace)
{
hash = hash * 23 + (line.File == null ? 0 : line.File.GetHashCode());
hash = hash * 23 + (line.Method == null ? 0 : line.Method.GetHashCode());
hash = hash * 23 + line.LineNumber.GetHashCode();
}
return hash;
}
}
public void WriteDataTo(BinaryWriter writer)
{
writer.Write((int)_runner);
writer.Write((int) _status);
if (_name == null)
writer.Write("");
else
writer.Write(_name);
if (_displayName == null)
writer.Write("");
else
writer.Write(_displayName);
if (_message == null)
writer.Write("");
else
writer.Write((string) _message);
writer.Write((double)TimeSpent.Ticks);
writer.Write((int)_stackTrace.Length);
foreach (var line in _stackTrace)
{
if (line.Method == null)
writer.Write("");
else
writer.Write((string) line.Method);
if (line.File == null)
writer.Write("");
else
writer.Write((string) line.File);
writer.Write((int) line.LineNumber);
}
}
public void SetDataFrom(BinaryReader reader)
{
var stackTrace = new List<IStackLine>();
_runner = (TestRunner)reader.ReadInt32();
_status = (TestRunStatus) reader.ReadInt32();
_name = reader.ReadString();
_displayName = reader.ReadString();
if (_displayName == "")
_displayName = null;
_message = reader.ReadString();
TimeSpent = new TimeSpan((long)reader.ReadDouble());
var count = reader.ReadInt32();
for (int i = 0; i < count; i++)
{
var method = reader.ReadString();
var file = reader.ReadString();
var lineNumber = reader.ReadInt32();
var line = new StackLineMessage(method, file, lineNumber);
stackTrace.Add(line);
}
_stackTrace = stackTrace.ToArray();
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Figure element.
//
//---------------------------------------------------------------------------
using System.ComponentModel; // TypeConverter
using System.Windows.Controls; // TextBlock
using MS.Internal;
using MS.Internal.PtsHost.UnsafeNativeMethods; // PTS restrictions
namespace System.Windows.Documents
{
/// <summary>
/// Figure element.
/// </summary>
public class Figure : AnchoredBlock
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
/// <summary>
/// Initialized the new instance of a Figure
/// </summary>
public Figure() : this(null)
{
}
/// <summary>
/// Initialized the new instance of a Figure specifying a Block added
/// to a Figure as its first child.
/// </summary>
/// <param name="childBlock">
/// Block added as a first initial child of the Figure.
/// </param>
public Figure(Block childBlock) : this(childBlock, null)
{
}
/// <summary>
/// Creates a new Figure instance.
/// </summary>
/// <param name="childBlock">
/// Optional child of the new Figure, may be null.
/// </param>
/// <param name="insertionPosition">
/// Optional position at which to insert the new Figure. May
/// be null.
/// </param>
public Figure(Block childBlock, TextPointer insertionPosition) : base(childBlock, insertionPosition)
{
}
#endregion Constructors
//-------------------------------------------------------------------
//
// Public Properties
//
//-------------------------------------------------------------------
#region Public Properties
/// <summary>
/// DependencyProperty for <see cref="HorizontalAnchor" /> property.
/// </summary>
public static readonly DependencyProperty HorizontalAnchorProperty =
DependencyProperty.Register(
"HorizontalAnchor",
typeof(FigureHorizontalAnchor),
typeof(Figure),
new FrameworkPropertyMetadata(
FigureHorizontalAnchor.ColumnRight,
FrameworkPropertyMetadataOptions.AffectsParentMeasure),
new ValidateValueCallback(IsValidHorizontalAnchor));
/// <summary>
///
/// </summary>
public FigureHorizontalAnchor HorizontalAnchor
{
get { return (FigureHorizontalAnchor)GetValue(HorizontalAnchorProperty); }
set { SetValue(HorizontalAnchorProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="VerticalAnchor" /> property.
/// </summary>
public static readonly DependencyProperty VerticalAnchorProperty =
DependencyProperty.Register(
"VerticalAnchor",
typeof(FigureVerticalAnchor),
typeof(Figure),
new FrameworkPropertyMetadata(
FigureVerticalAnchor.ParagraphTop,
FrameworkPropertyMetadataOptions.AffectsParentMeasure),
new ValidateValueCallback(IsValidVerticalAnchor));
/// <summary>
///
/// </summary>
public FigureVerticalAnchor VerticalAnchor
{
get { return (FigureVerticalAnchor)GetValue(VerticalAnchorProperty); }
set { SetValue(VerticalAnchorProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="HorizontalOffset" /> property.
/// </summary>
public static readonly DependencyProperty HorizontalOffsetProperty =
DependencyProperty.Register(
"HorizontalOffset",
typeof(double),
typeof(Figure),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.AffectsParentMeasure),
new ValidateValueCallback(IsValidOffset));
/// <summary>
///
/// </summary>
[TypeConverter(typeof(LengthConverter))]
public double HorizontalOffset
{
get { return (double)GetValue(HorizontalOffsetProperty); }
set { SetValue(HorizontalOffsetProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="VerticalOffset" /> property.
/// </summary>
public static readonly DependencyProperty VerticalOffsetProperty =
DependencyProperty.Register(
"VerticalOffset",
typeof(double),
typeof(Figure),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.AffectsParentMeasure),
new ValidateValueCallback(IsValidOffset));
/// <summary>
///
/// </summary>
[TypeConverter(typeof(LengthConverter))]
public double VerticalOffset
{
get { return (double)GetValue(VerticalOffsetProperty); }
set { SetValue(VerticalOffsetProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="CanDelayPlacement" /> property.
/// </summary>
public static readonly DependencyProperty CanDelayPlacementProperty =
DependencyProperty.Register(
"CanDelayPlacement",
typeof(bool),
typeof(Figure),
new FrameworkPropertyMetadata(
true,
FrameworkPropertyMetadataOptions.AffectsParentMeasure));
/// <summary>
///
/// </summary>
public bool CanDelayPlacement
{
get { return (bool)GetValue(CanDelayPlacementProperty); }
set { SetValue(CanDelayPlacementProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="WrapDirection" /> property.
/// </summary>
public static readonly DependencyProperty WrapDirectionProperty =
DependencyProperty.Register(
"WrapDirection",
typeof(WrapDirection),
typeof(Figure),
new FrameworkPropertyMetadata(
WrapDirection.Both,
FrameworkPropertyMetadataOptions.AffectsParentMeasure),
new ValidateValueCallback(IsValidWrapDirection));
/// <summary>
///
/// </summary>
public WrapDirection WrapDirection
{
get { return (WrapDirection)GetValue(WrapDirectionProperty); }
set { SetValue(WrapDirectionProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="Width" /> property.
/// </summary>
public static readonly DependencyProperty WidthProperty =
DependencyProperty.Register(
"Width",
typeof(FigureLength),
typeof(Figure),
new FrameworkPropertyMetadata(
new FigureLength(1.0, FigureUnitType.Auto),
FrameworkPropertyMetadataOptions.AffectsMeasure));
/// <summary>
/// The Width property specifies the width of the element.
/// </summary>
public FigureLength Width
{
get { return (FigureLength)GetValue(WidthProperty); }
set { SetValue(WidthProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="Height" /> property.
/// </summary>
public static readonly DependencyProperty HeightProperty =
DependencyProperty.Register(
"Height",
typeof(FigureLength),
typeof(Figure),
new FrameworkPropertyMetadata(
new FigureLength(1.0, FigureUnitType.Auto),
FrameworkPropertyMetadataOptions.AffectsMeasure));
/// <summary>
/// The Height property specifies the height of the element.
/// </summary>
public FigureLength Height
{
get { return (FigureLength)GetValue(HeightProperty); }
set { SetValue(HeightProperty, value); }
}
#endregion Public Properties
//-------------------------------------------------------------------
//
// Private Methods
//
//-------------------------------------------------------------------
#region Private Methods
private static bool IsValidHorizontalAnchor(object o)
{
FigureHorizontalAnchor value = (FigureHorizontalAnchor)o;
return value == FigureHorizontalAnchor.ContentCenter
|| value == FigureHorizontalAnchor.ContentLeft
|| value == FigureHorizontalAnchor.ContentRight
|| value == FigureHorizontalAnchor.PageCenter
|| value == FigureHorizontalAnchor.PageLeft
|| value == FigureHorizontalAnchor.PageRight
|| value == FigureHorizontalAnchor.ColumnCenter
|| value == FigureHorizontalAnchor.ColumnLeft
|| value == FigureHorizontalAnchor.ColumnRight;
// || value == FigureHorizontalAnchor.CharacterCenter
// || value == FigureHorizontalAnchor.CharacterLeft
// || value == FigureHorizontalAnchor.CharacterRight;
}
private static bool IsValidVerticalAnchor(object o)
{
FigureVerticalAnchor value = (FigureVerticalAnchor)o;
return value == FigureVerticalAnchor.ContentBottom
|| value == FigureVerticalAnchor.ContentCenter
|| value == FigureVerticalAnchor.ContentTop
|| value == FigureVerticalAnchor.PageBottom
|| value == FigureVerticalAnchor.PageCenter
|| value == FigureVerticalAnchor.PageTop
|| value == FigureVerticalAnchor.ParagraphTop;
// || value == FigureVerticalAnchor.CharacterBottom
// || value == FigureVerticalAnchor.CharacterCenter
// || value == FigureVerticalAnchor.CharacterTop;
}
private static bool IsValidWrapDirection(object o)
{
WrapDirection value = (WrapDirection)o;
return value == WrapDirection.Both
|| value == WrapDirection.None
|| value == WrapDirection.Left
|| value == WrapDirection.Right;
}
private static bool IsValidOffset(object o)
{
double offset = (double)o;
double maxOffset = Math.Min(1000000, PTS.MaxPageSize);
double minOffset = -maxOffset;
if (Double.IsNaN(offset))
{
return false;
}
if (offset < minOffset || offset > maxOffset)
{
return false;
}
return true;
}
#endregion Private Methods
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using LibCSV;
using LibCSV.Dialects;
using LibCSV.Exceptions;
using NUnit.Framework;
using static NUnit.Framework.Assert;
namespace LibCSV.Tests
{
[TestFixture]
public class WriterTests
{
[Test]
public void WriteRow_Convertibles_WroteConvertibles()
{
WriteAndTestRow(
new object[] { 123, 123.45, 10M, 1, new DateTime(2015, 10, 26, 10, 11, 12) },
"123;123.45;10;1;10/26/2015 10:11:12\r\n", null);
}
[Test]
public void WriteRow_Nulls_WroteEmptyStrings()
{
WriteAndTestRow(new object[] { null, null }, ";\r\n", null);
}
[Test]
public void WriteRow_Strings_WroteStrings()
{
WriteAndTestRow(
new object[] { "This is string1", "This is string2" },
"\"This is string1\";\"This is string2\"\r\n", null);
}
[Test]
public void WriteRow_Dates_WroteDates()
{
WriteAndTestRow(
new object[]
{
new DateTime(2010, 9, 3, 0, 0, 0),
new DateTime(2010, 9, 4, 0, 0, 0)
},
"09/03/2010 00:00:00;09/04/2010 00:00:00\r\n", null);
}
[Test]
public void WriteRow_QuoteAll_Quoted()
{
var row = new object[]
{
1, 2, 3, new DumyObject(4)
};
string results;
using (var writer = new StringWriter())
{
var dialect = new Dialect(true, ';', '\"', '\\', true, "\r\n", QuoteStyle.QuoteAll, false, false);
using (var csvWriter = new CSVWriter(dialect, writer))
{
csvWriter.WriteRow(row);
}
results = writer.ToString();
}
AreEqual("\"1\";\"2\";\"3\";\"4\"\r\n", results);
}
[Test]
public void WriteRow_EscapeStrings_Escaped()
{
var row = new object[] { "\"" };
string results;
using (var writer = new StringWriter())
{
var dialect = new Dialect(true, ';', '\"', '\\', true, "\r\n", QuoteStyle.QuoteAll, false, false);
using (var csvWriter = new CSVWriter(dialect, writer))
{
csvWriter.WriteRow(row);
}
results = writer.ToString();
}
AreEqual("\"\\\"\"\r\n", results);
}
[Test]
public void WriteRow_DoNotEscapeStrings_NotEscaped()
{
var row = new object[] { "s" };
string results;
using (var writer = new StringWriter())
{
var dialect = new Dialect(false, ';', '\"', '\\', true, "\r\n", QuoteStyle.QuoteAll, false, false);
using (var csvWriter = new CSVWriter(dialect, writer))
{
csvWriter.WriteRow(row);
}
results = writer.ToString();
}
AreEqual("\"s\"\r\n", results);
}
[Test]
public void ConstructorFirst_DialectIsNull_ThrowsDialectIsNullException()
{
Throws<DialectIsNullException>(() =>
{
using (var writer = new CSVWriter(null, Guid.NewGuid().ToString(), "UTF-8"))
{
}
});
}
[Test]
public void ConstructorSecond_DialectIsNull_ThrowsDialectIsNullException()
{
Throws<DialectIsNullException>(() =>
{
using (var stringWriter = new StringWriter())
{
using (var writer = new CSVWriter(null, stringWriter))
{
}
}
});
}
[Test]
[TestCase(null)]
[TestCase("")]
[TestCase(" ")]
public void Constructor_FileNameIsNullOrEmpty_ThrowsFileNameIsNullOrEmptyException(string fileName)
{
Throws<FileNameIsNullOrEmptyException>(() =>
{
using (var dialect = new Dialect(true, ';', '\"', '\\', true, "\r\n", QuoteStyle.QuoteMinimal, false, false))
{
using (var writer = new CSVWriter(dialect, fileName, "UTF-8"))
{
}
}
});
}
[Test]
public void Constructor_FileNotExists_ThrowsCannotWriteToFileException()
{
Throws<CannotWriteToFileException>(() =>
{
using (var dialect = new Dialect(true, ';', '\"', '\\', true, "\r\n", QuoteStyle.QuoteMinimal, false, false))
{
using (var writer = new CSVWriter(dialect, "VeryLongNonExistingFileNameForTesting", "UTF-8"))
{
}
}
});
}
[Test]
public void Constructor_FileIsLocked_ThrowsCannotWriteToFileException()
{
Throws<CannotWriteToFileException>(() =>
{
using (var writer = new StreamWriter("test_write_file_locked.csv", false, Encoding.GetEncoding("utf-8")))
{
using (var dialect = new Dialect(true, ';', '\"', '\\', true, "\r\n", QuoteStyle.QuoteMinimal, false, false))
{
using (var csvWriter = new CSVWriter(dialect, "test_write_file_locked.csv", "UTF-8"))
{
}
}
}
});
}
[Test]
public void WriteRow_RowIsNull_ThrowsRowIsNullOrEmptyException()
{
Throws<RowIsNullOrEmptyException>(() =>
{
using (var stringWriter = new StringWriter())
{
using (var dialect = new Dialect(true, ';', '\"', '\\', true, "\r\n", QuoteStyle.QuoteMinimal, false, false))
{
using (var writer = new CSVWriter(dialect, stringWriter))
{
writer.WriteRow(null);
}
}
}
});
}
[Test]
public void WriteRow_ConvertiblesWithSpecifiedCulture_WroteConvertibles()
{
var ltCultureInfo = CultureInfo.GetCultureInfo("lt-LT");
WriteAndTestRow(
new object[] { 123, 123.45, 10M, 1, new DateTime(2015, 10, 26, 10, 11, 12) },
"123;123,45;10;1;2015-10-26 10:11:12\r\n", null, ltCultureInfo);
}
internal class DumyObject
{
public DumyObject(int number)
{
Number = number;
}
public int Number { get; set; }
public override string ToString()
{
return Number.ToString();
}
}
private void WriteAndTestRow(object[] input, string output, Dialect dialect, CultureInfo culture = null)
{
dialect = dialect ?? new Dialect(
true, ';', '\"', '\\', true, "\r\n", QuoteStyle.QuoteMinimal, false, false);
var oldCulture = Thread.CurrentThread.CurrentCulture;
try
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
string results;
using (var writer = new StringWriter())
{
using (var csvWriter = new CSVWriter(dialect, writer, culture))
{
csvWriter.WriteRow(input);
}
results = writer.ToString();
}
AreEqual(output, results);
}
finally
{
Thread.CurrentThread.CurrentCulture = oldCulture;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Box.AST;
namespace Box.Parsing
{
public static class LangParser
{
// NOTE: Referencing a field in the definition of a field will yield null.
// For recursive definitions use properties. Also make sure fields that
// are defined in terms of other fields occur last.
// TODO going to need to find a way to add in comments basically anywhere
private static Parser<T> Alt<T>( params Parser<T>[] parsers )
{
return ParserUtil.Alternate( parsers );
}
private static Parser<string> Lit( string value )
{
return ParserUtil.Match( value );
}
private static Parser<B> Bind<A, B>( Parser<A> parser, Func<A, Parser<B>> gen )
{
return ParserUtil.Bind( parser, gen );
}
private static Parser<B> Bind<A, B>( Parser<A> parser, Func<Parser<B>> gen )
{
return ParserUtil.Bind( parser, gen );
}
private static Parser<A> Unit<A>( A value )
{
return ParserUtil.Unit( value );
}
public static Parser<Empty> EndLine =
Alt(
Lit( "\r\n" ),
Lit( "\n" ),
Lit( "\r" ) ).Map( v => new Empty() );
// TODO probably need end of file in here too
public static Parser<Empty> Ws =
Alt(
EndLine,
CastEmpty( Lit( " " ) ),
CastEmpty( Lit( "\t" ) ),
CastEmpty( Lit( "\f" ) ),
CastEmpty( Lit( "\v" ) ) ).ZeroOrMore().Map( v => new Empty() );
private static Parser<Empty> LineComment =
Bind( Lit( "--" ), () =>
Bind( ParserUtil.ParseUntil( Alt( EndLine, ParserUtil.End ) ), () =>
Unit( new Empty() ) ) );
private static Parser<Empty> BlockComment =
Bind( Lit( "--[" ), () =>
Bind( Lit( "=" )
.ZeroOrMore()
.Map( value => value.Aggregate( "", (a, b) => a + b ) ), equals =>
Bind( Lit( "[" ), () =>
Bind( ParserUtil.ParseUntil( Lit( "--]" + equals + "]" ) ), () =>
Unit( new Empty() ) ) ) ) );
public static Parser<Empty> Comment =
Alt(
// TODO test the toggle block sometime
// Line Comment needs to happen first in order to pull off the toggle block trick
LineComment,
BlockComment );
public static Parser<Empty> Junk =
Bind( Ws, () =>
Bind( Comment, () =>
Bind( Ws, () =>
Unit( new Empty() ) ) ) );
public static Parser<NBoolean> Boolean =
Alt(
Lit( "true" ),
Lit( "false" ) )
.Map( value => new NBoolean( value == "true" ) );
private static Parser<int> Digits =
Alt( // TODO can use EatCharIf
Lit( "0" ),
Lit( "1" ),
Lit( "2" ),
Lit( "3" ),
Lit( "4" ),
Lit( "5" ),
Lit( "6" ),
Lit( "7" ),
Lit( "8" ),
Lit( "9" ) )
.OneOrMore()
.Map( value => value.Aggregate( "", (a, b) => a + b ) )
.Map( value => int.Parse( value ) );
private static Parser<string> NonNumSymbolChar =
Alt(
ParserUtil.EatCharIf( Char.IsLetter ).Map( c => new String( c, 1 ) ),
Lit( "_" ),
Lit( "~" ),
Lit( "@" ),
Lit( "$" ) );
public static Parser<string> Symbol =
Bind( NonNumSymbolChar, first =>
Bind( Alt(
NonNumSymbolChar,
Digits.Map( d => d.ToString() ) )
.ZeroOrMore()
.Map( value => value.Aggregate( "", (a, b) => a + b ) ), rest =>
Unit( first + rest ) ) );
private static Parser<IEnumerable<String>> NamespaceList =
Bind( Lit( "." ), () =>
Bind( Symbol, s =>
Unit( s ) ) ).ZeroOrMore();
public static Parser<NamespaceDesignator> NamespaceDesignator =
Bind( Symbol, s =>
Bind( NamespaceList, l =>
Unit( new NamespaceDesignator( new [] { s }.Concat( l ) ) ) ) );
public static Parser<UsingStatement> UsingStatement =
Bind( Ws, () =>
Bind( Lit( "using" ), () =>
Bind( Ws, () =>
Bind( NamespaceDesignator, nsd =>
Bind( Semi, () =>
Unit( new UsingStatement( nsd ) ) ) ) ) ) );
private static Parser<bool> Negative =
Lit( "-" )
.OneOrNone()
.Map( value => value.HasValue );
private static Parser<Number> WholeNumber =
Bind( Negative, neg =>
Bind( Digits, digits =>
Unit( new Number( digits, neg, 0, false, 0 ) ) ) );
private static Parser<Number> DecimalNumber =
Bind( Negative, neg =>
Bind( Digits, whole =>
Bind( Lit( "." ), () =>
Bind( Digits, deci =>
Unit( new Number( whole, neg, 0, false, deci ) ) ) ) ) );
private static Parser<Number> ExponentNumber =
Bind( Negative, negWhole =>
Bind( Digits, whole =>
Bind( Lit( "." ), () =>
Bind( Digits, deci =>
Bind(
Alt(
Lit( "E" ),
Lit( "e" ) ), () =>
Bind( Negative, negExp =>
Bind( Digits, exponent =>
Unit( new Number( whole, negWhole, exponent, negExp, deci ) ) ) ) ) ) ) ) );
public static Parser<Number> Number =
Alt(
// The order here matters. If we start with WholeNumber, then
// we will miss parse an exponent and/or decimal.
ExponentNumber,
DecimalNumber,
WholeNumber );
private static Parser<NString> NormalString =
Bind( Lit( "\"" ), () =>
Bind( ParserUtil.ParseUntil( Lit( "\"" ) ), str =>
Unit( new NString( str ) ) ) );
private static Parser<NString> RawString =
Bind( Lit( "[" ), () =>
Bind( Lit( "=" )
.ZeroOrMore()
.Map( value => value.Aggregate( "", (a, b) => a + b ) ), equals =>
Bind( Lit( "[" ), () =>
Bind( ParserUtil.ParseUntil( Lit( "]" + equals + "]" ) ), str =>
Unit( new NString( str ) ) ) ) ) );
public static Parser<NString> NString =
Alt(
NormalString,
RawString );
public static Parser<Empty> Semi =
Bind( Ws, () =>
Bind( Lit( ";" ), () =>
Bind( Ws, () =>
Unit( new Empty() ) ) ) );
public static Parser<Return> Return =
Bind( Ws, () =>
Bind( Lit( "return" ), () =>
Bind( Ws, () =>
Bind( Expr, expr =>
Bind( Semi, () =>
Unit( new Return( expr ) ) ) ) ) ) );
public static Parser<YieldReturn> YieldReturn =
Bind( Ws, () =>
Bind( Lit( "yield" ), () =>
Bind( Ws, () =>
Bind( Lit( "return" ), () =>
Bind( Ws, () =>
Bind( Expr, expr =>
Bind( Semi, () =>
Unit( new YieldReturn( expr ) ) ) ) ) ) ) ) );
public static Parser<YieldBreak> YieldBreak =
Bind( Ws, () =>
Bind( Lit( "yield" ), () =>
Bind( Ws, () =>
Bind( Lit( "break" ), () =>
Bind( Semi, () =>
Unit( new YieldBreak() ) ) ) ) ) );
public static Parser<Break> Break =
Bind( Ws, () =>
Bind( Lit( "break" ), () =>
Bind( Semi, () =>
Unit( new Break() ) ) ) );
public static Parser<Continue> Continue =
Bind( Ws, () =>
Bind( Lit( "continue" ), () =>
Bind( Semi, () =>
Unit( new Continue() ) ) ) );
// TODO test
public static Parser<While> While =
Bind( Ws, () =>
Bind( Lit( "while" ), () =>
Bind( Ws, () =>
Bind( Expr, test =>
Bind( Ws, () =>
Bind( Lit( "{" ), () =>
Bind( Ws, () =>
Bind( Statement.ZeroOrMore(), statements => // TODO whitespace between statements?
Bind( Ws, () =>
Bind( Lit( "}" ), () =>
Unit( new While( test, statements ) ) ) ) ) ) ) ) ) ) ) );
public static Parser<Expr> ParenExpr =
Bind( Ws, () =>
Bind( Lit( "(" ), () =>
Bind( Ws, () =>
Bind( Expr, e =>
Bind( Ws, () =>
Bind( Lit( ")" ), () =>
Bind( Ws, () =>
Unit( e ) ) ) ) ) ) ) );
private static Parser<Statement> CastStatement<T>( Parser<T> p )
where T : Statement
{
return p.Map( v => v as Statement );
}
private static Parser<Expr> CastExpr<T>( Parser<T> p )
where T : Expr
{
return p.Map( v => v as Expr );
}
private static Parser<Empty> CastEmpty<T>( Parser<T> p )
{
return p.Map( v => new Empty() );
}
// TODO test when finished
private static Parser<Statement> _stm =
Alt(
CastStatement( Return ),
CastStatement( YieldReturn ),
CastStatement( YieldBreak ),
CastStatement( UsingStatement ) );
public static Parser<Statement> Statement
{
get { return _stm; }
}
// TODO test when finished
private static Parser<Expr> _expr =
Alt(
CastExpr( Boolean ),
CastExpr( Number ),
CastExpr( NString ),
ParenExpr );
public static Parser<Expr> Expr
{
get { return _expr; }
}
}
}
| |
// 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.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp
{
[ExportSignatureHelpProvider("ElementAccessExpressionSignatureHelpProvider", LanguageNames.CSharp), Shared]
internal sealed class ElementAccessExpressionSignatureHelpProvider : AbstractCSharpSignatureHelpProvider
{
public override bool IsTriggerCharacter(char ch)
{
return IsTriggerCharacterInternal(ch);
}
private static bool IsTriggerCharacterInternal(char ch)
{
return ch == '[' || ch == ',';
}
public override bool IsRetriggerCharacter(char ch)
{
return ch == ']';
}
private static bool TryGetElementAccessExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace)
{
return CompleteElementAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace) ||
IncompleteElementAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace) ||
ConditionalAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace);
}
protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
ExpressionSyntax expression;
SyntaxToken openBrace;
if (!TryGetElementAccessExpression(root, position, document.GetLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out expression, out openBrace))
{
return null;
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol();
if (expressionSymbol is INamedTypeSymbol)
{
// foo?[$$]
var namedType = (INamedTypeSymbol)expressionSymbol;
if (namedType.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T &&
expression.IsKind(SyntaxKind.NullableType) &&
expression.IsChildNode<ArrayTypeSyntax>(a => a.ElementType))
{
// Speculatively bind the type part of the nullable as an expression
var nullableTypeSyntax = (NullableTypeSyntax)expression;
var speculativeBinding = semanticModel.GetSpeculativeSymbolInfo(position, nullableTypeSyntax.ElementType, SpeculativeBindingOption.BindAsExpression);
expressionSymbol = speculativeBinding.GetAnySymbol();
expression = nullableTypeSyntax.ElementType;
}
}
if (expressionSymbol != null && expressionSymbol is INamedTypeSymbol)
{
return null;
}
IEnumerable<IPropertySymbol> indexers;
ITypeSymbol expressionType;
if (!TryGetIndexers(position, semanticModel, expression, cancellationToken, out indexers, out expressionType) &&
!TryGetComIndexers(semanticModel, expression, cancellationToken, out indexers, out expressionType))
{
return null;
}
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
if (within == null)
{
return null;
}
var accessibleIndexers = indexers.Where(m => m.IsAccessibleWithin(within, throughTypeOpt: expressionType));
if (!accessibleIndexers.Any())
{
return null;
}
var symbolDisplayService = document.Project.LanguageServices.GetService<ISymbolDisplayService>();
accessibleIndexers = accessibleIndexers.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)
.Sort(symbolDisplayService, semanticModel, expression.SpanStart);
var anonymousTypeDisplayService = document.Project.LanguageServices.GetService<IAnonymousTypeDisplayService>();
var documentationCommentFormattingService = document.Project.LanguageServices.GetService<IDocumentationCommentFormattingService>();
var textSpan = GetTextSpan(expression, openBrace);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
return CreateSignatureHelpItems(accessibleIndexers.Select(p =>
Convert(p, openBrace, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, cancellationToken)).ToList(),
textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken));
}
private TextSpan GetTextSpan(ExpressionSyntax expression, SyntaxToken openBracket)
{
if (openBracket.Parent is BracketedArgumentListSyntax)
{
var conditional = expression.Parent as ConditionalAccessExpressionSyntax;
if (conditional != null)
{
return TextSpan.FromBounds(conditional.Span.Start, openBracket.FullSpan.End);
}
else
{
return CompleteElementAccessExpression.GetTextSpan(expression, openBracket);
}
}
else if (openBracket.Parent is ArrayRankSpecifierSyntax)
{
return IncompleteElementAccessExpression.GetTextSpan(expression, openBracket);
}
throw ExceptionUtilities.Unreachable;
}
public override SignatureHelpState GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken)
{
ExpressionSyntax expression;
SyntaxToken openBracket;
if (!TryGetElementAccessExpression(
root,
position,
syntaxFacts,
SignatureHelpTriggerReason.InvokeSignatureHelpCommand,
cancellationToken,
out expression,
out openBracket) ||
currentSpan.Start != expression.SpanStart)
{
return null;
}
// If the user is actively typing, it's likely that we're in a broken state and the
// syntax tree will be incorrect. Because of this we need to synthesize a new
// bracketed argument list so we can correctly map the cursor to the current argument
// and then we need to account for this and offset the position check accordingly.
int offset;
BracketedArgumentListSyntax argumentList;
var newBracketedArgumentList = SyntaxFactory.ParseBracketedArgumentList(openBracket.Parent.ToString());
if (expression.Parent is ConditionalAccessExpressionSyntax)
{
// The typed code looks like: <expression>?[
var conditional = (ConditionalAccessExpressionSyntax)expression.Parent;
var elementBinding = SyntaxFactory.ElementBindingExpression(newBracketedArgumentList);
var conditionalAccessExpression = SyntaxFactory.ConditionalAccessExpression(expression, elementBinding);
offset = expression.SpanStart - conditionalAccessExpression.SpanStart;
argumentList = ((ElementBindingExpressionSyntax)conditionalAccessExpression.WhenNotNull).ArgumentList;
}
else
{
// The typed code looks like:
// <expression>[
// or
// <identifier>?[
ElementAccessExpressionSyntax elementAccessExpression = SyntaxFactory.ElementAccessExpression(expression, newBracketedArgumentList);
offset = expression.SpanStart - elementAccessExpression.SpanStart;
argumentList = elementAccessExpression.ArgumentList;
}
position -= offset;
return SignatureHelpUtilities.GetSignatureHelpState(argumentList, position);
}
private bool TryGetComIndexers(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out IEnumerable<IPropertySymbol> indexers, out ITypeSymbol expressionType)
{
indexers = semanticModel.GetMemberGroup(expression, cancellationToken).OfType<IPropertySymbol>();
if (indexers.Any() && expression is MemberAccessExpressionSyntax)
{
expressionType = semanticModel.GetTypeInfo(((MemberAccessExpressionSyntax)expression).Expression, cancellationToken).Type;
return true;
}
expressionType = null;
return false;
}
private bool TryGetIndexers(int position, SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out IEnumerable<IPropertySymbol> indexers, out ITypeSymbol expressionType)
{
expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type;
if (expressionType == null)
{
indexers = null;
return false;
}
if (expressionType is IErrorTypeSymbol)
{
// If `expression` is a QualifiedNameSyntax then GetTypeInfo().Type won't have any CandidateSymbols, so
// we should then fall back to getting the actual symbol for the expression.
expressionType = (expressionType as IErrorTypeSymbol).CandidateSymbols.FirstOrDefault().GetSymbolType()
?? semanticModel.GetSymbolInfo(expression).GetAnySymbol().GetSymbolType();
}
indexers = semanticModel.LookupSymbols(position, expressionType, WellKnownMemberNames.Indexer).OfType<IPropertySymbol>();
return true;
}
private SignatureHelpItem Convert(
IPropertySymbol indexer,
SyntaxToken openToken,
SemanticModel semanticModel,
ISymbolDisplayService symbolDisplayService,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
IDocumentationCommentFormattingService documentationCommentFormattingService,
CancellationToken cancellationToken)
{
var position = openToken.SpanStart;
var item = CreateItem(indexer, semanticModel, position,
symbolDisplayService, anonymousTypeDisplayService,
indexer.IsParams(),
indexer.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService),
GetPreambleParts(indexer, position, semanticModel),
GetSeparatorParts(),
GetPostambleParts(indexer),
indexer.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService, cancellationToken)).ToList());
return item;
}
private IList<SymbolDisplayPart> GetPreambleParts(
IPropertySymbol indexer,
int position,
SemanticModel semanticModel)
{
var result = new List<SymbolDisplayPart>();
result.AddRange(indexer.Type.ToMinimalDisplayParts(semanticModel, position));
result.Add(Space());
result.AddRange(indexer.ContainingType.ToMinimalDisplayParts(semanticModel, position));
if (indexer.Name != WellKnownMemberNames.Indexer)
{
result.Add(Punctuation(SyntaxKind.DotToken));
result.Add(new SymbolDisplayPart(SymbolDisplayPartKind.PropertyName, indexer, indexer.Name));
}
result.Add(Punctuation(SyntaxKind.OpenBracketToken));
return result;
}
private IList<SymbolDisplayPart> GetPostambleParts(IPropertySymbol indexer)
{
return SpecializedCollections.SingletonList(
Punctuation(SyntaxKind.CloseBracketToken));
}
private static class CompleteElementAccessExpression
{
internal static bool IsTriggerToken(SyntaxToken token)
{
return !token.IsKind(SyntaxKind.None) &&
token.ValueText.Length == 1 &&
IsTriggerCharacterInternal(token.ValueText[0]) &&
token.Parent is BracketedArgumentListSyntax &&
token.Parent.Parent is ElementAccessExpressionSyntax;
}
internal static bool IsArgumentListToken(ElementAccessExpressionSyntax expression, SyntaxToken token)
{
return expression.ArgumentList.Span.Contains(token.SpanStart) &&
token != expression.ArgumentList.CloseBracketToken;
}
internal static TextSpan GetTextSpan(SyntaxNode expression, SyntaxToken openBracket)
{
Contract.ThrowIfFalse(openBracket.Parent is BracketedArgumentListSyntax &&
(openBracket.Parent.Parent is ElementAccessExpressionSyntax || openBracket.Parent.Parent is ElementBindingExpressionSyntax));
return SignatureHelpUtilities.GetSignatureHelpSpan((BracketedArgumentListSyntax)openBracket.Parent);
}
internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace)
{
ElementAccessExpressionSyntax elementAccessExpression;
if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out elementAccessExpression))
{
identifier = elementAccessExpression.Expression;
openBrace = elementAccessExpression.ArgumentList.OpenBracketToken;
return true;
}
identifier = null;
openBrace = default(SyntaxToken);
return false;
}
}
/// Error tolerance case for
/// "foo[$$]" or "foo?[$$]"
/// which is parsed as an ArrayTypeSyntax variable declaration instead of an ElementAccessExpression
private static class IncompleteElementAccessExpression
{
internal static bool IsArgumentListToken(ArrayTypeSyntax node, SyntaxToken token)
{
return node.RankSpecifiers.Span.Contains(token.SpanStart) &&
token != node.RankSpecifiers.First().CloseBracketToken;
}
internal static bool IsTriggerToken(SyntaxToken token)
{
return !token.IsKind(SyntaxKind.None) &&
token.ValueText.Length == 1 &&
IsTriggerCharacterInternal(token.ValueText[0]) &&
token.Parent is ArrayRankSpecifierSyntax;
}
internal static TextSpan GetTextSpan(SyntaxNode expression, SyntaxToken openBracket)
{
Contract.ThrowIfFalse(openBracket.Parent is ArrayRankSpecifierSyntax && openBracket.Parent.Parent is ArrayTypeSyntax);
return TextSpan.FromBounds(expression.SpanStart, openBracket.Parent.Span.End);
}
internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace)
{
ArrayTypeSyntax arrayTypeSyntax;
if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out arrayTypeSyntax))
{
identifier = arrayTypeSyntax.ElementType;
openBrace = arrayTypeSyntax.RankSpecifiers.First().OpenBracketToken;
return true;
}
identifier = null;
openBrace = default(SyntaxToken);
return false;
}
}
/// Error tolerance case for
/// "new String()?[$$]"
/// which is parsed as a BracketedArgumentListSyntax parented by an ElementBindingExpressionSyntax parented by a ConditionalAccessExpressionSyntax
private static class ConditionalAccessExpression
{
internal static bool IsTriggerToken(SyntaxToken token)
{
return !token.IsKind(SyntaxKind.None) &&
token.ValueText.Length == 1 &&
IsTriggerCharacterInternal(token.ValueText[0]) &&
token.Parent is BracketedArgumentListSyntax &&
token.Parent.Parent is ElementBindingExpressionSyntax &&
token.Parent.Parent.Parent is ConditionalAccessExpressionSyntax;
}
internal static bool IsArgumentListToken(ElementBindingExpressionSyntax expression, SyntaxToken token)
{
return expression.ArgumentList.Span.Contains(token.SpanStart) &&
token != expression.ArgumentList.CloseBracketToken;
}
internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace)
{
ElementBindingExpressionSyntax elementBindingExpression;
if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out elementBindingExpression))
{
identifier = ((ConditionalAccessExpressionSyntax)elementBindingExpression.Parent).Expression;
openBrace = elementBindingExpression.ArgumentList.OpenBracketToken;
return true;
}
identifier = null;
openBrace = default(SyntaxToken);
return false;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
namespace Apache.Geode.Client.FwkLauncher
{
using Apache.Geode.DUnitFramework;
class LauncherProcess
{
public static IChannel clientChannel = null;
public static string logFile = null;
// This port has been fixed for FwkLauncher.
static void Main(string[] args)
{
string myId = "0";
try
{
int launcherPort = 0;
string driverUrl;
ParseArguments(args, out driverUrl, out myId, out logFile, out launcherPort);
// NOTE: This is required so that remote client receive custom exceptions
RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
BinaryServerFormatterSinkProvider serverProvider =
new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
BinaryClientFormatterSinkProvider clientProvider =
new BinaryClientFormatterSinkProvider();
Dictionary<string, string> properties;
#region Create the communication channel to receive commands from server
properties = new Dictionary<string, string>();
properties["port"] = launcherPort.ToString();
clientChannel = new TcpChannel(properties, clientProvider, serverProvider);
ChannelServices.RegisterChannel(clientChannel, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(LauncherComm),
CommConstants.ClientService, WellKnownObjectMode.SingleCall);
#endregion
Util.ClientId = myId;
Util.LogFile = logFile;
if (!string.IsNullOrEmpty(driverUrl))
{
Util.DriverComm = ServerConnection<IDriverComm>.Connect(driverUrl);
Util.ClientListening();
}
}
catch (Exception ex)
{
Util.Log("FATAL: Client {0}, Exception caught: {1}", myId, ex);
}
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
}
private static void ShowUsage(string[] args)
{
if (args != null)
{
Util.Log("Args: ");
foreach (string arg in args)
{
Util.Log("\t{0}", arg);
}
}
string procName = Util.ProcessName;
Util.Log("Usage: " + procName + " [OPTION]");
Util.Log("Options are:");
Util.Log(" --id=ID \t\t ID of the launcher; process ID is used when not provided");
Util.Log(" --port=PORT \t\t Port number where the launcher listens for incoming requests.");
Util.Log(" --driver=URL \t Optional. The URL (e.g. tcp://<host>:<port>/<service>) of the Driver.");
Util.Log(" --log=LOGFILE \t Optional. The name of the logfile; standard output is used when not provided");
Util.Log(" --startdir=DIR \t Optional. Start in the given directory");
Util.Log(" --bg \t Optional. Start in background");
Environment.Exit(1);
}
private static void ParseArguments(string[] args, out string driverUrl, out string myId,
out string logFile, out int launcherPort)
{
if (args == null)
{
ShowUsage(args);
}
string IDOption = "--id=";
string DriverOption = "--driver=";
string LogOption = "--log=";
string StartDirOption = "--startdir=";
string BGOption = "--bg";
string Port = "--port=";
myId = Util.PID.ToString();
driverUrl = null;
logFile = null;
launcherPort = 0;
int argIndx = 0;
while (argIndx <= (args.Length - 1) && args[argIndx].StartsWith("--"))
{
string arg = args[argIndx];
if (arg.StartsWith(IDOption))
{
myId = arg.Substring(IDOption.Length);
}
else if (arg.StartsWith(DriverOption))
{
driverUrl = arg.Substring(DriverOption.Length);
}
else if (arg.StartsWith(LogOption))
{
logFile = arg.Substring(LogOption.Length);
}
else if (arg == BGOption)
{
string procArgs = string.Empty;
foreach (string newArg in args)
{
if (newArg != BGOption)
{
procArgs += '"' + newArg + "\" ";
}
}
procArgs = procArgs.Trim();
System.Diagnostics.Process bgProc;
if (!Util.StartProcess(Environment.GetCommandLineArgs()[0],
procArgs, false, null, false, false, false, true, out bgProc))
{
Util.Log("Failed to start background process with args: {0}",
procArgs);
Environment.Exit(1);
}
Environment.Exit(0);
}
else if (arg.StartsWith(StartDirOption))
{
string startDir = arg.Substring(StartDirOption.Length);
if (startDir.Length > 0)
{
Environment.CurrentDirectory = startDir;
}
}
else if (arg.StartsWith(Port))
{
string port = arg.Substring(Port.Length);
try
{
launcherPort = int.Parse(port);
}
catch
{
Util.Log("Port number should be an integer: {0}", port);
ShowUsage(args);
}
}
else
{
Util.Log("Unknown option: {0}", arg);
ShowUsage(args);
}
argIndx++;
}
if (args.Length != argIndx)
{
Util.Log("Incorrect number of arguments: {0}",
(args.Length - argIndx));
ShowUsage(args);
}
if (launcherPort == 0)
{
Util.Log("Port number is not specified.");
ShowUsage(args);
}
}
}
}
| |
using System;
using System.Net;
using Bloom;
using Moq;
using NUnit.Framework;
using TableLookupResult = Bloom.UpdateVersionTable.UpdateTableLookupResult; // shorthand
namespace BloomTests
{
[TestFixture]
public class UpdateVersionTableTests
{
[Test]
public void ThisVersionTooLarge_ReturnsEmptyString()
{
var t = new UpdateVersionTable();
t.RunningVersion = Version.Parse("99.99.99");
t.TextContentsOfTable = @"# the format is min,max,url
0.0.0,1.1.999, http://example.com/appcast.xml";
Assert.IsEmpty(t.LookupURLOfUpdate().URL);
}
[Test]
public void LookupURLOfUpdate_NoLineForDesiredVersion_ReportsError()
{
var t = new UpdateVersionTable();
t.TextContentsOfTable = @"0.0.0,3.1.99999, http://first.com/first";
t.RunningVersion = Version.Parse("3.2.0");
var lookupResult = t.LookupURLOfUpdate();
Assert.That(lookupResult.URL, Is.Null.Or.Empty);
Assert.That(lookupResult.Error.Message, Is.EqualTo("http://bloomlibrary.org/channels/UpgradeTableTestChannel.txt contains no record for this version of Bloom"));
}
[Test]
public void LookupURLOfUpdate_AllWell_ReportsNoErrorAndReturnsUrl()
{
var t = new UpdateVersionTable();
t.TextContentsOfTable = @"0.0.0,3.2.99999, http://first.com/first";
t.RunningVersion = Version.Parse("3.2.0");
var lookupResult = t.LookupURLOfUpdate();
Assert.IsFalse(lookupResult.IsConnectivityError);
Assert.IsNull(lookupResult.Error);
Assert.That(lookupResult.URL, Is.EqualTo("http://first.com/first"));
}
[Test]
public void LookupURLOfUpdate_TooManyCommas_LogsErrorGivesNoURL()
{
var t = new UpdateVersionTable();
t.TextContentsOfTable = @"0.0.0,3,1,99999, http://first.com/first"; // too many commas
t.RunningVersion = Version.Parse("3.2.0");
var lookupResult = t.LookupURLOfUpdate();
Assert.That(lookupResult.URL, Is.Null.Or.Empty);
Assert.IsTrue(lookupResult.Error.Message.StartsWith("Could not parse a line of the UpdateVersionTable"));
}
[Test]
public void LookupURLOfUpdate_TooFewCommas_LogsErrorGivesNoURL()
{
var t = new UpdateVersionTable();
t.TextContentsOfTable = @"0.0.0, http://first.com/first"; // too few commas
t.RunningVersion = Version.Parse("3.2.0");
var lookupResult = t.LookupURLOfUpdate();
Assert.That(lookupResult.URL, Is.Null.Or.Empty);
Assert.IsTrue(lookupResult.Error.Message.StartsWith("Could not parse a line of the UpdateVersionTable"));
}
[Test]
public void LookupURLOfUpdate_BadVersionNumber_LogsErrorGivesNoURL()
{
var t = new UpdateVersionTable();
t.TextContentsOfTable = @"random,3.1.99999, http://first.com/first"; // bad version number
t.RunningVersion = Version.Parse("3.2.0");
var lookupResult = t.LookupURLOfUpdate();
Assert.That(lookupResult.URL, Is.Null.Or.Empty);
Assert.IsTrue(lookupResult.Error.Message.StartsWith("Could not parse a version number in the UpdateVersionTable"));
}
[Test]
public void ServerAddressIsBogus_ErrorIsCorrect()
{
var t = new UpdateVersionTable {URLOfTable = "http://notthere7blah/foo.txt"};
//the jenkins server gets a ProtocolError, while my desktop gets a NameResolutionFailure
var e = t.LookupURLOfUpdate().Error.Status;
//This test can fail if the ISP "helpfully" returns a custom advertising filled access failure page.
Assert.IsTrue(e == WebExceptionStatus.NameResolutionFailure || e == WebExceptionStatus.ProtocolError );
}
// This started failing when we deployed the new bloomlibrary.org.
// Commenting out until we decide what to do about it.
//[Test]
//[Platform(Exclude = "Linux", Reason = "Windows-specific, fails on Linux without special access setup")]
//public void FileForThisChannelIsMissing_ErrorIsCorrect()
//{
// var t = new UpdateVersionTable { URLOfTable = "http://bloomlibrary.org/channels/UpgradeTableSomethingBogus.txt"};
// Assert.AreEqual(WebExceptionStatus.ProtocolError, t.LookupURLOfUpdate().Error.Status);
//}
[Test]
public void ValueOnLowerBound_ReturnsCorrectUrl()
{
var t = new UpdateVersionTable();
t.TextContentsOfTable = @"# the format is min,max,url
0.0.0,1.1.999, http://first.com/first
2.1.1,2.9.999, http://second.com/second
3.2.2,3.9.999, http://third.com/third";
t.RunningVersion = Version.Parse("0.0.0");
Assert.AreEqual("http://first.com/first", t.LookupURLOfUpdate().URL);
t.RunningVersion = Version.Parse("2.1.1");
Assert.AreEqual("http://second.com/second", t.LookupURLOfUpdate().URL);
t.RunningVersion = Version.Parse("3.2.2");
Assert.AreEqual("http://third.com/third", t.LookupURLOfUpdate().URL);
}
[Test]
public void ValueOnUpperBound_ReturnsCorrectUrl()
{
var t = new UpdateVersionTable();
t.TextContentsOfTable = @"# the format is min,max,url
0.0.0,1.1.999, http://first.com/first
2.1.1,2.9.999, http://second.com/second
3.2.2,3.9.999, http://third.com/third";
t.RunningVersion = Version.Parse("1.1.999");
Assert.AreEqual("http://first.com/first", t.LookupURLOfUpdate().URL);
t.RunningVersion = Version.Parse("2.9.999");
Assert.AreEqual("http://second.com/second", t.LookupURLOfUpdate().URL);
t.RunningVersion = Version.Parse("3.9.999");
Assert.AreEqual("http://third.com/third", t.LookupURLOfUpdate().URL);
}
[Test]
public void ValueOnInMiddle_ReturnsCorrectUrl()
{
var t = new UpdateVersionTable();
t.TextContentsOfTable = @"# the format is min,max,url
1.0.0,1.0.50, http://first.com/first
1.0.50,2.1.99, http://second.com/second
3.0.0,3.9.999, http://third.com/third";
t.RunningVersion = Version.Parse("1.0.40");
Assert.AreEqual("http://first.com/first", t.LookupURLOfUpdate().URL);
t.RunningVersion = Version.Parse("1.1.0");
Assert.AreEqual("http://second.com/second", t.LookupURLOfUpdate().URL);
t.RunningVersion = Version.Parse("3.0.1");
Assert.AreEqual("http://third.com/third", t.LookupURLOfUpdate().URL);
}
[Test]
[Platform(Exclude = "Linux", Reason = "Windows-specific, fails on Linux without special access setup")]
public void LookupURLOfUpdate_CanReadTableForAlphaFromServer()
{
var t = new UpdateVersionTable();
t.URLOfTable = "http://bloomlibrary.org/channels/UpgradeTableAlpha.txt";
t.RunningVersion = Version.Parse("3.7.2000"); // Pre-3.7 versions no longer supported
//the full result will be something like
//"https://s3.amazonaws.com/bloomlibrary.org/deltasAlpha"
//this just checks the part that is less likely to break (independent of channel)
Assert.That(t.LookupURLOfUpdate().URL.StartsWith("https://s3.amazonaws.com/bloomlibrary.org/deltas"));
}
[Test]
[Platform(Exclude = "Linux", Reason = "Windows-specific, fails on Linux without special access setup")]
public void LookupURLOfUpdateInternal_NotBehindCaptivePortal_Works()
{
var t = new UpdateVersionTable();
t.URLOfTable = "http://bloomlibrary.org/channels/UpgradeTableAlpha.txt";
t.RunningVersion = Version.Parse("2.0.2000");
//the full result would normally be something like
//"https://s3.amazonaws.com/bloomlibrary.org/deltasAlpha"
//check that feeding this a normal WebClient doesn't find an error.
var client = new BloomWebClient();
TableLookupResult dummy;
Assert.IsTrue(t.CanGetVersionTableFromWeb(client, out dummy));
}
[Test]
public void LookupURLOfUpdateInternal_BehindCaptivePortal_DoesNotCrash()
{
var t = new UpdateVersionTable();
t.URLOfTable = "http://bloomlibrary.org/channels/UpgradeTableAlpha.txt";
t.RunningVersion = Version.Parse("2.0.2000");
//the full result would normally be something like
//"https://s3.amazonaws.com/bloomlibrary.org/deltasAlpha"
//check that feeding this a mock WebClient that simulates a captive portal doesn't crash
var mockClient = GetMockWebClient();
TableLookupResult errorResult = null;
Assert.That(() => t.CanGetVersionTableFromWeb(mockClient, out errorResult), Throws.Nothing);
Assert.That(errorResult.URL, Is.EqualTo(string.Empty));
Assert.That(errorResult.Error.Message, Does.StartWith("Internet connection"));
}
private static IBloomWebClient GetMockWebClient()
{
const string portalHtml =
@"<html>
<body>
<div>Simulated captive portal</div>
</body>
</html>";
var mockClient = new Mock<IBloomWebClient>();
mockClient.Setup(x => x.DownloadString(It.IsAny<string>())).Returns(portalHtml);
return mockClient.Object;
}
/* We recorded the following actualy response from the ukarumpa captive portal
* in Sept 2019
*
* <html>
<body>
<link rel="icon" type="image/png" href="captiveportal-SILlogo.png">
<form method="post" action="https://homeportal.sil.org.pg:8003/index.php?zone=homeportal">
<input name="redirurl" type="hidden" value="">
<input name="zone" type="hidden" value="homeportal">
<center>
<table cellpadding="6" cellspacing="0" width="550" height="380" style="border:1px solid #000000">
<tr>
<td>
<div id="mainlevel">
<center>
<table width="100%" border="0" cellpadding="5" cellspacing="0">
<img width=48 height=48 src="captiveportal-SILlogo.png">
<tr>
<td>
<center>
<div id="mainarea">
<center>
<table width="100%" border="0" cellpadding="5" cellspacing="5">
<tr>
<td>
<div id="maindivarea">
<center>
<div id='statusbox'>
<font color='red' face='arial' size='+1'>
<b>
</b>
</font>
</div>
<br />
<div id='loginbox'>
<table>
<tr><td colspan="2"><center>Welcome to the SILPNG Home Captive Portal!</td></tr>
<tr><td> </td></tr>
<tr><td class="text-right">Username:</td><td><input name="auth_user" type="text" autofocus style="border: 1px dashed;"></td></tr>
<tr><td class="text-right">Password:</td><td><input name="auth_pass" type="password" style="border: 1px dashed;"></td></tr>
<tr><td> </td></tr>
<tr>
<td colspan="2"><center><input name="accept" type="submit" value="Continue"></center></td>
</tr>
</table>
</div>
</center>
</div>
</td>
</tr>
</table>
</center>
</div>
</center>
</td>
</tr>
</table>
</center>
</div>
</td>
</tr>
</table>
</br></br>
<!-- JavaScript to Show/Hide Info -->
<script type="text/javascript" language="JavaScript">
function ReverseDisplay(d) {
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}
</script>
<a href="javascript:ReverseDisplay('popupinfo')">
Click here for more information on the logout pop-up window
</a>
<div id="popupinfo" style="display:none;">
<p>Please update your browser to have this new pop-up exception and create a new bookmark for this login page.</br></br>
<strong>Create an Allow Pop-up Exception For:</strong></br>
https://homeportal.sil.org.pg:8003</br></br>
<strong>Create a Bookmark for this Login Page:</strong></br>
<a href="https://homeportal.sil.org.pg:8003/index.php?zone=homeportal">https://homeportal.sil.org.pg:8003/index.php?zone=homeportal</a>
</p>
</div>
</center>
</form>
</body>
</html>
*/
}
}
| |
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap 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 of the License, or
// (at your option) any later version.
//
// SharpMap 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 SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// SOURCECODE IS MODIFIED FROM ANOTHER WORK AND IS ORIGINALLY BASED ON GeoTools.NET:
/*
* Copyright (C) 2002 Urban Science Applications, Inc.
*
* 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
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using NetTopologySuite.Geometries;
using NetTopologySuite.IO;
namespace SharpMap.Converters.WellKnownText
{
/// <summary>
/// Converts a Well-known Text representation to a <see cref="NetTopologySuite.Geometries.Geometry"/> instance.
/// </summary>
/// <remarks>
/// <para>The Well-Known Text (WKT) representation of Geometry is designed to exchange geometry data in ASCII form.</para>
/// Examples of WKT representations of geometry objects are:
/// <list type="table">
/// <listheader><term>Geometry </term><description>WKT Representation</description></listheader>
/// <item><term>A Point</term>
/// <description>POINT(15 20)<br/> Note that point coordinates are specified with no separating comma.</description></item>
/// <item><term>A LineString with four points:</term>
/// <description>LINESTRING(0 0, 10 10, 20 25, 50 60)</description></item>
/// <item><term>A Polygon with one exterior ring and one interior ring:</term>
/// <description>POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))</description></item>
/// <item><term>A MultiPoint with three Point values:</term>
/// <description>MultiPoint(0 0, 20 20, 60 60)</description></item>
/// <item><term>A MultiLineString with two LineString values:</term>
/// <description>MultiLineString((10 10, 20 20), (15 15, 30 15))</description></item>
/// <item><term>A MultiPolygon with two Polygon values:</term>
/// <description>MultiPolygon(((0 0,10 0,10 10,0 10,0 0)),((5 5,7 5,7 7,5 7, 5 5)))</description></item>
/// <item><term>A GeometryCollection consisting of two Point values and one LineString:</term>
/// <description>GEOMETRYCOLLECTION(POINT(10 10), POINT(30 30), LINESTRING(15 15, 20 20))</description></item>
/// </list>
/// </remarks>
public class GeometryFromWKT
{
/// <summary>
/// Converts a Well-known text representation to a <see cref="NetTopologySuite.Geometries.Geometry"/>.
/// </summary>
/// <param name="wellKnownText">A <see cref="NetTopologySuite.Geometries.Geometry"/> tagged text string ( see the OpenGIS Simple Features Specification.</param>
/// <returns>Returns a <see cref="NetTopologySuite.Geometries.Geometry"/> specified by wellKnownText. Throws an exception if there is a parsing problem.</returns>
public static Geometry Parse(string wellKnownText)
{
// throws a parsing exception is there is a problem.
using (var reader = new StringReader(wellKnownText))
return Parse(reader);
}
/// <summary>
/// Converts a Well-known Text representation to a <see cref="NetTopologySuite.Geometries.Geometry"/>.
/// </summary>
/// <param name="reader">A Reader which will return a Geometry Tagged Text
/// string (see the OpenGIS Simple Features Specification)</param>
/// <returns>Returns a <see cref="NetTopologySuite.Geometries.Geometry"/> read from StreamReader.
/// An exception will be thrown if there is a parsing problem.</returns>
public static Geometry Parse(TextReader reader)
{
WKTReader wkt = new WKTReader();
return wkt.Read(reader);
/*
var tokenizer = new WktStreamTokenizer(reader);
return ReadGeometryTaggedText(tokenizer);
*/
}
/// <summary>
/// Returns the next array of Coordinates in the stream.
/// </summary>
/// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text format. The
/// next element returned by the stream should be "(" (the beginning of "(x1 y1, x2 y2, ..., xn yn)" or
/// "EMPTY".</param>
/// <returns>The next array of Coordinates in the stream, or an empty array of "EMPTY" is the
/// next element returned by the stream.</returns>
private static Coordinate[] GetCoordinates(WktStreamTokenizer tokenizer)
{
var coordinates = new List<Coordinate>();
string nextToken = GetNextEmptyOrOpener(tokenizer);
if (nextToken == "EMPTY")
return coordinates.ToArray();
var externalCoordinate = new Coordinate();
externalCoordinate.X = GetNextNumber(tokenizer);
externalCoordinate.Y = GetNextNumber(tokenizer);
coordinates.Add(externalCoordinate);
nextToken = GetNextCloserOrComma(tokenizer);
while (nextToken == ",")
{
var internalCoordinate = new Coordinate(GetNextNumber(tokenizer), GetNextNumber(tokenizer));
coordinates.Add(internalCoordinate);
nextToken = GetNextCloserOrComma(tokenizer);
}
return coordinates.ToArray();
}
/// <summary>
/// Returns the next number in the stream.
/// </summary>
/// <param name="tokenizer">Tokenizer over a stream of text in Well-known text format. The next token
/// must be a number.</param>
/// <returns>Returns the next number in the stream.</returns>
/// <remarks>
/// ParseException is thrown if the next token is not a number.
/// </remarks>
private static double GetNextNumber(WktStreamTokenizer tokenizer)
{
tokenizer.NextToken();
return tokenizer.GetNumericValue();
}
/// <summary>
/// Returns the next "EMPTY" or "(" in the stream as uppercase text.
/// </summary>
/// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text
/// format. The next token must be "EMPTY" or "(".</param>
/// <returns>the next "EMPTY" or "(" in the stream as uppercase
/// text.</returns>
/// <remarks>
/// ParseException is thrown if the next token is not "EMPTY" or "(".
/// </remarks>
private static string GetNextEmptyOrOpener(WktStreamTokenizer tokenizer)
{
tokenizer.NextToken();
string nextWord = tokenizer.GetStringValue();
if (nextWord == "EMPTY" || nextWord == "(")
return nextWord;
throw new Exception("Expected 'EMPTY' or '(' but encountered '" + nextWord + "'");
}
/// <summary>
/// Returns the next ")" or "," in the stream.
/// </summary>
/// <param name="tokenizer">tokenizer over a stream of text in Well-known Text
/// format. The next token must be ")" or ",".</param>
/// <returns>Returns the next ")" or "," in the stream.</returns>
/// <remarks>
/// ParseException is thrown if the next token is not ")" or ",".
/// </remarks>
private static string GetNextCloserOrComma(WktStreamTokenizer tokenizer)
{
tokenizer.NextToken();
string nextWord = tokenizer.GetStringValue();
if (nextWord == "," || nextWord == ")")
{
return nextWord;
}
throw new Exception("Expected ')' or ',' but encountered '" + nextWord + "'");
}
/// <summary>
/// Returns the next ")" in the stream.
/// </summary>
/// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text
/// format. The next token must be ")".</param>
/// <returns>Returns the next ")" in the stream.</returns>
/// <remarks>
/// ParseException is thrown if the next token is not ")".
/// </remarks>
private static string GetNextCloser(WktStreamTokenizer tokenizer)
{
string nextWord = GetNextWord(tokenizer);
if (nextWord == ")")
return nextWord;
throw new Exception("Expected ')' but encountered '" + nextWord + "'");
}
/// <summary>
/// Returns the next word in the stream as uppercase text.
/// </summary>
/// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text
/// format. The next token must be a word.</param>
/// <returns>Returns the next word in the stream as uppercase text.</returns>
/// <remarks>
/// Exception is thrown if the next token is not a word.
/// </remarks>
private static string GetNextWord(WktStreamTokenizer tokenizer)
{
TokenType type = tokenizer.NextToken();
string token = tokenizer.GetStringValue();
if (type == TokenType.Number)
throw new Exception("Expected a number but got " + token);
if (type == TokenType.Word)
return token.ToUpper();
if (token == "(")
return "(";
if (token == ")")
return ")";
if (token == ",")
return ",";
throw new Exception("Not a valid symbol in WKT format.");
}
/// <summary>
/// Creates a Geometry using the next token in the stream.
/// </summary>
/// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text
/// format. The next tokens must form a <Geometry Tagged Text>.</param>
/// <returns>Returns a Geometry specified by the next token in the stream.</returns>
/// <remarks>
/// Exception is thrown if the coordinates used to create a Polygon
/// shell and holes do not form closed linestrings, or if an unexpected
/// token is encountered.
/// </remarks>
private static Geometry ReadGeometryTaggedText(WktStreamTokenizer tokenizer)
{
tokenizer.NextToken();
var type = tokenizer.GetStringValue().ToUpper();
Geometry geometry;
GeometryFactory factory = new GeometryFactory();
switch (type)
{
case "POINT":
geometry = ReadPointText(tokenizer, factory);
break;
case "LINESTRING":
geometry = ReadLineStringText(tokenizer, factory);
break;
case "MultiPoint":
geometry = ReadMultiPointText(tokenizer, factory);
break;
case "MultiLineString":
geometry = ReadMultiLineStringText(tokenizer, factory);
break;
case "POLYGON":
geometry = ReadPolygonText(tokenizer, factory);
break;
case "MultiPolygon":
geometry = ReadMultiPolygonText(tokenizer, factory);
break;
case "GEOMETRYCOLLECTION":
geometry = ReadGeometryCollectionText(tokenizer, factory);
break;
default:
throw new Exception(String.Format(Map.NumberFormatEnUs, "Geometrytype '{0}' is not supported.",
type));
}
return geometry;
}
/// <summary>
/// Creates a <see cref="MultiPolygon"/> using the next token in the stream.
/// </summary>
/// <param name="tokenizer">tokenizer over a stream of text in Well-known Text
/// format. The next tokens must form a MultiPolygon.</param>
/// <param name="factory">The factory to create the result geometry</param>
/// <returns>a <code>MultiPolygon</code> specified by the next token in the
/// stream, or if if the coordinates used to create the <see cref="Polygon"/>
/// shells and holes do not form closed linestrings.</returns>
private static MultiPolygon ReadMultiPolygonText(WktStreamTokenizer tokenizer, GeometryFactory factory)
{
var polygons = new List<Polygon>();
string nextToken = GetNextEmptyOrOpener(tokenizer);
if (nextToken == "EMPTY")
return factory.CreateMultiPolygon(polygons.ToArray());
var polygon = ReadPolygonText(tokenizer, factory);
polygons.Add(polygon);
nextToken = GetNextCloserOrComma(tokenizer);
while (nextToken == ",")
{
polygon = ReadPolygonText(tokenizer, factory);
polygons.Add(polygon);
nextToken = GetNextCloserOrComma(tokenizer);
}
return factory.CreateMultiPolygon(polygons.ToArray());
}
/// <summary>
/// Creates a Polygon using the next token in the stream.
/// </summary>
/// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text
/// format. The next tokens must form a <Polygon Text>.</param>
/// <param name="factory">The factory to create the result geometry</param>
/// <returns>Returns a Polygon specified by the next token
/// in the stream</returns>
/// <remarks>
/// ParseException is thrown if the coordinates used to create the Polygon
/// shell and holes do not form closed linestrings, or if an unexpected
/// token is encountered.
/// </remarks>
private static Polygon ReadPolygonText(WktStreamTokenizer tokenizer, GeometryFactory factory)
{
string nextToken = GetNextEmptyOrOpener(tokenizer);
if (nextToken == "EMPTY")
return factory.CreatePolygon(null, null);
var exteriorRing = factory.CreateLinearRing(GetCoordinates(tokenizer));
nextToken = GetNextCloserOrComma(tokenizer);
var interiorRings = new List<LinearRing>();
while (nextToken == ",")
{
//Add holes
interiorRings.Add(factory.CreateLinearRing(GetCoordinates(tokenizer)));
nextToken = GetNextCloserOrComma(tokenizer);
}
return factory.CreatePolygon(exteriorRing, interiorRings.ToArray());
}
/// <summary>
/// Creates a Point using the next token in the stream.
/// </summary>
/// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text
/// format. The next tokens must form a <Point Text>.</param>
/// <param name="factory">The factory to create the result geometry</param>
/// <returns>Returns a Point specified by the next token in
/// the stream.</returns>
/// <remarks>
/// ParseException is thrown if an unexpected token is encountered.
/// </remarks>
private static Point ReadPointText(WktStreamTokenizer tokenizer, GeometryFactory factory)
{
var nextToken = GetNextEmptyOrOpener(tokenizer);
if (nextToken == "EMPTY")
return factory.CreatePoint((Coordinate)null);
var c = new Coordinate(GetNextNumber(tokenizer), GetNextNumber(tokenizer));
GetNextCloser(tokenizer);
return factory.CreatePoint(c);
}
/// <summary>
/// Creates a Point using the next token in the stream.
/// </summary>
/// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text
/// format. The next tokens must form a <Point Text>.</param>
/// <param name="factory">The factory to create the result geometry</param>
/// <returns>Returns a Point specified by the next token in
/// the stream.</returns>
/// <remarks>
/// ParseException is thrown if an unexpected token is encountered.
/// </remarks>
private static MultiPoint ReadMultiPointText(WktStreamTokenizer tokenizer, GeometryFactory factory)
{
string nextToken = GetNextEmptyOrOpener(tokenizer);
if (nextToken == "EMPTY")
return factory.CreateMultiPointFromCoords((Coordinate[])null);
var points = new List<Coordinate>();
points.Add(new Coordinate(GetNextNumber(tokenizer), GetNextNumber(tokenizer)));
nextToken = GetNextCloserOrComma(tokenizer);
while (nextToken == ",")
{
points.Add(new Coordinate(GetNextNumber(tokenizer), GetNextNumber(tokenizer)));
nextToken = GetNextCloserOrComma(tokenizer);
}
return factory.CreateMultiPointFromCoords(points.ToArray());
}
/// <summary>
/// Creates a <see cref="MultiLineString"/> using the next token in the stream.
/// </summary>
/// <param name="tokenizer">tokenizer over a stream of text in Well-known Text format. The next tokens must form a MultiLineString Text</param>
/// <param name="factory">The factory to create the result geometry</param>
/// <returns>a <see cref="MultiLineString"/> specified by the next token in the stream</returns>
private static MultiLineString ReadMultiLineStringText(WktStreamTokenizer tokenizer, GeometryFactory factory)
{
string nextToken = GetNextEmptyOrOpener(tokenizer);
if (nextToken == "EMPTY")
return factory.CreateMultiLineString(null);
var lineStrings = new List<LineString>();
lineStrings.Add(ReadLineStringText(tokenizer, factory));
nextToken = GetNextCloserOrComma(tokenizer);
while (nextToken == ",")
{
lineStrings.Add(ReadLineStringText(tokenizer, factory));
nextToken = GetNextCloserOrComma(tokenizer);
}
return factory.CreateMultiLineString(lineStrings.ToArray());
}
/// <summary>
/// Creates a LineString using the next token in the stream.
/// </summary>
/// <param name="tokenizer">Tokenizer over a stream of text in Well-known Text format. The next
/// tokens must form a LineString Text.</param>
/// <param name="factory">The factory to create the result geometry</param>
/// <returns>Returns a LineString specified by the next token in the stream.</returns>
/// <remarks>
/// ParseException is thrown if an unexpected token is encountered.
/// </remarks>
private static LineString ReadLineStringText(WktStreamTokenizer tokenizer, GeometryFactory factory)
{
return factory.CreateLineString(GetCoordinates(tokenizer));
}
/// <summary>
/// Creates a <see cref="GeometryCollection"/> using the next token in the stream.
/// </summary>
/// <param name="tokenizer"> Tokenizer over a stream of text in Well-known Text
/// format. The next tokens must form a GeometryCollection Text.</param>
/// <param name="factory">The factory to create the result geometry</param>
/// <returns>
/// A <see cref="GeometryCollection"/> specified by the next token in the stream.</returns>
private static GeometryCollection ReadGeometryCollectionText(WktStreamTokenizer tokenizer, GeometryFactory factory)
{
var nextToken = GetNextEmptyOrOpener(tokenizer);
if (nextToken.Equals("EMPTY"))
return factory.CreateGeometryCollection(null);
var geometries = new List<Geometry>();
geometries.Add(ReadGeometryTaggedText(tokenizer));
nextToken = GetNextCloserOrComma(tokenizer);
while (nextToken.Equals(","))
{
geometries.Add(ReadGeometryTaggedText(tokenizer));
nextToken = GetNextCloserOrComma(tokenizer);
}
return factory.CreateGeometryCollection(geometries.ToArray());
}
}
}
| |
using System;
using System.Globalization;
namespace Division42.Framework.Formatters
{
/// <summary>
/// Class to hold information about a specific data size.
/// </summary>
/// <threadsafety static="true" instance="false"/>
public abstract class DataSizeFormatterBase : IDataSizeFormatter
{
/// <summary>
/// Initializes a new instance of the <see cref="DataSizeFormatterBase"/> class.
/// </summary>
/// <param name="sizeInBits">The size in bits.</param>
protected DataSizeFormatterBase(UInt64 sizeInBits)
{
this._sizeInBytes = sizeInBits / 8;
this._sizeInBits = sizeInBits;
}
/// <summary>
/// Gets the short identifier.
/// </summary>
public abstract String ShortIdentifier { get; }
/// <summary>
/// Gets the long identifier.
/// </summary>
public abstract String LongIdentifier { get; }
/// <summary>
/// Gets the size of the divisor.
/// </summary>
public abstract UInt64 DivisorForSize { get; }
/// <summary>
/// Gets the default decimal places.
/// </summary>
public abstract UInt16 DefaultDecimalPlaces { get; }
/// <summary>
/// Gets the size in bytes.
/// </summary>
public UInt64 SizeInBytes
{
get { return _sizeInBytes; }
}
/// <summary>
/// The size, in bytes.
/// </summary>
private UInt64 _sizeInBytes = 0;
/// <summary>
/// Gets the size in bits.
/// </summary>
/// <remarks></remarks>
public UInt64 SizeInBits
{
get { return _sizeInBits; }
}
/// <summary>
/// The size, in bits.
/// </summary>
private UInt64 _sizeInBits = 0;
/// <summary>
/// The value for Kilo, or 2 to the 10.
/// </summary>
public static readonly UInt64 Kilo = (UInt64)Math.Pow(2, 10);
/// <summary>
/// The value for Mega, or 2 to the 20.
/// </summary>
public static readonly UInt64 Mega = (UInt64)Math.Pow(2, 20);
/// <summary>
/// The value for Giga, or 2 to the 30.
/// </summary>
public static readonly UInt64 Giga = (UInt64)Math.Pow(2, 30);
/// <summary>
/// The value for Tera, or 2 to the 40.
/// </summary>
public static readonly UInt64 Tera = (UInt64)Math.Pow(2, 40);
/// <summary>
/// The value for Peta, or 2 to the 50.
/// </summary>
public static readonly UInt64 Peta = (UInt64)Math.Pow(2, 50);
/// <summary>
/// The value for Exa, or 2 to the 60.
/// </summary>
public static readonly UInt64 Exa = (UInt64)Math.Pow(2, 60);
/// <summary>
/// Toes the size of the byte auto.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public virtual DataSizeFormatterBase ToByteAutoSize()
{
if (this.SizeInBytes >= 0 && this.SizeInBytes < Kilo)
return new ByteSizeFormatter(this._sizeInBits);
else if (this.SizeInBytes >= Kilo && this.SizeInBytes < Mega)
return new KilobyteSizeFormatter(this._sizeInBits);
else if (this.SizeInBytes >= Mega && this.SizeInBytes < Giga)
return new MegabyteSizeResult(this._sizeInBits);
else if (this.SizeInBytes >= Giga && this.SizeInBytes < Tera)
return new GigabyteSizeFormatter(this._sizeInBits);
else if (this.SizeInBytes >= Tera && this.SizeInBytes < Peta)
return new TerabyteSizeFormatter(this._sizeInBits);
else if (this.SizeInBytes >= Peta && this.SizeInBytes < Exa)
return new PetabyteSizeFormatter(this._sizeInBits);
else if (this.SizeInBytes >= Exa)
return new ExabyteSizeResult(this._sizeInBits);
else
return new ByteSizeFormatter(this._sizeInBits);
}
/// <summary>
/// Gets a <see cref="ByteSizeFormatter"/> of the current data result.
/// </summary>
public ByteSizeFormatter ToByte()
{
return new ByteSizeFormatter(_sizeInBytes);
}
/// <summary>
/// Gets a <see cref="KilobyteSizeFormatter"/> of the current data result.
/// </summary>
public KilobyteSizeFormatter ToKilobyte()
{
return new KilobyteSizeFormatter(_sizeInBytes);
}
/// <summary>
/// Gets a <see cref="MegabyteSizeResult"/> of the current data result.
/// </summary>
public MegabyteSizeResult ToMegabyte()
{
return new MegabyteSizeResult(_sizeInBytes);
}
/// <summary>
/// Gets a <see cref="GigabyteSizeFormatter"/> of the current data result.
/// </summary>
public GigabyteSizeFormatter ToGigabyte()
{
return new GigabyteSizeFormatter(_sizeInBytes);
}
/// <summary>
/// Gets a <see cref="TerabyteSizeFormatter"/> of the current data result.
/// </summary>
public TerabyteSizeFormatter ToTerabyte()
{
return new TerabyteSizeFormatter(_sizeInBytes);
}
/// <summary>
/// Gets a <see cref="PetabyteSizeFormatter"/> of the current data result.
/// </summary>
public PetabyteSizeFormatter ToPetabyte()
{
return new PetabyteSizeFormatter(_sizeInBytes);
}
/// <summary>
/// Gets a <see cref="ExabyteSizeResult"/> of the current data result.
/// </summary>
public ExabyteSizeResult ToExabyte()
{
return new ExabyteSizeResult(_sizeInBytes);
}
/// <summary>
/// Gets a long string description of the current data result, using the default number of decimal places.
/// </summary>
public String ToLongBitString()
{
return ToLongBitString(DefaultDecimalPlaces);
}
/// <summary>
/// Gets a long string description of the current data result, using the specified number of decimal places.
/// </summary>
/// <param name="decimalPlaces">The number of decimal places.</param>
public String ToLongBitString(UInt16 decimalPlaces)
{
Double result = (Double)_sizeInBits / (Double)DivisorForSize;
return String.Format(CultureInfo.CurrentCulture, "{0:N" + decimalPlaces + "} {1}", result, PluralizedLongBitIdentifier);
}
/// <summary>
/// Gets a short string description of the current data result, using the default number of decimal places.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public String ToShortBitString()
{
return ToShortBitString(DefaultDecimalPlaces);
}
/// <summary>
/// Gets a short string description of the current data result, using the default number of decimal places.
/// </summary>
/// <param name="decimalPlaces">The number of decimal places.</param>
public String ToShortBitString(UInt16 decimalPlaces)
{
Double result = (Double)_sizeInBits / (Double)DivisorForSize;
return String.Format(CultureInfo.CurrentCulture, "{0:N" + decimalPlaces + "} {1}", result, PluralizedShortBitIdentifier);
}
/// <summary>
/// Gets a long string description of the current data result, using the default number of decimal places.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public String ToLongByteString()
{
return ToLongByteString(DefaultDecimalPlaces);
}
/// <summary>
/// Gets a long string description of the current data result, using the specified number of decimal places.
/// </summary>
/// <param name="decimalPlaces">The number of decimal places.</param>
public String ToLongByteString(UInt16 decimalPlaces)
{
Double result = (Double)_sizeInBytes / (Double)DivisorForSize;
return String.Format(CultureInfo.CurrentCulture, "{0:N" + decimalPlaces + "} {1}", result, PluralizedLongByteIdentifier);
}
/// <summary>
/// Gets a short string description of the current data result, using the default number of decimal places.
/// </summary>
public String ToShortByteString()
{
return ToShortByteString(DefaultDecimalPlaces);
}
/// <summary>
/// Gets a short string description of the current data result, using the specified number of decimal places.
/// </summary>
/// <param name="decimalPlaces">The number of decimal places.</param>
public String ToShortByteString(UInt16 decimalPlaces)
{
Double result = (Double)_sizeInBytes / (Double)DivisorForSize;
return String.Format(CultureInfo.CurrentCulture, "{0:N" + decimalPlaces + "} {1}", result, PluralizedShortByteIdentifier);
}
/// <summary>
/// Gets the pluralized version of the long bit identifier, if necessary.
/// </summary>
/// <remarks>Starts with the <see cref="LongIdentifier"/>, and adds an
/// "s" if the size is greater than zero.</remarks>
protected String PluralizedLongBitIdentifier
{
get
{
Double result = (Double)_sizeInBits / (Double)DivisorForSize;
return (result > 1 ? LongIdentifier + "s" : LongIdentifier);
}
}
/// <summary>
/// Gets the pluralized version of the short bit identifier, if necessary.
/// </summary>
/// <remarks>Starts with the <see cref="ShortIdentifier"/>, and adds an
/// "s" if the size is greater than zero.</remarks>
protected String PluralizedShortBitIdentifier
{
get
{
Double result = (Double)_sizeInBits / (Double)DivisorForSize;
return (result > 1 ? ShortIdentifier + "s" : ShortIdentifier);
}
}
/// <summary>
/// Gets the pluralized version of the long byte identifier, if necessary.
/// </summary>
/// <remarks>Starts with the <see cref="LongIdentifier"/>, and adds an
/// "s" if the size is greater than zero.</remarks>
protected String PluralizedLongByteIdentifier
{
get
{
Double result = (Double)_sizeInBytes / (Double)DivisorForSize;
return (result > 1 ? LongIdentifier + "s" : LongIdentifier);
}
}
/// <summary>
/// Gets the pluralized version of the short byte identifier, if necessary.
/// </summary>
/// <remarks>Starts with the <see cref="ShortIdentifier"/>, and adds an
/// "s" if the size is greater than zero.</remarks>
protected String PluralizedShortByteIdentifier
{
get
{
Double result = (Double)_sizeInBytes / (Double)DivisorForSize;
return (result > 1 ? ShortIdentifier + "s" : ShortIdentifier);
}
}
}
}
| |
using System;
using System.IO;
namespace FezEngine.Mod {
public class LimitedStream : MemoryStream {
public Stream LimitStream;
public long LimitOffset;
public long LimitLength;
public bool LimitStreamShared = false;
private long pos = 0;
protected byte[] cachedBuffer;
protected long cachedOffset;
protected long cachedLength;
protected bool cacheBuffer_ = true;
public bool CacheBuffer {
get {
return cacheBuffer_;
}
set {
if (!value) {
cachedBuffer = null;
}
cacheBuffer_ = value;
}
}
public override bool CanRead {
get {
return LimitStream.CanRead;
}
}
public override bool CanSeek {
get {
return LimitStream.CanSeek;
}
}
public override bool CanWrite {
get {
return LimitStream.CanWrite;
}
}
public override long Length {
get {
return LimitLength;
}
}
public override long Position {
get {
return LimitStreamShared ? pos : LimitStream.Position - LimitOffset;
}
set {
LimitStream.Position = value + LimitOffset;
pos = value;
}
}
public LimitedStream(Stream stream, long offset, long length)
: base() {
LimitStream = stream;
LimitOffset = offset;
LimitLength = length;
LimitStream.Seek(offset, SeekOrigin.Begin);
}
public override void Flush() {
LimitStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count) {
if (LimitOffset + LimitLength <= Position + count) {
throw new Exception("out of something");
}
int read = LimitStream.Read(buffer, offset, count);
pos += read;
return read;
}
public override int ReadByte() {
if (LimitOffset + LimitLength <= Position + 1) {
throw new Exception("out of something");
}
int b = LimitStream.ReadByte();
if (b != -1) {
pos++;
}
return b;
}
public override long Seek(long offset, SeekOrigin origin) {
switch (origin) {
case SeekOrigin.Begin:
if (LimitOffset + LimitLength <= offset) {
throw new Exception("out of something");
}
pos = offset;
return LimitStream.Seek(LimitOffset + offset, SeekOrigin.Begin);
case SeekOrigin.Current:
if (LimitOffset + LimitLength <= Position + offset) {
throw new Exception("out of something");
}
pos += offset;
return LimitStream.Seek(offset, SeekOrigin.Current);
case SeekOrigin.End:
if (LimitLength - offset < 0) {
throw new Exception("out of something");
}
pos = LimitLength - offset;
return LimitStream.Seek(LimitOffset + LimitLength - offset, SeekOrigin.Begin);
default:
return 0;
}
}
public override void SetLength(long value) {
if (LimitStreamShared) {
LimitLength = value;
return;
}
LimitStream.SetLength(LimitOffset + value + LimitLength);
}
public override void Write(byte[] buffer, int offset, int count) {
if (LimitOffset + LimitLength <= Position + count) {
throw new Exception("out of something");
}
LimitStream.Write(buffer, offset, count);
pos += count;
}
public override byte[] GetBuffer() {
if (cachedBuffer != null && cachedOffset == LimitOffset && cachedLength == LimitLength) {
return cachedBuffer;
}
if (!cacheBuffer_) {
return ToArray();
}
cachedOffset = LimitOffset;
cachedLength = LimitLength;
return cachedBuffer = ToArray();
}
private readonly byte[] toArrayReadBuffer = new byte[2048];
public override byte[] ToArray() {
byte[] buffer;
int read;
long origPosition = LimitStream.Position;
LimitStream.Seek(LimitOffset, SeekOrigin.Begin);
long length = LimitLength == 0 ? LimitStream.Length : LimitLength;
if (length == 0) {
//most performant way would be to use the base MemoryStream, but
//System.NotSupportedException: Stream does not support writing.
MemoryStream ms = new MemoryStream();
LimitStream.Seek(LimitOffset, SeekOrigin.Begin);
while (0 < (read = LimitStream.Read(toArrayReadBuffer, 0, toArrayReadBuffer.Length))) {
base.Write(toArrayReadBuffer, 0, read);
}
LimitStream.Seek(origPosition, SeekOrigin.Begin);
buffer = base.ToArray();
ms.Close();
return buffer;
}
buffer = new byte[length];
int readCompletely = 0;
while (readCompletely < length) {
read = LimitStream.Read(buffer, readCompletely, buffer.Length - readCompletely);
readCompletely += read;
}
LimitStream.Seek(origPosition, SeekOrigin.Begin);
return buffer;
}
public override void Close() {
base.Close();
if (!LimitStreamShared) {
LimitStream.Close();
}
}
protected override void Dispose(bool disposing) {
if (!LimitStreamShared) {
//LimitStream.Dispose(disposing);
//Dispose and close are not the same, but whatever
LimitStream.Close();
}
base.Dispose(disposing);
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Text;
using LumiSoft.Net;
using LumiSoft.Net.SMTP;
using LumiSoft.Net.AUTH;
namespace LumiSoft.Net.SMTP.Server
{
/// <summary>
/// SMTP Session.
/// </summary>
public class SMTP_Session : SocketServerSession
{
private SMTP_Server m_pServer = null;
private Stream m_pMsgStream = null;
private SMTP_Cmd_Validator m_CmdValidator = null;
private long m_BDAT_ReadedCount = 0;
private string m_EhloName = "";
private string m_Reverse_path = ""; // Holds sender's reverse path.
private Hashtable m_Forward_path = null; // Holds Mail to.
private int m_BadCmdCount = 0; // Holds number of bad commands.
private BodyType m_BodyType;
private bool m_BDat = false;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="sessionID">Session ID.</param>
/// <param name="socket">Server connected socket.</param>
/// <param name="bindInfo">BindInfo what accepted socket.</param>
/// <param name="server">Reference to server.</param>
internal SMTP_Session(string sessionID,SocketEx socket,IPBindInfo bindInfo,SMTP_Server server) : base(sessionID,socket,bindInfo,server)
{
m_pServer = server;
m_BodyType = BodyType.x7_bit;
m_Forward_path = new Hashtable();
m_CmdValidator = new SMTP_Cmd_Validator();
// Start session proccessing
StartSession();
}
#region method StartSession
/// <summary>
/// Starts session.
/// </summary>
private void StartSession()
{
// Add session to session list
m_pServer.AddSession(this);
try{
// Check if ip is allowed to connect this computer
ValidateIP_EventArgs oArg = m_pServer.OnValidate_IpAddress(this);
if(oArg.Validated){
//--- Dedicated SSL connection, switch to SSL -----------------------------------//
if(this.BindInfo.SslMode == SslMode.SSL){
try{
this.Socket.SwitchToSSL(this.BindInfo.Certificate);
if(this.Socket.Logger != null){
this.Socket.Logger.AddTextEntry("SSL negotiation completed successfully.");
}
}
catch(Exception x){
if(this.Socket.Logger != null){
this.Socket.Logger.AddTextEntry("SSL handshake failed ! " + x.Message);
EndSession();
return;
}
}
}
//-------------------------------------------------------------------------------//
if(!string.IsNullOrEmpty(m_pServer.GreetingText)){
this.Socket.WriteLine("220 " + m_pServer.GreetingText);
}
else{
this.Socket.WriteLine("220 " + Net_Utils.GetLocalHostName(this.BindInfo.HostName) + " SMTP Server ready");
}
BeginRecieveCmd();
}
else{
// There is user specified error text, send it to connected socket
if(oArg.ErrorText.Length > 0){
this.Socket.WriteLine(oArg.ErrorText);
}
EndSession();
}
}
catch(Exception x){
OnError(x);
}
}
#endregion
#region method EndSession
/// <summary>
/// Ends session, closes socket.
/// </summary>
private void EndSession()
{
try{
try{
// Message storing not completed successfully, otherwise it must be null here.
// This can happen if BDAT -> QUIT and LAST BDAT block wasn't sent or
// when session times out on DATA or BDAT command.
if(m_pMsgStream != null){
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"Message storing not completed successfully",m_pMsgStream);
m_pMsgStream = null;
}
}
catch{
}
if(this.Socket != null){
// Write logs to log file, if needed
if(m_pServer.LogCommands){
this.Socket.Logger.Flush();
}
this.Socket.Shutdown(SocketShutdown.Both);
this.Socket.Disconnect();
//this.Socket = null;
}
}
catch{ // We don't need to check errors here, because they only may be Socket closing errors.
}
finally{
m_pServer.RemoveSession(this);
}
}
#endregion
#region method Kill
/// <summary>
/// Kill this session.
/// </summary>
public override void Kill()
{
EndSession();
}
#endregion
#region method OnSessionTimeout
/// <summary>
/// Is called by server when session has timed out.
/// </summary>
internal protected override void OnSessionTimeout()
{
try{
this.Socket.WriteLine("421 Session timeout, closing transmission channel");
}
catch{
}
EndSession();
}
#endregion
#region method OnError
/// <summary>
/// Is called when error occures.
/// </summary>
/// <param name="x"></param>
private void OnError(Exception x)
{
try{
// We must see InnerException too, SocketException may be as inner exception.
SocketException socketException = null;
if(x is SocketException){
socketException = (SocketException)x;
}
else if(x.InnerException != null && x.InnerException is SocketException){
socketException = (SocketException)x.InnerException;
}
if(socketException != null){
// Client disconnected without shutting down.
if(socketException.ErrorCode == 10054 || socketException.ErrorCode == 10053){
if(m_pServer.LogCommands){
this.Socket.Logger.AddTextEntry("Client aborted/disconnected");
}
EndSession();
// Exception handled, return
return;
}
// Connection timed out.
else if(socketException.ErrorCode == 10060){
if(m_pServer.LogCommands){
this.Socket.Logger.AddTextEntry("Connection timeout.");
}
EndSession();
// Exception handled, return
return;
}
}
m_pServer.OnSysError("",x);
}
catch(Exception ex){
m_pServer.OnSysError("",ex);
}
}
#endregion
#region method BeginRecieveCmd
/// <summary>
/// Starts recieveing command.
/// </summary>
private void BeginRecieveCmd()
{
MemoryStream strm = new MemoryStream();
this.Socket.BeginReadLine(strm,1024,strm,new SocketCallBack(this.EndRecieveCmd));
}
#endregion
#region method EndRecieveCmd
/// <summary>
/// Is called if command is recieved.
/// </summary>
/// <param name="result"></param>
/// <param name="count"></param>
/// <param name="exception"></param>
/// <param name="tag"></param>
private void EndRecieveCmd(SocketCallBackResult result,long count,Exception exception,object tag)
{
try{
switch(result)
{
case SocketCallBackResult.Ok:
MemoryStream strm = (MemoryStream)tag;
string cmdLine = System.Text.Encoding.Default.GetString(strm.ToArray());
// Exceute command
if(SwitchCommand(cmdLine)){
// Session end, close session
EndSession();
}
break;
case SocketCallBackResult.LengthExceeded:
this.Socket.WriteLine("500 Line too long.");
BeginRecieveCmd();
break;
case SocketCallBackResult.SocketClosed:
EndSession();
break;
case SocketCallBackResult.Exception:
OnError(exception);
break;
}
}
catch(ReadException x){
if(x.ReadReplyCode == ReadReplyCode.LengthExceeded){
this.Socket.WriteLine("500 Line too long.");
BeginRecieveCmd();
}
else if(x.ReadReplyCode == ReadReplyCode.SocketClosed){
EndSession();
}
else if(x.ReadReplyCode == ReadReplyCode.UnKnownError){
OnError(x);
}
}
catch(Exception x){
OnError(x);
}
}
#endregion
#region method SwitchCommand
/// <summary>
/// Executes SMTP command.
/// </summary>
/// <param name="SMTP_commandTxt">Original command text.</param>
/// <returns>Returns true if must end session(command loop).</returns>
private bool SwitchCommand(string SMTP_commandTxt)
{
//---- Parse command --------------------------------------------------//
string[] cmdParts = SMTP_commandTxt.TrimStart().Split(new char[]{' '});
string SMTP_command = cmdParts[0].ToUpper().Trim();
string argsText = Core.GetArgsText(SMTP_commandTxt,SMTP_command);
//---------------------------------------------------------------------//
bool getNextCmd = true;
switch(SMTP_command)
{
case "HELO":
HELO(argsText);
getNextCmd = false;
break;
case "EHLO":
EHLO(argsText);
getNextCmd = false;
break;
case "STARTTLS":
STARTTLS(argsText);
getNextCmd = false;
break;
case "AUTH":
AUTH(argsText);
break;
case "MAIL":
MAIL(argsText);
getNextCmd = false;
break;
case "RCPT":
RCPT(argsText);
getNextCmd = false;
break;
case "DATA":
BeginDataCmd(argsText);
getNextCmd = false;
break;
case "BDAT":
BeginBDATCmd(argsText);
getNextCmd = false;
break;
case "RSET":
RSET(argsText);
getNextCmd = false;
break;
// case "VRFY":
// VRFY();
// break;
// case "EXPN":
// EXPN();
// break;
case "HELP":
HELP();
break;
case "NOOP":
NOOP();
getNextCmd = false;
break;
case "QUIT":
QUIT(argsText);
getNextCmd = false;
return true;
default:
this.Socket.WriteLine("500 command unrecognized");
//---- Check that maximum bad commands count isn't exceeded ---------------//
if(m_BadCmdCount > m_pServer.MaxBadCommands-1){
this.Socket.WriteLine("421 Too many bad commands, closing transmission channel");
return true;
}
m_BadCmdCount++;
//-------------------------------------------------------------------------//
break;
}
if(getNextCmd){
BeginRecieveCmd();
}
return false;
}
#endregion
#region method HELO
private void HELO(string argsText)
{
/* Rfc 2821 4.1.1.1
These commands, and a "250 OK" reply to one of them, confirm that
both the SMTP client and the SMTP server are in the initial state,
that is, there is no transaction in progress and all state tables and
buffers are cleared.
Arguments:
Host name.
Syntax:
"HELO" SP Domain CRLF
*/
m_EhloName = argsText;
ResetState();
this.Socket.BeginWriteLine("250 " + Net_Utils.GetLocalHostName(this.BindInfo.HostName) + " Hello [" + this.RemoteEndPoint.Address.ToString() + "]",new SocketCallBack(this.EndSend));
m_CmdValidator.Helo_ok = true;
}
#endregion
#region method EHLO
private void EHLO(string argsText)
{
/* Rfc 2821 4.1.1.1
These commands, and a "250 OK" reply to one of them, confirm that
both the SMTP client and the SMTP server are in the initial state,
that is, there is no transaction in progress and all state tables and
buffers are cleared.
*/
m_EhloName = argsText;
ResetState();
//--- Construct supported AUTH types value ----------------------------//
string authTypesString = "";
if((m_pServer.SupportedAuthentications & SaslAuthTypes.Login) != 0){
authTypesString += "LOGIN ";
}
if((m_pServer.SupportedAuthentications & SaslAuthTypes.Cram_md5) != 0){
authTypesString += "CRAM-MD5 ";
}
if((m_pServer.SupportedAuthentications & SaslAuthTypes.Digest_md5) != 0){
authTypesString += "DIGEST-MD5 ";
}
authTypesString = authTypesString.Trim();
//-----------------------------------------------------------------------//
string reply = "";
reply += "250-" + Net_Utils.GetLocalHostName(this.BindInfo.HostName) + " Hello [" + this.RemoteEndPoint.Address.ToString() + "]\r\n";
reply += "250-PIPELINING\r\n";
reply += "250-SIZE " + m_pServer.MaxMessageSize + "\r\n";
// reply += "250-DSN\r\n";
// reply += "250-HELP\r\n";
reply += "250-8BITMIME\r\n";
reply += "250-BINARYMIME\r\n";
reply += "250-CHUNKING\r\n";
if(authTypesString.Length > 0){
reply += "250-AUTH " + authTypesString + "\r\n";
}
if(!this.Socket.SSL && this.BindInfo.Certificate != null){
reply += "250-STARTTLS\r\n";
}
reply += "250 Ok\r\n";
this.Socket.BeginWriteLine(reply,null,new SocketCallBack(this.EndSend));
m_CmdValidator.Helo_ok = true;
}
#endregion
#region method STARTTLS
private void STARTTLS(string argsText)
{
/* RFC 2487 STARTTLS 5. STARTTLS Command.
The format for the STARTTLS command is:
STARTTLS
with no parameters.
After the client gives the STARTTLS command, the server responds with
one of the following reply codes:
220 Ready to start TLS
501 Syntax error (no parameters allowed)
454 TLS not available due to temporary reason
5.2 Result of the STARTTLS Command
Upon completion of the TLS handshake, the SMTP protocol is reset to
the initial state (the state in SMTP after a server issues a 220
service ready greeting).
*/
if(this.Socket.SSL){
this.Socket.WriteLine("500 TLS already started !");
return;
}
if(this.BindInfo.Certificate == null){
this.Socket.WriteLine("454 TLS not available, SSL certificate isn't specified !");
return;
}
this.Socket.WriteLine("220 Ready to start TLS");
try{
this.Socket.SwitchToSSL(this.BindInfo.Certificate);
if(m_pServer.LogCommands){
this.Socket.Logger.AddTextEntry("TLS negotiation completed successfully.");
}
}
catch(Exception x){
this.Socket.WriteLine("500 TLS handshake failed ! " + x.Message);
}
ResetState();
BeginRecieveCmd();
}
#endregion
#region method AUTH
private void AUTH(string argsText)
{
/* Rfc 2554 AUTH --------------------------------------------------//
Restrictions:
After an AUTH command has successfully completed, no more AUTH
commands may be issued in the same session. After a successful
AUTH command completes, a server MUST reject any further AUTH
commands with a 503 reply.
Remarks:
If an AUTH command fails, the server MUST behave the same as if
the client had not issued the AUTH command.
*/
if(this.Authenticated){
this.Socket.WriteLine("503 already authenticated");
return;
}
try{
//------ Parse parameters -------------------------------------//
string userName = "";
string password = "";
AuthUser_EventArgs aArgs = null;
string[] param = argsText.Split(new char[]{' '});
switch(param[0].ToUpper())
{
case "PLAIN":
this.Socket.WriteLine("504 Unrecognized authentication type.");
break;
case "LOGIN":
#region LOGIN authentication
//---- AUTH = LOGIN ------------------------------
/* Login
C: AUTH LOGIN
S: 334 VXNlcm5hbWU6
C: username_in_base64
S: 334 UGFzc3dvcmQ6
C: password_in_base64
or (initial-response argument included to avoid one 334 server response)
C: AUTH LOGIN username_in_base64
S: 334 UGFzc3dvcmQ6
C: password_in_base64
VXNlcm5hbWU6 base64_decoded= USERNAME
UGFzc3dvcmQ6 base64_decoded= PASSWORD
*/
// Note: all strings are base64 strings eg. VXNlcm5hbWU6 = UserName.
// No user name included (initial-response argument)
if(param.Length == 1){
// Query UserName
this.Socket.WriteLine("334 VXNlcm5hbWU6");
string userNameLine = this.Socket.ReadLine();
// Encode username from base64
if(userNameLine.Length > 0){
userName = System.Text.Encoding.Default.GetString(Convert.FromBase64String(userNameLine));
}
}
// User name included, use it
else{
userName = System.Text.Encoding.Default.GetString(Convert.FromBase64String(param[1]));
}
// Query Password
this.Socket.WriteLine("334 UGFzc3dvcmQ6");
string passwordLine = this.Socket.ReadLine();
// Encode password from base64
if(passwordLine.Length > 0){
password = System.Text.Encoding.Default.GetString(Convert.FromBase64String(passwordLine));
}
aArgs = m_pServer.OnAuthUser(this,userName,password,"",AuthType.Plain);
if(aArgs.Validated){
this.Socket.WriteLine("235 Authentication successful.");
this.SetUserName(userName);
}
else{
this.Socket.WriteLine("535 Authentication failed");
}
#endregion
break;
case "CRAM-MD5":
#region CRAM-MD5 authentication
/* Cram-M5
C: AUTH CRAM-MD5
S: 334 <md5_calculation_hash_in_base64>
C: base64(username password_hash)
*/
string md5Hash = "<" + Guid.NewGuid().ToString().ToLower() + ">";
this.Socket.WriteLine("334 " + Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(md5Hash)));
string reply = this.Socket.ReadLine();
reply = System.Text.Encoding.Default.GetString(Convert.FromBase64String(reply));
string[] replyArgs = reply.Split(' ');
userName = replyArgs[0];
aArgs = m_pServer.OnAuthUser(this,userName,replyArgs[1],md5Hash,AuthType.CRAM_MD5);
if(aArgs.Validated){
this.Socket.WriteLine("235 Authentication successful.");
this.SetUserName(userName);
}
else{
this.Socket.WriteLine("535 Authentication failed");
}
#endregion
break;
case "DIGEST-MD5":
#region DIGEST-MD5 authentication
/* RFC 2831 AUTH DIGEST-MD5
*
* Example:
*
* C: AUTH DIGEST-MD5
* S: 334 base64(realm="elwood.innosoft.com",nonce="OA6MG9tEQGm2hh",qop="auth",algorithm=md5-sess)
* C: base64(username="chris",realm="elwood.innosoft.com",nonce="OA6MG9tEQGm2hh",
* nc=00000001,cnonce="OA6MHXh6VqTrRk",digest-uri="smtp/elwood.innosoft.com",
* response=d388dad90d4bbd760a152321f2143af7,qop=auth)
* S: 334 base64(rspauth=ea40f60335c427b5527b84dbabcdfffd)
* C:
* S: 235 Authentication successful.
*/
string nonce = Auth_HttpDigest.CreateNonce();
string opaque = Auth_HttpDigest.CreateOpaque();
Auth_HttpDigest digest = new Auth_HttpDigest(this.BindInfo.HostName,nonce,opaque);
digest.Algorithm = "md5-sess";
this.Socket.WriteLine("334 " + AuthHelper.Base64en(digest.ToChallange(false)));
string clientResponse = AuthHelper.Base64de(this.Socket.ReadLine());
digest = new Auth_HttpDigest(clientResponse,"AUTHENTICATE");
// Check that realm,nonce and opaque in client response are same as we specified.
if(this.BindInfo.HostName != digest.Realm){
this.Socket.WriteLine("535 Authentication failed, 'realm' won't match.");
return;
}
if(nonce != digest.Nonce){
this.Socket.WriteLine("535 Authentication failed, 'nonce' won't match.");
return;
}
if(opaque != digest.Opaque){
this.Socket.WriteLine("535 Authentication failed, 'opaque' won't match.");
return;
}
userName = digest.UserName;
aArgs = m_pServer.OnAuthUser(this,userName,digest.Response,clientResponse,AuthType.DIGEST_MD5);
if(aArgs.Validated){
// Send server computed password hash
this.Socket.WriteLine("334 " + AuthHelper.Base64en("rspauth=" + aArgs.ReturnData));
// We must got empty line here
clientResponse = this.Socket.ReadLine();
if(clientResponse == ""){
this.Socket.WriteLine("235 Authentication successful.");
this.SetUserName(userName);
}
else{
this.Socket.WriteLine("535 Authentication failed, unexpected client response.");
}
}
else{
this.Socket.WriteLine("535 Authentication failed.");
}
#endregion
break;
default:
this.Socket.WriteLine("504 Unrecognized authentication type.");
break;
}
//-----------------------------------------------------------------//
}
catch{
this.Socket.WriteLine("535 Authentication failed.");
}
}
#endregion
#region method MAIL
private void MAIL(string argsText)
{
/* RFC 2821 3.3
NOTE:
This command tells the SMTP-receiver that a new mail transaction is
starting and to reset all its state tables and buffers, including any
recipients or mail data. The <reverse-path> portion of the first or
only argument contains the source mailbox (between "<" and ">"
brackets), which can be used to report errors (see section 4.2 for a
discussion of error reporting). If accepted, the SMTP server returns
a 250 OK reply.
MAIL FROM:<reverse-path> [SP <mail-parameters> ] <CRLF>
reverse-path = "<" [ A-d-l ":" ] Mailbox ">"
Mailbox = Local-part "@" Domain
body-value ::= "7BIT" / "8BITMIME" / "BINARYMIME"
Examples:
C: MAIL FROM:<ned@thor.innosoft.com>
C: MAIL FROM:<ned@thor.innosoft.com> SIZE=500000 BODY=8BITMIME AUTH=xxxx
*/
if(!m_CmdValidator.MayHandle_MAIL){
if(m_CmdValidator.MailFrom_ok){
this.Socket.BeginWriteLine("503 Sender already specified",new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend));
}
return;
}
//------ Parse parameters -------------------------------------------------------------------//
string senderEmail = "";
long messageSize = 0;
BodyType bodyType = BodyType.x7_bit;
bool isFromParam = false;
// Parse while all params parsed or while is breaked
while(argsText.Length > 0){
if(argsText.ToLower().StartsWith("from:")){
// Remove from:
argsText = argsText.Substring(5).Trim();
// If there is more parameters
if(argsText.IndexOf(" ") > -1){
senderEmail = argsText.Substring(0,argsText.IndexOf(" "));
argsText = argsText.Substring(argsText.IndexOf(" ")).Trim();
}
else{
senderEmail = argsText;
argsText = "";
}
// If address between <>, remove <>
if(senderEmail.StartsWith("<") && senderEmail.EndsWith(">")){
senderEmail = senderEmail.Substring(1,senderEmail.Length - 2);
}
isFromParam = true;
}
else if(argsText.ToLower().StartsWith("size=")){
// Remove size=
argsText = argsText.Substring(5).Trim();
string sizeS = "";
// If there is more parameters
if(argsText.IndexOf(" ") > -1){
sizeS = argsText.Substring(0,argsText.IndexOf(" "));
argsText = argsText.Substring(argsText.IndexOf(" ")).Trim();
}
else{
sizeS = argsText;
argsText = "";
}
// See if value ok
if(Core.IsNumber(sizeS)){
messageSize = Convert.ToInt64(sizeS);
}
else{
this.Socket.BeginWriteLine("501 SIZE parameter value is invalid. Syntax:{MAIL FROM:<address> [SIZE=msgSize] [BODY=8BITMIME]}",new SocketCallBack(this.EndSend));
return;
}
}
else if(argsText.ToLower().StartsWith("body=")){
// Remove body=
argsText = argsText.Substring(5).Trim();
string bodyTypeS = "";
// If there is more parameters
if(argsText.IndexOf(" ") > -1){
bodyTypeS = argsText.Substring(0,argsText.IndexOf(" "));
argsText = argsText.Substring(argsText.IndexOf(" ")).Trim();
}
else{
bodyTypeS = argsText;
argsText = "";
}
// See if value ok
switch(bodyTypeS.ToUpper())
{
case "7BIT":
bodyType = BodyType.x7_bit;
break;
case "8BITMIME":
bodyType = BodyType.x8_bit;
break;
case "BINARYMIME":
bodyType = BodyType.binary;
break;
default:
this.Socket.BeginWriteLine("501 BODY parameter value is invalid. Syntax:{MAIL FROM:<address> [BODY=(7BIT/8BITMIME)]}",new SocketCallBack(this.EndSend));
return;
}
}
else if(argsText.ToLower().StartsWith("auth=")){
// Currently just eat AUTH keyword
// Remove auth=
argsText = argsText.Substring(5).Trim();
string authS = "";
// If there is more parameters
if(argsText.IndexOf(" ") > -1){
authS = argsText.Substring(0,argsText.IndexOf(" "));
argsText = argsText.Substring(argsText.IndexOf(" ")).Trim();
}
else{
authS = argsText;
argsText = "";
}
}
else{
this.Socket.BeginWriteLine("501 Error in parameters. Syntax:{MAIL FROM:<address> [SIZE=msgSize] [BODY=8BITMIME]}",new SocketCallBack(this.EndSend));
return;
}
}
// If required parameter 'FROM:' is missing
if(!isFromParam){
this.Socket.BeginWriteLine("501 Required param FROM: is missing. Syntax:{MAIL FROM:<address> [SIZE=msgSize] [BODY=8BITMIME]}",new SocketCallBack(this.EndSend));
return;
}
//---------------------------------------------------------------------------------------------//
//--- Check message size
if(m_pServer.MaxMessageSize > messageSize){
// Check if sender is ok
ValidateSender_EventArgs eArgs = m_pServer.OnValidate_MailFrom(this,senderEmail,senderEmail);
if(eArgs.Validated){
// See note above
ResetState();
// Store reverse path
m_Reverse_path = senderEmail;
m_CmdValidator.MailFrom_ok = true;
//-- Store params
m_BodyType = bodyType;
this.Socket.BeginWriteLine("250 OK <" + senderEmail + "> Sender ok",new SocketCallBack(this.EndSend));
}
else{
if(eArgs.ErrorText != null && eArgs.ErrorText.Length > 0){
this.Socket.BeginWriteLine("550 " + eArgs.ErrorText,new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine("550 You are refused to send mail here",new SocketCallBack(this.EndSend));
}
}
}
else{
this.Socket.BeginWriteLine("552 Message exceeds allowed size",new SocketCallBack(this.EndSend));
}
}
#endregion
#region method RCPT
private void RCPT(string argsText)
{
/* RFC 2821 4.1.1.3 RCPT
NOTE:
This command is used to identify an individual recipient of the mail
data; multiple recipients are specified by multiple use of this
command. The argument field contains a forward-path and may contain
optional parameters.
Relay hosts SHOULD strip or ignore source routes, and
names MUST NOT be copied into the reverse-path.
Example:
RCPT TO:<@hosta.int,@jkl.org:userc@d.bar.org>
will normally be sent directly on to host d.bar.org with envelope
commands
RCPT TO:<userc@d.bar.org>
RCPT TO:<userc@d.bar.org> SIZE=40000
RCPT TO:<forward-path> [ SP <rcpt-parameters> ] <CRLF>
*/
/* RFC 2821 3.3
If a RCPT command appears without a previous MAIL command,
the server MUST return a 503 "Bad sequence of commands" response.
*/
if(!m_CmdValidator.MayHandle_RCPT || m_BDat){
this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend));
return;
}
// Check that recipient count isn't exceeded
if(m_Forward_path.Count > m_pServer.MaxRecipients){
this.Socket.BeginWriteLine("452 Too many recipients",new SocketCallBack(this.EndSend));
return;
}
//------ Parse parameters -------------------------------------------------------------------//
string recipientEmail = "";
long messageSize = 0;
bool isToParam = false;
// Parse while all params parsed or while is breaked
while(argsText.Length > 0){
if(argsText.ToLower().StartsWith("to:")){
// Remove to:
argsText = argsText.Substring(3).Trim();
// If there is more parameters
if(argsText.IndexOf(" ") > -1){
recipientEmail = argsText.Substring(0,argsText.IndexOf(" "));
argsText = argsText.Substring(argsText.IndexOf(" ")).Trim();
}
else{
recipientEmail = argsText;
argsText = "";
}
// If address between <>, remove <>
if(recipientEmail.StartsWith("<") && recipientEmail.EndsWith(">")){
recipientEmail = recipientEmail.Substring(1,recipientEmail.Length - 2);
}
// See if value ok
if(recipientEmail.Length == 0){
this.Socket.BeginWriteLine("501 Recipient address isn't specified. Syntax:{RCPT TO:<address> [SIZE=msgSize]}",new SocketCallBack(this.EndSend));
return;
}
isToParam = true;
}
else if(argsText.ToLower().StartsWith("size=")){
// Remove size=
argsText = argsText.Substring(5).Trim();
string sizeS = "";
// If there is more parameters
if(argsText.IndexOf(" ") > -1){
sizeS = argsText.Substring(0,argsText.IndexOf(" "));
argsText = argsText.Substring(argsText.IndexOf(" ")).Trim();
}
else{
sizeS = argsText;
argsText = "";
}
// See if value ok
if(Core.IsNumber(sizeS)){
messageSize = Convert.ToInt64(sizeS);
}
else{
this.Socket.BeginWriteLine("501 SIZE parameter value is invalid. Syntax:{RCPT TO:<address> [SIZE=msgSize]}",new SocketCallBack(this.EndSend));
return;
}
}
else{
this.Socket.BeginWriteLine("501 Error in parameters. Syntax:{RCPT TO:<address> [SIZE=msgSize]}",new SocketCallBack(this.EndSend));
return;
}
}
// If required parameter 'TO:' is missing
if(!isToParam){
this.Socket.BeginWriteLine("501 Required param TO: is missing. Syntax:<RCPT TO:{address> [SIZE=msgSize]}",new SocketCallBack(this.EndSend));
return;
}
//---------------------------------------------------------------------------------------------//
// Check message size
if(m_pServer.MaxMessageSize > messageSize){
// Check if email address is ok
ValidateRecipient_EventArgs rcpt_args = m_pServer.OnValidate_MailTo(this,recipientEmail,recipientEmail,this.Authenticated);
if(rcpt_args.Validated){
// Check if mailbox size isn't exceeded
if(m_pServer.Validate_MailBoxSize(this,recipientEmail,messageSize)){
// Store reciptient
if(!m_Forward_path.Contains(recipientEmail)){
m_Forward_path.Add(recipientEmail,recipientEmail);
}
m_CmdValidator.RcptTo_ok = true;
this.Socket.BeginWriteLine("250 OK <" + recipientEmail + "> Recipient ok",new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine("552 Mailbox size limit exceeded",new SocketCallBack(this.EndSend));
}
}
// Recipient rejected
else{
if(rcpt_args.LocalRecipient){
this.Socket.BeginWriteLine("550 <" + recipientEmail + "> No such user here",new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine("550 <" + recipientEmail + "> Relay not allowed",new SocketCallBack(this.EndSend));
}
}
}
else{
this.Socket.BeginWriteLine("552 Message exceeds allowed size",new SocketCallBack(this.EndSend));
}
}
#endregion
#region method DATA
#region method BeginDataCmd
private void BeginDataCmd(string argsText)
{
/* RFC 2821 4.1.1
NOTE:
Several commands (RSET, DATA, QUIT) are specified as not permitting
parameters. In the absence of specific extensions offered by the
server and accepted by the client, clients MUST NOT send such
parameters and servers SHOULD reject commands containing them as
having invalid syntax.
*/
if(argsText.Length > 0){
this.Socket.BeginWriteLine("500 Syntax error. Syntax:{DATA}",new SocketCallBack(this.EndSend));
return;
}
/* RFC 2821 4.1.1.4 DATA
NOTE:
If accepted, the SMTP server returns a 354 Intermediate reply and
considers all succeeding lines up to but not including the end of
mail data indicator to be the message text. When the end of text is
successfully received and stored the SMTP-receiver sends a 250 OK
reply.
The mail data is terminated by a line containing only a period, that
is, the character sequence "<CRLF>.<CRLF>" (see section 4.5.2). This
is the end of mail data indication.
When the SMTP server accepts a message either for relaying or for
final delivery, it inserts a trace record (also referred to
interchangeably as a "time stamp line" or "Received" line) at the top
of the mail data. This trace record indicates the identity of the
host that sent the message, the identity of the host that received
the message (and is inserting this time stamp), and the date and time
the message was received. Relayed messages will have multiple time
stamp lines. Details for formation of these lines, including their
syntax, is specified in section 4.4.
*/
/* RFC 2821 DATA
NOTE:
If there was no MAIL, or no RCPT, command, or all such commands
were rejected, the server MAY return a "command out of sequence"
(503) or "no valid recipients" (554) reply in response to the DATA
command.
*/
if(!m_CmdValidator.MayHandle_DATA || m_BDat){
this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend));
return;
}
if(m_Forward_path.Count == 0){
this.Socket.BeginWriteLine("554 no valid recipients given",new SocketCallBack(this.EndSend));
return;
}
// Get message store stream
GetMessageStoreStream_eArgs eArgs = m_pServer.OnGetMessageStoreStream(this);
m_pMsgStream = eArgs.StoreStream;
// reply: 354 Start mail input
this.Socket.WriteLine("354 Start mail input; end with <CRLF>.<CRLF>");
//---- Construct server headers for message----------------------------------------------------------------//
string header = "Received: from " + Core.GetHostName(this.RemoteEndPoint.Address) + " (" + this.RemoteEndPoint.Address.ToString() + ")\r\n";
header += "\tby " + this.BindInfo.HostName + " with SMTP; " + DateTime.Now.ToUniversalTime().ToString("r",System.Globalization.DateTimeFormatInfo.InvariantInfo) + "\r\n";
byte[] headers = System.Text.Encoding.ASCII.GetBytes(header);
m_pMsgStream.Write(headers,0,headers.Length);
//---------------------------------------------------------------------------------------------------------//
// Begin recieving data
this.Socket.BeginReadPeriodTerminated(m_pMsgStream,m_pServer.MaxMessageSize,null,new SocketCallBack(this.EndDataCmd));
}
#endregion
#region method EndDataCmd
/// <summary>
/// Is called when DATA command is finnished.
/// </summary>
/// <param name="result"></param>
/// <param name="count"></param>
/// <param name="exception"></param>
/// <param name="tag"></param>
private void EndDataCmd(SocketCallBackResult result,long count,Exception exception,object tag)
{
try{
switch(result)
{
case SocketCallBackResult.Ok:
// Notify Message stream owner that message storing completed ok.
MessageStoringCompleted_eArgs oArg = m_pServer.OnMessageStoringCompleted(this,null,m_pMsgStream);
if(oArg.ServerReply.ErrorReply){
this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("500","Error storing message"),new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("250","OK"),new SocketCallBack(this.EndSend));
}
break;
case SocketCallBackResult.LengthExceeded:
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"Requested mail action aborted: exceeded storage allocation",m_pMsgStream);
this.Socket.BeginWriteLine("552 Requested mail action aborted: exceeded storage allocation",new SocketCallBack(this.EndSend));
break;
case SocketCallBackResult.SocketClosed:
if(m_pMsgStream != null){
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"SocketClosed",m_pMsgStream);
m_pMsgStream = null;
}
// Stream is already closed, probably by the EndSession method, do nothing.
//else{
//}
EndSession();
break;
case SocketCallBackResult.Exception:
if(m_pMsgStream != null){
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"Exception: " + exception.Message,m_pMsgStream);
m_pMsgStream = null;
}
// Stream is already closed, probably by the EndSession method, do nothing.
//else{
//}
OnError(exception);
break;
}
/* RFC 2821 4.1.1.4 DATA
NOTE:
Receipt of the end of mail data indication requires the server to
process the stored mail transaction information. This processing
consumes the information in the reverse-path buffer, the forward-path
buffer, and the mail data buffer, and on the completion of this
command these buffers are cleared.
*/
ResetState();
}
catch(Exception x){
OnError(x);
}
}
#endregion
#endregion
#region function BDAT
#region method BeginBDATCmd
private void BeginBDATCmd(string argsText)
{
/*RFC 3030 2
The BDAT verb takes two arguments.The first argument indicates the length,
in octets, of the binary data chunk. The second optional argument indicates
that the data chunk is the last.
The message data is sent immediately after the trailing <CR>
<LF> of the BDAT command line. Once the receiver-SMTP receives the
specified number of octets, it will return a 250 reply code.
The optional LAST parameter on the BDAT command indicates that this
is the last chunk of message data to be sent. The last BDAT command
MAY have a byte-count of zero indicating there is no additional data
to be sent. Any BDAT command sent after the BDAT LAST is illegal and
MUST be replied to with a 503 "Bad sequence of commands" reply code.
The state resulting from this error is indeterminate. A RSET command
MUST be sent to clear the transaction before continuing.
A 250 response MUST be sent to each successful BDAT data block within
a mail transaction.
bdat-cmd ::= "BDAT" SP chunk-size [ SP end-marker ] CR LF
chunk-size ::= 1*DIGIT
end-marker ::= "LAST"
*/
if(!m_CmdValidator.MayHandle_BDAT){
this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend));
return;
}
string[] param = argsText.Split(new char[]{' '});
if(param.Length > 0 && param.Length < 3){
if(Core.IsNumber(param[0])){
int countToRead = Convert.ToInt32(param[0]);
// LAST specified
bool lastChunk = false;
if(param.Length == 2){
lastChunk = true;
}
// First BDAT command call.
if(!m_BDat){
// Get message store stream
GetMessageStoreStream_eArgs eArgs = m_pServer.OnGetMessageStoreStream(this);
m_pMsgStream = eArgs.StoreStream;
// Add header to first bdat block only
//---- Construct server headers for message----------------------------------------------------------------//
string header = "Received: from " + Core.GetHostName(this.RemoteEndPoint.Address) + " (" + this.RemoteEndPoint.Address.ToString() + ")\r\n";
header += "\tby " + this.BindInfo.HostName + " with SMTP; " + DateTime.Now.ToUniversalTime().ToString("r",System.Globalization.DateTimeFormatInfo.InvariantInfo) + "\r\n";
byte[] headers = System.Text.Encoding.ASCII.GetBytes(header);
m_pMsgStream.Write(headers,0,headers.Length);
//---------------------------------------------------------------------------------------------------------//
}
// Begin junking data, maximum allowed message size exceeded.
// BDAT comman is dummy, after commandline binary data is at once follwed,
// so server server must junk all data and then report error.
if((m_BDAT_ReadedCount + countToRead) > m_pServer.MaxMessageSize){
this.Socket.BeginReadSpecifiedLength(new JunkingStream(),countToRead,lastChunk,new SocketCallBack(this.EndBDatCmd));
}
// Begin reading data
else{
this.Socket.BeginReadSpecifiedLength(m_pMsgStream,countToRead,lastChunk,new SocketCallBack(this.EndBDatCmd));
}
m_BDat = true;
}
else{
this.Socket.BeginWriteLine("500 Syntax error. Syntax:{BDAT chunk-size [LAST]}",new SocketCallBack(this.EndSend));
}
}
else{
this.Socket.BeginWriteLine("500 Syntax error. Syntax:{BDAT chunk-size [LAST]}",new SocketCallBack(this.EndSend));
}
}
#endregion
#region method EndBDatCmd
private void EndBDatCmd(SocketCallBackResult result,long count,Exception exception,object tag)
{
try{
switch(result)
{
case SocketCallBackResult.Ok:
m_BDAT_ReadedCount += count;
// BDAT command completed, got all data junks
if((bool)tag){
// Maximum allowed message size exceeded.
if((m_BDAT_ReadedCount) > m_pServer.MaxMessageSize){
m_pServer.OnMessageStoringCompleted(this,"Requested mail action aborted: exceeded storage allocation",m_pMsgStream);
this.Socket.BeginWriteLine("552 Requested mail action aborted: exceeded storage allocation",new SocketCallBack(this.EndSend));
}
else{
// Notify Message stream owner that message storing completed ok.
MessageStoringCompleted_eArgs oArg = m_pServer.OnMessageStoringCompleted(this,null,m_pMsgStream);
if(oArg.ServerReply.ErrorReply){
this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("500","Error storing message"),new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("250","Message(" + m_BDAT_ReadedCount + " bytes) stored ok."),new SocketCallBack(this.EndSend));
}
}
/* RFC 2821 4.1.1.4 DATA
NOTE:
Receipt of the end of mail data indication requires the server to
process the stored mail transaction information. This processing
consumes the information in the reverse-path buffer, the forward-path
buffer, and the mail data buffer, and on the completion of this
command these buffers are cleared.
*/
ResetState();
}
// Got BDAT data block, BDAT must continue, that wasn't last data block.
else{
// Maximum allowed message size exceeded.
if((m_BDAT_ReadedCount) > m_pServer.MaxMessageSize){
this.Socket.BeginWriteLine("552 Requested mail action aborted: exceeded storage allocation",new SocketCallBack(this.EndSend));
}
else{
this.Socket.BeginWriteLine("250 Data block of " + count + " bytes recieved OK.",new SocketCallBack(this.EndSend));
}
}
break;
case SocketCallBackResult.SocketClosed:
if(m_pMsgStream != null){
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"SocketClosed",m_pMsgStream);
m_pMsgStream = null;
}
// Stream is already closed, probably by the EndSession method, do nothing.
//else{
//}
EndSession();
return;
case SocketCallBackResult.Exception:
if(m_pMsgStream != null){
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"Exception: " + exception.Message,m_pMsgStream);
m_pMsgStream = null;
}
// Stream is already closed, probably by the EndSession method, do nothing.
//else{
//}
OnError(exception);
return;
}
}
catch(Exception x){
OnError(x);
}
}
#endregion
#endregion
#region method RSET
private void RSET(string argsText)
{
/* RFC 2821 4.1.1
NOTE:
Several commands (RSET, DATA, QUIT) are specified as not permitting
parameters. In the absence of specific extensions offered by the
server and accepted by the client, clients MUST NOT send such
parameters and servers SHOULD reject commands containing them as
having invalid syntax.
*/
if(argsText.Length > 0){
this.Socket.BeginWriteLine("500 Syntax error. Syntax:{RSET}",new SocketCallBack(this.EndSend));
return;
}
/* RFC 2821 4.1.1.5 RESET (RSET)
NOTE:
This command specifies that the current mail transaction will be
aborted. Any stored sender, recipients, and mail data MUST be
discarded, and all buffers and state tables cleared. The receiver
MUST send a "250 OK" reply to a RSET command with no arguments.
*/
try{
// Message storing aborted by RSET.
// This can happen if BDAT -> RSET and LAST BDAT block wasn't sent.
if(m_pMsgStream != null){
// We must call that method to notify Message stream owner to close/dispose that stream.
m_pServer.OnMessageStoringCompleted(this,"Message storing aborted by RSET",m_pMsgStream);
m_pMsgStream = null;
}
}
catch{
}
ResetState();
this.Socket.BeginWriteLine("250 OK",new SocketCallBack(this.EndSend));
}
#endregion
#region method VRFY
private void VRFY()
{
/* RFC 821 VRFY
Example:
S: VRFY Lumi
R: 250 Ivar Lumi <ivx@lumisoft.ee>
S: VRFY lum
R: 550 String does not match anything.
*/
// ToDo: Parse user, add new event for cheking user
this.Socket.BeginWriteLine("502 Command not implemented",new SocketCallBack(this.EndSend));
}
#endregion
#region mehtod NOOP
private void NOOP()
{
/* RFC 2821 4.1.1.9 NOOP (NOOP)
NOTE:
This command does not affect any parameters or previously entered
commands. It specifies no action other than that the receiver send
an OK reply.
*/
this.Socket.BeginWriteLine("250 OK",new SocketCallBack(this.EndSend));
}
#endregion
#region method QUIT
private void QUIT(string argsText)
{
/* RFC 2821 4.1.1
NOTE:
Several commands (RSET, DATA, QUIT) are specified as not permitting
parameters. In the absence of specific extensions offered by the
server and accepted by the client, clients MUST NOT send such
parameters and servers SHOULD reject commands containing them as
having invalid syntax.
*/
if(argsText.Length > 0){
this.Socket.BeginWriteLine("500 Syntax error. Syntax:<QUIT>",new SocketCallBack(this.EndSend));
return;
}
/* RFC 2821 4.1.1.10 QUIT (QUIT)
NOTE:
This command specifies that the receiver MUST send an OK reply, and
then close the transmission channel.
*/
// reply: 221 - Close transmission cannel
this.Socket.WriteLine("221 Service closing transmission channel");
// this.Socket.BeginSendLine("221 Service closing transmission channel",null);
}
#endregion
//---- Optional commands
#region function EXPN
private void EXPN()
{
/* RFC 821 EXPN
NOTE:
This command asks the receiver to confirm that the argument
identifies a mailing list, and if so, to return the
membership of that list. The full name of the users (if
known) and the fully specified mailboxes are returned in a
multiline reply.
Example:
S: EXPN lsAll
R: 250-ivar lumi <ivx@lumisoft.ee>
R: 250-<willy@lumisoft.ee>
R: 250 <kaido@lumisoft.ee>
*/
this.Socket.WriteLine("502 Command not implemented");
}
#endregion
#region function HELP
private void HELP()
{
/* RFC 821 HELP
NOTE:
This command causes the receiver to send helpful information
to the sender of the HELP command. The command may take an
argument (e.g., any command name) and return more specific
information as a response.
*/
this.Socket.WriteLine("502 Command not implemented");
}
#endregion
#region method ResetState
private void ResetState()
{
//--- Reset variables
m_BodyType = BodyType.x7_bit;
m_Forward_path.Clear();
m_Reverse_path = "";
// m_Authenticated = false; // Keep AUTH
m_CmdValidator.Reset();
m_CmdValidator.Helo_ok = true;
m_pMsgStream = null;
m_BDat = false;
m_BDAT_ReadedCount = 0;
}
#endregion
#region function EndSend
/// <summary>
/// Is called when asynchronous send completes.
/// </summary>
/// <param name="result">If true, then send was successfull.</param>
/// <param name="count">Count sended.</param>
/// <param name="exception">Exception happend on send. NOTE: available only is result=false.</param>
/// <param name="tag">User data.</param>
private void EndSend(SocketCallBackResult result,long count,Exception exception,object tag)
{
try{
switch(result)
{
case SocketCallBackResult.Ok:
BeginRecieveCmd();
break;
case SocketCallBackResult.SocketClosed:
EndSession();
break;
case SocketCallBackResult.Exception:
OnError(exception);
break;
}
}
catch(Exception x){
OnError(x);
}
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets client reported EHLO/HELO name.
/// </summary>
public string EhloName
{
get{ return m_EhloName; }
}
/// <summary>
/// Gets body type.
/// </summary>
public BodyType BodyType
{
get{ return m_BodyType; }
}
/// <summary>
/// Gets sender.
/// </summary>
public string MailFrom
{
get{ return m_Reverse_path; }
}
/// <summary>
/// Gets recipients.
/// </summary>
public string[] MailTo
{
get{
string[] to = new string[m_Forward_path.Count];
m_Forward_path.Values.CopyTo(to,0);
return to;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using Tools;
using Xunit;
namespace System.Numerics.Tests
{
public class op_multiplyTest
{
private static int s_samples = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunMultiplyPositive()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One Large BigInteger
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + "u*");
}
// Multiply Method - Two Large BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - Two Small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - One large and one small BigIntegers
for (int i = 0; i < s_samples; i++)
{
try
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
catch (IndexOutOfRangeException)
{
// TODO: Refactor this
Console.WriteLine("Array1: " + Print(tempByteArray1));
Console.WriteLine("Array2: " + Print(tempByteArray2));
throw;
}
}
}
[Fact]
public static void RunMultiplyPositiveWith0()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One large BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - One small BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
}
[Fact]
public static void RunMultiplyAxiomXmult1()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X*1 = X
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.One + " b*", Int32.MaxValue.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.One + " b*", Int64.MaxValue.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt + BigInteger.One + " b*", randBigInt + "u+");
}
}
[Fact]
public static void RunMultiplyAxiomXmult0()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X*0 = 0
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
}
}
[Fact]
public static void RunMultiplyAxiomComm()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*");
// 32 bit boundary n1=0 n2=1
VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*");
}
[Fact]
public static void RunMultiplyBoundary()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*");
// 32 bit boundary n1=0 n2=1
VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*");
}
[Fact]
public static void RunMultiplyTests()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Multiply Method - One Large BigInteger
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + "u*");
}
// Multiply Method - Two Large BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - Two Small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - One large and one small BigIntegers
for (int i = 0; i < s_samples; i++)
{
try
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
catch (IndexOutOfRangeException)
{
// TODO: Refactor this
Console.WriteLine("Array1: " + Print(tempByteArray1));
Console.WriteLine("Array2: " + Print(tempByteArray2));
throw;
}
}
// Multiply Method - One large BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(s_random);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Multiply Method - One small BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { 0 };
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
tempByteArray1 = new byte[] { 0 };
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*");
}
// Axiom: X*1 = X
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.One + " b*", Int32.MaxValue.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.One + " b*", Int64.MaxValue.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt + BigInteger.One + " b*", randBigInt + "u+");
}
// Axiom: X*0 = 0
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt + BigInteger.Zero + " b*", BigInteger.Zero.ToString());
}
// Axiom: a*b = b*a
VerifyIdentityString(Int32.MaxValue + " " + Int64.MaxValue + " b*", Int64.MaxValue + " " + Int32.MaxValue + " b*");
for (int i = 0; i < s_samples; i++)
{
String randBigInt1 = Print(GetRandomByteArray(s_random));
String randBigInt2 = Print(GetRandomByteArray(s_random));
VerifyIdentityString(randBigInt1 + randBigInt2 + "b*", randBigInt2 + randBigInt1 + "b*");
}
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*");
// 32 bit boundary n1=0 n2=1
VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*");
}
private static void VerifyMultiplyString(string opstring)
{
StackCalc sc = new StackCalc(opstring);
while (sc.DoNextOperation())
{
Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString());
}
}
private static void VerifyIdentityString(string opstring1, string opstring2)
{
StackCalc sc1 = new StackCalc(opstring1);
while (sc1.DoNextOperation())
{
//Run the full calculation
sc1.DoNextOperation();
}
StackCalc sc2 = new StackCalc(opstring2);
while (sc2.DoNextOperation())
{
//Run the full calculation
sc2.DoNextOperation();
}
Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString());
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 100));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
private static String Print(byte[] bytes)
{
return MyBigIntImp.Print(bytes);
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class InventoryDetail : IEquatable<InventoryDetail>
{
/// <summary>
/// Initializes a new instance of the <see cref="InventoryDetail" /> class.
/// Initializes a new instance of the <see cref="InventoryDetail" />class.
/// </summary>
/// <param name="WarehouseLocationId">WarehouseLocationId (required).</param>
/// <param name="CustomFields">CustomFields.</param>
/// <param name="Sku">Sku.</param>
public InventoryDetail(int? WarehouseLocationId = null, Dictionary<string, Object> CustomFields = null, string Sku = null)
{
// to ensure "WarehouseLocationId" is required (not null)
if (WarehouseLocationId == null)
{
throw new InvalidDataException("WarehouseLocationId is a required property for InventoryDetail and cannot be null");
}
else
{
this.WarehouseLocationId = WarehouseLocationId;
}
this.CustomFields = CustomFields;
this.Sku = Sku;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets WarehouseLocationId
/// </summary>
[DataMember(Name="warehouseLocationId", EmitDefaultValue=false)]
public int? WarehouseLocationId { get; set; }
/// <summary>
/// Gets or Sets Quantity
/// </summary>
[DataMember(Name="quantity", EmitDefaultValue=false)]
public int? Quantity { get; private set; }
/// <summary>
/// Gets or Sets DistributionDate
/// </summary>
[DataMember(Name="distributionDate", EmitDefaultValue=false)]
public DateTime? DistributionDate { get; private set; }
/// <summary>
/// Gets or Sets UnitsPerCase
/// </summary>
[DataMember(Name="unitsPerCase", EmitDefaultValue=false)]
public int? UnitsPerCase { get; private set; }
/// <summary>
/// Gets or Sets UnitsPerWrap
/// </summary>
[DataMember(Name="unitsPerWrap", EmitDefaultValue=false)]
public int? UnitsPerWrap { get; private set; }
/// <summary>
/// Gets or Sets RevisionDate
/// </summary>
[DataMember(Name="revisionDate", EmitDefaultValue=false)]
public string RevisionDate { get; private set; }
/// <summary>
/// Gets or Sets ProductionLot
/// </summary>
[DataMember(Name="productionLot", EmitDefaultValue=false)]
public string ProductionLot { get; private set; }
/// <summary>
/// Gets or Sets OldestReceiptDate
/// </summary>
[DataMember(Name="oldestReceiptDate", EmitDefaultValue=false)]
public DateTime? OldestReceiptDate { get; private set; }
/// <summary>
/// Gets or Sets LobId
/// </summary>
[DataMember(Name="lobId", EmitDefaultValue=false)]
public int? LobId { get; private set; }
/// <summary>
/// Gets or Sets PoNo
/// </summary>
[DataMember(Name="poNo", EmitDefaultValue=false)]
public string PoNo { get; private set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { get; set; }
/// <summary>
/// Gets or Sets Sku
/// </summary>
[DataMember(Name="sku", EmitDefaultValue=false)]
public string Sku { 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 InventoryDetail {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" WarehouseLocationId: ").Append(WarehouseLocationId).Append("\n");
sb.Append(" Quantity: ").Append(Quantity).Append("\n");
sb.Append(" DistributionDate: ").Append(DistributionDate).Append("\n");
sb.Append(" UnitsPerCase: ").Append(UnitsPerCase).Append("\n");
sb.Append(" UnitsPerWrap: ").Append(UnitsPerWrap).Append("\n");
sb.Append(" RevisionDate: ").Append(RevisionDate).Append("\n");
sb.Append(" ProductionLot: ").Append(ProductionLot).Append("\n");
sb.Append(" OldestReceiptDate: ").Append(OldestReceiptDate).Append("\n");
sb.Append(" LobId: ").Append(LobId).Append("\n");
sb.Append(" PoNo: ").Append(PoNo).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).Append("\n");
sb.Append(" Sku: ").Append(Sku).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 string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as InventoryDetail);
}
/// <summary>
/// Returns true if InventoryDetail instances are equal
/// </summary>
/// <param name="other">Instance of InventoryDetail to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(InventoryDetail other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.WarehouseLocationId == other.WarehouseLocationId ||
this.WarehouseLocationId != null &&
this.WarehouseLocationId.Equals(other.WarehouseLocationId)
) &&
(
this.Quantity == other.Quantity ||
this.Quantity != null &&
this.Quantity.Equals(other.Quantity)
) &&
(
this.DistributionDate == other.DistributionDate ||
this.DistributionDate != null &&
this.DistributionDate.Equals(other.DistributionDate)
) &&
(
this.UnitsPerCase == other.UnitsPerCase ||
this.UnitsPerCase != null &&
this.UnitsPerCase.Equals(other.UnitsPerCase)
) &&
(
this.UnitsPerWrap == other.UnitsPerWrap ||
this.UnitsPerWrap != null &&
this.UnitsPerWrap.Equals(other.UnitsPerWrap)
) &&
(
this.RevisionDate == other.RevisionDate ||
this.RevisionDate != null &&
this.RevisionDate.Equals(other.RevisionDate)
) &&
(
this.ProductionLot == other.ProductionLot ||
this.ProductionLot != null &&
this.ProductionLot.Equals(other.ProductionLot)
) &&
(
this.OldestReceiptDate == other.OldestReceiptDate ||
this.OldestReceiptDate != null &&
this.OldestReceiptDate.Equals(other.OldestReceiptDate)
) &&
(
this.LobId == other.LobId ||
this.LobId != null &&
this.LobId.Equals(other.LobId)
) &&
(
this.PoNo == other.PoNo ||
this.PoNo != null &&
this.PoNo.Equals(other.PoNo)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
) &&
(
this.Sku == other.Sku ||
this.Sku != null &&
this.Sku.Equals(other.Sku)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.WarehouseLocationId != null)
hash = hash * 59 + this.WarehouseLocationId.GetHashCode();
if (this.Quantity != null)
hash = hash * 59 + this.Quantity.GetHashCode();
if (this.DistributionDate != null)
hash = hash * 59 + this.DistributionDate.GetHashCode();
if (this.UnitsPerCase != null)
hash = hash * 59 + this.UnitsPerCase.GetHashCode();
if (this.UnitsPerWrap != null)
hash = hash * 59 + this.UnitsPerWrap.GetHashCode();
if (this.RevisionDate != null)
hash = hash * 59 + this.RevisionDate.GetHashCode();
if (this.ProductionLot != null)
hash = hash * 59 + this.ProductionLot.GetHashCode();
if (this.OldestReceiptDate != null)
hash = hash * 59 + this.OldestReceiptDate.GetHashCode();
if (this.LobId != null)
hash = hash * 59 + this.LobId.GetHashCode();
if (this.PoNo != null)
hash = hash * 59 + this.PoNo.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
if (this.Sku != null)
hash = hash * 59 + this.Sku.GetHashCode();
return hash;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.