context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//------------------------------------------------------------------------------
// <copyright file="MD5HashStream.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Class to make thread safe stream access and calculate MD5 hash.
/// </summary>
internal class MD5HashStream : IDisposable
{
/// <summary>
/// Stream object.
/// </summary>
private Stream stream;
/// <summary>
/// Semaphore object. In our case, we can only have one operation at the same time.
/// </summary>
private SemaphoreSlim semaphore;
/// <summary>
/// In restart mode, we start a separate thread to calculate MD5hash of transferred part.
/// This variable indicates whether finished to calculate this part of MD5hash.
/// </summary>
private volatile bool finishedSeparateMd5Calculator = false;
/// <summary>
/// Indicates whether succeeded in calculating MD5hash of the transferred bytes.
/// </summary>
private bool succeededSeparateMd5Calculator = false;
/// <summary>
/// Running md5 hash of the blob being downloaded.
/// </summary>
private MD5 md5hash;
/// <summary>
/// Offset of the transferred bytes. We should calculate MD5hash on all bytes before this offset.
/// </summary>
private long md5hashOffset;
/// <summary>
/// Initializes a new instance of the <see cref="MD5HashStream"/> class.
/// </summary>
/// <param name="stream">Stream object.</param>
/// <param name="lastTransferOffset">Offset of the transferred bytes.</param>
/// <param name="md5hashCheck">Whether need to calculate MD5Hash.</param>
public MD5HashStream(
Stream stream,
long lastTransferOffset,
bool md5hashCheck)
{
this.stream = stream;
this.md5hashOffset = lastTransferOffset;
if ((0 == this.md5hashOffset)
|| (!md5hashCheck))
{
this.finishedSeparateMd5Calculator = true;
this.succeededSeparateMd5Calculator = true;
}
else
{
this.semaphore = new SemaphoreSlim(1, 1);
}
if (md5hashCheck)
{
if (CloudStorageAccount.UseV1MD5)
{
this.md5hash = new MD5CryptoServiceProvider();
}
else
{
this.md5hash = new NativeMD5();
}
}
if ((!this.finishedSeparateMd5Calculator)
&& (!this.stream.CanRead))
{
throw new NotSupportedException(string.Format(
CultureInfo.CurrentCulture,
Resources.StreamMustSupportReadException,
"Stream"));
}
if (!this.stream.CanSeek)
{
throw new NotSupportedException(string.Format(
CultureInfo.CurrentCulture,
Resources.StreamMustSupportSeekException,
"Stream"));
}
}
/// <summary>
/// Gets a value indicating whether need to calculate MD5 hash.
/// </summary>
public bool CheckMd5Hash
{
get
{
return null != this.md5hash;
}
}
/// <summary>
/// Gets MD5 hash bytes.
/// </summary>
public byte[] Hash
{
get
{
return null == this.md5hash ? null : this.md5hash.Hash;
}
}
/// <summary>
/// Gets a value indicating whether already finished to calculate MD5 hash of transferred bytes.
/// </summary>
public bool FinishedSeparateMd5Calculator
{
get
{
return this.finishedSeparateMd5Calculator;
}
}
/// <summary>
/// Gets a value indicating whether already succeeded in calculating MD5 hash of transferred bytes.
/// </summary>
public bool SucceededSeparateMd5Calculator
{
get
{
this.WaitMD5CalculationToFinish();
return this.succeededSeparateMd5Calculator;
}
}
/// <summary>
/// Calculate MD5 hash of transferred bytes.
/// </summary>
/// <param name="memoryManager">Reference to MemoryManager object to require buffer from.</param>
/// <param name="checkCancellation">Action to check whether to cancel this calculation.</param>
public void CalculateMd5(MemoryManager memoryManager, Action checkCancellation)
{
if (null == this.md5hash)
{
return;
}
byte[] buffer = null;
try
{
buffer = Utils.RequireBuffer(memoryManager, checkCancellation);
}
catch (Exception)
{
lock (this.md5hash)
{
this.finishedSeparateMd5Calculator = true;
}
throw;
}
long offset = 0;
int readLength = 0;
while (true)
{
lock (this.md5hash)
{
if (offset >= this.md5hashOffset)
{
Debug.Assert(
offset == this.md5hashOffset,
"We should stop the separate calculator thread just at the transferred offset");
this.succeededSeparateMd5Calculator = true;
this.finishedSeparateMd5Calculator = true;
break;
}
readLength = (int)Math.Min(this.md5hashOffset - offset, buffer.Length);
}
try
{
checkCancellation();
readLength = this.Read(offset, buffer, 0, readLength);
lock (this.md5hash)
{
this.md5hash.TransformBlock(buffer, 0, readLength, null, 0);
}
}
catch (Exception)
{
lock (this.md5hash)
{
this.finishedSeparateMd5Calculator = true;
}
memoryManager.ReleaseBuffer(buffer);
throw;
}
offset += readLength;
}
memoryManager.ReleaseBuffer(buffer);
}
/// <summary>
/// Begin async read from stream.
/// </summary>
/// <param name="readOffset">Offset in stream to read from.</param>
/// <param name="buffer">The buffer to read the data into.</param>
/// <param name="offset">The byte offset in buffer at which to begin writing data read from the stream.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <param name="cancellationToken">Token used to cancel the asynchronous reading.</param>
/// <returns>A task that represents the asynchronous read operation. The value of the
/// <c>TResult</c> parameter contains the total number of bytes read into the buffer.</returns>
public async Task<int> ReadAsync(long readOffset, byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await this.WaitOnSemaphoreAsync(cancellationToken);
try
{
this.stream.Position = readOffset;
return await this.stream.ReadAsync(
buffer,
offset,
count,
cancellationToken);
}
finally
{
this.ReleaseSemaphore();
}
}
/// <summary>
/// Begin async write to stream.
/// </summary>
/// <param name="writeOffset">Offset in stream to write to.</param>
/// <param name="buffer">The buffer to write the data from.</param>
/// <param name="offset">The byte offset in buffer from which to begin writing.</param>
/// <param name="count">The maximum number of bytes to write.</param>
/// <param name="cancellationToken">Token used to cancel the asynchronous writing.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public async Task WriteAsync(long writeOffset, byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await this.WaitOnSemaphoreAsync(cancellationToken);
try
{
this.stream.Position = writeOffset;
await this.stream.WriteAsync(
buffer,
offset,
count,
cancellationToken);
}
finally
{
this.ReleaseSemaphore();
}
}
/// <summary>
/// Computes the hash value for the specified region of the input byte array
/// and copies the specified region of the input byte array to the specified
/// region of the output byte array.
/// </summary>
/// <param name="streamOffset">Offset in stream of the block on which to calculate MD5 hash.</param>
/// <param name="inputBuffer">The input to compute the hash code for.</param>
/// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the input byte array to use as data.</param>
/// <param name="outputBuffer">A copy of the part of the input array used to compute the hash code.</param>
/// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param>
/// <returns>Whether succeeded in calculating MD5 hash
/// or not finished the separate thread to calculate MD5 hash at the time. </returns>
public bool MD5HashTransformBlock(long streamOffset, byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if (null == this.md5hash)
{
return true;
}
if (!this.finishedSeparateMd5Calculator)
{
lock (this.md5hash)
{
if (!this.finishedSeparateMd5Calculator)
{
if (streamOffset == this.md5hashOffset)
{
this.md5hashOffset += inputCount;
}
return true;
}
else
{
if (!this.succeededSeparateMd5Calculator)
{
return false;
}
}
}
}
if (streamOffset >= this.md5hashOffset)
{
Debug.Assert(
this.finishedSeparateMd5Calculator,
"The separate thread to calculate MD5 hash should have finished or md5hashOffset should get updated.");
this.md5hash.TransformBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
}
return true;
}
/// <summary>
/// Computes the hash value for the specified region of the specified byte array.
/// </summary>
/// <param name="inputBuffer">The input to compute the hash code for.</param>
/// <param name="inputOffset">The offset into the byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the byte array to use as data.</param>
/// <returns>An array that is a copy of the part of the input that is hashed.</returns>
public byte[] MD5HashTransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
this.WaitMD5CalculationToFinish();
if (!this.succeededSeparateMd5Calculator)
{
return null;
}
return null == this.md5hash ? null : this.md5hash.TransformFinalBlock(inputBuffer, inputOffset, inputCount);
}
/// <summary>
/// Releases or resets unmanaged resources.
/// </summary>
public virtual void Dispose()
{
this.Dispose(true);
}
/// <summary>
/// Private dispose method to release managed/unmanaged objects.
/// If disposing = true clean up managed resources as well as unmanaged resources.
/// If disposing = false only clean up unmanaged resources.
/// </summary>
/// <param name="disposing">Indicates whether or not to dispose managed resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (null != this.md5hash)
{
this.md5hash.Clear();
this.md5hash = null;
}
if (null != this.semaphore)
{
this.semaphore.Dispose();
this.semaphore = null;
}
}
}
/// <summary>
/// Read from stream.
/// </summary>
/// <param name="readOffset">Offset in stream to read from.</param>
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>The total number of bytes read into the buffer.</returns>
private int Read(long readOffset, byte[] buffer, int offset, int count)
{
if (!this.finishedSeparateMd5Calculator)
{
this.semaphore.Wait();
}
try
{
this.stream.Position = readOffset;
int readBytes = this.stream.Read(buffer, offset, count);
return readBytes;
}
finally
{
this.ReleaseSemaphore();
}
}
/// <summary>
/// Wait for one semaphore.
/// </summary>
/// <param name="cancellationToken">Token used to cancel waiting on the semaphore.</param>
private async Task WaitOnSemaphoreAsync(CancellationToken cancellationToken)
{
if (!this.finishedSeparateMd5Calculator)
{
await this.semaphore.WaitAsync(cancellationToken);
}
}
/// <summary>
/// Release semaphore.
/// </summary>
private void ReleaseSemaphore()
{
if (!this.finishedSeparateMd5Calculator)
{
this.semaphore.Release();
}
}
/// <summary>
/// Wait for MD5 calculation to be finished.
/// In our test, MD5 calculation is really fast,
/// and SpinOnce has sleep mechanism, so use Spin instead of sleep here.
/// </summary>
private void WaitMD5CalculationToFinish()
{
if (this.finishedSeparateMd5Calculator)
{
return;
}
SpinWait sw = new SpinWait();
while (!this.finishedSeparateMd5Calculator)
{
sw.SpinOnce();
}
sw.Reset();
}
}
}
| |
using System;
namespace Imms.Implementation {
static partial class FingerTree<TValue> {
internal abstract partial class FTree<TChild>
where TChild : Measured<TChild>, new() {
private sealed class Compound : FTree<TChild> {
const int
IN_END = 6;
const int
IN_MIDDLE_OF_DEEP = 3;
const int
IN_MIDDLE_OF_LEFT = 1;
const int
IN_MIDDLE_OF_RIGHT = 5;
const int
IN_START = 0;
const int
IN_START_OF_DEEP = 2;
const int
IN_START_OF_RIGHT = 4;
const int
OUTSIDE = 7;
public FTree<Digit> DeepTree;
public Digit LeftDigit;
public Digit RightDigit;
public Compound(Digit leftDigit, FTree<Digit> deepTree, Digit rightDigit, Lineage lineage)
: base(leftDigit.Measure + deepTree.Measure + rightDigit.Measure, TreeType.Compound, lineage, 3) {
leftDigit.AssertNotNull();
deepTree.AssertNotNull();
rightDigit.AssertNotNull();
_mutate(leftDigit, deepTree, rightDigit);
}
public override Leaf<TValue> this[int index] {
get {
index.AssertEqual(i => i < Measure);
var m1 = LeftDigit.Measure;
var m2 = DeepTree.Measure + m1;
if (index < m1) return LeftDigit[index];
if (index < m2) return DeepTree[index - m1];
if (index < Measure) return RightDigit[index - m2];
throw ImplErrors.Arg_out_of_range("index", index);
}
}
public override bool IsFragment {
get { return false; }
}
public override TChild Left {
get { return LeftDigit.Left; }
}
public override TChild Right {
get { return RightDigit.Right; }
}
public override string Print() {
return string.Format("[[{0} | {1} | {2}]]", LeftDigit.Print(), DeepTree.Print(), RightDigit.Print());
}
FTree<TChild> CreateCheckNull(Lineage lineage, Digit left = null, FTree<Digit> deep = null, Digit right = null) {
var memberPermutation = left != null ? 1 << 0 : 0;
memberPermutation |= (deep != null && deep.Measure != 0) ? 1 << 1 : 0;
memberPermutation |= right != null ? 1 << 2 : 0;
switch (memberPermutation) {
case 0 << 0| 0 << 1 | 0 << 2:
return Empty;
case 1 << 0 | 0 << 1 | 0 << 2:
return new Single(left, lineage);
case 1 << 0 | 1 << 1 | 0 << 2:
var r2 = deep.Right;
var deep1 = deep.RemoveLast(lineage);
return MutateOrCreate(left, deep1, r2, lineage);
case 1 << 0 | 1 << 1 | 1 << 2:
return MutateOrCreate(left, deep, right, lineage);
case 0 << 0 | 1 << 1 | 1 << 2:
return MutateOrCreate(deep.Left, deep.RemoveFirst(lineage), right, lineage);
case 1 << 0 | 0 << 1 | 1 << 2:
return MutateOrCreate(left, deep, right, lineage);
case 0 << 0 | 1 << 1 | 0 << 2:
left = deep.Left;
deep = deep.RemoveFirst(lineage);
if (deep.Measure != 0) {
right = deep.Right;
deep = deep.RemoveLast(lineage);
return MutateOrCreate(left, deep, right, lineage);
}
return new Single(left, lineage);
case 0 << 0 | 0 << 1 | 1 << 2:
return new Single(right, lineage);
default:
throw ImplErrors.Invalid_execution_path("Explicitly checked all possible tree permutations.");
}
}
/// <summary>
/// This method will re-initialize this instance using the specified parameters.
/// </summary>
private FTree<TChild> _mutate(Digit left, FTree<Digit> deep, Digit right) {
LeftDigit = left;
DeepTree = deep;
RightDigit = right;
Measure = left.Measure + deep.Measure + right.Measure;
return this;
}
/// <summary>
/// <para>
/// This method can mutate the current instance and return it, or return a new instance, based on the supplied
/// Lineage.
/// </para>
/// <para>If the current Lineage allows mutation from the specified Lineage, the instance will be MUTATED and returned.</para>
/// <para>Otherwise, the method will return a NEW instance that is a member of the supplied Lineage. </para>
/// </summary>
private FTree<TChild> MutateOrCreate(Digit left, FTree<Digit> deep, Digit right, Lineage lineage) {
if (_lineage.AllowMutation(lineage)) {
return _mutate(left, deep, right);
} else return new Compound(left, deep, right, lineage);
}
public override FTree<TChild> AddFirst(TChild item, Lineage lineage) {
FTree<TChild> ret;
#if ASSERTS
var expectedSize = Measure + item.Measure;
#endif
if (LeftDigit.Size < 4) ret = MutateOrCreate(LeftDigit.AddFirst(item, lineage), DeepTree, RightDigit, lineage);
else {
var leftmost = new Digit(item, LeftDigit.First, lineage);
var rightmost = LeftDigit.RemoveFirst(lineage);
var newDeep = DeepTree.AddFirst(rightmost, lineage);
ret = MutateOrCreate(leftmost, newDeep, RightDigit, lineage);
}
#if ASSERTS
ret.Measure.AssertEqual(expectedSize);
ret.Left.AssertEqual(item);
#endif
return ret;
}
public override FTree<TChild> AddLast(TChild item, Lineage lineage) {
#if ASSERTS
var expectedSize = Measure + item.Measure;
#endif
FTree<TChild> ret;
if (RightDigit.Size < 4) ret = MutateOrCreate(LeftDigit, DeepTree, RightDigit.AddLast(item, lineage), lineage);
else {
var rightmost = new Digit(RightDigit.Fourth, item, lineage);
var leftmost = RightDigit.RemoveLast(lineage);
var newDeep = DeepTree.AddLast(leftmost, lineage);
ret = MutateOrCreate(LeftDigit, newDeep, rightmost, lineage);
}
#if ASSERTS
ret.Measure.AssertEqual(expectedSize);
ret.Right.AssertEqual(item);
#endif
return ret;
}
public override FTree<TChild> RemoveFirst(Lineage lineage) {
FTree<TChild> ret;
#if ASSERTS
var expected = Measure - Left.Measure;
#endif
if (LeftDigit.Size > 1) {
var newLeft = LeftDigit.RemoveFirst(lineage);
ret = MutateOrCreate(newLeft, DeepTree, RightDigit, lineage);
} else if (DeepTree.Measure > 0) {
var newLeft = DeepTree.Left;
var newDeep = DeepTree.RemoveFirst(lineage);
ret = MutateOrCreate(newLeft, newDeep, RightDigit, lineage);
} else ret = new Single(RightDigit, lineage);
#if ASSERTS
ret.Measure.AssertEqual(expected);
#endif
return ret;
}
public override FTree<TChild> RemoveLast(Lineage lineage) {
FTree<TChild> ret;
#if ASSERTS
var expectedSize = Measure - Right.Measure;
#endif
if (RightDigit.Size > 1) {
var newRight = RightDigit.RemoveLast(lineage);
ret = MutateOrCreate(LeftDigit, DeepTree, newRight, lineage);
} else if (DeepTree.Measure > 0) {
var newRight = DeepTree.Right;
var newDeep = DeepTree.RemoveLast(lineage);
ret = MutateOrCreate(LeftDigit, newDeep, newRight, lineage);
} else ret = new Single(LeftDigit, lineage);
#if ASSERTS
ret.Measure.AssertEqual(expectedSize);
#endif
return ret;
}
public override void Split(int index, out FTree<TChild> left, out TChild child, out FTree<TChild> right, Lineage lineage) {
#if ASSERTS
var oldMeasure = Measure;
var oldValue = this[index];
#endif
switch (WhereIsThisIndex(index)) {
case IN_START:
case IN_MIDDLE_OF_LEFT:
Digit lLeft, lRight;
LeftDigit.Split(index, out lLeft, out child, out lRight, lineage);
index -= lLeft == null ? 0 : lLeft.Measure;
left = CreateCheckNull(Lineage.Immutable, lLeft);
right = CreateCheckNull(lineage, lRight, DeepTree, RightDigit);
break;
case IN_START_OF_DEEP:
case IN_MIDDLE_OF_DEEP:
index -= LeftDigit.Measure;
FTree<Digit> mLeft, mRight;
Digit mCenter;
DeepTree.Split(index, out mLeft, out mCenter, out mRight, lineage);
Digit mcLeft, mcRight;
index -= mLeft.Measure;
mCenter.Split(index, out mcLeft, out child, out mcRight, lineage);
index -= mcLeft == null ? 0 : mcLeft.Measure;
left = CreateCheckNull(Lineage.Immutable, LeftDigit, mLeft, mcLeft);
right = CreateCheckNull(lineage, mcRight, mRight, RightDigit);
break;
case IN_MIDDLE_OF_RIGHT:
case IN_START_OF_RIGHT:
Digit rLeft, rRight;
index -= LeftDigit.Measure + DeepTree.Measure;
RightDigit.Split(index, out rLeft, out child, out rRight, lineage);
index -= rLeft == null ? 0 : rLeft.Measure;
right = CreateCheckNull(Lineage.Immutable, rRight);
left = CreateCheckNull(lineage, LeftDigit, DeepTree, rLeft);
break;
case IN_END:
case OUTSIDE:
throw ImplErrors.Arg_out_of_range("index", index);
default:
throw ImplErrors.Invalid_execution_path("Index didn't match any of the cases.");
}
#if ASSERTS
oldMeasure.AssertEqual(left.Measure + child.Measure + right.Measure);
oldValue.AssertEqual(child[index]);
#endif
}
FTree<TChild> FixLeftDigit(Lineage lineage) {
if (!LeftDigit.IsFragment) return this;
if (DeepTree.Measure == 0) {
Digit first, last;
LeftDigit.Fuse(RightDigit, out first, out last, lineage);
return CreateCheckNull(lineage, first, DeepTree, last);
} else {
var fromDeep = DeepTree.Left;
var newDeep = DeepTree.RemoveFirst(lineage);
Digit first, last;
LeftDigit.Fuse(fromDeep, out first, out last, lineage);
if (last == null) return MutateOrCreate(first, newDeep, RightDigit, lineage);
return MutateOrCreate(first, newDeep.AddFirst(last, lineage), RightDigit, lineage);
}
}
FTree<TChild> FixRightDigit(Lineage lineage) {
if (!RightDigit.IsFragment) return this;
FTree<TChild> ret;
if (DeepTree.Measure == 0) {
Digit first, last;
LeftDigit.Fuse(RightDigit, out first, out last, lineage);
ret = CreateCheckNull(lineage, first, DeepTree, last);
return ret;
} else {
var fromDeep = DeepTree.Right;
var newDeep = DeepTree.RemoveLast(lineage);
Digit first, last;
fromDeep.Fuse(RightDigit, out first, out last, lineage);
if (last == null) ret = MutateOrCreate(LeftDigit, newDeep, first, lineage);
else ret = MutateOrCreate(LeftDigit, newDeep.AddLast(first, lineage), last, lineage);
}
#if ASSERTS
ret.Measure.AssertEqual(Measure);
#endif
return ret;
}
public override FTree<TChild> Insert(int index, Leaf<TValue> leaf, Lineage lineage) {
var whereIsThisIndex = WhereIsThisIndex(index);
#if ASSERTS
var newMeasure = Measure + 1;
var oldValue = this[index].Value;
#endif
FTree<Digit> newDeep;
FTree<TChild> res = null;
switch (whereIsThisIndex) {
case IN_START:
case IN_MIDDLE_OF_LEFT:
Digit leftL, leftR;
LeftDigit.Insert(index, leaf, out leftL, out leftR, lineage);
newDeep = leftR != null ? DeepTree.AddFirst(leftR, lineage) : DeepTree;
res = MutateOrCreate(leftL, newDeep, RightDigit, lineage);
break;
case IN_START_OF_DEEP:
case IN_MIDDLE_OF_DEEP:
if (DeepTree.Measure == 0) goto case IN_START_OF_RIGHT;
newDeep = DeepTree.Insert(index - LeftDigit.Measure, leaf, lineage);
res = MutateOrCreate(LeftDigit, newDeep, RightDigit, lineage);
break;
case IN_START_OF_RIGHT:
case IN_MIDDLE_OF_RIGHT:
Digit rightR;
Digit rightL;
RightDigit.Insert(index - LeftDigit.Measure - DeepTree.Measure, leaf, out rightL, out rightR, lineage);
newDeep = rightR != null ? DeepTree.AddLast(rightL, lineage) : DeepTree;
rightR = rightR ?? rightL;
res = MutateOrCreate(LeftDigit, newDeep, rightR, lineage);
break;
}
#if ASSERTS
res.Measure.AssertEqual(newMeasure);
res[index].Value.AssertEqual(leaf.Value);
res[index + 1].Value.AssertEqual(oldValue);
#endif
return res;
}
public override void Iter(Action<Leaf<TValue>> action) {
#if ASSERTS
action.AssertNotNull();
#endif
LeftDigit.Iter(action);
DeepTree.Iter(action);
RightDigit.Iter(action);
}
public override void IterBack(Action<Leaf<TValue>> action) {
#if ASSERTS
action.AssertNotNull();
#endif
RightDigit.IterBack(action);
DeepTree.IterBack(action);
LeftDigit.IterBack(action);
}
public override bool IterBackWhile(Func<Leaf<TValue>, bool> action) {
if (!RightDigit.IterBackWhile(action)) return false;
if (!DeepTree.IterBackWhile(action)) return false;
if (!LeftDigit.IterBackWhile(action)) return false;
return true;
}
public override bool IterWhile(Func<Leaf<TValue>, bool> action) {
if (!LeftDigit.IterWhile(action)) return false;
if (!DeepTree.IterWhile(action)) return false;
if (!RightDigit.IterWhile(action)) return false;
return true;
}
public override FTree<TChild> RemoveAt(int index, Lineage lineage) {
var whereIsThisIndex = WhereIsThisIndex(index);
Digit newLeft;
FTree<TChild> ret = this;
#if ASSERTS
var newMeasure = Measure - 1;
var expectedAtIndex = index != Measure - 1 ? this[index + 1] : null;
var expectedBeforeIndex = index != 0 ? this[index - 1] : null;
#endif
switch (whereIsThisIndex) {
case IN_START:
case IN_MIDDLE_OF_LEFT:
if (LeftDigit.IsFragment) {
var fixedTree = FixLeftDigit(lineage);
ret = fixedTree.RemoveAt(index, lineage);
} else {
newLeft = LeftDigit.Remove(index, lineage);
ret = CreateCheckNull(lineage, newLeft, DeepTree, RightDigit);
}
break;
case IN_START_OF_DEEP:
case IN_MIDDLE_OF_DEEP:
if (DeepTree.Measure == 0) goto case IN_START_OF_RIGHT;
var deep = DeepTree;
FTree<Digit> newDeep;
if (deep.IsFragment) {
newDeep = deep.AddFirst(LeftDigit, lineage);
newDeep = newDeep.RemoveAt(index, lineage);
newLeft = newDeep.Left;
newDeep = newDeep.RemoveFirst(lineage);
ret = MutateOrCreate(newLeft, newDeep, RightDigit, lineage);
} else {
newDeep = DeepTree.RemoveAt(index - LeftDigit.Measure, lineage);
ret = CreateCheckNull(lineage, LeftDigit, newDeep, RightDigit);
}
break;
case IN_START_OF_RIGHT:
case IN_MIDDLE_OF_RIGHT:
if (RightDigit.IsFragment) {
var fixedTree = FixRightDigit(lineage);
ret = fixedTree.RemoveAt(index, lineage);
} else {
var newRight = RightDigit.Remove(index - LeftDigit.Measure - DeepTree.Measure, lineage);
ret = CreateCheckNull(lineage, LeftDigit, DeepTree, newRight);
}
break;
case IN_END:
case OUTSIDE:
throw ImplErrors.Arg_out_of_range("index", index);
default:
throw ImplErrors.Invalid_execution_path("Checked all possible index locations already.");
}
#if ASSERTS
ret.Measure.AssertEqual(newMeasure);
if (expectedAtIndex != null) ret[index].Value.AssertEqual(expectedAtIndex.Value);
if (expectedBeforeIndex != null) ret[index-1].Value.AssertEqual(expectedBeforeIndex.Value);
#endif
return ret;
}
public override FTree<TChild> Reverse(Lineage lineage) {
return MutateOrCreate(RightDigit.Reverse(lineage), DeepTree.Reverse(lineage), LeftDigit.Reverse(lineage), lineage);
}
public override FTree<TChild> Update(int index, Leaf<TValue> leaf, Lineage lineage) {
var whereIsThisIndex = WhereIsThisIndex(index);
FTree<TChild> ret;
#if ASSERTS
var oldSize = Measure;
#endif
switch (whereIsThisIndex) {
case IN_START:
case IN_MIDDLE_OF_LEFT:
var newLeft = LeftDigit.Update(index, leaf, lineage);
ret = MutateOrCreate(newLeft, DeepTree, RightDigit, lineage);
break;
case IN_START_OF_DEEP:
case IN_MIDDLE_OF_DEEP:
if (DeepTree.Measure == 0) goto case IN_START_OF_RIGHT;
var newDeep = DeepTree.Update(index - LeftDigit.Measure, leaf, lineage);
ret = MutateOrCreate(LeftDigit, newDeep, RightDigit, lineage);
break;
case IN_START_OF_RIGHT:
case IN_MIDDLE_OF_RIGHT:
var newRight = RightDigit.Update(index - LeftDigit.Measure - DeepTree.Measure, leaf, lineage);
ret = MutateOrCreate(LeftDigit, DeepTree, newRight, lineage);
break;
default:
throw ImplErrors.Arg_out_of_range("index", index);
}
#if ASSERTS
ret.Measure.AssertEqual(oldSize);
ret[index].AssertEqual(leaf);
#endif
return ret;
}
/// <summary>
/// Returns 0 if index is 0 (meaning, empty).
/// Returns 1 if index is in left digit
/// Returns 2 if index encompasses the left digit.
/// Returns 3 if he index is in the deep tree.
/// Returns 4 if the index encompasses the left digit + deep tree
/// Returns 5 if the index is in the right digit.
/// Returns 6 if the index encompasses the entire tree.
/// Returns 7 if the index is outside the tree.
/// </summary>
/// <param name="index"> </param>
/// <returns> </returns>
int WhereIsThisIndex(int index) {
if (index == 0) return IN_START;
if (index < LeftDigit.Measure) return IN_MIDDLE_OF_LEFT;
if (index == LeftDigit.Measure) return DeepTree.Measure == 0 ? IN_START_OF_RIGHT : IN_START_OF_DEEP;
if (index < LeftDigit.Measure + DeepTree.Measure) return IN_MIDDLE_OF_DEEP;
if (index == LeftDigit.Measure + DeepTree.Measure) return IN_START_OF_RIGHT;
if (index < Measure) return IN_MIDDLE_OF_RIGHT;
if (index == Measure) return IN_END;
return OUTSIDE;
}
public override FingerTreeElement GetChild(int index) {
switch (index) {
case 0:
return LeftDigit;
case 1:
return DeepTree;
case 2:
return RightDigit;
default:
throw ImplErrors.Arg_out_of_range("index", index);
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml;
using NUnit.Framework;
using SIL.DictionaryServices.Lift;
using SIL.DictionaryServices.Model;
using SIL.Lift;
using SIL.Lift.Options;
using SIL.Lift.Validation;
using SIL.TestUtilities;
namespace SIL.DictionaryServices.Tests.Lift
{
[TestFixture]
public class LiftWriterTests
{
class LiftExportTestSessionBase : IDisposable
{
protected LiftWriter _liftWriter;
private readonly StringBuilder _stringBuilder;
protected readonly string _filePath;
protected LiftExportTestSessionBase()
{
_filePath = Path.GetTempFileName();
_stringBuilder = new StringBuilder();
}
public void Dispose()
{
if (_liftWriter != null)
{
LiftWriter.Dispose();
}
File.Delete(_filePath);
}
public string FilePath
{
get { return _filePath; }
}
public StringBuilder StringBuilder
{
get { return _stringBuilder; }
}
public LiftWriter LiftWriter
{
get { return _liftWriter; }
}
public LexEntry CreateItem()
{
return new LexEntry();
}
public string OutputString()
{
LiftWriter.End();
return StringBuilder.ToString();
}
private void AddTestLexEntry(string lexicalForm)
{
LexEntry entry = CreateItem();
entry.LexicalForm["test"] = lexicalForm;
LiftWriter.Add(entry);
}
public void AddTwoTestLexEntries()
{
AddTestLexEntry("sunset");
AddTestLexEntry("flower");
LiftWriter.End();
}
}
class LiftExportAsFragmentTestSession : LiftExportTestSessionBase
{
public LiftExportAsFragmentTestSession()
{
_liftWriter = new LiftWriter(StringBuilder, true);
}
}
class LiftExportAsFullDocumentTestSession : LiftExportTestSessionBase
{
public LiftExportAsFullDocumentTestSession()
{
_liftWriter = new LiftWriter(StringBuilder, false);
}
}
class LiftExportAsFileTestSession : LiftExportTestSessionBase
{
public LiftExportAsFileTestSession()
{
_liftWriter = new LiftWriter(_filePath, LiftWriter.ByteOrderStyle.BOM);
}
}
[SetUp]
public void Setup()
{
}
[TearDown]
public void TearDown()
{
GC.Collect();
}
private static void AssertHasOneMatch(string xpath, LiftExportTestSessionBase session)
{
AssertThatXmlIn.String(session.StringBuilder.ToString()).
HasSpecifiedNumberOfMatchesForXpath(xpath,1);
}
private static void AssertHasAtLeastOneMatch(string xpath, LiftExportTestSessionBase session)
{
AssertThatXmlIn.String(session.StringBuilder.ToString()).HasAtLeastOneMatchForXpath(xpath);
}
[Obsolete("Use AssertThatXmlInXPath.String(...)")] // CP 2011-01
private static string GetSenseElement(LexSense sense)
{
return string.Format("<sense id=\"{0}\">", sense.GetOrCreateId());
}
private static string GetStringAttributeOfTopElement(string attribute, LiftExportTestSessionBase session)
{
var doc = new XmlDocument();
doc.LoadXml(session.StringBuilder.ToString());
return doc.FirstChild.Attributes[attribute].ToString();
}
[Obsolete("Use AssertEqualsCanonicalString(string, string) instead")]
private static void AssertEqualsCanonicalString(string expected, LiftExportTestSessionBase session)
{
string canonicalAnswer = CanonicalXml.ToCanonicalStringFragment(expected);
Assert.AreEqual(canonicalAnswer, session.StringBuilder.ToString());
}
private static void AssertEqualsCanonicalString(string expected, string actual)
{
string canonicalAnswer = CanonicalXml.ToCanonicalStringFragment(expected);
Assert.AreEqual(canonicalAnswer, actual);
}
[Test]
public void AddUsingWholeList_TwoEntries_HasTwoEntries()
{
using (var session = new LiftExportAsFullDocumentTestSession())
{
session.AddTwoTestLexEntries();
var doc = new XmlDocument();
doc.LoadXml(session.StringBuilder.ToString());
Assert.AreEqual(2, doc.SelectNodes("lift/entry").Count);
}
}
[Test]
public void AttributesWithProblematicCharacters()
{
const string expected = "lang=\"x"y\">";
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
sense.Gloss["x\"y"] = "test";
session.LiftWriter.Add(sense);
session.LiftWriter.End();
string result = session.OutputString();
Assert.IsTrue(result.Contains(expected));
}
}
[Test]
public void BlankExample()
{
using (var session = new LiftExportAsFragmentTestSession())
{
session.LiftWriter.Add(new LexExampleSentence());
AssertEqualsCanonicalString("<example />", session.OutputString());
}
}
[Test]
public void BlankGrammi()
{
var sense = new LexSense();
var o = sense.GetOrCreateProperty<OptionRef>(
LexSense.WellKnownProperties.PartOfSpeech
);
o.Value = string.Empty;
using (var session = new LiftExportAsFragmentTestSession())
{
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("sense[not(grammatical-info)]", session);
AssertHasAtLeastOneMatch("sense[not(trait)]", session);
}
}
[Test]
public void BlankMultiText()
{
using (var session = new LiftExportAsFragmentTestSession())
{
session.LiftWriter.AddMultitextForms(null, new MultiText());
AssertEqualsCanonicalString("", session);
}
}
[Test]
public void BlankSense()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
session.LiftWriter.Add(sense);
AssertEqualsCanonicalString(
String.Format("<sense id=\"{0}\" />", sense.GetOrCreateId()),
session.OutputString()
);
}
}
[Test]
public void Citation()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
var citation = entry.GetOrCreateProperty<MultiText>(
LexEntry.WellKnownProperties.Citation
);
citation["zz"] = "orange";
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("entry/citation/form[@lang='zz']/text[text()='orange']", session);
AssertHasAtLeastOneMatch("entry/citation/form[@lang='zz'][not(trait)]", session);
AssertHasAtLeastOneMatch("entry[not(field)]", session);
}
}
[Test]
public void CitationWithStarredForm()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var e = session.CreateItem();
var citation = e.GetOrCreateProperty<MultiText>(
LexEntry.WellKnownProperties.Citation
);
citation.SetAlternative("x", "orange");
citation.SetAnnotationOfAlternativeIsStarred("x", true);
// _lexEntryRepository.SaveItem(e);
session.LiftWriter.Add(e);
session.LiftWriter.End();
AssertHasAtLeastOneMatch(
"entry/citation/form[@lang='x']/annotation[@name='flag' and @value='1']",
session
);
}
}
[Test]
public void EntryWith2SimpleVariants()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var e = session.CreateItem();
var variant = new LexVariant();
variant.SetAlternative("etr","one");
e.Variants.Add(variant);
variant = new LexVariant();
variant.SetAlternative("etr", "two");
e.Variants.Add(variant);
session.LiftWriter.Add(e);
session.LiftWriter.End();
AssertHasOneMatch("entry/variant/form[@lang='etr' and text='one']", session);
AssertHasOneMatch("entry/variant/form[@lang='etr' and text='two']", session);
}
}
[Test]
public void EntryWithSimpleEtymology()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var e = session.CreateItem();
var etymology = new LexEtymology("theType", "theSource");
etymology.SetAlternative("etr", "one");
e.Etymologies.Add(etymology);
session.LiftWriter.Add(e);
session.LiftWriter.End();
AssertHasOneMatch("entry/etymology/form[@lang='etr' and text='one']", session);
AssertHasOneMatch("entry/etymology[@type='theType' and @source='theSource']", session);
}
}
[Test]
public void EntryWithFullEtymology()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var e = session.CreateItem();
var etymology = new LexEtymology("theType", "theSource");
etymology.SetAlternative("etr", "theProtoform");
etymology.Gloss.SetAlternative("en", "engloss");
etymology.Gloss.SetAlternative("fr", "frgloss");
etymology.Comment.SetAlternative("en", "metathesis?");
e.Etymologies.Add(etymology);
session.LiftWriter.Add(e);
session.LiftWriter.End();
AssertHasOneMatch("entry/etymology/form[@lang='etr' and text='theProtoform']", session);
AssertHasOneMatch("entry/etymology[@type='theType' and @source='theSource']", session);
//handling of comments may change, the issue has been raised on the LIFT google group
AssertHasOneMatch("entry/etymology/field[@type='comment']/form[@lang='en' and text='metathesis?']", session);
}
}
[Test]
public void EntryWithBorrowedWord()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var e = session.CreateItem();
//notice, no form given
e.Etymologies.Add(new LexEtymology("theType", "theSource"));
session.LiftWriter.Add(e);
session.LiftWriter.End();
AssertHasOneMatch("entry/etymology[@type='theType' and @source='theSource']", session);
}
}
[Test]
public void EntryWithSimplePronunciation()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var e = session.CreateItem();
var phonetic = new LexPhonetic();
phonetic.SetAlternative("ipa", "one");
e.Pronunciations.Add(phonetic);
session.LiftWriter.Add(e);
session.LiftWriter.End();
AssertHasOneMatch("entry/pronunciation/form[@lang='ipa' and text='one']", session);
}
}
[Test]
public void SenseWith2Notes()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
var note = new LexNote("grammar");
note.SetAlternative("etr", "one");
sense.Notes.Add(note);
var note2 = new LexNote("comment");
note2.SetAlternative("etr", "blah");
sense.Notes.Add(note2);
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasOneMatch("sense/note/form[@lang='etr' and text='one']", session);
AssertHasOneMatch("sense/note[@type='grammar']", session);
AssertHasOneMatch("sense/note[@type='comment']", session);
}
}
[Test]
public void SenseWith2Reversals()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
var reversal = new LexReversal {Type = "revType"};
reversal.SetAlternative("en", "one");
sense.Reversals.Add(reversal);
var reversal2 = new LexReversal();
reversal2.SetAlternative("en", "two");
sense.Reversals.Add(reversal2);
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasOneMatch("sense/reversal/form[@lang='en' and text='one']", session);
AssertHasOneMatch("sense/reversal/form[@lang='en' and text='two']", session);
AssertHasOneMatch("sense/reversal[@type='revType']", session);
AssertHasOneMatch("sense/reversal/@type", session); //only one had a type
}
}
[Test]
public void EntryWithTypedNote()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
var note = new LexNote("comic");
note.SetAlternative("etr", "one");
sense.Notes.Add(note);
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasOneMatch("sense/note/form[@lang='etr' and text='one']", session);
AssertHasOneMatch("sense/note[@type='comic']", session);
}
}
[Test]
public void VariantWith2Traits()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var variant = new LexVariant();
variant.SetAlternative("etr", "one");
variant.Traits.Add(new LexTrait("a", "A"));
variant.Traits.Add(new LexTrait("b", "B"));
session.LiftWriter.AddVariant(variant);
session.LiftWriter.End();
AssertHasOneMatch("variant/trait[@name='a' and @value='A']", session);
AssertHasOneMatch("variant/trait[@name='b' and @value='B']", session);
}
}
[Test]
public void VariantWith2SimpleFields()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var variant = new LexVariant();
variant.SetAlternative("etr", "one");
var fieldA = new LexField("a");
fieldA.SetAlternative("en", "aaa");
variant.Fields.Add(fieldA);
var fieldB = new LexField("b");
fieldB.SetAlternative("en", "bbb");
variant.Fields.Add(fieldB);
session.LiftWriter.AddVariant(variant);
session.LiftWriter.End();
AssertHasOneMatch("variant/field[@type='a']/form[@lang='en' and text = 'aaa']", session);
AssertHasOneMatch("variant/field[@type='b']/form[@lang='en' and text = 'bbb']", session);
}
}
[Test]
public void FieldWithTraits()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var variant = new LexVariant();
variant.SetAlternative("etr", "one");
var fieldA = new LexField("a");
fieldA.SetAlternative("en", "aaa");
fieldA.Traits.Add(new LexTrait("one", "1"));
variant.Fields.Add(fieldA);
session.LiftWriter.AddVariant(variant);
session.LiftWriter.End();
AssertHasOneMatch("variant/field[@type='a']/trait[@name='one' and @value='1']", session);
}
}
[Test]
public void CustomMultiTextOnEntry()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var entry = session.CreateItem();
var m = entry.GetOrCreateProperty<MultiText>("flubadub");
m["zz"] = "orange";
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("entry/field[@type='flubadub']/form[@lang='zz' and text='orange']", session);
}
}
[Test]
public void CustomMultiTextOnExample()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var example = new LexExampleSentence();
var m = example.GetOrCreateProperty<MultiText>("flubadub");
m["zz"] = "orange";
session.LiftWriter.Add(example);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("example/field[@type='flubadub']/form[@lang='zz' and text='orange']", session);
}
}
[Test]
public void CustomMultiTextOnSense()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
var m = sense.GetOrCreateProperty<MultiText>("flubadub");
m["zz"] = "orange";
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("sense/field[@type='flubadub']/form[@lang='zz' and text='orange']", session);
}
}
[Test]
public void CustomOptionRefCollectionOnEntry()
{
using (var session = new LiftExportAsFragmentTestSession())
{
//_fieldToOptionListName.Add("flubs", "colors");
LexEntry entry = session.CreateItem();
var o = entry.GetOrCreateProperty<OptionRefCollection>("flubs");
o.AddRange(new[] {"orange", "blue"});
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("entry/trait[@name='flubs' and @value='orange']", session);
AssertHasAtLeastOneMatch("entry/trait[@name='flubs' and @value='blue']", session);
AssertHasAtLeastOneMatch("entry[count(trait) =2]", session);
}
}
[Test]
public void CustomOptionRefCollectionOnExample()
{
using (var session = new LiftExportAsFragmentTestSession())
{
//_fieldToOptionListName.Add("flubs", "colors");
var example = new LexExampleSentence();
var o = example.GetOrCreateProperty<OptionRefCollection>("flubs");
o.AddRange(new[] {"orange", "blue"});
session.LiftWriter.Add(example);
session.LiftWriter.End();
string expected = CanonicalXml.ToCanonicalStringFragment(
"<example><trait name=\"flubs\" value=\"orange\" /><trait name=\"flubs\" value=\"blue\" /></example>"
);
Assert.AreEqual(
expected,
session.StringBuilder.ToString()
);
}
}
[Test]
public void CustomOptionRefCollectionOnSense()
{
using (var session = new LiftExportAsFragmentTestSession())
{
//_fieldToOptionListName.Add("flubs", "colors");
var sense = new LexSense();
var o = sense.GetOrCreateProperty<OptionRefCollection>("flubs");
o.AddRange(new[] {"orange", "blue"});
session.LiftWriter.Add(sense);
session.LiftWriter.End();
string expected = CanonicalXml.ToCanonicalStringFragment(
GetSenseElement(sense) +
"<trait name=\"flubs\" value=\"orange\" /><trait name=\"flubs\" value=\"blue\" /></sense>"
);
Assert.AreEqual(
expected,
session.StringBuilder.ToString());
}
}
[Test]
public void CustomOptionRefOnEntry()
{
using (var session = new LiftExportAsFragmentTestSession())
{
//_fieldToOptionListName.Add("flub", "kindsOfFlubs");
LexEntry entry = session.CreateItem();
var o = entry.GetOrCreateProperty<OptionRef>("flub");
o.Value = "orange";
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
AssertHasAtLeastOneMatch(
"entry/trait[@name='flub' and @value='orange']",
session
);
}
}
[Test]
public void CustomOptionRefOnExample()
{
using (var session = new LiftExportAsFragmentTestSession())
{
//_fieldToOptionListName.Add("flub", "kindsOfFlubs");
var example = new LexExampleSentence();
var o = example.GetOrCreateProperty<OptionRef>("flub");
o.Value = "orange";
session.LiftWriter.Add(example);
session.LiftWriter.End();
string expected = CanonicalXml.ToCanonicalStringFragment(
"<example><trait name=\"flub\" value=\"orange\" /></example>"
);
Assert.AreEqual(
expected,
session.StringBuilder.ToString()
);
}
}
[Test]
public void CustomOptionRefOnSense()
{
using (var session = new LiftExportAsFragmentTestSession())
{
//_fieldToOptionListName.Add("flub", "kindsOfFlubs");
var sense = new LexSense();
var o = sense.GetOrCreateProperty<OptionRef>("flub");
o.Value = "orange";
session.LiftWriter.Add(sense);
session.LiftWriter.End();
string expected = CanonicalXml.ToCanonicalStringFragment(
GetSenseElement(sense) + "<trait name=\"flub\" value=\"orange\" /></sense>"
);
Assert.AreEqual(
expected,
session.StringBuilder.ToString()
);
}
}
[Test]
public void CustomOptionRefOnSenseWithGrammi()
{
using (var session = new LiftExportAsFragmentTestSession())
{
//_fieldToOptionListName.Add("flub", "kindsOfFlubs");
var sense = new LexSense();
var grammi = sense.GetOrCreateProperty<OptionRef>(
LexSense.WellKnownProperties.PartOfSpeech
);
grammi.Value = "verb";
var o = sense.GetOrCreateProperty<OptionRef>("flub");
o.Value = "orange";
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("sense/trait[@name='flub' and @value='orange']", session);
AssertHasAtLeastOneMatch("sense[count(trait)=1]", session);
}
}
[Test]
public void DefinitionOnSense_OutputAsDefinition()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
var m = sense.GetOrCreateProperty<MultiText>(
LexSense.WellKnownProperties.Definition
);
m["zz"] = "orange";
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("sense/definition/form[@lang='zz']/text[text()='orange']", session);
AssertHasAtLeastOneMatch("sense[not(field)]", session);
}
}
[Test]
public void DeletedEntry()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var entry = new LexEntry();
session.LiftWriter.AddDeletedEntry(entry);
session.LiftWriter.End();
Assert.IsNotNull(GetStringAttributeOfTopElement("dateDeleted", session));
}
}
[Test]
public void DocumentStart()
{
using (var session = new LiftExportAsFullDocumentTestSession())
{
//NOTE: the utf-16 here is an artifact of the xmlwriter when writing to a stringbuilder,
//which is what we use for tests. The file version puts out utf-8
//CheckAnswer("<?xml version=\"1.0\" encoding=\"utf-16\"?><lift producer=\"WeSay.1Pt0Alpha\"/>");// xmlns:flex=\"http://fieldworks.sil.org\" />");
session.LiftWriter.End();
AssertHasAtLeastOneMatch(string.Format("lift[@version='{0}']", Validator.LiftVersion), session);
AssertHasAtLeastOneMatch(string.Format("lift[@producer='{0}']", LiftWriter.ProducerString), session);
}
}
[Test]
public void EmptyCustomMultiText()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
sense.GetOrCreateProperty<MultiText>("flubadub");
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("sense[not(field)]", session);
}
}
[Test]
public void EmptyCustomOptionRef()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
sense.GetOrCreateProperty<OptionRef>("flubadub");
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("sense[not(trait)]", session);
}
}
[Test]
public void EmptyCustomOptionRefCollection()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
sense.GetOrCreateProperty<OptionRefCollection>("flubadub");
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("sense[not(trait)]", session);
}
}
[Test]
public void EmptyDefinitionOnSense_NotOutput()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
sense.GetOrCreateProperty<MultiText>(LexSense.WellKnownProperties.Definition);
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("sense[not(definition)]", session);
AssertHasAtLeastOneMatch("sense[not(field)]", session);
}
}
[Test]
public void EmptyExampleSource_NoAttribute()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var ex = new LexExampleSentence();
ex.GetOrCreateProperty<OptionRef>(
LexExampleSentence.WellKnownProperties.Source
);
session.LiftWriter.Add(ex);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("example[not(@source)]", session);
}
}
[Test]
public void EmptyNoteOnEntry_NoOutput()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
entry.GetOrCreateProperty<MultiText>(PalasoDataObject.WellKnownProperties.Note);
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("entry[not(note)]", session);
AssertHasAtLeastOneMatch("entry[not(field)]", session);
}
}
[Test]
public void Entry_EntryHasIdWithInvalidXMLCharacters_CharactersEscaped()
{
const string expected = "id=\"<>&"'\"";
using (var session = new LiftExportAsFragmentTestSession())
{
var entry = session.CreateItem();
// technically the only invalid characters in an attribute are & < and " (when surrounded by ")
entry.Id = "<>&\"\'";
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
string result = session.OutputString();
Assert.IsTrue(result.Contains(expected));
}
}
[Test]
public void Entry_ScaryUnicodeCharacter_SafeXmlEmitted()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
entry.LexicalForm["test"] = '\u001F'.ToString();
session.LiftWriter.Add(entry);
session.LiftWriter.End();
var doc = new XmlDocument();
//this next line will crash if things aren't safe
doc.LoadXml(session.StringBuilder.ToString());
}
}
[Test]
public void Entry_HasId_RemembersId()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
entry.Id = "my id";
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
string result = session.StringBuilder.ToString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath("//entry[@id='my id']");
}
}
[Test]
public void Entry_NoId_GetsHumanReadableId()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var entry = session.CreateItem();
entry.LexicalForm["test"] = "lexicalForm";
//_lexEntryRepository.SaveItem(entry);
// make dateModified different than dateCreated
session.LiftWriter.Add(entry);
session.LiftWriter.End();
string expectedId = LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(
entry, new Dictionary<string, int>()
);
string result = session.StringBuilder.ToString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(String.Format("//entry[@id=\"{0}\"]", expectedId));
}
}
[Test]
public void EntryGuid()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
session.LiftWriter.Add(entry);
session.LiftWriter.End();
string result = session.StringBuilder.ToString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(String.Format("//entry[@guid=\"{0}\"]", entry.Guid));
}
}
[Test]
public void EmptyRelationNotOutput()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
entry.AddRelationTarget(LexEntry.WellKnownProperties.BaseForm, string.Empty);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
Assert.IsFalse(session.StringBuilder.ToString().Contains("relation"));
}
}
[Test]
public void EntryHasDateCreated()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
session.LiftWriter.Add(entry);
session.LiftWriter.End();
string result = session.StringBuilder.ToString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
String.Format("//entry[@dateCreated=\"{0}\"]", entry.CreationTime.ToString("yyyy-MM-ddTHH:mm:ssZ"))
);
}
}
[Test]
public void EntryHasDateModified()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
entry.LexicalForm["test"] = "lexicalForm";
// make dateModified different than dateCreated
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
string result = session.StringBuilder.ToString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
String.Format("//entry[@dateModified=\"{0}\"]", entry.ModificationTime.ToString("yyyy-MM-ddTHH:mm:ssZ"))
);
}
}
/// <summary>
/// Regression: WS-34576
/// </summary>
[Test]
public void Add_CultureUsesPeriodForTimeSeparator_DateAttributesOutputWithColon()
{
var culture = new CultureInfo("en-US");
culture.DateTimeFormat.TimeSeparator = ".";
Thread.CurrentThread.CurrentCulture = culture;
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
entry.LexicalForm["test"] = "lexicalForm";
// make dateModified different than dateCreated
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
string result = session.StringBuilder.ToString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
String.Format("//entry[@dateModified=\"{0}\"]",
entry.ModificationTime.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture))
);
Assert.IsTrue(result.Contains(":"), "should contain colons");
Assert.IsFalse(result.Contains("."), "should not contain periods");
}
}
[Test]
public void EntryWithSenses()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
entry.LexicalForm["blue"] = "ocean";
LexSense sense1 = new LexSense();
sense1.Gloss["a"] = "aaa";
entry.Senses.Add(sense1);
LexSense sense2 = new LexSense();
sense2.Gloss["b"] = "bbb";
entry.Senses.Add(sense2);
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
string result = session.StringBuilder.ToString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath("//entry/sense/gloss[@lang='a']/text[text()='aaa']");
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath("//entry/sense/gloss[@lang='b']/text[text()='bbb']");
AssertHasAtLeastOneMatch("entry[count(sense)=2]", session);
}
}
[Test]
public void ExampleSentence()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var example = new LexExampleSentence();
example.Sentence["blue"] = "ocean's eleven";
example.Sentence["red"] = "red sunset tonight";
session.LiftWriter.Add(example);
AssertEqualsCanonicalString(
"<example><form lang=\"blue\"><text>ocean's eleven</text></form><form lang=\"red\"><text>red sunset tonight</text></form></example>",
session.OutputString()
);
}
}
[Test]
public void ExampleSentenceWithTranslation()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var example = new LexExampleSentence();
example.Sentence["blue"] = "ocean's eleven";
example.Sentence["red"] = "red sunset tonight";
example.Translation["green"] = "blah blah";
session.LiftWriter.Add(example);
var outPut = session.OutputString();
AssertEqualsCanonicalString(
"<example><form lang=\"blue\"><text>ocean's eleven</text></form><form lang=\"red\"><text>red sunset tonight</text></form><translation><form lang=\"green\"><text>blah blah</text></form></translation></example>", outPut);
}
}
[Test]
public void ExampleSourceAsAttribute()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexExampleSentence ex = new LexExampleSentence();
OptionRef z = ex.GetOrCreateProperty<OptionRef>(
LexExampleSentence.WellKnownProperties.Source
);
z.Value = "hearsay";
session.LiftWriter.Add(ex);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("example[@source='hearsay']", session);
}
}
[Test]
public void FlagCleared_NoOutput()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
entry.SetFlag("ATestFlag");
entry.ClearFlag("ATestFlag");
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("entry[not(trait)]", session);
}
}
[Test]
public void FlagOnEntry_OutputAsTrait()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
entry.SetFlag("ATestFlag");
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("entry/trait[@name='ATestFlag' and @value]", session);
}
}
/* this is not relevant, as we are currently using form_guid as the id
[Test]
public void DuplicateFormsGetHomographNumbers()
{
LexEntry entry = new LexEntry();
entry.LexicalForm["blue"] = "ocean";
session.LiftWriter.Add(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
Assert.IsTrue(_stringBuilder.ToString().Contains("\"ocean\""), "ocean not contained in {0}", _stringBuilder.ToString());
Assert.IsTrue(_stringBuilder.ToString().Contains("ocean_2"), "ocean_2 not contained in {0}", _stringBuilder.ToString());
Assert.IsTrue(_stringBuilder.ToString().Contains("ocean_3"), "ocean_3 not contained in {0}", _stringBuilder.ToString());
}
*/
[Test]
public void GetHumanReadableId_EntryHasId_GivesId()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
entry.Id = "my id";
//_lexEntryRepository.SaveItem(entry);
Assert.AreEqual(
"my id",
LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, new Dictionary<string, int>())
);
}
}
/* this tests a particular implementation detail (idCounts), which isn't used anymore:
[Test]
public void GetHumanReadableId_EntryHasId_RegistersId()
{
LexEntry entry = new LexEntry("my id", Guid.NewGuid());
Dictionary<string, int> idCounts = new Dictionary<string, int>();
LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, idCounts);
Assert.AreEqual(1, idCounts["my id"]);
}
*/
/* this is not relevant, as we are currently using form_guid as the id
[Test]
public void GetHumanReadableId_EntryHasAlreadyUsedId_GivesIncrementedId()
{
LexEntry entry = new LexEntry("my id", Guid.NewGuid());
Dictionary<string, int> idCounts = new Dictionary<string, int>();
LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, idCounts);
Assert.AreEqual("my id_2", LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, idCounts));
}
*/
/* this is not relevant, as we are currently using form_guid as the id
[Test]
public void GetHumanReadableId_EntryHasAlreadyUsedId_IncrementsIdCount()
{
LexEntry entry = new LexEntry("my id", Guid.NewGuid());
Dictionary<string, int> idCounts = new Dictionary<string, int>();
LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, idCounts);
LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, idCounts);
Assert.AreEqual(2, idCounts["my id"]);
}
*/
/* this is not relevant, as we are currently using form_guid as the id
[Test]
public void GetHumanReadableId_EntryHasNoIdAndNoLexicalForms_GivesDefaultId()
{
LexEntry entry = new LexEntry();
Assert.AreEqual("NoForm", LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, new Dictionary<string, int>()));
}
*/
/* this is not currently relevant, as we are now using form_guid as the id
[Test]
public void GetHumanReadableId_EntryHasNoIdAndNoLexicalFormsButAlreadyUsedId_GivesIncrementedDefaultId()
{
LexEntry entry = new LexEntry();
Dictionary<string, int> idCounts = new Dictionary<string, int>();
LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, idCounts);
Assert.AreEqual("NoForm_2", LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, idCounts));
}
*/
/* this is not currently relevant, as we are now using form_guid as the id
[Test]
public void GetHumanReadableId_EntryHasNoId_GivesIdMadeFromFirstLexicalForm()
{
LexEntry entry = new LexEntry();
entry.LexicalForm["green"] = "grass";
entry.LexicalForm["blue"] = "ocean";
Assert.AreEqual("grass", LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, new Dictionary<string, int>()));
}
*/
/* this is not currently relevant, as we are now using form_guid as the id
[Test]
public void GetHumanReadableId_EntryHasNoId_RegistersIdMadeFromFirstLexicalForm()
{
LexEntry entry = new LexEntry();
entry.LexicalForm["green"] = "grass";
entry.LexicalForm["blue"] = "ocean";
Dictionary<string, int> idCounts = new Dictionary<string, int>();
LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, idCounts);
Assert.AreEqual(1, idCounts["grass"]);
}
*/
/* this is not currently relevant, as we are now using form_guid as the id
[Test]
public void GetHumanReadableId_EntryHasNoIdAndIsSameAsAlreadyEncountered_GivesIncrementedId()
{
LexEntry entry = new LexEntry();
entry.LexicalForm["green"] = "grass";
entry.LexicalForm["blue"] = "ocean";
Dictionary<string, int> idCounts = new Dictionary<string, int>();
LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, idCounts);
Assert.AreEqual("grass_2", LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, idCounts));
}
*/
/* this is not currently relevant, as we are now using form_guid as the id
[Test]
public void GetHumanReadableId_EntryHasNoIdAndIsSameAsAlreadyEncountered_IncrementsIdCount()
{
LexEntry entry = new LexEntry();
entry.LexicalForm["green"] = "grass";
entry.LexicalForm["blue"] = "ocean";
Dictionary<string, int> idCounts = new Dictionary<string, int>();
LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, idCounts);
LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, idCounts);
Assert.AreEqual(2, idCounts["grass"]);
}
*/
/* this is not currently relevant, as we are now using form_guid as the id
[Test]
public void GetHumanReadableId_IdsDifferByWhiteSpaceTypeOnly_WhitespaceTreatedAsSpaces()
{
LexEntry entry = new LexEntry();
entry.LexicalForm["green"] = "string\t1\n2\r3 4";
Assert.AreEqual("string 1 2 3 4", LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, new Dictionary<string, int>()));
}
*/
[Test]
public void GetHumanReadableId_IdIsSpace_NoForm()
{
var entry = new LexEntry(" ", Guid.NewGuid());
Assert.IsTrue(
LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(
entry, new Dictionary<string, int>()
).StartsWith("Id'dPrematurely_")
);
}
[Test]
public void GetHumanReadableId_IdIsSpace_TreatedAsThoughNonExistentId()
{
var entry = new LexEntry(" ", Guid.NewGuid());
entry.LexicalForm["green"] = "string";
Assert.IsTrue(
LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(entry, new Dictionary<string, int>()).StartsWith
("string"));
}
[Test]
public void Gloss()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
sense.Gloss["blue"] = "ocean";
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch(
"sense/gloss[@lang='blue']/text[text()='ocean']",
session
);
}
}
[Test] // Ummmm no it shouldn't CP 2013-05. Flex expects the opposite of this.
public void Gloss_MultipleGlossesSplitIntoSeparateEntries()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
sense.Gloss["a"] = "aaa; bbb; ccc";
sense.Gloss["x"] = "xx";
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("sense[count(gloss)=2]", session);
AssertHasAtLeastOneMatch("sense/gloss[@lang='a' and text='aaa; bbb; ccc']", session);
AssertHasAtLeastOneMatch("sense/gloss[@lang='x' and text='xx']", session);
}
}
[Test]
public void GlossWithProblematicCharacters()
{
const string expected = "<text>LessThan<GreaterThan>Ampersan&</text>";
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
sense.Gloss["blue"] = "LessThan<GreaterThan>Ampersan&";
session.LiftWriter.Add(sense);
string result = session.OutputString();
Assert.IsTrue(result.Contains(expected));
}
}
[Test]
public void GlossWithStarredForm()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexSense sense = new LexSense();
sense.Gloss.SetAlternative("x", "orange");
sense.Gloss.SetAnnotationOfAlternativeIsStarred("x", true);
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("sense/gloss[@lang='x']/annotation[@name='flag' and @value='1']", session);
}
}
[Test]
public void Grammi()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
var o = sense.GetOrCreateProperty<OptionRef>(
LexSense.WellKnownProperties.PartOfSpeech
);
o.Value = "orange";
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("sense/grammatical-info[@value='orange']", session);
AssertHasAtLeastOneMatch("sense[not(trait)]", session);
}
}
[Test]
public void GrammiWithStarredForm()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexSense sense = new LexSense();
OptionRef o = sense.GetOrCreateProperty<OptionRef>(
LexSense.WellKnownProperties.PartOfSpeech
);
o.Value = "orange";
o.IsStarred = true;
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch(
"sense/grammatical-info[@value='orange']/annotation[@name='flag' and @value='1']",
session
);
}
}
[Test]
public void LexemeForm_SingleWritingSystem()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry e = session.CreateItem();
e.LexicalForm["xx"] = "foo";
//_lexEntryRepository.SaveItem(e);
session.LiftWriter.Add(e);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("//lexical-unit/form[@lang='xx']", session);
}
}
[Test]
public void LexEntry_becomes_entry()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
session.LiftWriter.Add(entry);
session.LiftWriter.End();
Assert.IsTrue(session.StringBuilder.ToString().StartsWith("<entry"));
}
}
[Test]
public void LexicalUnit()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry e = session.CreateItem();
e.LexicalForm.SetAlternative("x", "orange");
//_lexEntryRepository.SaveItem(e);
session.LiftWriter.Add(e);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("entry/lexical-unit/form[@lang='x']/text[text()='orange']", session);
AssertHasAtLeastOneMatch("entry/lexical-unit/form[@lang='x'][not(trait)]", session);
}
}
[Test]
public void LexicalUnitWithStarredForm()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry e = session.CreateItem();
e.LexicalForm.SetAlternative("x", "orange");
e.LexicalForm.SetAnnotationOfAlternativeIsStarred("x", true);
//_lexEntryRepository.SaveItem(e);
session.LiftWriter.Add(e);
session.LiftWriter.End();
AssertHasAtLeastOneMatch(
"entry/lexical-unit/form[@lang='x']/annotation[@name='flag' and @value='1']",
session
);
}
}
[Test]
public void LexSense_becomes_sense()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
session.LiftWriter.Add(sense);
session.LiftWriter.End();
Assert.IsTrue(session.StringBuilder.ToString().StartsWith("<sense"));
}
}
[Test]
public void MultiText()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var text = new MultiText();
text["blue"] = "ocean";
text["red"] = "sunset";
session.LiftWriter.AddMultitextForms(null, text);
AssertEqualsCanonicalString(
"<form lang=\"blue\"><text>ocean</text></form><form lang=\"red\"><text>sunset</text></form>",
session.OutputString()
);
}
}
[Test]
public void NoteOnEntry_OutputAsNote()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
MultiText m =
entry.GetOrCreateProperty<MultiText>(PalasoDataObject.WellKnownProperties.Note);
m["zz"] = "orange";
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("entry/note/form[@lang='zz' and text='orange']", session);
AssertHasAtLeastOneMatch("entry[not(field)]", session);
}
}
[Test]
public void NoteOnExample_OutputAsNote()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexExampleSentence example = new LexExampleSentence();
MultiText m =
example.GetOrCreateProperty<MultiText>(PalasoDataObject.WellKnownProperties.Note);
m["zz"] = "orange";
session.LiftWriter.Add(example);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("example/note/form[@lang='zz' and text='orange']", session);
AssertHasAtLeastOneMatch("example[not(field)]", session);
}
}
[Test]
public void NoteOnSense_OutputAsNote()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexSense sense = new LexSense();
MultiText m =
sense.GetOrCreateProperty<MultiText>(PalasoDataObject.WellKnownProperties.Note);
m["zz"] = "orange";
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertHasAtLeastOneMatch("sense/note/form[@lang='zz' and text='orange']", session);
AssertHasAtLeastOneMatch("sense[not(field)]", session);
}
}
[Test]
public void Picture_OutputAsPictureURLRef()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexSense sense = new LexSense();
PictureRef p = sense.GetOrCreateProperty<PictureRef>("Picture");
p.Value = "bird.jpg";
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertEqualsCanonicalString(GetSenseElement(sense) + "<illustration href=\"bird.jpg\" /></sense>", session);
}
}
[Test]
public void Picture_OutputAsPictureWithCaption()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexSense sense = new LexSense();
PictureRef p = sense.GetOrCreateProperty<PictureRef>("Picture");
p.Value = "bird.jpg";
p.Caption = new MultiText();
p.Caption["aa"] = "aCaption";
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertEqualsCanonicalString(
GetSenseElement(sense) +
"<illustration href=\"bird.jpg\"><label><form lang=\"aa\"><text>aCaption</text></form></label></illustration></sense>",
session
);
}
}
[Test]
public void Sense_HasId_RemembersId()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexSense s = new LexSense();
s.Id = "my id";
session.LiftWriter.Add(s);
session.LiftWriter.End();
string result = session.StringBuilder.ToString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath("//sense[@id='my id']");
}
}
[Test]
public void Sense_NoId_GetsId()
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexSense sense = new LexSense();
session.LiftWriter.Add(sense);
session.LiftWriter.End();
string result = session.StringBuilder.ToString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
String.Format("//sense[@id='{0}']", sense.Id)
);
}
}
[Test]
public void SensesAreLastObjectsInEntry() // this helps conversions to sfm review: It would be great if this wasn't necessary CP 2011-01
{
using (var session = new LiftExportAsFragmentTestSession())
{
LexEntry entry = session.CreateItem();
entry.LexicalForm["blue"] = "ocean";
LexSense sense1 = new LexSense();
sense1.Gloss["a"] = "aaa";
entry.Senses.Add(sense1);
LexSense sense2 = new LexSense();
sense2.Gloss["b"] = "bbb";
entry.Senses.Add(sense2);
MultiText citation =
entry.GetOrCreateProperty<MultiText>(LexEntry.WellKnownProperties.Citation);
citation["zz"] = "orange";
MultiText note =
entry.GetOrCreateProperty<MultiText>(PalasoDataObject.WellKnownProperties.Note);
note["zz"] = "orange";
MultiText field = entry.GetOrCreateProperty<MultiText>("custom");
field["zz"] = "orange";
//_lexEntryRepository.SaveItem(entry);
session.LiftWriter.Add(entry);
session.LiftWriter.End();
string result = session.StringBuilder.ToString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath("//gloss[@lang='a']/text[text()='aaa']");
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath("//gloss[@lang='b']/text[text()='bbb']");
AssertThatXmlIn.String(result).HasNoMatchForXpath("/entry/sense[2]/following-sibling::*");
}
}
[Test]
public void SenseWithExample()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
var example = new LexExampleSentence();
example.Sentence["red"] = "red sunset tonight";
sense.ExampleSentences.Add(example);
session.LiftWriter.Add(sense);
string result = session.OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/sense/example/form[@lang='red']/text[text()='red sunset tonight']"
);
}
}
[Test]
public void SenseWithSynonymRelations()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
var synonymRelationType = new LexRelationType(
"synonym",
LexRelationType.Multiplicities.Many,
LexRelationType.TargetTypes.Sense
);
var antonymRelationType = new LexRelationType(
"antonym",
LexRelationType.Multiplicities.Many,
LexRelationType.TargetTypes.Sense
);
var relations = new LexRelationCollection();
sense.Properties.Add(new KeyValuePair<string, IPalasoDataObjectProperty>("relations", relations));
relations.Relations.Add(new LexRelation(synonymRelationType.ID, "one", sense));
relations.Relations.Add(new LexRelation(synonymRelationType.ID, "two", sense));
relations.Relations.Add(new LexRelation(antonymRelationType.ID, "bee", sense));
session.LiftWriter.Add(sense);
string result = session.OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/sense/relation[@type='synonym' and @ref='one']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/sense/relation[@type='synonym' and @ref='two']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/sense/relation[@type='antonym' and @ref='bee']"
);
}
}
[Test]
public void AddRelationTarget_SenseWithSynonymRelations()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
sense.AddRelationTarget("synonym", "one");
sense.AddRelationTarget("synonym", "two");
sense.AddRelationTarget("antonym", "bee");
session.LiftWriter.Add(sense);
string result = session.OutputString();
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/sense/relation[@type='synonym' and @ref='one']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/sense/relation[@type='synonym' and @ref='two']"
);
AssertThatXmlIn.String(result).HasAtLeastOneMatchForXpath(
"/sense/relation[@type='antonym' and @ref='bee']"
);
}
}
[Test]
public void SenseWithRelationWithEmbeddedXml()
{
using (var session = new LiftExportAsFragmentTestSession())
{
var sense = new LexSense();
var synonymRelationType = new LexRelationType(
"synonym",
LexRelationType.Multiplicities.Many,
LexRelationType.TargetTypes.Sense
);
var relations = new LexRelationCollection();
sense.Properties.Add(new KeyValuePair<string, IPalasoDataObjectProperty>("relations", relations));
var lexRelation = new LexRelation(synonymRelationType.ID, "one", sense);
lexRelation.EmbeddedXmlElements.Add("<trait name='x' value='X'/>");
lexRelation.EmbeddedXmlElements.Add("<field id='z'><text>hello</text></field>");
relations.Relations.Add(lexRelation);
session.LiftWriter.Add(sense);
session.LiftWriter.End();
AssertThatXmlIn.String(session.StringBuilder.ToString()).HasSpecifiedNumberOfMatchesForXpath("//sense/relation/trait",1);
AssertThatXmlIn.String(session.StringBuilder.ToString()).HasSpecifiedNumberOfMatchesForXpath("//sense/relation/field", 1);
}
}
[Test]
public void WriteToFile()
{
using (var session = new LiftExportAsFileTestSession())
{
session.AddTwoTestLexEntries();
var doc = new XmlDocument();
doc.Load(session.FilePath);
Assert.AreEqual(2, doc.SelectNodes("lift/entry").Count);
}
}
[Test]
public void Add_MultiTextWithWellFormedXML_IsExportedAsXML()
{
const string expected =
"<form\r\n\tlang=\"de\">\r\n\t<text>This <span href=\"reference\">is well formed</span> XML!</text>\r\n</form>";
using (var session = new LiftExportAsFragmentTestSession())
{
var multiText = new MultiText();
multiText.SetAlternative("de", "This <span href=\"reference\">is well formed</span> XML!");
session.LiftWriter.AddMultitextForms(null, multiText);
session.LiftWriter.End();
Assert.AreEqual(expected, session.OutputString());
}
}
[Test]
public void Add_MultiTextWithWellFormedXMLAndScaryCharacter_IsExportedAsXML()
{
const string expected =
"<form\r\n\tlang=\"de\">\r\n\t<text>This <span href=\"reference\">is well  formed</span> XML!</text>\r\n</form>";
using (var session = new LiftExportAsFragmentTestSession())
{
var multiText = new MultiText();
multiText.SetAlternative("de", "This <span href=\"reference\">is well \u001F formed</span> XML!");
session.LiftWriter.AddMultitextForms(null, multiText);
session.LiftWriter.End();
Assert.AreEqual(expected, session.OutputString());
}
}
[Test]
public void Add_MultiTextWithScaryUnicodeChar_IsExported()
{
const string expected =
"<form\r\n\tlang=\"de\">\r\n\t<text>This has a segment separator character at the end</text>\r\n</form>";
// 1F is the character for "Segment Separator" and you can insert it by right-clicking in windows
using (var session = new LiftExportAsFragmentTestSession())
{
var multiText = new MultiText();
multiText.SetAlternative("de", "This has a segment separator character at the end\u001F");
session.LiftWriter.AddMultitextForms(null, multiText);
session.LiftWriter.End();
Assert.AreEqual(expected, session.OutputString());
}
}
[Test]
public void Add_MalformedXmlWithWithScaryUnicodeChar_IsExportedAsText()
{
const string expected = "<form\r\n\tlang=\"de\">\r\n\t<text>This <span href=\"reference\">is not well  formed<span> XML!</text>\r\n</form>";
// 1F is the character for "Segment Separator" and you can insert it by right-clicking in windows
using (var session = new LiftExportAsFragmentTestSession())
{
var multiText = new MultiText();
multiText.SetAlternative("de", "This <span href=\"reference\">is not well \u001F formed<span> XML!");
session.LiftWriter.AddMultitextForms(null, multiText);
session.LiftWriter.End();
Assert.AreEqual(expected, session.OutputString());
}
}
[Test]
public void Add_MultiTextWithMalFormedXML_IsExportedText()
{
const string expected =
"<form\r\n\tlang=\"de\">\r\n\t<text>This <span href=\"reference\">is not well formed<span> XML!</text>\r\n</form>";
using (var session = new LiftExportAsFragmentTestSession())
{
var multiText = new MultiText();
multiText.SetAlternative("de", "This <span href=\"reference\">is not well formed<span> XML!");
session.LiftWriter.AddMultitextForms(null, multiText);
session.LiftWriter.End();
Assert.AreEqual(expected, session.OutputString());
}
}
[Test]
public void Add_TextWithSpanAndMeaningfulWhiteSpace_FormattingAndWhitespaceIsUntouched()
{
const string formattedText = "\rThis's <span href=\"reference\">\n is a\t\t\n\r\t span</span> with annoying whitespace!\r\n";
const string expected = "<form\r\n\tlang=\"de\">\r\n\t<text>" + formattedText + "</text>\r\n</form>";
using (var session = new LiftExportAsFragmentTestSession())
{
var multiText = new MultiText();
multiText.SetAlternative("de", formattedText);
session.LiftWriter.AddMultitextForms(null, multiText);
session.LiftWriter.End();
Assert.AreEqual(expected, session.OutputString());
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Numerics;
using System.Threading;
using Debug = System.Management.Automation.Diagnostics;
using System.Security.Cryptography;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This class implements get-random cmdlet.
/// </summary>
/// <!-- author: LukaszA -->
[Cmdlet(VerbsCommon.Get, "Random", DefaultParameterSetName = GetRandomCommand.RandomNumberParameterSet,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113446", RemotingCapability = RemotingCapability.None)]
[OutputType(typeof(Int32), typeof(Int64), typeof(Double))]
public class GetRandomCommand : PSCmdlet
{
#region Parameter set handling
private const string RandomNumberParameterSet = "RandomNumberParameterSet";
private const string RandomListItemParameterSet = "RandomListItemParameterSet";
private enum MyParameterSet
{
Unknown,
RandomNumber,
RandomListItem
}
private MyParameterSet _effectiveParameterSet;
private MyParameterSet EffectiveParameterSet
{
get
{
// cache MyParameterSet enum instead of doing string comparison every time
if (_effectiveParameterSet == MyParameterSet.Unknown)
{
if ((this.MyInvocation.ExpectingInput) && (this.Maximum == null) && (this.Minimum == null))
{
_effectiveParameterSet = MyParameterSet.RandomListItem;
}
else if (ParameterSetName.Equals(GetRandomCommand.RandomListItemParameterSet, StringComparison.OrdinalIgnoreCase))
{
_effectiveParameterSet = MyParameterSet.RandomListItem;
}
else if (this.ParameterSetName.Equals(GetRandomCommand.RandomNumberParameterSet, StringComparison.OrdinalIgnoreCase))
{
if ((this.Maximum != null) && (this.Maximum.GetType().IsArray))
{
this.InputObject = (object[])this.Maximum;
_effectiveParameterSet = MyParameterSet.RandomListItem;
}
else
{
_effectiveParameterSet = MyParameterSet.RandomNumber;
}
}
else
{
Debug.Assert(false, "Unrecognized parameter set");
}
}
return _effectiveParameterSet;
}
}
#endregion Parameter set handling
#region Error handling
private void ThrowMinGreaterThanOrEqualMax(object min, object max)
{
if (min == null)
{
throw PSTraceSource.NewArgumentNullException("min");
}
if (max == null)
{
throw PSTraceSource.NewArgumentNullException("max");
}
ErrorRecord errorRecord = new ErrorRecord(
new ArgumentException(string.Format(
CultureInfo.InvariantCulture, GetRandomCommandStrings.MinGreaterThanOrEqualMax, min, max)),
"MinGreaterThanOrEqualMax",
ErrorCategory.InvalidArgument,
null);
this.ThrowTerminatingError(errorRecord);
}
#endregion
#region Random generator state
private static ReaderWriterLockSlim s_runspaceGeneratorMapLock = new ReaderWriterLockSlim();
// 1-to-1 mapping of runspaces and random number generators
private static Dictionary<Guid, PolymorphicRandomNumberGenerator> s_runspaceGeneratorMap = new Dictionary<Guid, PolymorphicRandomNumberGenerator>();
private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e)
{
switch (e.RunspaceStateInfo.State)
{
case RunspaceState.Broken:
case RunspaceState.Closed:
try
{
GetRandomCommand.s_runspaceGeneratorMapLock.EnterWriteLock();
GetRandomCommand.s_runspaceGeneratorMap.Remove(((Runspace)sender).InstanceId);
}
finally
{
GetRandomCommand.s_runspaceGeneratorMapLock.ExitWriteLock();
}
break;
}
}
private PolymorphicRandomNumberGenerator _generator;
/// <summary>
/// Gets and sets generator associated with the current runspace.
/// </summary>
private PolymorphicRandomNumberGenerator Generator
{
get
{
if (_generator == null)
{
Guid runspaceId = this.Context.CurrentRunspace.InstanceId;
bool needToInitialize = false;
try
{
GetRandomCommand.s_runspaceGeneratorMapLock.EnterReadLock();
needToInitialize = !GetRandomCommand.s_runspaceGeneratorMap.TryGetValue(runspaceId, out _generator);
}
finally
{
GetRandomCommand.s_runspaceGeneratorMapLock.ExitReadLock();
}
if (needToInitialize)
{
this.Generator = new PolymorphicRandomNumberGenerator();
}
}
return _generator;
}
set
{
_generator = value;
Runspace myRunspace = this.Context.CurrentRunspace;
try
{
GetRandomCommand.s_runspaceGeneratorMapLock.EnterWriteLock();
if (!GetRandomCommand.s_runspaceGeneratorMap.ContainsKey(myRunspace.InstanceId))
{
// make sure we won't leave the generator around after runspace exits
myRunspace.StateChanged += CurrentRunspace_StateChanged;
}
GetRandomCommand.s_runspaceGeneratorMap[myRunspace.InstanceId] = _generator;
}
finally
{
GetRandomCommand.s_runspaceGeneratorMapLock.ExitWriteLock();
}
}
}
#endregion
#region Common parameters
/// <summary>
/// Seed used to reinitialize random numbers generator.
/// </summary>
[Parameter]
[ValidateNotNull]
public int? SetSeed { get; set; }
#endregion Common parameters
#region Parameters for RandomNumberParameterSet
/// <summary>
/// Maximum number to generate.
/// </summary>
[Parameter(ParameterSetName = RandomNumberParameterSet, Position = 0)]
public object Maximum { get; set; }
/// <summary>
/// Minimum number to generate.
/// </summary>
[Parameter(ParameterSetName = RandomNumberParameterSet)]
public object Minimum { get; set; }
private bool IsInt(object o)
{
if (o == null || o is int)
{
return true;
}
return false;
}
private bool IsInt64(object o)
{
if (o == null || o is Int64)
{
return true;
}
return false;
}
private object ProcessOperand(object o)
{
if (o == null)
{
return null;
}
PSObject pso = PSObject.AsPSObject(o);
object baseObject = pso.BaseObject;
if (baseObject is string)
{
// The type argument passed in does not decide the number type we want to convert to. ScanNumber will return
// int/long/double based on the string form number passed in.
baseObject = System.Management.Automation.Language.Parser.ScanNumber((string)baseObject, typeof(int));
}
return baseObject;
}
private double ConvertToDouble(object o, double defaultIfNull)
{
if (o == null)
{
return defaultIfNull;
}
double result = (double)LanguagePrimitives.ConvertTo(o, typeof(double), CultureInfo.InvariantCulture);
return result;
}
#endregion
#region Parameters and variables for RandomListItemParameterSet
private List<object> _chosenListItems;
private int _numberOfProcessedListItems;
/// <summary>
/// List from which random elements are chosen.
/// </summary>
[Parameter(ParameterSetName = RandomListItemParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public object[] InputObject { get; set; }
/// <summary>
/// Number of items to output (number of list items or of numbers).
/// </summary>
[Parameter(ParameterSetName = GetRandomCommand.RandomListItemParameterSet)]
[ValidateRange(1, int.MaxValue)]
public int Count { get; set; }
#endregion
#region Cmdlet processing methods
private double GetRandomDouble(double min, double max)
{
double randomNumber;
double diff = max - min;
// I couldn't find a better fix for bug #216893 then
// to test and retry if a random number falls outside the bounds
// because of floating-point-arithmetic inaccuracies.
//
// Performance in the normal case is not impacted much.
// In low-precision situations we should converge to a solution quickly
// (diff gets smaller at a quick pace).
if (double.IsInfinity(diff))
{
do
{
double r = this.Generator.NextDouble();
randomNumber = min + r * max - r * min;
}
while (randomNumber >= max);
}
else
{
do
{
double r = this.Generator.NextDouble();
randomNumber = min + r * diff;
diff = diff * r;
}
while (randomNumber >= max);
}
return randomNumber;
}
/// <summary>
/// Get a random Int64 type number.
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
private Int64 GetRandomInt64(Int64 min, Int64 max)
{
// Randomly generate eight bytes and convert the byte array to UInt64
var buffer = new byte[sizeof(UInt64)];
UInt64 randomUint64;
BigInteger bigIntegerDiff = (BigInteger)max - (BigInteger)min;
// When the difference is less than int.MaxValue, use Random.Next(int, int)
if (bigIntegerDiff <= int.MaxValue)
{
int randomDiff = this.Generator.Next(0, (int)(max - min));
return min + randomDiff;
}
// The difference of two Int64 numbers would not exceed UInt64.MaxValue, so it can be represented by a UInt64 number.
UInt64 uint64Diff = (UInt64)bigIntegerDiff;
// Calculate the number of bits to represent the diff in type UInt64
int bitsToRepresentDiff = 0;
UInt64 diffCopy = uint64Diff;
for (; diffCopy != 0; bitsToRepresentDiff++)
{
diffCopy >>= 1;
}
// Get the mask for the number of bits
UInt64 mask = (0xffffffffffffffff >> (64 - bitsToRepresentDiff));
do
{
// Randomly fill the buffer
this.Generator.NextBytes(buffer);
randomUint64 = BitConverter.ToUInt64(buffer, 0);
// Get the last 'bitsToRepresentDiff' number of randon bits
randomUint64 &= mask;
} while (uint64Diff <= randomUint64);
double result = min * 1.0 + randomUint64 * 1.0;
return (Int64)result;
}
/// <summary>
/// This method implements the BeginProcessing method for get-random command.
/// </summary>
protected override void BeginProcessing()
{
if (this.SetSeed.HasValue)
{
this.Generator = new PolymorphicRandomNumberGenerator(this.SetSeed.Value);
}
if (this.EffectiveParameterSet == MyParameterSet.RandomNumber)
{
object maxOperand = ProcessOperand(this.Maximum);
object minOperand = ProcessOperand(this.Minimum);
if (IsInt(maxOperand) && IsInt(minOperand))
{
int min = minOperand != null ? (int)minOperand : 0;
int max = maxOperand != null ? (int)maxOperand : int.MaxValue;
if (min >= max)
{
this.ThrowMinGreaterThanOrEqualMax(min, max);
}
int randomNumber = this.Generator.Next(min, max);
Debug.Assert(min <= randomNumber, "lower bound <= random number");
Debug.Assert(randomNumber < max, "random number < upper bound");
this.WriteObject(randomNumber);
}
else if ((IsInt64(maxOperand) || IsInt(maxOperand)) && (IsInt64(minOperand) || IsInt(minOperand)))
{
Int64 min = minOperand != null ? ((minOperand is Int64) ? (Int64)minOperand : (int)minOperand) : 0;
Int64 max = maxOperand != null ? ((maxOperand is Int64) ? (Int64)maxOperand : (int)maxOperand) : Int64.MaxValue;
if (min >= max)
{
this.ThrowMinGreaterThanOrEqualMax(min, max);
}
Int64 randomNumber = this.GetRandomInt64(min, max);
Debug.Assert(min <= randomNumber, "lower bound <= random number");
Debug.Assert(randomNumber < max, "random number < upper bound");
this.WriteObject(randomNumber);
}
else
{
double min = (minOperand is double) ? (double)minOperand : this.ConvertToDouble(this.Minimum, 0.0);
double max = (maxOperand is double) ? (double)maxOperand : this.ConvertToDouble(this.Maximum, double.MaxValue);
if (min >= max)
{
this.ThrowMinGreaterThanOrEqualMax(min, max);
}
double randomNumber = this.GetRandomDouble(min, max);
Debug.Assert(min <= randomNumber, "lower bound <= random number");
Debug.Assert(randomNumber < max, "random number < upper bound");
this.WriteObject(randomNumber);
}
}
else if (this.EffectiveParameterSet == MyParameterSet.RandomListItem)
{
_chosenListItems = new List<object>();
_numberOfProcessedListItems = 0;
if (this.Count == 0) // -Count not specified
{
this.Count = 1; // default to one random item by default
}
}
}
// rough proof that when choosing random K items out of N items
// each item has got K/N probability of being included in the final list
//
// probability that a particular item in this.chosenListItems is NOT going to be replaced
// when processing I-th input item [assumes I > K]:
// P_one_step(I) = 1 - ((K / I) * ((K - 1) / K) + ((I - K) / I) = (I - 1) / I
// <--A--> <-----B-----> <-----C----->
// A - probability that I-th element is going to be replacing an element from this.chosenListItems
// (see (1) in the code below)
// B - probability that a particular element from this.chosenListItems is NOT going to be replaced
// (see (2) in the code below)
// C - probability that I-th element is NOT going to be replacing an element from this.chosenListItems
// (see (1) in the code below)
//
// probability that a particular item in this.chosenListItems is NOT going to be replaced
// when processing input items J through N [assumes J > K]
// P_removal(J) = Multiply(for I = J to N) P(I) =
// = ((J - 1) / J) * (J / (J + 1)) * ... * ((N - 2) / (N - 1)) * ((N - 1) / N) =
// = (J - 1) / N
//
// probability that when processing an element it is going to be put into this.chosenListItems
// P_insertion(I) = 1.0 when I <= K - see (3) in the code below
// P_insertion(I) = K/N otherwise - see (1) in the code below
//
// probability that a given element is going to be a part of the final list
// P_final(I) = P_insertion(I) * P_removal(max(I + 1, K + 1))
// [for I <= K] = 1.0 * ((K + 1) - 1) / N = K / N
// [otherwise] = (K / I) * ((I + 1) - 1) / N = K / N
//
// which proves that P_final(I) = K / N for all values of I. QED.
/// <summary>
/// This method implements the ProcessRecord method for get-random command.
/// </summary>
protected override void ProcessRecord()
{
if (this.EffectiveParameterSet == MyParameterSet.RandomListItem)
{
foreach (object item in this.InputObject)
{
if (_numberOfProcessedListItems < this.Count) // (3)
{
Debug.Assert(_chosenListItems.Count == _numberOfProcessedListItems, "Initial K elements should all be included in this.chosenListItems");
_chosenListItems.Add(item);
}
else
{
Debug.Assert(_chosenListItems.Count == this.Count, "After processing K initial elements, the length of this.chosenItems should stay equal to K");
if (this.Generator.Next(_numberOfProcessedListItems + 1) < this.Count) // (1)
{
int indexToReplace = this.Generator.Next(_chosenListItems.Count); // (2)
_chosenListItems[indexToReplace] = item;
}
}
_numberOfProcessedListItems++;
}
}
}
/// <summary>
/// This method implements the EndProcessing method for get-random command.
/// </summary>
protected override void EndProcessing()
{
if (this.EffectiveParameterSet == MyParameterSet.RandomListItem)
{
// make sure the order is truly random
// (all permutations with the same probability)
// O(n) time
int n = _chosenListItems.Count;
for (int i = 0; i < n; i++)
{
// randomly choose j from [i...n)
int j = this.Generator.Next(i, n);
this.WriteObject(_chosenListItems[j]);
// remove the output object from consideration in the next iteration.
if (i != j)
{
_chosenListItems[j] = _chosenListItems[i];
}
}
}
}
#endregion Processing methods
}
/// <summary>
/// Provides an adapter API for random numbers that may be either cryptographically random, or
/// generated with the regular pseudo-random number generator. Re-implementations of
/// methods using the NextBytes() primitive based on the CLR implementation:
/// https://referencesource.microsoft.com/#mscorlib/system/random.cs.
/// </summary>
internal class PolymorphicRandomNumberGenerator
{
/// <summary>
/// Constructor.
/// </summary>
public PolymorphicRandomNumberGenerator()
{
_cryptographicGenerator = RandomNumberGenerator.Create();
_pseudoGenerator = null;
}
internal PolymorphicRandomNumberGenerator(int seed)
{
_cryptographicGenerator = null;
_pseudoGenerator = new Random(seed);
}
private Random _pseudoGenerator = null;
private RandomNumberGenerator _cryptographicGenerator = null;
/// <summary>
/// Generates a random floating-point number that is greater than or equal to 0.0, and less than 1.0.
/// </summary>
/// <returns>A random floating-point number that is greater than or equal to 0.0, and less than 1.0.</returns>
internal double NextDouble()
{
// According to the CLR source:
// "Including this division at the end gives us significantly improved random number distribution."
return Next() * (1.0 / Int32.MaxValue);
}
/// <summary>
/// Generates a non-negative random integer.
/// </summary>
/// <returns>A non-negative random integer.</returns>
internal int Next()
{
int result;
// The CLR implementation just fudges
// Int32.MaxValue down to (Int32.MaxValue - 1). This implementation
// errs on the side of correctness.
do
{
result = InternalSample();
}
while (result == Int32.MaxValue);
if (result < 0)
{
result += Int32.MaxValue;
}
return result;
}
/// <summary>
/// Returns a random integer that is within a specified range.
/// </summary>
/// <param name="maxValue">The exclusive upper bound of the random number returned.</param>
/// <returns></returns>
internal int Next(int maxValue)
{
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException("maxValue", GetRandomCommandStrings.MaxMustBeGreaterThanZeroApi);
}
return Next(0, maxValue);
}
/// <summary>
/// Returns a random integer that is within a specified range.
/// </summary>
/// <param name="minValue">The inclusive lower bound of the random number returned.</param>
/// <param name="maxValue">The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.</param>
/// <returns></returns>
public int Next(int minValue, int maxValue)
{
if (minValue > maxValue)
{
throw new ArgumentOutOfRangeException("minValue", GetRandomCommandStrings.MinGreaterThanOrEqualMaxApi);
}
long range = (long)maxValue - (long)minValue;
if (range <= int.MaxValue)
{
return ((int)(NextDouble() * range) + minValue);
}
else
{
double largeSample = InternalSampleLargeRange() * (1.0 / (2 * ((uint)Int32.MaxValue)));
int result = (int)((long)(largeSample * range) + minValue);
return result;
}
}
/// <summary>
/// Fills the elements of a specified array of bytes with random numbers.
/// </summary>
/// <param name="buffer">The array to be filled.</param>
internal void NextBytes(byte[] buffer)
{
if (_cryptographicGenerator != null)
{
_cryptographicGenerator.GetBytes(buffer);
}
else
{
_pseudoGenerator.NextBytes(buffer);
}
}
/// <summary>
/// Samples a random integer.
/// </summary>
/// <returns>A random integer, using the full range of Int32.</returns>
private int InternalSample()
{
int result;
byte[] data = new byte[sizeof(int)];
NextBytes(data);
result = BitConverter.ToInt32(data, 0);
return result;
}
/// <summary>
/// Samples a random int when the range is large. This does
/// not need to be in the range of -Double.MaxValue .. Double.MaxValue,
/// just 0.. (2 * Int32.MaxValue) - 1 .
/// </summary>
/// <returns></returns>
private double InternalSampleLargeRange()
{
double result;
do
{
result = InternalSample();
} while (result == Int32.MaxValue);
result += Int32.MaxValue;
return result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Xml.Linq;
namespace DocumentFormat.OpenXml.Linq
{
/// <summary>
/// Declares XNamespace and XName fields for the xmlns:inkml="http://www.w3.org/2003/InkML" namespace.
/// </summary>
public static class INKML
{
/// <summary>
/// Defines the XML namespace associated with the inkml prefix.
/// </summary>
public static readonly XNamespace inkml = "http://www.w3.org/2003/InkML";
/// <summary>
/// Represents the inkml:activeArea XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="inkSource" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.height" />, <see cref="NoNamespace.size" />, <see cref="NoNamespace.units" />, <see cref="NoNamespace.width" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ActiveArea.</description></item>
/// </list>
/// </remarks>
public static readonly XName activeArea = inkml + "activeArea";
/// <summary>
/// Represents the inkml:annotation XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="brush" />, <see cref="brushProperty" />, <see cref="ink" />, <see cref="traceGroup" />, <see cref="traceView" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.encoding" />, <see cref="NoNamespace.type" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Annotation.</description></item>
/// </list>
/// </remarks>
public static readonly XName annotation = inkml + "annotation";
/// <summary>
/// Represents the inkml:annotationXML XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="brush" />, <see cref="brushProperty" />, <see cref="ink" />, <see cref="traceGroup" />, <see cref="traceView" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="EMMA.emma_" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.encoding" />, <see cref="NoNamespace.href" />, <see cref="NoNamespace.type" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: AnnotationXml.</description></item>
/// </list>
/// </remarks>
public static readonly XName annotationXML = inkml + "annotationXML";
/// <summary>
/// Represents the inkml:bind XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="mapping" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.column" />, <see cref="NoNamespace.source" />, <see cref="NoNamespace.target" />, <see cref="NoNamespace.variable" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Bind.</description></item>
/// </list>
/// </remarks>
public static readonly XName bind = inkml + "bind";
/// <summary>
/// Represents the inkml:brush XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="context" />, <see cref="definitions" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="annotation" />, <see cref="annotationXML" />, <see cref="brushProperty" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.brushRef" />, <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Brush.</description></item>
/// </list>
/// </remarks>
public static readonly XName brush = inkml + "brush";
/// <summary>
/// Represents the inkml:brushProperty XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="brush" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="annotation" />, <see cref="annotationXML" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.name" />, <see cref="NoNamespace.units" />, <see cref="NoNamespace.value" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: BrushProperty.</description></item>
/// </list>
/// </remarks>
public static readonly XName brushProperty = inkml + "brushProperty";
/// <summary>
/// Represents the inkml:canvas XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="context" />, <see cref="definitions" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="traceFormat" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.traceFormatRef" />, <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Canvas.</description></item>
/// </list>
/// </remarks>
public static readonly XName canvas = inkml + "canvas";
/// <summary>
/// Represents the inkml:canvasTransform XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="context" />, <see cref="definitions" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="mapping" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.invertible" />, <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: CanvasTransform.</description></item>
/// </list>
/// </remarks>
public static readonly XName canvasTransform = inkml + "canvasTransform";
/// <summary>
/// Represents the inkml:channel XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="intermittentChannels" />, <see cref="traceFormat" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="mapping" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.@default" />, <see cref="NoNamespace.max" />, <see cref="NoNamespace.min" />, <see cref="NoNamespace.name" />, <see cref="NoNamespace.orientation" />, <see cref="NoNamespace.respectTo" />, <see cref="NoNamespace.type" />, <see cref="NoNamespace.units" />, <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Channel.</description></item>
/// </list>
/// </remarks>
public static readonly XName channel = inkml + "channel";
/// <summary>
/// Represents the inkml:channelProperties XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="inkSource" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="channelProperty" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ChannelProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName channelProperties = inkml + "channelProperties";
/// <summary>
/// Represents the inkml:channelProperty XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="channelProperties" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.channel" />, <see cref="NoNamespace.name" />, <see cref="NoNamespace.units" />, <see cref="NoNamespace.value" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ChannelProperty.</description></item>
/// </list>
/// </remarks>
public static readonly XName channelProperty = inkml + "channelProperty";
/// <summary>
/// Represents the inkml:context XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="definitions" />, <see cref="ink" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="brush" />, <see cref="canvas" />, <see cref="canvasTransform" />, <see cref="inkSource" />, <see cref="timestamp" />, <see cref="traceFormat" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.brushRef" />, <see cref="NoNamespace.canvasRef" />, <see cref="NoNamespace.canvasTransformRef" />, <see cref="NoNamespace.contextRef" />, <see cref="NoNamespace.inkSourceRef" />, <see cref="NoNamespace.timestampRef" />, <see cref="NoNamespace.traceFormatRef" />, <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Context.</description></item>
/// </list>
/// </remarks>
public static readonly XName context = inkml + "context";
/// <summary>
/// Represents the inkml:definitions XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="ink" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="brush" />, <see cref="canvas" />, <see cref="canvasTransform" />, <see cref="context" />, <see cref="inkSource" />, <see cref="mapping" />, <see cref="timestamp" />, <see cref="trace" />, <see cref="traceFormat" />, <see cref="traceGroup" />, <see cref="traceView" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Definitions.</description></item>
/// </list>
/// </remarks>
public static readonly XName definitions = inkml + "definitions";
/// <summary>
/// Represents the inkml:ink XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following child XML elements: <see cref="annotation" />, <see cref="annotationXML" />, <see cref="context" />, <see cref="definitions" />, <see cref="trace" />, <see cref="traceGroup" />, <see cref="traceView" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.documentID" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Ink.</description></item>
/// </list>
/// </remarks>
public static readonly XName ink = inkml + "ink";
/// <summary>
/// Represents the inkml:inkSource XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="context" />, <see cref="definitions" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="activeArea" />, <see cref="channelProperties" />, <see cref="latency" />, <see cref="sampleRate" />, <see cref="srcProperty" />, <see cref="traceFormat" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.description" />, <see cref="NoNamespace.manufacturer" />, <see cref="NoNamespace.model" />, <see cref="NoNamespace.serialNo" />, <see cref="NoNamespace.specificationRef" />, <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: InkSource.</description></item>
/// </list>
/// </remarks>
public static readonly XName inkSource = inkml + "inkSource";
/// <summary>
/// Represents the inkml:intermittentChannels XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="traceFormat" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="channel" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: IntermittentChannels.</description></item>
/// </list>
/// </remarks>
public static readonly XName intermittentChannels = inkml + "intermittentChannels";
/// <summary>
/// Represents the inkml:latency XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="inkSource" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.value" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Latency.</description></item>
/// </list>
/// </remarks>
public static readonly XName latency = inkml + "latency";
/// <summary>
/// Represents the inkml:mapping XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="canvasTransform" />, <see cref="channel" />, <see cref="definitions" />, <see cref="mapping" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="bind" />, <see cref="mapping" />, <see cref="matrix" />, <see cref="table" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.mappingRef" />, <see cref="NoNamespace.type" />, <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Mapping.</description></item>
/// </list>
/// </remarks>
public static readonly XName mapping = inkml + "mapping";
/// <summary>
/// Represents the inkml:matrix XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="mapping" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Matrix.</description></item>
/// </list>
/// </remarks>
public static readonly XName matrix = inkml + "matrix";
/// <summary>
/// Represents the inkml:sampleRate XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="inkSource" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.uniform" />, <see cref="NoNamespace.value" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: SampleRate.</description></item>
/// </list>
/// </remarks>
public static readonly XName sampleRate = inkml + "sampleRate";
/// <summary>
/// Represents the inkml:srcProperty XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="inkSource" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.name" />, <see cref="NoNamespace.units" />, <see cref="NoNamespace.value" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: SourceProperty.</description></item>
/// </list>
/// </remarks>
public static readonly XName srcProperty = inkml + "srcProperty";
/// <summary>
/// Represents the inkml:table XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="mapping" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.apply" />, <see cref="NoNamespace.interpolation" />, <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Table.</description></item>
/// </list>
/// </remarks>
public static readonly XName table = inkml + "table";
/// <summary>
/// Represents the inkml:timestamp XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="context" />, <see cref="definitions" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.time" />, <see cref="NoNamespace.timeOffset" />, <see cref="NoNamespace.timestampRef" />, <see cref="NoNamespace.timeString" />, <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Timestamp.</description></item>
/// </list>
/// </remarks>
public static readonly XName timestamp = inkml + "timestamp";
/// <summary>
/// Represents the inkml:trace XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="definitions" />, <see cref="ink" />, <see cref="traceGroup" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.brushRef" />, <see cref="NoNamespace.contextRef" />, <see cref="NoNamespace.continuation" />, <see cref="NoNamespace.duration" />, <see cref="NoNamespace.priorRef" />, <see cref="NoNamespace.timeOffset" />, <see cref="NoNamespace.type" />, <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Trace.</description></item>
/// </list>
/// </remarks>
public static readonly XName trace = inkml + "trace";
/// <summary>
/// Represents the inkml:traceFormat XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="canvas" />, <see cref="context" />, <see cref="definitions" />, <see cref="inkSource" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="channel" />, <see cref="intermittentChannels" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TraceFormat.</description></item>
/// </list>
/// </remarks>
public static readonly XName traceFormat = inkml + "traceFormat";
/// <summary>
/// Represents the inkml:traceGroup XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="definitions" />, <see cref="ink" />, <see cref="traceGroup" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="annotation" />, <see cref="annotationXML" />, <see cref="trace" />, <see cref="traceGroup" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.brushRef" />, <see cref="NoNamespace.contextRef" />, <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TraceGroup.</description></item>
/// </list>
/// </remarks>
public static readonly XName traceGroup = inkml + "traceGroup";
/// <summary>
/// Represents the inkml:traceView XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="definitions" />, <see cref="ink" />, <see cref="traceView" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="annotation" />, <see cref="annotationXML" />, <see cref="traceView" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.contextRef" />, <see cref="NoNamespace.from" />, <see cref="NoNamespace.to" />, <see cref="NoNamespace.traceDataRef" />, <see cref="XML.id" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TraceView.</description></item>
/// </list>
/// </remarks>
public static readonly XName traceView = inkml + "traceView";
}
}
| |
//
// CVDisplayLink.cs: Implements the managed CVDisplayLink
//
// Authors: Kenneth J. Pouncey
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
using MonoMac.OpenGL;
namespace MonoMac.CoreVideo {
public class CVDisplayLink : INativeObject, IDisposable {
internal IntPtr handle;
GCHandle callbackHandle;
public CVDisplayLink (IntPtr handle)
{
if (handle == IntPtr.Zero)
throw new Exception ("Invalid parameters to display link creation");
CVDisplayLinkRetain (handle);
this.handle = handle;
}
[Preserve (Conditional=true)]
internal CVDisplayLink (IntPtr handle, bool owns)
{
if (!owns)
CVDisplayLinkRetain (handle);
this.handle = handle;
}
~CVDisplayLink ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
[DllImport (Constants.CoreVideoLibrary)]
extern static void CVDisplayLinkRetain (IntPtr handle);
[DllImport (Constants.CoreVideoLibrary)]
extern static void CVDisplayLinkRelease (IntPtr handle);
protected virtual void Dispose (bool disposing)
{
if (callbackHandle.IsAllocated) {
callbackHandle.Free();
}
if (handle != IntPtr.Zero){
CVDisplayLinkRelease (handle);
handle = IntPtr.Zero;
}
}
[DllImport (Constants.CoreVideoLibrary)]
extern static CVReturn CVDisplayLinkCreateWithActiveCGDisplays (IntPtr displayLinkOut);
public CVDisplayLink ()
{
IntPtr displayLinkOut = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (IntPtr)));
try {
CVReturn ret = CVDisplayLinkCreateWithActiveCGDisplays (displayLinkOut);
if (ret != CVReturn.Success)
throw new Exception ("CVDisplayLink returned: " + ret);
this.handle = Marshal.ReadIntPtr (displayLinkOut);
} finally {
Marshal.FreeHGlobal (displayLinkOut);
}
}
[DllImport (Constants.CoreVideoLibrary)]
extern static CVReturn CVDisplayLinkSetCurrentCGDisplay (IntPtr displayLink, int displayId);
public CVReturn SetCurrentDisplay (int displayId)
{
return CVDisplayLinkSetCurrentCGDisplay (this.handle, displayId);
}
[DllImport (Constants.CoreVideoLibrary)]
extern static CVReturn CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext (IntPtr displayLink, IntPtr cglContext, IntPtr cglPixelFormat);
public CVReturn SetCurrentDisplay (CGLContext cglContext, CGLPixelFormat cglPixelFormat)
{
return CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext (this.handle, cglContext.Handle, cglPixelFormat.Handle);
}
[DllImport (Constants.CoreVideoLibrary)]
extern static int CVDisplayLinkGetCurrentCGDisplay (IntPtr displayLink);
public int GetCurrentDisplay ()
{
return CVDisplayLinkGetCurrentCGDisplay (this.handle);
}
[DllImport (Constants.CoreVideoLibrary)]
extern static CVReturn CVDisplayLinkStart (IntPtr displayLink);
public CVReturn Start ()
{
return CVDisplayLinkStart (this.handle);
}
[DllImport (Constants.CoreVideoLibrary)]
extern static CVReturn CVDisplayLinkStop (IntPtr displayLink);
public CVReturn Stop ()
{
return CVDisplayLinkStop (this.handle);
}
[DllImport (Constants.CoreVideoLibrary)]
extern static CVTime CVDisplayLinkGetNominalOutputVideoRefreshPeriod (IntPtr displayLink);
public CVTime NominalOutputVideoRefreshPeriod {
get {
return CVDisplayLinkGetNominalOutputVideoRefreshPeriod (this.handle);
}
}
[DllImport (Constants.CoreVideoLibrary)]
extern static CVTime CVDisplayLinkGetOutputVideoLatency (IntPtr displayLink);
public CVTime OutputVideoLatency {
get {
return CVDisplayLinkGetOutputVideoLatency (this.handle);
}
}
[DllImport (Constants.CoreVideoLibrary)]
extern static double CVDisplayLinkGetActualOutputVideoRefreshPeriod (IntPtr displayLink);
public double ActualOutputVideoRefreshPeriod {
get {
return CVDisplayLinkGetActualOutputVideoRefreshPeriod (this.handle);
}
}
[DllImport (Constants.CoreVideoLibrary)]
extern static bool CVDisplayLinkIsRunning (IntPtr displayLink);
public bool IsRunning {
get {
return CVDisplayLinkIsRunning (this.handle);
}
}
[DllImport (Constants.CoreVideoLibrary)]
extern static CVReturn CVDisplayLinkGetCurrentTime (IntPtr displayLink, out CVTimeStamp outTime);
public CVReturn GetCurrentTime (out CVTimeStamp outTime)
{
CVReturn ret = CVDisplayLinkGetCurrentTime (this.Handle, out outTime);
return ret;
}
public delegate CVReturn DisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut);
delegate CVReturn CVDisplayLinkOutputCallback (IntPtr displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut, IntPtr displayLinkContext);
static CVDisplayLinkOutputCallback static_OutputCallback = new CVDisplayLinkOutputCallback (OutputCallback);
#if !MONOMAC
[MonoPInvokeCallback (typeof (CVDisplayLinkOutputCallback))]
#endif
static CVReturn OutputCallback (IntPtr displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut, IntPtr displayLinkContext)
{
GCHandle callbackHandle = GCHandle.FromIntPtr (displayLinkContext);
DisplayLinkOutputCallback func = (DisplayLinkOutputCallback) callbackHandle.Target;
CVDisplayLink delegateDisplayLink = new CVDisplayLink(displayLink, false);
return func (delegateDisplayLink, ref inNow, ref inOutputTime, flagsIn, ref flagsOut);
}
[DllImport (Constants.CoreVideoLibrary)]
extern static CVReturn CVDisplayLinkSetOutputCallback (IntPtr displayLink, CVDisplayLinkOutputCallback function, IntPtr userInfo);
public CVReturn SetOutputCallback (DisplayLinkOutputCallback callback)
{
callbackHandle = GCHandle.Alloc (callback);
CVReturn ret = CVDisplayLinkSetOutputCallback (this.Handle, static_OutputCallback, GCHandle.ToIntPtr (callbackHandle));
return ret;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.ApigeeConnect.V1
{
/// <summary>Settings for <see cref="ConnectionServiceClient"/> instances.</summary>
public sealed partial class ConnectionServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="ConnectionServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="ConnectionServiceSettings"/>.</returns>
public static ConnectionServiceSettings GetDefault() => new ConnectionServiceSettings();
/// <summary>Constructs a new <see cref="ConnectionServiceSettings"/> object with default settings.</summary>
public ConnectionServiceSettings()
{
}
private ConnectionServiceSettings(ConnectionServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListConnectionsSettings = existing.ListConnectionsSettings;
OnCopy(existing);
}
partial void OnCopy(ConnectionServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ConnectionServiceClient.ListConnections</c> and <c>ConnectionServiceClient.ListConnectionsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 1000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.Unknown"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListConnectionsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(1000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.Unknown)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="ConnectionServiceSettings"/> object.</returns>
public ConnectionServiceSettings Clone() => new ConnectionServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="ConnectionServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class ConnectionServiceClientBuilder : gaxgrpc::ClientBuilderBase<ConnectionServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ConnectionServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ConnectionServiceClientBuilder()
{
UseJwtAccessWithScopes = ConnectionServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ConnectionServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ConnectionServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override ConnectionServiceClient Build()
{
ConnectionServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ConnectionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ConnectionServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ConnectionServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ConnectionServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<ConnectionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ConnectionServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ConnectionServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => ConnectionServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ConnectionServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>ConnectionService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service Interface for the Apigee Connect connection management APIs.
/// </remarks>
public abstract partial class ConnectionServiceClient
{
/// <summary>
/// The default endpoint for the ConnectionService service, which is a host of "apigeeconnect.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "apigeeconnect.googleapis.com:443";
/// <summary>The default ConnectionService scopes.</summary>
/// <remarks>
/// The default ConnectionService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="ConnectionServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="ConnectionServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ConnectionServiceClient"/>.</returns>
public static stt::Task<ConnectionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ConnectionServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ConnectionServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="ConnectionServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ConnectionServiceClient"/>.</returns>
public static ConnectionServiceClient Create() => new ConnectionServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ConnectionServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="ConnectionServiceSettings"/>.</param>
/// <returns>The created <see cref="ConnectionServiceClient"/>.</returns>
internal static ConnectionServiceClient Create(grpccore::CallInvoker callInvoker, ConnectionServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ConnectionService.ConnectionServiceClient grpcClient = new ConnectionService.ConnectionServiceClient(callInvoker);
return new ConnectionServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC ConnectionService client</summary>
public virtual ConnectionService.ConnectionServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Lists connections that are currently active for the given Apigee Connect
/// endpoint.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Connection"/> resources.</returns>
public virtual gax::PagedEnumerable<ListConnectionsResponse, Connection> ListConnections(ListConnectionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists connections that are currently active for the given Apigee Connect
/// endpoint.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Connection"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListConnectionsResponse, Connection> ListConnectionsAsync(ListConnectionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists connections that are currently active for the given Apigee Connect
/// endpoint.
/// </summary>
/// <param name="parent">
/// Required. Parent name of the form:
/// `projects/{project_number or project_id}/endpoints/{endpoint}`.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Connection"/> resources.</returns>
public virtual gax::PagedEnumerable<ListConnectionsResponse, Connection> ListConnections(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListConnections(new ListConnectionsRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists connections that are currently active for the given Apigee Connect
/// endpoint.
/// </summary>
/// <param name="parent">
/// Required. Parent name of the form:
/// `projects/{project_number or project_id}/endpoints/{endpoint}`.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Connection"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListConnectionsResponse, Connection> ListConnectionsAsync(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListConnectionsAsync(new ListConnectionsRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists connections that are currently active for the given Apigee Connect
/// endpoint.
/// </summary>
/// <param name="parent">
/// Required. Parent name of the form:
/// `projects/{project_number or project_id}/endpoints/{endpoint}`.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Connection"/> resources.</returns>
public virtual gax::PagedEnumerable<ListConnectionsResponse, Connection> ListConnections(EndpointName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListConnections(new ListConnectionsRequest
{
ParentAsEndpointName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists connections that are currently active for the given Apigee Connect
/// endpoint.
/// </summary>
/// <param name="parent">
/// Required. Parent name of the form:
/// `projects/{project_number or project_id}/endpoints/{endpoint}`.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Connection"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListConnectionsResponse, Connection> ListConnectionsAsync(EndpointName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListConnectionsAsync(new ListConnectionsRequest
{
ParentAsEndpointName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
}
/// <summary>ConnectionService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service Interface for the Apigee Connect connection management APIs.
/// </remarks>
public sealed partial class ConnectionServiceClientImpl : ConnectionServiceClient
{
private readonly gaxgrpc::ApiCall<ListConnectionsRequest, ListConnectionsResponse> _callListConnections;
/// <summary>
/// Constructs a client wrapper for the ConnectionService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ConnectionServiceSettings"/> used within this client.</param>
public ConnectionServiceClientImpl(ConnectionService.ConnectionServiceClient grpcClient, ConnectionServiceSettings settings)
{
GrpcClient = grpcClient;
ConnectionServiceSettings effectiveSettings = settings ?? ConnectionServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callListConnections = clientHelper.BuildApiCall<ListConnectionsRequest, ListConnectionsResponse>(grpcClient.ListConnectionsAsync, grpcClient.ListConnections, effectiveSettings.ListConnectionsSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callListConnections);
Modify_ListConnectionsApiCall(ref _callListConnections);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ListConnectionsApiCall(ref gaxgrpc::ApiCall<ListConnectionsRequest, ListConnectionsResponse> call);
partial void OnConstruction(ConnectionService.ConnectionServiceClient grpcClient, ConnectionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ConnectionService client</summary>
public override ConnectionService.ConnectionServiceClient GrpcClient { get; }
partial void Modify_ListConnectionsRequest(ref ListConnectionsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Lists connections that are currently active for the given Apigee Connect
/// endpoint.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Connection"/> resources.</returns>
public override gax::PagedEnumerable<ListConnectionsResponse, Connection> ListConnections(ListConnectionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListConnectionsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListConnectionsRequest, ListConnectionsResponse, Connection>(_callListConnections, request, callSettings);
}
/// <summary>
/// Lists connections that are currently active for the given Apigee Connect
/// endpoint.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Connection"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListConnectionsResponse, Connection> ListConnectionsAsync(ListConnectionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListConnectionsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListConnectionsRequest, ListConnectionsResponse, Connection>(_callListConnections, request, callSettings);
}
}
public partial class ListConnectionsRequest : gaxgrpc::IPageRequest
{
}
public partial class ListConnectionsResponse : gaxgrpc::IPageResponse<Connection>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Connection> GetEnumerator() => Connections.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
using VB = Microsoft.VisualBasic;
using Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
internal partial class frmCustomerTransaction : System.Windows.Forms.Form
{
private ADODB.Recordset withEventsField_adoPrimaryRS;
public ADODB.Recordset adoPrimaryRS {
get { return withEventsField_adoPrimaryRS; }
set {
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord;
}
withEventsField_adoPrimaryRS = value;
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord;
}
}
}
bool mbChangedByCode;
int mvBookMark;
bool mbEditFlag;
bool mbAddNewFlag;
bool mbDataChanged;
List<TextBox> txtFields = new List<TextBox>();
List<TextBox> txtFloat = new List<TextBox>();
int gID;
short gSection;
const short sec_Payment = 0;
const short sec_Debit = 1;
const short sec_Credit = 2;
private void loadLanguage()
{
//frmCustomerTransaction= No Code [Customer Transaction]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmCustomerTransaction.Caption = rsLang("LanguageLayoutLnk_Description"): frmCustomerTransaction.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074;
//Undo|Checked
if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1282;
//Statement|Checked
if (modRecordSet.rsLang.RecordCount){cmdStatement.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdStatement.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1010;
//General|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1284;
//Invoice Name|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1285;
//Department|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1286;
//Responsible Person Name|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_4.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_4.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1287;
//Surname|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_5.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_5.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1288;
//Telephone|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_8.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_8.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1289;
//Fax|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_9.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_9.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1290;
//Email|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_10.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_10.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1291;
//Physical Address|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_6.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.Filter = "LanguageLayoutLnk_LanguageID=" + 1292;
//Postal Address|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_7.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_7.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.Filter = "LanguageLayoutLnk_LanguageID=" + 1319;
//Financials|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.Filter = "LanguageLayoutLnk_LanguageID=" + 1293;
//Credit Limit|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_12.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_12.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.Filter = "LanguageLayoutLnk_LanguageID=" + 1295;
//Current|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_13.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_13.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.Filter = "LanguageLayoutLnk_LanguageID=" + 1297;
//60 Days|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_15.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_15.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.Filter = "LanguageLayoutLnk_LanguageID=" + 1299;
//120 Days|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_17.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_17.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.Filter = "LanguageLayoutLnk_LanguageID=" + 1296;
//30 Days|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_14.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_14.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.Filter = "LanguageLayoutLnk_LanguageID=" + 1298;
//90 Days|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_16.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_16.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.Filter = "LanguageLayoutLnk_LanguageID=" + 1300;
//150 Days|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_18.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_18.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//_lbl_2 = No Code [Transaction]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lbl_2.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.Filter = "LanguageLayoutLnk_LanguageID=" + 1327;
//Narrative|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1328;
//Notes|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1329;
//Amount|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_11.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_11.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1330;
//Settlement|Checked
if (modRecordSet.rsLang.RecordCount){lblSett.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;lblSett.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1331;
//Settlement|Checked
if (modRecordSet.rsLang.RecordCount){Label2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1332;
//Process|Checked
if (modRecordSet.rsLang.RecordCount){cmdProcess.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdProcess.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmCustomerTransaction.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void buildDataControls()
{
//doDataControl(Me.cmbChannel, "SELECT ChannelID, Channel_Name FROM Channel ORDER BY ChannelID", "Customer_ChannelID", "ChannelID", "Channel_Name")
}
private void doDataControl(ref myDataGridView dataControl, ref string sql, ref string DataField, ref string boundColumn, ref string listField)
{
//Dim rs As ADODB.Recordset
// rs = getRS(sql)
//UPGRADE_WARNING: Couldn't resolve default property of object dataControl.DataSource. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
// dataControl.DataSource = rs
//UPGRADE_ISSUE: Control method dataControl.DataSource was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
// dataControl.DataSource = adoPrimaryRS
//UPGRADE_ISSUE: Control method dataControl.DataField was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
// dataControl.DataField = DataField
//UPGRADE_WARNING: Couldn't resolve default property of object dataControl.boundColumn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
// dataControl.boundColumn = boundColumn
//UPGRADE_WARNING: Couldn't resolve default property of object dataControl.listField. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
// dataControl.listField = listField
}
public void loadItem(ref int id, ref short section)
{
System.Windows.Forms.TextBox oText = null;
System.Windows.Forms.CheckBox oCheck = null;
// ERROR: Not supported in C#: OnErrorStatement
this.lblSett.Visible = true;
this.txtSettlement.Visible = true;
if (id) {
adoPrimaryRS = modRecordSet.getRS(ref "select * from Customer WHERE CustomerID = " + id);
} else {
this.Close();
return;
}
gSection = section;
switch (gSection) {
case sec_Payment:
this.Text = "Account Payment";
break;
case sec_Debit:
this.lblSett.Visible = false;
this.txtSettlement.Visible = false;
this.Text = "Debit Journal-Increase amount owing";
break;
case sec_Credit:
this.lblSett.Visible = false;
this.txtSettlement.Visible = false;
this.Text = "Credit Journal-Decrease amount owing";
break;
default:
this.Close();
return;
break;
}
_lbl_2.Text = "&3. Transaction (" + this.Text + ")";
// If adoPrimaryRS.BOF Or adoPrimaryRS.EOF Then
// Else
BindingSource bind = new BindingSource();
bind.DataSource = adoPrimaryRS;
foreach (TextBox oText_loopVariable in this.txtFields) {
oText = oText_loopVariable;
oText.DataBindings.Add(bind.DataSource);
oText.MaxLength = adoPrimaryRS.Fields(oText.DataBindings).DefinedSize;
}
// For Each oText In Me.txtInteger
// Set oText.DataBindings.Add(adoPrimaryRS)
// txtInteger_LostFocus oText.Index
// Next
foreach (TextBox oText_loopVariable in this.txtFloat) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
if (string.IsNullOrEmpty(oText.Text))
oText.Text = "0";
oText.Text = Convert.ToString(Convert.ToDouble(oText.Text) * 100);
oText.Leave += txtFloat_Leave;
//txtFloat_Leave(txtFloat.Item((oText.TabIndex)), New System.EventArgs())
}
//Bind the check boxes to the data provider
// For Each oCheck In Me.chkFields
// Set oCheck.DataBindings.Add(adoPrimaryRS)
// Next
buildDataControls();
mbDataChanged = false;
loadLanguage();
ShowDialog();
// End If
}
private void cmdProcess_Click(System.Object eventSender, System.EventArgs eventArgs)
{
decimal amount = default(decimal);
string sql = null;
string sql1 = null;
ADODB.Recordset rs = default(ADODB.Recordset);
string id = null;
decimal days120 = default(decimal);
decimal days60 = default(decimal);
decimal current = default(decimal);
decimal days30 = default(decimal);
decimal days90 = default(decimal);
decimal days150 = default(decimal);
System.Windows.Forms.Application.DoEvents();
if (string.IsNullOrEmpty(txtNarrative.Text)) {
Interaction.MsgBox("Narrative is a mandarory field", MsgBoxStyle.Exclamation, this.Text);
txtNarrative.Focus();
return;
}
if (Convert.ToDecimal(txtAmount.Text) == 0) {
Interaction.MsgBox("Amount is a mandarory field", MsgBoxStyle.Exclamation, this.Text);
txtAmount.Focus();
return;
}
sql = "INSERT INTO CustomerTransaction ( CustomerTransaction_CustomerID, CustomerTransaction_TransactionTypeID, CustomerTransaction_DayEndID, CustomerTransaction_MonthEndID, CustomerTransaction_ReferenceID, CustomerTransaction_Date, CustomerTransaction_Description, CustomerTransaction_Amount, CustomerTransaction_Reference, CustomerTransaction_PersonName )";
switch (gSection) {
case sec_Payment:
sql = sql + "SELECT " + adoPrimaryRS.Fields("CustomerID").Value + " AS Customer, 3 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(this.txtNotes.Text, "'", "''") + "' AS description, " + Convert.ToDecimal(0 - Convert.ToDecimal(this.txtAmount.Text)) + " AS amount, '" + Strings.Replace(this.txtNarrative.Text, "'", "''") + "' AS reference, 'System' AS person FROM Company;";
break;
case sec_Debit:
sql = sql + "SELECT " + adoPrimaryRS.Fields("CustomerID").Value + " AS Customer, 4 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(this.txtNotes.Text, "'", "''") + "' AS description, " + Convert.ToDecimal(this.txtAmount.Text) + " AS amount, '" + Strings.Replace(this.txtNarrative.Text, "'", "''") + "' AS reference, 'System' AS person FROM Company;";
break;
case sec_Credit:
sql = sql + "SELECT " + adoPrimaryRS.Fields("CustomerID").Value + " AS Customer, 5 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(this.txtNotes.Text, "'", "''") + "' AS description, " + Convert.ToDecimal(0 - Convert.ToDecimal(this.txtAmount.Text)) + " AS amount, '" + Strings.Replace(this.txtNarrative.Text, "'", "''") + "' AS reference, 'System' AS person FROM Company;";
break;
}
modRecordSet.cnnDB.Execute(sql);
rs = modRecordSet.getRS(ref "SELECT MAX(CustomerTransactionID) AS id From CustomerTransaction");
if (rs.BOF | rs.EOF) {
} else {
id = rs.Fields("id").Value;
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_Current = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_Current) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_30Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_30Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_60Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_60Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_90Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_90Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_120Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_120Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_150Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_150Days) Is Null));");
rs = modRecordSet.getRS(ref "SELECT CustomerTransaction.CustomerTransaction_CustomerID, CustomerTransaction.CustomerTransaction_Amount, Customer.Customer_Current, Customer.Customer_30Days, Customer.Customer_60Days, Customer.Customer_90Days, Customer.Customer_120Days, Customer.Customer_150Days FROM Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID Where (((CustomerTransaction.CustomerTransactionID) = " + id + "));");
amount = rs.Fields("CustomerTransaction_Amount").Value;
current = rs.Fields("Customer_Current").Value;
days30 = rs.Fields("Customer_30Days").Value;
days60 = rs.Fields("Customer_60Days").Value;
days90 = rs.Fields("Customer_90Days").Value;
days120 = rs.Fields("Customer_120Days").Value;
days150 = rs.Fields("Customer_150Days").Value;
if (amount < 0) {
days150 = days150 + amount;
if ((days150 < 0)) {
amount = days150;
days150 = 0;
} else {
amount = 0;
}
days120 = days120 + amount;
if ((days120 < 0)) {
amount = days120;
days120 = 0;
} else {
amount = 0;
}
days90 = days90 + amount;
if ((days90 < 0)) {
amount = days90;
days90 = 0;
} else {
amount = 0;
}
days60 = days60 + amount;
if ((days60 < 0)) {
amount = days60;
days60 = 0;
} else {
amount = 0;
}
days30 = days30 + amount;
if ((days30 < 0)) {
amount = days30;
days30 = 0;
} else {
amount = 0;
}
}
current = current + amount;
modRecordSet.cnnDB.Execute("UPDATE Customer SET Customer.Customer_Current = " + current + ", Customer.Customer_30Days = " + days30 + ", Customer.Customer_60Days = " + days60 + ", Customer.Customer_90Days = " + days90 + ", Customer.Customer_120Days = " + days120 + ", Customer.Customer_150Days = 0" + days150 + " WHERE (((Customer.CustomerID)=" + rs.Fields("CustomerTransaction_CustomerID").Value + "));");
}
if (Conversion.Val(txtSettlement.Text) > 0) {
sql1 = "INSERT INTO CustomerTransaction ( CustomerTransaction_CustomerID, CustomerTransaction_TransactionTypeID, CustomerTransaction_DayEndID, CustomerTransaction_MonthEndID, CustomerTransaction_ReferenceID, CustomerTransaction_Date, CustomerTransaction_Description, CustomerTransaction_Amount, CustomerTransaction_Reference, CustomerTransaction_PersonName )";
sql1 = sql1 + "SELECT " + adoPrimaryRS.Fields("CustomerID").Value + " AS Customer, 8 AS [type], Company.Company_DayEndID, Company.Company_MonthEndID, 0 AS referenceID, Now() AS [Date], '" + Strings.Replace(this.txtNotes.Text, "'", "''") + "' AS description, " + Convert.ToDecimal(0 - Convert.ToDecimal(this.txtSettlement.Text)) + " AS amount,'" + Strings.Replace(this.txtNarrative.Text, "'", "''") + "', 'System' AS person FROM Company;";
modRecordSet.cnnDB.Execute(sql1);
rs = modRecordSet.getRS(ref "SELECT MAX(CustomerTransactionID) AS id From CustomerTransaction");
if (rs.BOF | rs.EOF) {
} else {
id = rs.Fields("id").Value;
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_Current = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_Current) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_30Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_30Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_60Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_60Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_90Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_90Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_120Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_120Days) Is Null));");
modRecordSet.cnnDB.Execute("UPDATE Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID SET Customer.Customer_150Days = 0 WHERE (((CustomerTransaction.CustomerTransactionID)=" + id + ") AND ((Customer.Customer_150Days) Is Null));");
rs = modRecordSet.getRS(ref "SELECT CustomerTransaction.CustomerTransaction_CustomerID, CustomerTransaction.CustomerTransaction_Amount, Customer.Customer_Current, Customer.Customer_30Days, Customer.Customer_60Days, Customer.Customer_90Days, Customer.Customer_120Days, Customer.Customer_150Days FROM Customer INNER JOIN CustomerTransaction ON Customer.CustomerID = CustomerTransaction.CustomerTransaction_CustomerID Where (((CustomerTransaction.CustomerTransactionID) = " + id + "));");
amount = rs.Fields("CustomerTransaction_Amount").Value;
current = rs.Fields("Customer_Current").Value;
days30 = rs.Fields("Customer_30Days").Value;
days60 = rs.Fields("Customer_60Days").Value;
days90 = rs.Fields("Customer_90Days").Value;
days120 = rs.Fields("Customer_120Days").Value;
days150 = rs.Fields("Customer_150Days").Value;
if (amount < 0) {
days150 = days150 + amount;
if ((days150 < 0)) {
amount = days150;
days150 = 0;
} else {
amount = 0;
}
days120 = days120 + amount;
if ((days120 < 0)) {
amount = days120;
days120 = 0;
} else {
amount = 0;
}
days90 = days90 + amount;
if ((days90 < 0)) {
amount = days90;
days90 = 0;
} else {
amount = 0;
}
days60 = days60 + amount;
if ((days60 < 0)) {
amount = days60;
days60 = 0;
} else {
amount = 0;
}
days30 = days30 + amount;
if ((days30 < 0)) {
amount = days30;
days30 = 0;
} else {
amount = 0;
}
}
//current = amount
current = current + amount;
modRecordSet.cnnDB.Execute("UPDATE Customer SET Customer.Customer_Current = " + current + ", Customer.Customer_30Days = " + days30 + ", Customer.Customer_60Days = " + days60 + ", Customer.Customer_90Days = " + days90 + ", Customer.Customer_120Days = " + days120 + ", Customer.Customer_150Days = 0" + days150 + " WHERE (((Customer.CustomerID)=" + rs.Fields("CustomerTransaction_CustomerID").Value + "));");
}
}
cmdStatement_Click(cmdStatement, new System.EventArgs());
this.Close();
}
private void cmdProcess_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
txtTotalAmount.Text = Strings.FormatNumber(Convert.ToDecimal(txtAmount.Text) + Convert.ToDecimal(txtSettlement.Text), 2);
}
private void cmdStatement_Click(System.Object eventSender, System.EventArgs eventArgs)
{
modApplication.report_CustomerStatement(ref adoPrimaryRS.Fields("CustomerID").Value);
}
private void frmCustomerTransaction_Resize(System.Object eventSender, System.EventArgs eventArgs)
{
System.Windows.Forms.Button cmdLast = new System.Windows.Forms.Button();
System.Windows.Forms.Button cmdNext = new System.Windows.Forms.Button();
System.Windows.Forms.Label lblStatus = new System.Windows.Forms.Label();
// ERROR: Not supported in C#: OnErrorStatement
lblStatus.Width = sizeConvertors.twipsToPixels(this.Width, true) - 1500;
cmdNext.Left = lblStatus.Width + 700;
cmdLast.Left = cmdNext.Left + 340;
}
private void frmCustomerTransaction_KeyDown(System.Object eventSender, System.Windows.Forms.KeyEventArgs eventArgs)
{
short KeyCode = eventArgs.KeyCode;
short Shift = eventArgs.KeyData / 0x10000;
if (mbEditFlag | mbAddNewFlag)
return;
switch (KeyCode) {
case System.Windows.Forms.Keys.Escape:
KeyCode = 0;
System.Windows.Forms.Application.DoEvents();
adoPrimaryRS.Move(0);
cmdClose_Click(cmdClose, new System.EventArgs());
break;
}
}
private void frmCustomerTransaction_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
}
private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This will display the current record position for this recordset
}
private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This is where you put validation code
//This event gets called when the following actions occur
bool bCancel = false;
switch (adReason) {
case ADODB.EventReasonEnum.adRsnAddNew:
break;
case ADODB.EventReasonEnum.adRsnClose:
break;
case ADODB.EventReasonEnum.adRsnDelete:
break;
case ADODB.EventReasonEnum.adRsnFirstChange:
break;
case ADODB.EventReasonEnum.adRsnMove:
break;
case ADODB.EventReasonEnum.adRsnRequery:
break;
case ADODB.EventReasonEnum.adRsnResynch:
break;
case ADODB.EventReasonEnum.adRsnUndoAddNew:
break;
case ADODB.EventReasonEnum.adRsnUndoDelete:
break;
case ADODB.EventReasonEnum.adRsnUndoUpdate:
break;
case ADODB.EventReasonEnum.adRsnUpdate:
break;
}
if (bCancel)
adStatus = ADODB.EventStatusEnum.adStatusCancel;
}
private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs)
{
System.Windows.Forms.TextBox oText = null;
// ERROR: Not supported in C#: OnErrorStatement
if (mbAddNewFlag) {
this.Close();
} else {
mbEditFlag = false;
mbAddNewFlag = false;
adoPrimaryRS.CancelUpdate();
if (mvBookMark > 0) {
adoPrimaryRS.Bookmark = mvBookMark;
} else {
adoPrimaryRS.MoveFirst();
}
foreach (TextBox oText_loopVariable in this.txtFloat) {
oText = oText_loopVariable;
if (string.IsNullOrEmpty(oText.Text))
oText.Text = "0";
oText.Text = oText.Text * 100;
oText.Leave += txtFloat_Leave;
//txtFloat_Leave(txtFloat.Item(oText.TabIndex), New System.EventArgs())
}
mbDataChanged = false;
}
}
private bool update_Renamed()
{
bool functionReturnValue = false;
// ERROR: Not supported in C#: OnErrorStatement
functionReturnValue = true;
return functionReturnValue;
// If _txtFields_2.Text = "" Then
// _txtFields_2.Text = "[Customer]"
// End If
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
if (mbAddNewFlag) {
adoPrimaryRS.MoveLast();
//move to the new record
}
mbEditFlag = false;
mbAddNewFlag = false;
mbDataChanged = false;
return functionReturnValue;
UpdateErr:
Interaction.MsgBox(Err().Description);
functionReturnValue = false;
return functionReturnValue;
}
private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
{
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
if (update_Renamed()) {
this.Close();
}
}
private void txtAmount_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocusNumeric(ref txtAmount);
}
private void txtAmount_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
modUtilities.MyKeyPress(ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtAmount_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyLostFocus(ref txtAmount, ref 2);
}
private void txtFields_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
//Dim Index As Short = txtFields.GetIndex(eventSender)
int t = 0;
TextBox n = new TextBox();
n = (TextBox)eventSender;
t = GetIndex.GetIndexer(ref n, ref txtFields);
modUtilities.MyGotFocus(ref txtFields[t]);
}
private void txtInteger_MyGotFocus(ref short Index)
{
// MyGotFocusNumeric txtInteger(Index)
}
private void txtInteger_KeyPress(ref short Index, ref short KeyAscii)
{
// KeyPress KeyAscii
}
private void txtInteger_MyLostFocus(ref short Index)
{
// LostFocus txtInteger(Index), 0
}
private void txtFloat_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
//Dim Index As Short = txtFloat.GetIndex(eventSender)
int t = 0;
TextBox n = new TextBox();
n = (TextBox)eventSender;
t = GetIndex.GetIndexer(ref n, ref txtFloat);
modUtilities.MyGotFocusNumeric(ref txtFloat[t]);
}
private void txtFloat_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
//Dim Index As Short = txtFloat.GetIndex(eventSender)
modUtilities.MyKeyPress(ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtFloat_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
//Dim Index As Short = txtFloat.GetIndex(eventSender)
int t = 0;
TextBox n = new TextBox();
n = (TextBox)eventSender;
t = GetIndex.GetIndexer(ref n, ref txtFloat);
modUtilities.MyLostFocus(ref txtFloat[t], ref 2);
}
private void txtNarrative_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocus(ref txtNarrative);
}
private void txtNotes_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocus(ref txtNotes);
}
private void txtSettlement_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyGotFocusNumeric(ref txtSettlement);
}
private void txtSettlement_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
modUtilities.MyKeyPress(ref KeyAscii);
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtSettlement_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
modUtilities.MyLostFocus(ref txtSettlement, ref 2);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.FullyQualify;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.FullyQualify
{
public class FullyQualifyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new CSharpFullyQualifyCodeFixProvider());
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions)
=> FlattenActions(actions);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestTypeFromMultipleNamespaces1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|IDictionary|] Method()
{
Foo();
}
}",
@"class Class
{
System.Collections.IDictionary Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestTypeFromMultipleNamespaces2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|IDictionary|] Method()
{
Foo();
}
}",
@"class Class
{
System.Collections.Generic.IDictionary Method()
{
Foo();
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithNoArgs()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|List|] Method()
{
Foo();
}
}",
@"class Class
{
System.Collections.Generic.List Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithCorrectArgs()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|List<int>|] Method()
{
Foo();
}
}",
@"class Class
{
System.Collections.Generic.List<int> Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestSmartTagDisplayText()
{
await TestSmartTagTextAsync(
@"class Class
{
[|List<int>|] Method()
{
Foo();
}
}",
"System.Collections.Generic.List");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericWithWrongArgs()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|List<int, string>|] Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnVar1()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class var { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnVar2()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class Bar { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericInLocalDeclaration()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Foo()
{
[|List<int>|] a = new List<int>();
}
}",
@"class Class
{
void Foo()
{
System.Collections.Generic.List<int> a = new List<int>();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericItemType()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
List<[|Int32|]> l;
}",
@"using System.Collections.Generic;
class Class
{
List<System.Int32> l;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateWithExistingUsings()
{
await TestInRegularAndScriptAsync(
@"using System;
class Class
{
[|List<int>|] Method()
{
Foo();
}
}",
@"using System;
class Class
{
System.Collections.Generic.List<int> Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateInNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace N
{
class Class
{
[|List<int>|] Method()
{
Foo();
}
}
}",
@"namespace N
{
class Class
{
System.Collections.Generic.List<int> Method()
{
Foo();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenerateInNamespaceWithUsings()
{
await TestInRegularAndScriptAsync(
@"namespace N
{
using System;
class Class
{
[|List<int>|] Method()
{
Foo();
}
}
}",
@"namespace N
{
using System;
class Class
{
System.Collections.Generic.List<int> Method()
{
Foo();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestExistingUsing()
{
await TestActionCountAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Foo();
}
}",
count: 2);
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Foo();
}
}",
@"using System.Collections.Generic;
class Class
{
System.Collections.IDictionary Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingIfUniquelyBound()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Class
{
[|String|] Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingIfUniquelyBoundGeneric()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
[|List<int>|] Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnEnum()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Foo()
{
var a = [|Colors|].Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}",
@"class Class
{
void Foo()
{
var a = A.Colors.Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnClassInheritance()
{
await TestInRegularAndScriptAsync(
@"class Class : [|Class2|]
{
}
namespace A
{
class Class2
{
}
}",
@"class Class : A.Class2
{
}
namespace A
{
class Class2
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestOnImplementedInterface()
{
await TestInRegularAndScriptAsync(
@"class Class : [|IFoo|]
{
}
namespace A
{
interface IFoo
{
}
}",
@"class Class : A.IFoo
{
}
namespace A
{
interface IFoo
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAllInBaseList()
{
await TestInRegularAndScriptAsync(
@"class Class : [|IFoo|], Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IFoo
{
}
}",
@"class Class : B.IFoo, Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IFoo
{
}
}");
await TestInRegularAndScriptAsync(
@"class Class : B.IFoo, [|Class2|]
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IFoo
{
}
}",
@"class Class : B.IFoo, A.Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IFoo
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttributeUnexpanded()
{
await TestInRegularAndScriptAsync(
@"[[|Obsolete|]]
class Class
{
}",
@"[System.Obsolete]
class Class
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttributeExpanded()
{
await TestInRegularAndScriptAsync(
@"[[|ObsoleteAttribute|]]
class Class
{
}",
@"[System.ObsoleteAttribute]
class Class
{
}");
}
[WorkItem(527360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527360")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestExtensionMethods()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Foo
{
void Bar()
{
var values = new List<int>() { 1, 2, 3 };
values.[|Where|](i => i > 1);
}
}");
}
[WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAfterNew()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Foo()
{
List<int> l;
l = new [|List<int>|]();
}
}",
@"class Class
{
void Foo()
{
List<int> l;
l = new System.Collections.Generic.List<int>();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestArgumentsInMethodCall()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Test()
{
Console.WriteLine([|DateTime|].Today);
}
}",
@"class Class
{
void Test()
{
Console.WriteLine(System.DateTime.Today);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestCallSiteArgs()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Test([|DateTime|] dt)
{
}
}",
@"class Class
{
void Test(System.DateTime dt)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestUsePartialClass()
{
await TestInRegularAndScriptAsync(
@"namespace A
{
public class Class
{
[|PClass|] c;
}
}
namespace B
{
public partial class PClass
{
}
}",
@"namespace A
{
public class Class
{
B.PClass c;
}
}
namespace B
{
public partial class PClass
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericClassInNestedNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
[|GenericClass<int>|] c;
}
}",
@"namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
A.B.GenericClass<int> c;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestBeforeStaticMethod()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Test()
{
[|Math|].Sqrt();
}",
@"class Class
{
void Test()
{
System.Math.Sqrt();
}");
}
[WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestBeforeNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace A
{
class Class
{
[|C|].Test t;
}
}
namespace B
{
namespace C
{
class Test
{
}
}
}",
@"namespace A
{
class Class
{
B.C.Test t;
}
}
namespace B
{
namespace C
{
class Test
{
}
}
}");
}
[WorkItem(527395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestSimpleNameWithLeadingTrivia()
{
await TestInRegularAndScriptAsync(
@"class Class { void Test() { /*foo*/[|Int32|] i; } }",
@"class Class { void Test() { /*foo*/System.Int32 i; } }",
ignoreTrivia: false);
}
[WorkItem(527395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGenericNameWithLeadingTrivia()
{
await TestInRegularAndScriptAsync(
@"class Class { void Test() { /*foo*/[|List<int>|] l; } }",
@"class Class { void Test() { /*foo*/System.Collections.Generic.List<int> l; } }",
ignoreTrivia: false);
}
[WorkItem(538740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyTypeName()
{
await TestInRegularAndScriptAsync(
@"public class Program
{
public class Inner
{
}
}
class Test
{
[|Inner|] i;
}",
@"public class Program
{
public class Inner
{
}
}
class Test
{
Program.Inner i;
}");
}
[WorkItem(538740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyTypeName_NotForGenericType()
{
await TestMissingInRegularAndScriptAsync(
@"class Program<T>
{
public class Inner
{
}
}
class Test
{
[|Inner|] i;
}");
}
[WorkItem(538764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538764")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyThroughAlias()
{
await TestInRegularAndScriptAsync(
@"using Alias = System;
class C
{
[|Int32|] i;
}",
@"using Alias = System;
class C
{
Alias.Int32 i;
}");
}
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyPrioritizeTypesOverNamespaces1()
{
await TestInRegularAndScriptAsync(
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
[|C|] c;
}",
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
Outer.C.C c;
}");
}
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestFullyQualifyPrioritizeTypesOverNamespaces2()
{
await TestInRegularAndScriptAsync(
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
[|C|] c;
}",
@"namespace Outer
{
namespace C
{
class C
{
}
}
}
class Test
{
Outer.C c;
}",
index: 1);
}
[WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task BugFix5950()
{
await TestAsync(
@"using System.Console; WriteLine([|Expression|].Constant(123));",
@"using System.Console; WriteLine(System.Linq.Expressions.Expression.Constant(123));",
parseOptions: GetScriptOptions());
}
[WorkItem(540318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAfterAlias()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
System::[|Console|] :: WriteLine(""TEST"");
}
}");
}
[WorkItem(540942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540942")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnIncompleteStatement()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.IO;
class C
{
static void Main(string[] args)
{
[|Path|] }
}");
}
[WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAssemblyAttribute()
{
await TestInRegularAndScriptAsync(
@"[assembly: [|InternalsVisibleTo|](""Project"")]",
@"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project"")]");
}
[WorkItem(543388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543388")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnAliasName()
{
await TestMissingInRegularAndScriptAsync(
@"using [|GIBBERISH|] = Foo.GIBBERISH;
class Program
{
static void Main(string[] args)
{
GIBBERISH x;
}
}
namespace Foo
{
public class GIBBERISH
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestMissingOnAttributeOverloadResolutionError()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Runtime.InteropServices;
class M
{
[[|DllImport|]()]
static extern int? My();
}");
}
[WorkItem(544950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544950")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestNotOnAbstractConstructor()
{
await TestMissingInRegularAndScriptAsync(
@"using System.IO;
class Program
{
static void Main(string[] args)
{
var s = new [|Stream|]();
}
}");
}
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestAttribute()
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestActionCountAsync(input, 1);
await TestInRegularAndScriptAsync(
input,
@"[assembly: System.Runtime.InteropServices.Guid(""9ed54f84-a89d-4fcd-a854-44251e925f09"")]");
}
[WorkItem(546027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546027")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TestGeneratePropertyFromAttribute()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
[AttributeUsage(AttributeTargets.Class)]
class MyAttrAttribute : Attribute
{
}
[MyAttr(123, [|Version|] = 1)]
class D
{
}");
}
[WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task ShouldTriggerOnCS0308()
{
// CS0308: The non-generic type 'A' cannot be used with type arguments
await TestInRegularAndScriptAsync(
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
[|IEnumerable<int>|] f;
}
}",
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
System.Collections.Generic.IEnumerable<int> f;
}
}");
}
[WorkItem(947579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947579")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task AmbiguousTypeFix()
{
await TestInRegularAndScriptAsync(
@"using n1;
using n2;
class B
{
void M1()
{
[|var a = new A();|]
}
}
namespace n1
{
class A
{
}
}
namespace n2
{
class A
{
}
}",
@"using n1;
using n2;
class B
{
void M1()
{
var a = new n1.A();
}
}
namespace n1
{
class A
{
}
}
namespace n2
{
class A
{
}
}");
}
[WorkItem(995857, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995857")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task NonPublicNamespaces()
{
await TestInRegularAndScriptAsync(
@"namespace MS.Internal.Xaml
{
private class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
[|Xaml|]
}
}",
@"namespace MS.Internal.Xaml
{
private class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
System.Xaml
}
}");
await TestInRegularAndScriptAsync(
@"namespace MS.Internal.Xaml
{
public class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
[|Xaml|]
}
}",
@"namespace MS.Internal.Xaml
{
public class A
{
}
}
namespace System.Xaml
{
public class A
{
}
}
public class Program
{
static void M()
{
MS.Internal.Xaml
}
}", index: 1);
}
[WorkItem(11071, "https://github.com/dotnet/roslyn/issues/11071")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task AmbiguousFixOrdering()
{
await TestInRegularAndScriptAsync(
@"using n1;
using n2;
[[|Inner|].C]
class B
{
}
namespace n1
{
namespace Inner
{
}
}
namespace n2
{
namespace Inner
{
class CAttribute
{
}
}
}",
@"using n1;
using n2;
[n2.Inner.C]
class B
{
}
namespace n1
{
namespace Inner
{
}
}
namespace n2
{
namespace Inner
{
class CAttribute
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TupleTest()
{
await TestInRegularAndScriptAsync(
@"class Class
{
([|IDictionary|], string) Method()
{
Foo();
}
}",
@"class Class
{
(System.Collections.IDictionary, string) Method()
{
Foo();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)]
public async Task TupleWithOneName()
{
await TestInRegularAndScriptAsync(
@"class Class
{
([|IDictionary|] a, string) Method()
{
Foo();
}
}",
@"class Class
{
(System.Collections.IDictionary a, string) Method()
{
Foo();
}
}");
}
[WorkItem(18275, "https://github.com/dotnet/roslyn/issues/18275")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestContextualKeyword1()
{
await TestMissingInRegularAndScriptAsync(
@"
namespace N
{
class nameof
{
}
}
class C
{
void M()
{
[|nameof|]
}
}");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.ReminderService;
using Orleans.Runtime.Services;
using Orleans.Timers;
using UnitTests.GrainInterfaces;
#pragma warning disable 612,618
namespace UnitTests.Grains
{
// NOTE: if you make any changes here, copy them to ReminderTestCopyGrain
public class ReminderTestGrain2 : Grain, IReminderTestGrain2, IRemindable
{
private readonly IReminderTable reminderTable;
private readonly IReminderRegistry unvalidatedReminderRegistry;
Dictionary<string, IGrainReminder> allReminders;
Dictionary<string, long> sequence;
private TimeSpan period;
private static long aCCURACY = 50 * TimeSpan.TicksPerMillisecond; // when we use ticks to compute sequence numbers, we might get wrong results as timeouts don't happen with precision of ticks ... we keep this as a leeway
private ILogger logger;
private string myId; // used to distinguish during debugging between multiple activations of the same grain
private string filePrefix;
public ReminderTestGrain2(IServiceProvider services, IReminderTable reminderTable, ILoggerFactory loggerFactory)
{
this.reminderTable = reminderTable;
this.unvalidatedReminderRegistry = new UnvalidatedReminderRegistry(services);
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
this.myId = this.Data.ActivationId.ToString();// new Random().Next();
this.allReminders = new Dictionary<string, IGrainReminder>();
this.sequence = new Dictionary<string, long>();
this.period = GetDefaultPeriod(this.logger);
this.logger.Info("OnActivateAsync.");
this.filePrefix = "g" + this.Identity.PrimaryKey + "_";
return GetMissingReminders();
}
public override Task OnDeactivateAsync()
{
this.logger.Info("OnDeactivateAsync");
return Task.CompletedTask;
}
public async Task<IGrainReminder> StartReminder(string reminderName, TimeSpan? p = null, bool validate = false)
{
TimeSpan usePeriod = p ?? this.period;
this.logger.Info("Starting reminder {0}.", reminderName);
IGrainReminder r = null;
if (validate)
r = await RegisterOrUpdateReminder(reminderName, usePeriod - TimeSpan.FromSeconds(2), usePeriod);
else
r = await this.unvalidatedReminderRegistry.RegisterOrUpdateReminder(reminderName, usePeriod - TimeSpan.FromSeconds(2), usePeriod);
this.allReminders[reminderName] = r;
this.sequence[reminderName] = 0;
string fileName = GetFileName(reminderName);
File.Delete(fileName); // if successfully started, then remove any old data
this.logger.Info("Started reminder {0}", r);
return r;
}
public Task ReceiveReminder(string reminderName, TickStatus status)
{
// it can happen that due to failure, when a new activation is created,
// it doesn't know which reminders were registered against the grain
// hence, this activation may receive a reminder that it didn't register itself, but
// the previous activation (incarnation of the grain) registered... so, play it safe
if (!this.sequence.ContainsKey(reminderName))
{
// allReminders.Add(reminderName, r); // not using allReminders at the moment
//counters.Add(reminderName, 0);
this.sequence.Add(reminderName, 0); // we'll get upto date to the latest sequence number while processing this tick
}
// calculating tick sequence number
// we do all arithmetics on DateTime by converting into long because we dont have divide operation on DateTime
// using dateTime.Ticks is not accurate as between two invocations of ReceiveReminder(), there maybe < period.Ticks
// if # of ticks between two consecutive ReceiveReminder() is larger than period.Ticks, everything is fine... the problem is when its less
// thus, we reduce our accuracy by ACCURACY ... here, we are preparing all used variables for the given accuracy
long now = status.CurrentTickTime.Ticks / aCCURACY; //DateTime.UtcNow.Ticks / ACCURACY;
long first = status.FirstTickTime.Ticks / aCCURACY;
long per = status.Period.Ticks / aCCURACY;
long sequenceNumber = 1 + ((now - first) / per);
// end of calculating tick sequence number
// do switch-ing here
if (sequenceNumber < this.sequence[reminderName])
{
this.logger.Info("ReceiveReminder: {0} Incorrect tick {1} vs. {2} with status {3}.", reminderName, this.sequence[reminderName], sequenceNumber, status);
return Task.CompletedTask;
}
this.sequence[reminderName] = sequenceNumber;
this.logger.Info("ReceiveReminder: {0} Sequence # {1} with status {2}.", reminderName, this.sequence[reminderName], status);
string fileName = GetFileName(reminderName);
string counterValue = this.sequence[reminderName].ToString(CultureInfo.InvariantCulture);
File.WriteAllText(fileName, counterValue);
return Task.CompletedTask;
}
public async Task StopReminder(string reminderName)
{
this.logger.Info("Stopping reminder {0}.", reminderName);
// we dont reset counter as we want the test methods to be able to read it even after stopping the reminder
//return UnregisterReminder(allReminders[reminderName]);
IGrainReminder reminder = null;
if (this.allReminders.TryGetValue(reminderName, out reminder))
{
await UnregisterReminder(reminder);
}
else
{
// during failures, there may be reminders registered by an earlier activation that we dont have cached locally
// therefore, we need to update our local cache
await GetMissingReminders();
if (this.allReminders.TryGetValue(reminderName, out reminder))
{
await UnregisterReminder(reminder);
}
else
{
//var reminders = await this.GetRemindersList();
throw new OrleansException(string.Format(
"Could not find reminder {0} in grain {1}", reminderName, this.IdentityString));
}
}
}
private async Task GetMissingReminders()
{
List<IGrainReminder> reminders = await base.GetReminders();
this.logger.Info("Got missing reminders {0}", Utils.EnumerableToString(reminders));
foreach (IGrainReminder l in reminders)
{
if (!this.allReminders.ContainsKey(l.ReminderName))
{
this.allReminders.Add(l.ReminderName, l);
}
}
}
public async Task StopReminder(IGrainReminder reminder)
{
this.logger.Info("Stopping reminder (using ref) {0}.", reminder);
// we dont reset counter as we want the test methods to be able to read it even after stopping the reminder
await UnregisterReminder(reminder);
}
public Task<TimeSpan> GetReminderPeriod(string reminderName)
{
return Task.FromResult(this.period);
}
public Task<long> GetCounter(string name)
{
string fileName = GetFileName(name);
string data = File.ReadAllText(fileName);
long counterValue = long.Parse(data);
return Task.FromResult(counterValue);
}
public Task<IGrainReminder> GetReminderObject(string reminderName)
{
return base.GetReminder(reminderName);
}
public async Task<List<IGrainReminder>> GetRemindersList()
{
return await base.GetReminders();
}
private string GetFileName(string reminderName)
{
return string.Format("{0}{1}", this.filePrefix, reminderName);
}
public static TimeSpan GetDefaultPeriod(ILogger log)
{
int period = 12; // Seconds
var reminderPeriod = TimeSpan.FromSeconds(period);
log.Info("Using reminder period of {0} in ReminderTestGrain", reminderPeriod);
return reminderPeriod;
}
public async Task EraseReminderTable()
{
await this.reminderTable.TestOnlyClearTable();
}
}
// NOTE: do not make changes here ... this is a copy of ReminderTestGrain
// changes to make when copying:
// 1. rename logger to ReminderCopyGrain
// 2. filePrefix should start with "gc", instead of "g"
public class ReminderTestCopyGrain : Grain, IReminderTestCopyGrain, IRemindable
{
private readonly IReminderRegistry unvalidatedReminderRegistry;
Dictionary<string, IGrainReminder> allReminders;
Dictionary<string, long> sequence;
private TimeSpan period;
private static long aCCURACY = 50 * TimeSpan.TicksPerMillisecond; // when we use ticks to compute sequence numbers, we might get wrong results as timeouts don't happen with precision of ticks ... we keep this as a leeway
private ILogger logger;
private long myId; // used to distinguish during debugging between multiple activations of the same grain
private string filePrefix;
public ReminderTestCopyGrain(IServiceProvider services, ILoggerFactory loggerFactory)
{
this.unvalidatedReminderRegistry = new UnvalidatedReminderRegistry(services); ;
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override async Task OnActivateAsync()
{
this.myId = new Random().Next();
this.allReminders = new Dictionary<string, IGrainReminder>();
this.sequence = new Dictionary<string, long>();
this.period = ReminderTestGrain2.GetDefaultPeriod(this.logger);
this.logger.Info("OnActivateAsync.");
this.filePrefix = "gc" + this.Identity.PrimaryKey + "_";
await GetMissingReminders();
}
public override Task OnDeactivateAsync()
{
this.logger.Info("OnDeactivateAsync.");
return Task.CompletedTask;
}
public async Task<IGrainReminder> StartReminder(string reminderName, TimeSpan? p = null, bool validate = false)
{
TimeSpan usePeriod = p ?? this.period;
this.logger.Info("Starting reminder {0} for {1}", reminderName, this.Identity);
IGrainReminder r = null;
if (validate)
r = await RegisterOrUpdateReminder(reminderName, /*TimeSpan.FromSeconds(3)*/usePeriod - TimeSpan.FromSeconds(2), usePeriod);
else
r = await this.unvalidatedReminderRegistry.RegisterOrUpdateReminder(
reminderName,
usePeriod - TimeSpan.FromSeconds(2),
usePeriod);
if (this.allReminders.ContainsKey(reminderName))
{
this.allReminders[reminderName] = r;
this.sequence[reminderName] = 0;
}
else
{
this.allReminders.Add(reminderName, r);
this.sequence.Add(reminderName, 0);
}
File.Delete(GetFileName(reminderName)); // if successfully started, then remove any old data
this.logger.Info("Started reminder {0}.", r);
return r;
}
public Task ReceiveReminder(string reminderName, TickStatus status)
{
// it can happen that due to failure, when a new activation is created,
// it doesn't know which reminders were registered against the grain
// hence, this activation may receive a reminder that it didn't register itself, but
// the previous activation (incarnation of the grain) registered... so, play it safe
if (!this.sequence.ContainsKey(reminderName))
{
// allReminders.Add(reminderName, r); // not using allReminders at the moment
//counters.Add(reminderName, 0);
this.sequence.Add(reminderName, 0); // we'll get upto date to the latest sequence number while processing this tick
}
// calculating tick sequence number
// we do all arithmetics on DateTime by converting into long because we dont have divide operation on DateTime
// using dateTime.Ticks is not accurate as between two invocations of ReceiveReminder(), there maybe < period.Ticks
// if # of ticks between two consecutive ReceiveReminder() is larger than period.Ticks, everything is fine... the problem is when its less
// thus, we reduce our accuracy by ACCURACY ... here, we are preparing all used variables for the given accuracy
long now = status.CurrentTickTime.Ticks / aCCURACY; //DateTime.UtcNow.Ticks / ACCURACY;
long first = status.FirstTickTime.Ticks / aCCURACY;
long per = status.Period.Ticks / aCCURACY;
long sequenceNumber = 1 + ((now - first) / per);
// end of calculating tick sequence number
// do switch-ing here
if (sequenceNumber < this.sequence[reminderName])
{
this.logger.Info("{0} Incorrect tick {1} vs. {2} with status {3}.", reminderName, this.sequence[reminderName], sequenceNumber, status);
return Task.CompletedTask;
}
this.sequence[reminderName] = sequenceNumber;
this.logger.Info("{0} Sequence # {1} with status {2}.", reminderName, this.sequence[reminderName], status);
File.WriteAllText(GetFileName(reminderName), this.sequence[reminderName].ToString());
return Task.CompletedTask;
}
public async Task StopReminder(string reminderName)
{
this.logger.Info("Stopping reminder {0}.", reminderName);
// we dont reset counter as we want the test methods to be able to read it even after stopping the reminder
//return UnregisterReminder(allReminders[reminderName]);
IGrainReminder reminder = null;
if (this.allReminders.TryGetValue(reminderName, out reminder))
{
await UnregisterReminder(reminder);
}
else
{
// during failures, there may be reminders registered by an earlier activation that we dont have cached locally
// therefore, we need to update our local cache
await GetMissingReminders();
await UnregisterReminder(this.allReminders[reminderName]);
}
}
private async Task GetMissingReminders()
{
List<IGrainReminder> reminders = await base.GetReminders();
foreach (IGrainReminder l in reminders)
{
if (!this.allReminders.ContainsKey(l.ReminderName))
{
this.allReminders.Add(l.ReminderName, l);
}
}
}
public async Task StopReminder(IGrainReminder reminder)
{
this.logger.Info("Stopping reminder (using ref) {0}.", reminder);
// we dont reset counter as we want the test methods to be able to read it even after stopping the reminder
await UnregisterReminder(reminder);
}
public Task<TimeSpan> GetReminderPeriod(string reminderName)
{
return Task.FromResult(this.period);
}
public Task<long> GetCounter(string name)
{
return Task.FromResult(long.Parse(File.ReadAllText(GetFileName(name))));
}
public async Task<IGrainReminder> GetReminderObject(string reminderName)
{
return await base.GetReminder(reminderName);
}
public async Task<List<IGrainReminder>> GetRemindersList()
{
return await base.GetReminders();
}
private string GetFileName(string reminderName)
{
return string.Format("{0}{1}", this.filePrefix, reminderName);
}
}
public class WrongReminderGrain : Grain, IReminderGrainWrong
{
private ILogger logger;
public WrongReminderGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
this.logger.Info("OnActivateAsync.");
return Task.CompletedTask;
}
public async Task<bool> StartReminder(string reminderName)
{
this.logger.Info("Starting reminder {0}.", reminderName);
IGrainReminder r = await RegisterOrUpdateReminder(reminderName, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3));
this.logger.Info("Started reminder {0}. It shouldn't have succeeded!", r);
return true;
}
}
internal class UnvalidatedReminderRegistry : GrainServiceClient<IReminderService>, IReminderRegistry
{
public UnvalidatedReminderRegistry(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
public Task<IGrainReminder> RegisterOrUpdateReminder(string reminderName, TimeSpan dueTime, TimeSpan period)
{
return this.GrainService.RegisterOrUpdateReminder(this.CallingGrainReference, reminderName, dueTime, period);
}
public Task UnregisterReminder(IGrainReminder reminder)
{
return this.GrainService.UnregisterReminder(reminder);
}
public Task<IGrainReminder> GetReminder(string reminderName)
{
return this.GrainService.GetReminder(this.CallingGrainReference, reminderName);
}
public Task<List<IGrainReminder>> GetReminders()
{
return this.GrainService.GetReminders(this.CallingGrainReference);
}
}
}
#pragma warning restore 612,618
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Alensia.Core.Common;
using Alensia.Core.I18n;
using Alensia.Core.UI.Cursor;
using Alensia.Core.UI.Screen;
using Malee;
using UniRx;
using UnityEngine;
using UnityEngine.Assertions;
using Zenject;
using Object = UnityEngine.Object;
using UECursor = UnityEngine.Cursor;
namespace Alensia.Core.UI
{
public class UIContext : ManagedMonoBehavior, IRuntimeUIContext
{
[Inject]
public DiContainer DiContainer { get; }
public UIStyle Style
{
get { return _style.Value; }
set
{
Assert.IsNotNull(value, "value != null");
_style.Value = value;
}
}
public CultureInfo Locale => Translator?.LocaleService?.Locale;
[Inject]
public ITranslator Translator { get; }
public Transform ScreenRoot => _screenRoot ?? transform;
public IEnumerable<IScreen> Screens => ScreenRoot.GetComponents<IScreen>();
public IReadOnlyDictionary<string, ScreenDefinition> ScreenDefinitions { get; private set; }
public IInteractableComponent ActiveComponent
{
get { return _activeComponent.Value; }
set { _activeComponent.Value = value; }
}
public CursorState CursorState
{
get { return _cursorState; }
set
{
value?.Apply();
_cursorState = value;
}
}
public string DefaultCursor
{
get { return _defaultCursor; }
set { _defaultCursor = value; }
}
public IObservable<CultureInfo> OnLocaleChange => Translator?.LocaleService?.OnLocaleChange;
public IObservable<IInteractableComponent> OnActiveComponentChange => _activeComponent?.Where(_ => Initialized);
public IObservable<UIStyle> OnStyleChange => _style;
[SerializeField] private UIStyleReactiveProperty _style;
[SerializeField] private Transform _screenRoot;
[SerializeField, Reorderable] private ScreenDefinitionList _screens;
[SerializeField, PredefinedLiteral(typeof(CursorNames))] private string _defaultCursor;
[SerializeField] private CursorState _cursorState;
private readonly IReactiveProperty<IInteractableComponent> _activeComponent;
private IDisposable _cursor;
public UIContext()
{
_style = new UIStyleReactiveProperty();
_activeComponent = new ReactiveProperty<IInteractableComponent>();
_defaultCursor = CursorNames.Default;
_cursorState = CursorState.Vislbe;
}
protected override void OnInitialized()
{
ScreenDefinitions = _screens?.ToDictionary(i => i.Name, i => i) ??
new Dictionary<string, ScreenDefinition>();
CreateScreens();
var whenNull = OnActiveComponentChange
.Where(c => c == null)
.Select(c => (string) null);
var whenNotNull = OnActiveComponentChange
.Where(c => c != null)
.SelectMany(c => c.OnCursorChange);
whenNotNull.Merge(whenNull)
.Select(c => c ?? CursorNames.Default)
.Select(FindCursor)
.Where(c => c != null)
.Subscribe(UpdateCursor, Debug.LogError)
.AddTo(this);
CursorState?.Apply();
base.OnInitialized();
}
protected virtual void CreateScreens()
{
var active = Screens.ToDictionary(s => s.Name, s => s);
ScreenDefinitions.Values
.Where(s => !active.ContainsKey(s.Name))
.ToList()
.ForEach(CreateScreen);
}
protected virtual void CreateScreen(ScreenDefinition definition)
{
var item = definition.Item;
IScreen screen;
if (item.scene != ScreenRoot.gameObject.scene)
{
screen = Object.Instantiate(item, ScreenRoot).GetComponent<IScreen>();
}
else
{
screen = item.GetComponent<IScreen>();
if (item.transform.parent != ScreenRoot)
{
item.transform.SetParent(ScreenRoot);
}
}
if (screen == null)
{
Debug.LogWarning($"Missing IScreen component on object: '{item.name}'.");
}
screen?.Initialize(this);
}
public virtual IScreen FindScreen(string screen)
{
return ScreenRoot.Find(screen)?.GetComponent<IScreen>();
}
public virtual void ShowScreen(string screen)
{
var instance = FindScreen(screen);
if (instance != null && !instance.Visible)
{
instance.Visible = true;
}
}
public virtual void HideScreen(string screen)
{
Assert.IsNotNull(screen, "name != null");
var instance = FindScreen(screen);
if (instance != null && instance.Visible)
{
instance.Visible = false;
}
}
public T Instantiate<T>(GameObject prefab, Transform parent) where T : IUIElement
{
T ui;
if (prefab.scene != parent.gameObject.scene)
{
ui = Object.Instantiate(prefab, parent).GetComponent<T>();
}
else
{
ui = prefab.GetComponent<T>();
if (prefab.transform.parent != parent)
{
prefab.transform.SetParent(parent);
}
}
if (ui == null)
{
throw new ArgumentException(
$"Unable to find a suitable component on object: '{prefab.name}'.");
}
var handler = ui as IComponentHandler;
if (handler == null)
{
ui.Initialize(this);
}
else
{
handler.Component.Initialize(this);
}
return ui;
}
protected override void OnDisposed()
{
_cursor?.Dispose();
_cursor = null;
base.OnDisposed();
}
protected virtual CursorDefinition FindCursor(string cursor)
{
var cursors = Style?.CursorSet;
var key = cursor ?? DefaultCursor;
if (cursors == null || key == null) return null;
return cursors[key] ?? (DefaultCursor != null ? cursors[DefaultCursor] : null);
}
protected virtual void UpdateCursor(CursorDefinition cursor)
{
lock (this)
{
_cursor?.Dispose();
_cursor = cursor.Create().SubscribeWithState(cursor.Hotspot, (image, pos) =>
{
//TODO Can't use CursorMode.Auto, because it doesn't work on Linux yet.
//(See: https://forum.unity3d.com/threads/cursor-setcursor-does-not-work-in-editor.476617/)
UECursor.SetCursor(image, pos, CursorMode.ForceSoftware);
});
}
}
}
}
| |
// <copyright file="EventFiringWebDriver.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Support.Events
{
/// <summary>
/// A wrapper around an arbitrary WebDriver instance which supports registering for
/// events, e.g. for logging purposes.
/// </summary>
public class EventFiringWebDriver : IWebDriver, IJavaScriptExecutor, ITakesScreenshot, IWrapsDriver
{
private IWebDriver driver;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringWebDriver"/> class.
/// </summary>
/// <param name="parentDriver">The driver to register events for.</param>
public EventFiringWebDriver(IWebDriver parentDriver)
{
this.driver = parentDriver;
}
/// <summary>
/// Fires before the driver begins navigation.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> Navigating;
/// <summary>
/// Fires after the driver completes navigation
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> Navigated;
/// <summary>
/// Fires before the driver begins navigation back one entry in the browser history list.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> NavigatingBack;
/// <summary>
/// Fires after the driver completes navigation back one entry in the browser history list.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> NavigatedBack;
/// <summary>
/// Fires before the driver begins navigation forward one entry in the browser history list.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> NavigatingForward;
/// <summary>
/// Fires after the driver completes navigation forward one entry in the browser history list.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> NavigatedForward;
/// <summary>
/// Fires before the driver clicks on an element.
/// </summary>
public event EventHandler<WebElementEventArgs> ElementClicking;
/// <summary>
/// Fires after the driver has clicked on an element.
/// </summary>
public event EventHandler<WebElementEventArgs> ElementClicked;
/// <summary>
/// Fires before the driver changes the value of an element via Clear(), SendKeys() or Toggle().
/// </summary>
public event EventHandler<WebElementEventArgs> ElementValueChanging;
/// <summary>
/// Fires after the driver has changed the value of an element via Clear(), SendKeys() or Toggle().
/// </summary>
public event EventHandler<WebElementEventArgs> ElementValueChanged;
/// <summary>
/// Fires before the driver starts to find an element.
/// </summary>
public event EventHandler<FindElementEventArgs> FindingElement;
/// <summary>
/// Fires after the driver completes finding an element.
/// </summary>
public event EventHandler<FindElementEventArgs> FindElementCompleted;
/// <summary>
/// Fires before a script is executed.
/// </summary>
public event EventHandler<WebDriverScriptEventArgs> ScriptExecuting;
/// <summary>
/// Fires after a script is executed.
/// </summary>
public event EventHandler<WebDriverScriptEventArgs> ScriptExecuted;
/// <summary>
/// Fires when an exception is thrown.
/// </summary>
public event EventHandler<WebDriverExceptionEventArgs> ExceptionThrown;
/// <summary>
/// Gets the <see cref="IWebDriver"/> wrapped by this EventsFiringWebDriver instance.
/// </summary>
public IWebDriver WrappedDriver
{
get { return this.driver; }
}
/// <summary>
/// Gets or sets the URL the browser is currently displaying.
/// </summary>
/// <remarks>
/// Setting the <see cref="Url"/> property will load a new web page in the current browser window.
/// This is done using an HTTP GET operation, and the method will block until the
/// load is complete. This will follow redirects issued either by the server or
/// as a meta-redirect from within the returned HTML. Should a meta-redirect "rest"
/// for any duration of time, it is best to wait until this timeout is over, since
/// should the underlying page change while your test is executing the results of
/// future calls against this interface will be against the freshly loaded page.
/// </remarks>
/// <seealso cref="INavigation.GoToUrl(string)"/>
/// <seealso cref="INavigation.GoToUrl(System.Uri)"/>
public string Url
{
get
{
string url = string.Empty;
try
{
url = this.driver.Url;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return url;
}
set
{
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.driver, value);
this.OnNavigating(e);
this.driver.Url = value;
this.OnNavigated(e);
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
}
}
/// <summary>
/// Gets the title of the current browser window.
/// </summary>
public string Title
{
get
{
string title = string.Empty;
try
{
title = this.driver.Title;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return title;
}
}
/// <summary>
/// Gets the source of the page last loaded by the browser.
/// </summary>
/// <remarks>
/// If the page has been modified after loading (for example, by JavaScript)
/// there is no guarantee that the returned text is that of the modified page.
/// Please consult the documentation of the particular driver being used to
/// determine whether the returned text reflects the current state of the page
/// or the text last sent by the web server. The page source returned is a
/// representation of the underlying DOM: do not expect it to be formatted
/// or escaped in the same way as the response sent from the web server.
/// </remarks>
public string PageSource
{
get
{
string source = string.Empty;
try
{
source = this.driver.PageSource;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return source;
}
}
/// <summary>
/// Gets the current window handle, which is an opaque handle to this
/// window that uniquely identifies it within this driver instance.
/// </summary>
public string CurrentWindowHandle
{
get
{
string handle = string.Empty;
try
{
handle = this.driver.CurrentWindowHandle;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return handle;
}
}
/// <summary>
/// Gets the window handles of open browser windows.
/// </summary>
public ReadOnlyCollection<string> WindowHandles
{
get
{
ReadOnlyCollection<string> handles = null;
try
{
handles = this.driver.WindowHandles;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return handles;
}
}
/// <summary>
/// Close the current window, quitting the browser if it is the last window currently open.
/// </summary>
public void Close()
{
try
{
this.driver.Close();
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
}
/// <summary>
/// Quits this driver, closing every associated window.
/// </summary>
public void Quit()
{
try
{
this.driver.Quit();
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
}
/// <summary>
/// Instructs the driver to change its settings.
/// </summary>
/// <returns>An <see cref="IOptions"/> object allowing the user to change
/// the settings of the driver.</returns>
public IOptions Manage()
{
return new EventFiringOptions(this);
}
/// <summary>
/// Instructs the driver to navigate the browser to another location.
/// </summary>
/// <returns>An <see cref="INavigation"/> object allowing the user to access
/// the browser's history and to navigate to a given URL.</returns>
public INavigation Navigate()
{
return new EventFiringNavigation(this);
}
/// <summary>
/// Instructs the driver to send future commands to a different frame or window.
/// </summary>
/// <returns>An <see cref="ITargetLocator"/> object which can be used to select
/// a frame or window.</returns>
public ITargetLocator SwitchTo()
{
return new EventFiringTargetLocator(this);
}
/// <summary>
/// Find the first <see cref="IWebElement"/> using the given method.
/// </summary>
/// <param name="by">The locating mechanism to use.</param>
/// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns>
/// <exception cref="NoSuchElementException">If no element matches the criteria.</exception>
public IWebElement FindElement(By by)
{
IWebElement wrappedElement = null;
try
{
FindElementEventArgs e = new FindElementEventArgs(this.driver, by);
this.OnFindingElement(e);
IWebElement element = this.driver.FindElement(by);
this.OnFindElementCompleted(e);
wrappedElement = this.WrapElement(element);
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return wrappedElement;
}
/// <summary>
/// Find all <see cref="IWebElement">IWebElements</see> within the current context
/// using the given mechanism.
/// </summary>
/// <param name="by">The locating mechanism to use.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see>
/// matching the current criteria, or an empty list if nothing matches.</returns>
public ReadOnlyCollection<IWebElement> FindElements(By by)
{
List<IWebElement> wrappedElementList = new List<IWebElement>();
try
{
FindElementEventArgs e = new FindElementEventArgs(this.driver, by);
this.OnFindingElement(e);
ReadOnlyCollection<IWebElement> elements = this.driver.FindElements(by);
this.OnFindElementCompleted(e);
foreach (IWebElement element in elements)
{
IWebElement wrappedElement = this.WrapElement(element);
wrappedElementList.Add(wrappedElement);
}
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return wrappedElementList.AsReadOnly();
}
/// <summary>
/// Frees all managed and unmanaged resources used by this instance.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Executes JavaScript in the context of the currently selected frame or window.
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="args">The arguments to the script.</param>
/// <returns>The value returned by the script.</returns>
/// <remarks>
/// <para>
/// The <see cref="ExecuteScript"/>method executes JavaScript in the context of
/// the currently selected frame or window. This means that "document" will refer
/// to the current document. If the script has a return value, then the following
/// steps will be taken:
/// </para>
/// <para>
/// <list type="bullet">
/// <item><description>For an HTML element, this method returns a <see cref="IWebElement"/></description></item>
/// <item><description>For a number, a <see cref="long"/> is returned</description></item>
/// <item><description>For a boolean, a <see cref="bool"/> is returned</description></item>
/// <item><description>For all other cases a <see cref="string"/> is returned.</description></item>
/// <item><description>For an array,we check the first element, and attempt to return a
/// <see cref="List{T}"/> of that type, following the rules above. Nested lists are not
/// supported.</description></item>
/// <item><description>If the value is null or there is no return value,
/// <see langword="null"/> is returned.</description></item>
/// </list>
/// </para>
/// <para>
/// Arguments must be a number (which will be converted to a <see cref="long"/>),
/// a <see cref="bool"/>, a <see cref="string"/> or a <see cref="IWebElement"/>.
/// An exception will be thrown if the arguments do not meet these criteria.
/// The arguments will be made available to the JavaScript via the "arguments" magic
/// variable, as if the function were called via "Function.apply"
/// </para>
/// </remarks>
public object ExecuteScript(string script, params object[] args)
{
IJavaScriptExecutor javascriptDriver = this.driver as IJavaScriptExecutor;
if (javascriptDriver == null)
{
throw new NotSupportedException("Underlying driver instance does not support executing JavaScript");
}
object scriptResult = null;
try
{
object[] unwrappedArgs = UnwrapElementArguments(args);
WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.driver, script);
this.OnScriptExecuting(e);
scriptResult = javascriptDriver.ExecuteScript(script, unwrappedArgs);
this.OnScriptExecuted(e);
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return scriptResult;
}
/// <summary>
/// Executes JavaScript asynchronously in the context of the currently selected frame or window.
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="args">The arguments to the script.</param>
/// <returns>The value returned by the script.</returns>
public object ExecuteAsyncScript(string script, params object[] args)
{
object scriptResult = null;
IJavaScriptExecutor javascriptDriver = this.driver as IJavaScriptExecutor;
if (javascriptDriver == null)
{
throw new NotSupportedException("Underlying driver instance does not support executing JavaScript");
}
try
{
object[] unwrappedArgs = UnwrapElementArguments(args);
WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.driver, script);
this.OnScriptExecuting(e);
scriptResult = javascriptDriver.ExecuteAsyncScript(script, unwrappedArgs);
this.OnScriptExecuted(e);
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return scriptResult;
}
/// <summary>
/// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen.
/// </summary>
/// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
public Screenshot GetScreenshot()
{
ITakesScreenshot screenshotDriver = this.driver as ITakesScreenshot;
if (this.driver == null)
{
throw new NotSupportedException("Underlying driver instance does not support taking screenshots");
}
Screenshot screen = null;
screen = screenshotDriver.GetScreenshot();
return screen;
}
/// <summary>
/// Frees all managed and, optionally, unmanaged resources used by this instance.
/// </summary>
/// <param name="disposing"><see langword="true"/> to dispose of only managed resources;
/// <see langword="false"/> to dispose of managed and unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.driver.Dispose();
}
}
/// <summary>
/// Raises the <see cref="Navigating"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigating(WebDriverNavigationEventArgs e)
{
if (this.Navigating != null)
{
this.Navigating(this, e);
}
}
/// <summary>
/// Raises the <see cref="Navigated"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigated(WebDriverNavigationEventArgs e)
{
if (this.Navigated != null)
{
this.Navigated(this, e);
}
}
/// <summary>
/// Raises the <see cref="NavigatingBack"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigatingBack(WebDriverNavigationEventArgs e)
{
if (this.NavigatingBack != null)
{
this.NavigatingBack(this, e);
}
}
/// <summary>
/// Raises the <see cref="NavigatedBack"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigatedBack(WebDriverNavigationEventArgs e)
{
if (this.NavigatedBack != null)
{
this.NavigatedBack(this, e);
}
}
/// <summary>
/// Raises the <see cref="NavigatingForward"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigatingForward(WebDriverNavigationEventArgs e)
{
if (this.NavigatingForward != null)
{
this.NavigatingForward(this, e);
}
}
/// <summary>
/// Raises the <see cref="NavigatedForward"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigatedForward(WebDriverNavigationEventArgs e)
{
if (this.NavigatedForward != null)
{
this.NavigatedForward(this, e);
}
}
/// <summary>
/// Raises the <see cref="ElementClicking"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementEventArgs"/> that contains the event data.</param>
protected virtual void OnElementClicking(WebElementEventArgs e)
{
if (this.ElementClicking != null)
{
this.ElementClicking(this, e);
}
}
/// <summary>
/// Raises the <see cref="ElementClicked"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementEventArgs"/> that contains the event data.</param>
protected virtual void OnElementClicked(WebElementEventArgs e)
{
if (this.ElementClicked != null)
{
this.ElementClicked(this, e);
}
}
/// <summary>
/// Raises the <see cref="ElementValueChanging"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementEventArgs"/> that contains the event data.</param>
protected virtual void OnElementValueChanging(WebElementEventArgs e)
{
if (this.ElementValueChanging != null)
{
this.ElementValueChanging(this, e);
}
}
/// <summary>
/// Raises the <see cref="ElementValueChanged"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementEventArgs"/> that contains the event data.</param>
protected virtual void OnElementValueChanged(WebElementEventArgs e)
{
if (this.ElementValueChanged != null)
{
this.ElementValueChanged(this, e);
}
}
/// <summary>
/// Raises the <see cref="FindingElement"/> event.
/// </summary>
/// <param name="e">A <see cref="FindElementEventArgs"/> that contains the event data.</param>
protected virtual void OnFindingElement(FindElementEventArgs e)
{
if (this.FindingElement != null)
{
this.FindingElement(this, e);
}
}
/// <summary>
/// Raises the <see cref="FindElementCompleted"/> event.
/// </summary>
/// <param name="e">A <see cref="FindElementEventArgs"/> that contains the event data.</param>
protected virtual void OnFindElementCompleted(FindElementEventArgs e)
{
if (this.FindElementCompleted != null)
{
this.FindElementCompleted(this, e);
}
}
/// <summary>
/// Raises the <see cref="ScriptExecuting"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverScriptEventArgs"/> that contains the event data.</param>
protected virtual void OnScriptExecuting(WebDriverScriptEventArgs e)
{
if (this.ScriptExecuting != null)
{
this.ScriptExecuting(this, e);
}
}
/// <summary>
/// Raises the <see cref="ScriptExecuted"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverScriptEventArgs"/> that contains the event data.</param>
protected virtual void OnScriptExecuted(WebDriverScriptEventArgs e)
{
if (this.ScriptExecuted != null)
{
this.ScriptExecuted(this, e);
}
}
/// <summary>
/// Raises the <see cref="ExceptionThrown"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverExceptionEventArgs"/> that contains the event data.</param>
protected virtual void OnException(WebDriverExceptionEventArgs e)
{
if (this.ExceptionThrown != null)
{
this.ExceptionThrown(this, e);
}
}
private static object[] UnwrapElementArguments(object[] args)
{
// Walk the args: the various drivers expect unwrapped versions of the elements
List<object> unwrappedArgs = new List<object>();
foreach (object arg in args)
{
EventFiringWebElement eventElementArg = arg as EventFiringWebElement;
if (eventElementArg != null)
{
unwrappedArgs.Add(eventElementArg.WrappedElement);
}
else
{
unwrappedArgs.Add(arg);
}
}
return unwrappedArgs.ToArray();
}
private IWebElement WrapElement(IWebElement underlyingElement)
{
IWebElement wrappedElement = new EventFiringWebElement(this, underlyingElement);
return wrappedElement;
}
/// <summary>
/// Provides a mechanism for Navigating with the driver.
/// </summary>
private class EventFiringNavigation : INavigation
{
private EventFiringWebDriver parentDriver;
private INavigation wrappedNavigation;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringNavigation"/> class
/// </summary>
/// <param name="driver">Driver in use</param>
public EventFiringNavigation(EventFiringWebDriver driver)
{
this.parentDriver = driver;
this.wrappedNavigation = this.parentDriver.WrappedDriver.Navigate();
}
/// <summary>
/// Move the browser back
/// </summary>
public void Back()
{
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver);
this.parentDriver.OnNavigatingBack(e);
this.wrappedNavigation.Back();
this.parentDriver.OnNavigatedBack(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Move the browser forward
/// </summary>
public void Forward()
{
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver);
this.parentDriver.OnNavigatingForward(e);
this.wrappedNavigation.Forward();
this.parentDriver.OnNavigatedForward(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Navigate to a url for your test
/// </summary>
/// <param name="url">String of where you want the browser to go to</param>
public void GoToUrl(string url)
{
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver, url);
this.parentDriver.OnNavigating(e);
this.wrappedNavigation.GoToUrl(url);
this.parentDriver.OnNavigated(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Navigate to a url for your test
/// </summary>
/// <param name="url">Uri object of where you want the browser to go to</param>
public void GoToUrl(Uri url)
{
if (url == null)
{
throw new ArgumentNullException("url", "url cannot be null");
}
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver, url.ToString());
this.parentDriver.OnNavigating(e);
this.wrappedNavigation.GoToUrl(url);
this.parentDriver.OnNavigated(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Refresh the browser
/// </summary>
public void Refresh()
{
try
{
this.wrappedNavigation.Refresh();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
}
/// <summary>
/// Provides a mechanism for setting options needed for the driver during the test.
/// </summary>
private class EventFiringOptions : IOptions
{
private IOptions wrappedOptions;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringOptions"/> class
/// </summary>
/// <param name="driver">Instance of the driver currently in use</param>
public EventFiringOptions(EventFiringWebDriver driver)
{
this.wrappedOptions = driver.WrappedDriver.Manage();
}
/// <summary>
/// Gets an object allowing the user to manipulate cookies on the page.
/// </summary>
public ICookieJar Cookies
{
get { return this.wrappedOptions.Cookies; }
}
/// <summary>
/// Gets an object allowing the user to manipulate the currently-focused browser window.
/// </summary>
/// <remarks>"Currently-focused" is defined as the browser window having the window handle
/// returned when IWebDriver.CurrentWindowHandle is called.</remarks>
public IWindow Window
{
get { return this.wrappedOptions.Window; }
}
public ILogs Logs
{
get { return this.wrappedOptions.Logs; }
}
/// <summary>
/// Provides access to the timeouts defined for this driver.
/// </summary>
/// <returns>An object implementing the <see cref="ITimeouts"/> interface.</returns>
public ITimeouts Timeouts()
{
return new EventFiringTimeouts(this.wrappedOptions);
}
}
/// <summary>
/// Provides a mechanism for finding elements on the page with locators.
/// </summary>
private class EventFiringTargetLocator : ITargetLocator
{
private ITargetLocator wrappedLocator;
private EventFiringWebDriver parentDriver;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringTargetLocator"/> class
/// </summary>
/// <param name="driver">The driver that is currently in use</param>
public EventFiringTargetLocator(EventFiringWebDriver driver)
{
this.parentDriver = driver;
this.wrappedLocator = this.parentDriver.WrappedDriver.SwitchTo();
}
/// <summary>
/// Move to a different frame using its index
/// </summary>
/// <param name="frameIndex">The index of the </param>
/// <returns>A WebDriver instance that is currently in use</returns>
public IWebDriver Frame(int frameIndex)
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.Frame(frameIndex);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Move to different frame using its name
/// </summary>
/// <param name="frameName">name of the frame</param>
/// <returns>A WebDriver instance that is currently in use</returns>
public IWebDriver Frame(string frameName)
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.Frame(frameName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Move to a frame element.
/// </summary>
/// <param name="frameElement">a previously found FRAME or IFRAME element.</param>
/// <returns>A WebDriver instance that is currently in use.</returns>
public IWebDriver Frame(IWebElement frameElement)
{
IWebDriver driver = null;
try
{
IWrapsElement wrapper = frameElement as IWrapsElement;
driver = this.wrappedLocator.Frame(wrapper.WrappedElement);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Select the parent frame of the currently selected frame.
/// </summary>
/// <returns>An <see cref="IWebDriver"/> instance focused on the specified frame.</returns>
public IWebDriver ParentFrame()
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.ParentFrame();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Change to the Window by passing in the name
/// </summary>
/// <param name="windowName">name of the window that you wish to move to</param>
/// <returns>A WebDriver instance that is currently in use</returns>
public IWebDriver Window(string windowName)
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.Window(windowName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Change the active frame to the default
/// </summary>
/// <returns>Element of the default</returns>
public IWebDriver DefaultContent()
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.DefaultContent();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Finds the active element on the page and returns it
/// </summary>
/// <returns>Element that is active</returns>
public IWebElement ActiveElement()
{
IWebElement element = null;
try
{
element = this.wrappedLocator.ActiveElement();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return element;
}
/// <summary>
/// Switches to the currently active modal dialog for this particular driver instance.
/// </summary>
/// <returns>A handle to the dialog.</returns>
public IAlert Alert()
{
IAlert alert = null;
try
{
alert = this.wrappedLocator.Alert();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return alert;
}
}
/// <summary>
/// Defines the interface through which the user can define timeouts.
/// </summary>
private class EventFiringTimeouts : ITimeouts
{
private ITimeouts wrappedTimeouts;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringTimeouts"/> class
/// </summary>
/// <param name="options">The <see cref="IOptions"/> object to wrap.</param>
public EventFiringTimeouts(IOptions options)
{
this.wrappedTimeouts = options.Timeouts();
}
/// <summary>
/// Gets or sets the implicit wait timeout, which is the amount of time the
/// driver should wait when searching for an element if it is not immediately
/// present.
/// </summary>
/// <remarks>
/// When searching for a single element, the driver should poll the page
/// until the element has been found, or this timeout expires before throwing
/// a <see cref="NoSuchElementException"/>. When searching for multiple elements,
/// the driver should poll the page until at least one element has been found
/// or this timeout has expired.
/// <para>
/// Increasing the implicit wait timeout should be used judiciously as it
/// will have an adverse effect on test run time, especially when used with
/// slower location strategies like XPath.
/// </para>
/// </remarks>
public TimeSpan ImplicitWait
{
get { return this.wrappedTimeouts.ImplicitWait; }
set { this.wrappedTimeouts.ImplicitWait = value; }
}
/// <summary>
/// Gets or sets the asynchronous script timeout, which is the amount
/// of time the driver should wait when executing JavaScript asynchronously.
/// This timeout only affects the <see cref="IJavaScriptExecutor.ExecuteAsyncScript(string, object[])"/>
/// method.
/// </summary>
public TimeSpan AsynchronousJavaScript
{
get { return this.wrappedTimeouts.AsynchronousJavaScript; }
set { this.wrappedTimeouts.AsynchronousJavaScript = value; }
}
/// <summary>
/// Gets or sets the page load timeout, which is the amount of time the driver
/// should wait for a page to load when setting the <see cref="IWebDriver.Url"/>
/// property.
/// </summary>
public TimeSpan PageLoad
{
get { return this.wrappedTimeouts.PageLoad; }
set { this.wrappedTimeouts.PageLoad = value; }
}
}
/// <summary>
/// EventFiringWebElement allows you to have access to specific items that are found on the page
/// </summary>
private class EventFiringWebElement : IWebElement, IWrapsElement
{
private IWebElement underlyingElement;
private EventFiringWebDriver parentDriver;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringWebElement"/> class.
/// </summary>
/// <param name="driver">The <see cref="EventFiringWebDriver"/> instance hosting this element.</param>
/// <param name="element">The <see cref="IWebElement"/> to wrap for event firing.</param>
public EventFiringWebElement(EventFiringWebDriver driver, IWebElement element)
{
this.underlyingElement = element;
this.parentDriver = driver;
}
/// <summary>
/// Gets the underlying wrapped <see cref="IWebElement"/>.
/// </summary>
public IWebElement WrappedElement
{
get { return this.underlyingElement; }
}
/// <summary>
/// Gets the DOM Tag of element
/// </summary>
public string TagName
{
get
{
string tagName = string.Empty;
try
{
tagName = this.underlyingElement.TagName;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return tagName;
}
}
/// <summary>
/// Gets the text from the element
/// </summary>
public string Text
{
get
{
string text = string.Empty;
try
{
text = this.underlyingElement.Text;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return text;
}
}
/// <summary>
/// Gets a value indicating whether an element is currently enabled
/// </summary>
public bool Enabled
{
get
{
bool enabled = false;
try
{
enabled = this.underlyingElement.Enabled;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return enabled;
}
}
/// <summary>
/// Gets a value indicating whether this element is selected or not. This operation only applies to input elements such as checkboxes, options in a select and radio buttons.
/// </summary>
public bool Selected
{
get
{
bool selected = false;
try
{
selected = this.underlyingElement.Selected;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return selected;
}
}
/// <summary>
/// Gets the Location of an element and returns a Point object
/// </summary>
public Point Location
{
get
{
Point location = default(Point);
try
{
location = this.underlyingElement.Location;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return location;
}
}
/// <summary>
/// Gets the <see cref="Size"/> of the element on the page
/// </summary>
public Size Size
{
get
{
Size size = default(Size);
try
{
size = this.underlyingElement.Size;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return size;
}
}
/// <summary>
/// Gets a value indicating whether the element is currently being displayed
/// </summary>
public bool Displayed
{
get
{
bool displayed = false;
try
{
displayed = this.underlyingElement.Displayed;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return displayed;
}
}
/// <summary>
/// Gets the underlying EventFiringWebDriver for this element.
/// </summary>
protected EventFiringWebDriver ParentDriver
{
get { return this.parentDriver; }
}
/// <summary>
/// Method to clear the text out of an Input element
/// </summary>
public void Clear()
{
try
{
WebElementEventArgs e = new WebElementEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement);
this.parentDriver.OnElementValueChanging(e);
this.underlyingElement.Clear();
this.parentDriver.OnElementValueChanged(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Method for sending native key strokes to the browser
/// </summary>
/// <param name="text">String containing what you would like to type onto the screen</param>
public void SendKeys(string text)
{
try
{
WebElementEventArgs e = new WebElementEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement);
this.parentDriver.OnElementValueChanging(e);
this.underlyingElement.SendKeys(text);
this.parentDriver.OnElementValueChanged(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// If this current element is a form, or an element within a form, then this will be submitted to the remote server.
/// If this causes the current page to change, then this method will block until the new page is loaded.
/// </summary>
public void Submit()
{
try
{
this.underlyingElement.Submit();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Click this element. If this causes a new page to load, this method will block until
/// the page has loaded. At this point, you should discard all references to this element
/// and any further operations performed on this element will have undefined behavior unless
/// you know that the element and the page will still be present. If this element is not
/// clickable, then this operation is a no-op since it's pretty common for someone to
/// accidentally miss the target when clicking in Real Life
/// </summary>
public void Click()
{
try
{
WebElementEventArgs e = new WebElementEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement);
this.parentDriver.OnElementClicking(e);
this.underlyingElement.Click();
this.parentDriver.OnElementClicked(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// If this current element is a form, or an element within a form, then this will be submitted to the remote server. If this causes the current page to change, then this method will block until the new page is loaded.
/// </summary>
/// <param name="attributeName">Attribute you wish to get details of</param>
/// <returns>The attribute's current value or null if the value is not set.</returns>
public string GetAttribute(string attributeName)
{
string attribute = string.Empty;
try
{
attribute = this.underlyingElement.GetAttribute(attributeName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return attribute;
}
/// <summary>
/// Gets the value of a JavaScript property of this element.
/// </summary>
/// <param name="propertyName">The name JavaScript the JavaScript property to get the value of.</param>
/// <returns>The JavaScript property's current value. Returns a <see langword="null"/> if the
/// value is not set or the property does not exist.</returns>
public string GetProperty(string propertyName)
{
string elementProperty = string.Empty;
try
{
elementProperty = this.underlyingElement.GetProperty(propertyName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return elementProperty;
}
/// <summary>
/// Method to return the value of a CSS Property
/// </summary>
/// <param name="propertyName">CSS property key</param>
/// <returns>string value of the CSS property</returns>
public string GetCssValue(string propertyName)
{
string cssValue = string.Empty;
try
{
cssValue = this.underlyingElement.GetCssValue(propertyName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return cssValue;
}
/// <summary>
/// Finds the first element in the page that matches the <see cref="By"/> object
/// </summary>
/// <param name="by">By mechanism to find the element</param>
/// <returns>IWebElement object so that you can interaction that object</returns>
public IWebElement FindElement(By by)
{
IWebElement wrappedElement = null;
try
{
FindElementEventArgs e = new FindElementEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement, by);
this.parentDriver.OnFindingElement(e);
IWebElement element = this.underlyingElement.FindElement(by);
this.parentDriver.OnFindElementCompleted(e);
wrappedElement = this.parentDriver.WrapElement(element);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return wrappedElement;
}
/// <summary>
/// Finds the elements on the page by using the <see cref="By"/> object and returns a ReadOnlyCollection of the Elements on the page
/// </summary>
/// <param name="by">By mechanism to find the element</param>
/// <returns>ReadOnlyCollection of IWebElement</returns>
public ReadOnlyCollection<IWebElement> FindElements(By by)
{
List<IWebElement> wrappedElementList = new List<IWebElement>();
try
{
FindElementEventArgs e = new FindElementEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement, by);
this.parentDriver.OnFindingElement(e);
ReadOnlyCollection<IWebElement> elements = this.underlyingElement.FindElements(by);
this.parentDriver.OnFindElementCompleted(e);
foreach (IWebElement element in elements)
{
IWebElement wrappedElement = this.parentDriver.WrapElement(element);
wrappedElementList.Add(wrappedElement);
}
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return wrappedElementList.AsReadOnly();
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Dialogflow.Cx.V3.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedEnvironmentsClientTest
{
[xunit::FactAttribute]
public void GetEnvironmentRequestObject()
{
moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEnvironmentRequest request = new GetEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
};
Environment expectedResponse = new Environment
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
UpdateTime = new wkt::Timestamp(),
VersionConfigs =
{
new Environment.Types.VersionConfig(),
},
TestCasesConfig = new Environment.Types.TestCasesConfig(),
};
mockGrpcClient.Setup(x => x.GetEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null);
Environment response = client.GetEnvironment(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEnvironmentRequestObjectAsync()
{
moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEnvironmentRequest request = new GetEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
};
Environment expectedResponse = new Environment
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
UpdateTime = new wkt::Timestamp(),
VersionConfigs =
{
new Environment.Types.VersionConfig(),
},
TestCasesConfig = new Environment.Types.TestCasesConfig(),
};
mockGrpcClient.Setup(x => x.GetEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Environment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null);
Environment responseCallSettings = await client.GetEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Environment responseCancellationToken = await client.GetEnvironmentAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetEnvironment()
{
moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEnvironmentRequest request = new GetEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
};
Environment expectedResponse = new Environment
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
UpdateTime = new wkt::Timestamp(),
VersionConfigs =
{
new Environment.Types.VersionConfig(),
},
TestCasesConfig = new Environment.Types.TestCasesConfig(),
};
mockGrpcClient.Setup(x => x.GetEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null);
Environment response = client.GetEnvironment(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEnvironmentAsync()
{
moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEnvironmentRequest request = new GetEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
};
Environment expectedResponse = new Environment
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
UpdateTime = new wkt::Timestamp(),
VersionConfigs =
{
new Environment.Types.VersionConfig(),
},
TestCasesConfig = new Environment.Types.TestCasesConfig(),
};
mockGrpcClient.Setup(x => x.GetEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Environment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null);
Environment responseCallSettings = await client.GetEnvironmentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Environment responseCancellationToken = await client.GetEnvironmentAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetEnvironmentResourceNames()
{
moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEnvironmentRequest request = new GetEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
};
Environment expectedResponse = new Environment
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
UpdateTime = new wkt::Timestamp(),
VersionConfigs =
{
new Environment.Types.VersionConfig(),
},
TestCasesConfig = new Environment.Types.TestCasesConfig(),
};
mockGrpcClient.Setup(x => x.GetEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null);
Environment response = client.GetEnvironment(request.EnvironmentName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEnvironmentResourceNamesAsync()
{
moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEnvironmentRequest request = new GetEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
};
Environment expectedResponse = new Environment
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
UpdateTime = new wkt::Timestamp(),
VersionConfigs =
{
new Environment.Types.VersionConfig(),
},
TestCasesConfig = new Environment.Types.TestCasesConfig(),
};
mockGrpcClient.Setup(x => x.GetEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Environment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null);
Environment responseCallSettings = await client.GetEnvironmentAsync(request.EnvironmentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Environment responseCancellationToken = await client.GetEnvironmentAsync(request.EnvironmentName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteEnvironmentRequestObject()
{
moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteEnvironmentRequest request = new DeleteEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null);
client.DeleteEnvironment(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteEnvironmentRequestObjectAsync()
{
moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteEnvironmentRequest request = new DeleteEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null);
await client.DeleteEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteEnvironmentAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteEnvironment()
{
moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteEnvironmentRequest request = new DeleteEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null);
client.DeleteEnvironment(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteEnvironmentAsync()
{
moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteEnvironmentRequest request = new DeleteEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null);
await client.DeleteEnvironmentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteEnvironmentAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteEnvironmentResourceNames()
{
moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteEnvironmentRequest request = new DeleteEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteEnvironment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null);
client.DeleteEnvironment(request.EnvironmentName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteEnvironmentResourceNamesAsync()
{
moq::Mock<Environments.EnvironmentsClient> mockGrpcClient = new moq::Mock<Environments.EnvironmentsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteEnvironmentRequest request = new DeleteEnvironmentRequest
{
EnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteEnvironmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EnvironmentsClient client = new EnvironmentsClientImpl(mockGrpcClient.Object, null);
await client.DeleteEnvironmentAsync(request.EnvironmentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteEnvironmentAsync(request.EnvironmentName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record.Chart
{
using System;
using System.Text;
using NPOI.Util;
/**
* The area format record is used to define the colours and patterns for an area.
* NOTE: This source is automatically generated please do not modify this file. Either subclass or
* Remove the record in src/records/definitions.
* @author Glen Stampoultzis (glens at apache.org)
*/
public class AreaFormatRecord : StandardRecord, ICloneable
{
public const short FILL_PATTERN_NONE = 0x0;
public const short FILL_PATTERN_SOLID = 0x1;
public const short FILL_PATTERN_MEDIUM_GRAY = 0x2;
public const short FILL_PATTERN_DARK_GRAY = 0x3;
public const short FILL_PATTERN_LIGHT_GRAY = 0x4;
public const short FILL_PATTERN_HORIZONTAL_STRIPES = 0x5;
public const short FILL_PATTERN_VERTICAL_STRIPES = 0x6;
public const short FILL_PATTERN_DOWNWARD_DIAGONAL_STRIPES = 0x7;
public const short FILL_PATTERN_UPWARD_DIAGONAL_STRIPES = 0x8;
public const short FILL_PATTERN_GRID = 0x9;
public const short FILL_PATTERN_TRELLIS = 0xA;
public const short FILL_PATTERN_LIGHT_HORIZONTAL_STRIPES = 0xB;
public const short FILL_PATTERN_LIGHT_VERTICAL_STRIPES = 0xC;
public const short FILL_PATTERN_LIGHTDOWN= 0xD;
public const short FILL_PATTERN_LIGHTUP = 0xE;
public const short FILL_PATTERN_LIGHT_GRID = 0xF;
public const short FILL_PATTERN_LIGHT_TRELLIS = 0x10;
public const short FILL_PATTERN_GRAYSCALE_1_8 = 0x11;
public const short FILL_PATTERN_GRAYSCALE_1_16 = 0x12;
public const short sid = 0x100a;
private int field_1_foregroundColor;
private int field_2_backgroundColor;
private short field_3_pattern;
private short field_4_formatFlags;
private BitField automatic = BitFieldFactory.GetInstance(0x1);
private BitField invert = BitFieldFactory.GetInstance(0x2);
private short field_5_forecolorIndex;
private short field_6_backcolorIndex;
public AreaFormatRecord()
{
}
/**
* Constructs a AreaFormat record and s its fields appropriately.
*
* @param in the RecordInputstream to Read the record from
*/
public AreaFormatRecord(RecordInputStream in1)
{
field_1_foregroundColor = in1.ReadInt();
field_2_backgroundColor = in1.ReadInt();
field_3_pattern = in1.ReadShort();
field_4_formatFlags = in1.ReadShort();
field_5_forecolorIndex = in1.ReadShort();
field_6_backcolorIndex = in1.ReadShort();
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[AREAFORMAT]\n");
buffer.Append(" .foregroundColor = ")
.Append("0x").Append(HexDump.ToHex(ForegroundColor))
.Append(" (").Append(ForegroundColor).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .backgroundColor = ")
.Append("0x").Append(HexDump.ToHex(BackgroundColor))
.Append(" (").Append(BackgroundColor).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .pattern = ")
.Append("0x").Append(HexDump.ToHex(Pattern))
.Append(" (").Append(Pattern).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .formatFlags = ")
.Append("0x").Append(HexDump.ToHex(FormatFlags))
.Append(" (").Append(FormatFlags).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .automatic = ").Append(IsAutomatic).Append('\n');
buffer.Append(" .invert = ").Append(IsInvert).Append('\n');
buffer.Append(" .forecolorIndex = ")
.Append("0x").Append(HexDump.ToHex(ForecolorIndex))
.Append(" (").Append(ForecolorIndex).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .backcolorIndex = ")
.Append("0x").Append(HexDump.ToHex(BackcolorIndex))
.Append(" (").Append(BackcolorIndex).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append("[/AREAFORMAT]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteInt(field_1_foregroundColor);
out1.WriteInt(field_2_backgroundColor);
out1.WriteShort(field_3_pattern);
out1.WriteShort(field_4_formatFlags);
out1.WriteShort(field_5_forecolorIndex);
out1.WriteShort(field_6_backcolorIndex);
}
/**
* Size of record (exluding 4 byte header)
*/
protected override int DataSize
{
get{ return 4 + 4 + 2 + 2 + 2 + 2; }
}
public override short Sid
{
get{ return sid; }
}
public override Object Clone()
{
AreaFormatRecord rec = new AreaFormatRecord();
rec.field_1_foregroundColor = field_1_foregroundColor;
rec.field_2_backgroundColor = field_2_backgroundColor;
rec.field_3_pattern = field_3_pattern;
rec.field_4_formatFlags = field_4_formatFlags;
rec.field_5_forecolorIndex = field_5_forecolorIndex;
rec.field_6_backcolorIndex = field_6_backcolorIndex;
return rec;
}
/**
* the foreground color field for the AreaFormat record.
*/
public int ForegroundColor
{
get{return field_1_foregroundColor;}
set{this.field_1_foregroundColor = value;}
}
/**
* the background color field for the AreaFormat record.
*/
public int BackgroundColor
{
get{return field_2_backgroundColor;}
set{this.field_2_backgroundColor=value;}
}
/**
* the pattern field for the AreaFormat record.
*/
public short Pattern
{
get{return field_3_pattern;}
set{this.field_3_pattern =value;}
}
/**
* the format flags field for the AreaFormat record.
*/
public short FormatFlags
{
get{return field_4_formatFlags;}
set{this.field_4_formatFlags =value;}
}
/**
* the forecolor index field for the AreaFormat record.
*/
public short ForecolorIndex
{
get{return field_5_forecolorIndex;}
set{this.field_5_forecolorIndex =value;}
}
/**
* the backcolor index field for the AreaFormat record.
*/
public short BackcolorIndex
{
get{return field_6_backcolorIndex;}
set{this.field_6_backcolorIndex =value;}
}
/**
* automatic formatting
* @return the automatic field value.
*/
public bool IsAutomatic
{
get{return automatic.IsSet(field_4_formatFlags);}
set{
field_4_formatFlags = automatic.SetShortBoolean(field_4_formatFlags, value);
}
}
/**
* swap foreground and background colours when data is negative
* @return the invert field value.
*/
public bool IsInvert
{
get{return invert.IsSet(field_4_formatFlags);}
set{ field_4_formatFlags = invert.SetShortBoolean(field_4_formatFlags, value);}
}
}
}
| |
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace UMA.CharacterSystem.Editors
{
[CustomPropertyDrawer (typeof(DynamicCharacterAvatar.RaceAnimatorList))]
public class RaceAnimatorListPropertyDrawer : PropertyDrawer
{
float padding = 2f;
public DynamicCharacterAvatar thisDCA;
Texture2D warningIcon;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label){
if (warningIcon == null)
{
warningIcon = EditorGUIUtility.FindTexture("console.warnicon.sml");
}
EditorGUI.BeginProperty (position, label, property);
var r0 = new Rect (position.xMin, position.yMin, position.width, EditorGUIUtility.singleLineHeight);
SerializedProperty foldoutProp1 = property.FindPropertyRelative ("defaultAnimationController");
foldoutProp1.isExpanded = EditorGUI.Foldout (r0, foldoutProp1.isExpanded, "Race Animation Controllers");
if (foldoutProp1.isExpanded) {
EditorGUI.indentLevel++;
var valR = r0;
valR = new Rect (valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
EditorGUI.PropertyField (valR,property.FindPropertyRelative ("defaultAnimationController"));
valR = new Rect (valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
SerializedProperty foldoutProp2 = property.FindPropertyRelative ("animators");
foldoutProp2.isExpanded = EditorGUI.Foldout (valR, foldoutProp2.isExpanded, "Race Animators");
//we cant delete elements in the loop so ...
List<int> willDeleteArrayElementAtIndex = new List<int> ();
if (foldoutProp2.isExpanded) {
EditorGUI.indentLevel++;
var thisAnimatorsProp = property.FindPropertyRelative ("animators");
var numAnimators = thisAnimatorsProp.arraySize;
var warningStyle = new GUIStyle(EditorStyles.label);
warningStyle.fixedHeight = warningIcon.height + 4f;
warningStyle.contentOffset = new Vector2(0, -2f);
for (int i = 0; i < numAnimators; i++) {
var thisAnimtorProp = thisAnimatorsProp.GetArrayElementAtIndex (i);
valR = new Rect (valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
var propsR = valR;
propsR.width = propsR.width - 20f;
var rPropR = propsR;
rPropR.width = rPropR.width / 2;
var aPropR = rPropR;
aPropR.x = propsR.x + rPropR.width;
var rLabelR = rPropR;
rLabelR.width = (float)(rLabelR.width * 0.3)+(15f * (EditorGUI.indentLevel -1));
var rFieldR = rPropR;
rFieldR.x = rFieldR.x + rLabelR.width;
rFieldR.width = rFieldR.width - rLabelR.width;
//
var aLabelR = aPropR;
aLabelR.width = (float)(aLabelR.width * 0.3);
var aFieldR = aPropR;
aFieldR.x = aFieldR.x + aLabelR.width;
aFieldR.width = aFieldR.width - aLabelR.width;
var removeR = propsR;
removeR.x = aFieldR.xMax;
removeR.width = 20f;
EditorGUI.LabelField (rLabelR, "Race");
EditorGUI.indentLevel--;
EditorGUI.indentLevel--;
if (thisAnimtorProp.FindPropertyRelative ("raceName").stringValue == "") {
//draw an object field for RaceData
EditorGUI.BeginChangeCheck();
RaceData thisRD = null;
thisRD = (RaceData)EditorGUI.ObjectField (rFieldR, thisRD, typeof(RaceData),false);
//if this gets filled set the values
if(EditorGUI.EndChangeCheck()){
if (thisRD != null) {
thisAnimatorsProp.GetArrayElementAtIndex (i).FindPropertyRelative ("raceName").stringValue = thisRD.raceName;
}
}
}
else
{
EditorGUI.BeginDisabledGroup (true);
EditorGUI.TextField (rFieldR, thisAnimtorProp.FindPropertyRelative ("raceName").stringValue);
EditorGUI.EndDisabledGroup ();
}
EditorGUI.LabelField (aLabelR, "Animator");
var thisAnimatorName = thisAnimtorProp.FindPropertyRelative("animatorControllerName").stringValue;
if (thisAnimatorName == "")
{
//draw an object field for RunTimeAnimatorController
EditorGUI.BeginChangeCheck();
RuntimeAnimatorController thisRC = null;
thisRC = (RuntimeAnimatorController)EditorGUI.ObjectField (aFieldR, thisRC, typeof(RuntimeAnimatorController), false);
//if this gets filled set the values
if(EditorGUI.EndChangeCheck()){
if (thisRC != null) {
thisAnimatorsProp.GetArrayElementAtIndex (i).FindPropertyRelative ("animatorControllerName").stringValue = thisRC.name;
}
}
}
else
{
if (DynamicAssetLoader.Instance)
{
if (!CheckAnimatorAvailability(thisAnimatorName))
{
var warningRect = new Rect((removeR.xMin - 20f), removeR.yMin, 20f, removeR.height);
aFieldR.xMax = aFieldR.xMax - 20f;
//if its in an assetbundle we need a different message (i.e "turn on 'Dynamically Add From AssetBundles"')
var warningGUIContent = new GUIContent("", thisAnimtorProp.FindPropertyRelative("animatorControllerName").stringValue + " was not Live. If the asset is in an assetBundle check 'Dynamically Add from AssetBundles' below otherwise click this button to add it to the Global Library.");
warningGUIContent.image = warningIcon;
if (GUI.Button(warningRect, warningGUIContent, warningStyle))
{
var thisAnimator = FindMissingAnimator(thisAnimatorName);
if (thisAnimator != null)
UMAAssetIndexer.Instance.EvilAddAsset(thisAnimator.GetType(), thisAnimator);
else
UMAAssetIndexerEditor.ShowWindow();
}
}
}
EditorGUI.BeginDisabledGroup(true);
EditorGUI.TextField(aFieldR, thisAnimtorProp.FindPropertyRelative("animatorControllerName").stringValue);
EditorGUI.EndDisabledGroup();
}
if(GUI.Button(removeR,"X")){
willDeleteArrayElementAtIndex.Add(i);
}
EditorGUI.indentLevel++;
EditorGUI.indentLevel++;
}
if (willDeleteArrayElementAtIndex.Count > 0) {
foreach (int i in willDeleteArrayElementAtIndex) {
thisAnimatorsProp.DeleteArrayElementAtIndex (i);
}
}
thisAnimatorsProp.serializedObject.ApplyModifiedProperties();
valR = new Rect (valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
var butValR = valR;
//GUI doesn't know EditorGUI.indentLevel
butValR.xMin = valR.xMin + (15 * EditorGUI.indentLevel);
if(GUI.Button(butValR,"Add Race Animator")){
//add a new element to the list
thisAnimatorsProp.InsertArrayElementAtIndex(numAnimators);
thisAnimatorsProp.serializedObject.ApplyModifiedProperties();
//make sure its blank
thisAnimatorsProp.GetArrayElementAtIndex(numAnimators).FindPropertyRelative("raceName").stringValue = "";
thisAnimatorsProp.GetArrayElementAtIndex(numAnimators).FindPropertyRelative("animatorControllerName").stringValue = "";
thisAnimatorsProp.GetArrayElementAtIndex(numAnimators).FindPropertyRelative("animatorController").objectReferenceValue = null;
thisAnimatorsProp.serializedObject.ApplyModifiedProperties();
}
EditorGUI.indentLevel--;
}
valR = new Rect (valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
var dynamicallyAddFromResources = property.FindPropertyRelative ("dynamicallyAddFromResources").boolValue;
EditorGUI.BeginChangeCheck();
dynamicallyAddFromResources = EditorGUI.ToggleLeft(valR,"Dynamically Add from Global Library", dynamicallyAddFromResources);
if(EditorGUI.EndChangeCheck()){
property.FindPropertyRelative ("dynamicallyAddFromResources").boolValue = dynamicallyAddFromResources;
property.serializedObject.ApplyModifiedProperties ();
}
valR = new Rect (valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
EditorGUI.PropertyField (valR,property.FindPropertyRelative ("resourcesFolderPath"), new GUIContent("Global Library Folder Filter"));
valR = new Rect (valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
var dynamicallyAddFromAssetBundles = property.FindPropertyRelative ("dynamicallyAddFromAssetBundles").boolValue;
EditorGUI.BeginChangeCheck();
dynamicallyAddFromAssetBundles = EditorGUI.ToggleLeft(valR,"Dynamically Add from Asset Bundles", dynamicallyAddFromAssetBundles);
if(EditorGUI.EndChangeCheck()){
property.FindPropertyRelative ("dynamicallyAddFromAssetBundles").boolValue = dynamicallyAddFromAssetBundles;
property.serializedObject.ApplyModifiedProperties ();
}
valR = new Rect (valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
EditorGUI.PropertyField (valR,property.FindPropertyRelative ("assetBundleNames"), new GUIContent("AssetBundles to Search"));
EditorGUI.indentLevel--;
}
EditorGUI.EndProperty ();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label){
float h = EditorGUIUtility.singleLineHeight + padding;
int extraLines = 0;
SerializedProperty foldoutProp1 = property.FindPropertyRelative ("defaultAnimationController");
SerializedProperty foldoutProp2 = property.FindPropertyRelative ("animators");
if (foldoutProp1.isExpanded) {
extraLines += 6;
if (foldoutProp2.isExpanded) {
var thisAnimatorsProp = property.FindPropertyRelative ("animators");
extraLines += thisAnimatorsProp.arraySize;
extraLines++;
}
h *= (extraLines);
h += 10 + (extraLines * padding);
}
return h;
}
/// <summary>
/// with RuntimeAnimatorControllers, DynamicCharacterAvatar ony has a direct refrence for the default animator
/// (so that other animators can be assigned that can exist in asset bundles). The only way to get the others is from DynamicAssetLoader
/// so they MUST be in an assetBundle or in GlobalIndex or there is no way of finding them, if they are not, show a warning.
/// </summary>
/// <param name="recipeName"></param>
/// <returns></returns>
private bool CheckAnimatorAvailability(string racName)
{
if (Application.isPlaying)
return true;
bool found = false;
bool searchResources = true;
bool searchAssetBundles = true;
string resourcesFolderPath = "";
string assetBundlesToSearch = "";
RuntimeAnimatorController defaultController = null;
if (thisDCA != null)
{
searchResources = thisDCA.raceAnimationControllers.dynamicallyAddFromResources;
searchAssetBundles = thisDCA.raceAnimationControllers.dynamicallyAddFromAssetBundles;
resourcesFolderPath = thisDCA.raceAnimationControllers.resourcesFolderPath;
assetBundlesToSearch = thisDCA.raceAnimationControllers.assetBundleNames;
defaultController = thisDCA.raceAnimationControllers.defaultAnimationController != null ? thisDCA.raceAnimationControllers.defaultAnimationController : (thisDCA.animationController != null ? thisDCA.animationController : null);
}
if (defaultController)
if (defaultController.name == racName)
return true;
var dalDebug = DynamicAssetLoader.Instance.debugOnFail;
DynamicAssetLoader.Instance.debugOnFail = false;
found = DynamicAssetLoader.Instance.AddAssets<RuntimeAnimatorController>(searchResources, searchAssetBundles, true, assetBundlesToSearch, resourcesFolderPath, null, racName, null);
DynamicAssetLoader.Instance.debugOnFail = dalDebug;
return found;
}
private RuntimeAnimatorController FindMissingAnimator(string animatorName)
{
RuntimeAnimatorController foundAnimator = null;
//the following will find things like femaleHair1 if 'maleHair1' is the recipe name
var foundWardrobeGUIDS = AssetDatabase.FindAssets("t:RuntimeAnimatorController " + animatorName);
if (foundWardrobeGUIDS.Length > 0)
{
foreach (string guid in foundWardrobeGUIDS)
{
var tempAsset = AssetDatabase.LoadAssetAtPath<RuntimeAnimatorController>(AssetDatabase.GUIDToAssetPath(guid));
if (tempAsset.name == animatorName)
{
foundAnimator = tempAsset;
break;
}
}
}
return foundAnimator;
}
}
#endif
}
| |
//
// delegate.cs: Delegate Handler
//
// Authors:
// Ravi Pratap (ravi@ximian.com)
// Miguel de Icaza (miguel@ximian.com)
// Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2001 Ximian, Inc (http://www.ximian.com)
// Copyright 2003-2009 Novell, Inc (http://www.novell.com)
// Copyright 2011 Xamarin Inc
//
using System;
#if STATIC
using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
using IKVM.Reflection;
using IKVM.Reflection.Emit;
#else
using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
using System.Reflection;
using System.Reflection.Emit;
#endif
namespace Mono.CSharp {
//
// Delegate container implementation
//
public class Delegate : TypeDefinition, IParametersMember
{
FullNamedExpression ReturnType;
readonly ParametersCompiled parameters;
Constructor Constructor;
Method InvokeBuilder;
Method BeginInvokeBuilder;
Method EndInvokeBuilder;
static readonly string[] attribute_targets = new string [] { "type", "return" };
public static readonly string InvokeMethodName = "Invoke";
Expression instance_expr;
ReturnParameter return_attributes;
SecurityType declarative_security;
const Modifiers MethodModifiers = Modifiers.PUBLIC | Modifiers.VIRTUAL;
const Modifiers AllowedModifiers =
Modifiers.NEW |
Modifiers.PUBLIC |
Modifiers.PROTECTED |
Modifiers.INTERNAL |
Modifiers.UNSAFE |
Modifiers.PRIVATE;
public Delegate (TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, ParametersCompiled param_list,
Attributes attrs)
: base (parent, name, attrs, MemberKind.Delegate)
{
this.ReturnType = type;
ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod_flags,
IsTopLevel ? Modifiers.INTERNAL :
Modifiers.PRIVATE, name.Location, Report);
parameters = param_list;
spec = new TypeSpec (Kind, null, this, null, ModFlags | Modifiers.SEALED);
}
#region Properties
public TypeSpec MemberType {
get {
return ReturnType.Type;
}
}
public AParametersCollection Parameters {
get {
return parameters;
}
}
public FullNamedExpression TypExpression {
get {
return ReturnType;
}
}
#endregion
public override void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
if (a.Target == AttributeTargets.ReturnValue) {
CreateReturnBuilder ();
return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
return;
}
if (a.IsValidSecurityAttribute ()) {
a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
return;
}
base.ApplyAttributeBuilder (a, ctor, cdata, pa);
}
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Delegate;
}
}
ReturnParameter CreateReturnBuilder ()
{
return return_attributes ?? (return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location));
}
protected override bool DoDefineMembers ()
{
var builtin_types = Compiler.BuiltinTypes;
var ctor_parameters = ParametersCompiled.CreateFullyResolved (
new [] {
new Parameter (new TypeExpression (builtin_types.Object, Location), "object", Parameter.Modifier.NONE, null, Location),
new Parameter (new TypeExpression (builtin_types.IntPtr, Location), "method", Parameter.Modifier.NONE, null, Location)
},
new [] {
builtin_types.Object,
builtin_types.IntPtr
}
);
Constructor = new Constructor (this, Constructor.ConstructorName,
Modifiers.PUBLIC, null, ctor_parameters, Location);
Constructor.Define ();
//
// Here the various methods like Invoke, BeginInvoke etc are defined
//
// First, call the `out of band' special method for
// defining recursively any types we need:
//
var p = parameters;
if (!p.Resolve (this))
return false;
//
// Invoke method
//
// Check accessibility
foreach (var partype in p.Types) {
if (!IsAccessibleAs (partype)) {
Report.SymbolRelatedToPreviousError (partype);
Report.Error (59, Location,
"Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
partype.GetSignatureForError (), GetSignatureForError ());
}
}
var ret_type = ReturnType.ResolveAsType (this);
if (ret_type == null)
return false;
//
// We don't have to check any others because they are all
// guaranteed to be accessible - they are standard types.
//
if (!IsAccessibleAs (ret_type)) {
Report.SymbolRelatedToPreviousError (ret_type);
Report.Error (58, Location,
"Inconsistent accessibility: return type `" +
ret_type.GetSignatureForError () + "' is less " +
"accessible than delegate `" + GetSignatureForError () + "'");
return false;
}
CheckProtectedModifier ();
if (Compiler.Settings.StdLib && ret_type.IsSpecialRuntimeType) {
Method.Error1599 (Location, ret_type, Report);
return false;
}
VarianceDecl.CheckTypeVariance (ret_type, Variance.Covariant, this);
var resolved_rt = new TypeExpression (ret_type, Location);
InvokeBuilder = new Method (this, resolved_rt, MethodModifiers, new MemberName (InvokeMethodName), p, null);
InvokeBuilder.Define ();
//
// Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
//
if (!IsCompilerGenerated) {
DefineAsyncMethods (resolved_rt);
}
return true;
}
void DefineAsyncMethods (TypeExpression returnType)
{
var iasync_result = Module.PredefinedTypes.IAsyncResult;
var async_callback = Module.PredefinedTypes.AsyncCallback;
//
// It's ok when async types don't exist, the delegate will have Invoke method only
//
if (!iasync_result.Define () || !async_callback.Define ())
return;
//
// BeginInvoke
//
ParametersCompiled async_parameters;
if (Parameters.Count == 0) {
async_parameters = ParametersCompiled.EmptyReadOnlyParameters;
} else {
var compiled = new Parameter[Parameters.Count];
for (int i = 0; i < compiled.Length; ++i) {
var p = parameters[i];
compiled[i] = new Parameter (new TypeExpression (parameters.Types[i], Location),
p.Name,
p.ModFlags & Parameter.Modifier.RefOutMask,
p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
}
async_parameters = new ParametersCompiled (compiled);
}
async_parameters = ParametersCompiled.MergeGenerated (Compiler, async_parameters, false,
new Parameter[] {
new Parameter (new TypeExpression (async_callback.TypeSpec, Location), "callback", Parameter.Modifier.NONE, null, Location),
new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, Location), "object", Parameter.Modifier.NONE, null, Location)
},
new [] {
async_callback.TypeSpec,
Compiler.BuiltinTypes.Object
}
);
BeginInvokeBuilder = new Method (this,
new TypeExpression (iasync_result.TypeSpec, Location), MethodModifiers,
new MemberName ("BeginInvoke"), async_parameters, null);
BeginInvokeBuilder.Define ();
//
// EndInvoke is a bit more interesting, all the parameters labeled as
// out or ref have to be duplicated here.
//
//
// Define parameters, and count out/ref parameters
//
ParametersCompiled end_parameters;
int out_params = 0;
foreach (Parameter p in Parameters.FixedParameters) {
if ((p.ModFlags & Parameter.Modifier.RefOutMask) != 0)
++out_params;
}
if (out_params > 0) {
Parameter[] end_params = new Parameter[out_params];
int param = 0;
for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
Parameter p = parameters [i];
if ((p.ModFlags & Parameter.Modifier.RefOutMask) == 0)
continue;
end_params [param++] = new Parameter (new TypeExpression (p.Type, Location),
p.Name,
p.ModFlags & Parameter.Modifier.RefOutMask,
p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
}
end_parameters = new ParametersCompiled (end_params);
} else {
end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
}
end_parameters = ParametersCompiled.MergeGenerated (Compiler, end_parameters, false,
new Parameter (
new TypeExpression (iasync_result.TypeSpec, Location),
"result", Parameter.Modifier.NONE, null, Location),
iasync_result.TypeSpec);
//
// Create method, define parameters, register parameters with type system
//
EndInvokeBuilder = new Method (this, returnType, MethodModifiers, new MemberName ("EndInvoke"), end_parameters, null);
EndInvokeBuilder.Define ();
}
public override void PrepareEmit ()
{
if ((caching_flags & Flags.CloseTypeCreated) != 0)
return;
InvokeBuilder.PrepareEmit ();
if (BeginInvokeBuilder != null) {
BeginInvokeBuilder.TypeExpression = null;
EndInvokeBuilder.TypeExpression = null;
BeginInvokeBuilder.PrepareEmit ();
EndInvokeBuilder.PrepareEmit ();
}
}
public override void Emit ()
{
base.Emit ();
if (declarative_security != null) {
foreach (var de in declarative_security) {
#if STATIC
TypeBuilder.__AddDeclarativeSecurity (de);
#else
TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
#endif
}
}
var rtype = ReturnType.Type;
if (rtype != null) {
if (rtype.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
Module.PredefinedAttributes.Dynamic.EmitAttribute (CreateReturnBuilder ().Builder);
} else if (rtype.HasDynamicElement) {
Module.PredefinedAttributes.Dynamic.EmitAttribute (CreateReturnBuilder ().Builder, rtype, Location);
}
if (rtype.HasNamedTupleElement) {
Module.PredefinedAttributes.TupleElementNames.EmitAttribute (CreateReturnBuilder ().Builder, rtype, Location);
}
ConstraintChecker.Check (this, ReturnType.Type, ReturnType.Location);
}
Constructor.ParameterInfo.ApplyAttributes (this, Constructor.ConstructorBuilder);
Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
parameters.CheckConstraints (this);
parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
if (BeginInvokeBuilder != null) {
BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
EndInvokeBuilder.ParameterInfo.ApplyAttributes (this, EndInvokeBuilder.MethodBuilder);
BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
}
}
protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
{
base_type = Compiler.BuiltinTypes.MulticastDelegate;
base_class = null;
return null;
}
protected override TypeAttributes TypeAttr {
get {
return base.TypeAttr | TypeAttributes.Class | TypeAttributes.Sealed;
}
}
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
//TODO: duplicate
protected override bool VerifyClsCompliance ()
{
if (!base.VerifyClsCompliance ()) {
return false;
}
parameters.VerifyClsCompliance (this);
if (!InvokeBuilder.MemberType.IsCLSCompliant ()) {
Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
GetSignatureForError ());
}
return true;
}
public static MethodSpec GetConstructor (TypeSpec delType)
{
var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
return (MethodSpec) ctor;
}
//
// Returns the "Invoke" from a delegate type
//
public static MethodSpec GetInvokeMethod (TypeSpec delType)
{
var invoke = MemberCache.FindMember (delType,
MemberFilter.Method (InvokeMethodName, 0, null, null),
BindingRestriction.DeclaredOnly);
return (MethodSpec) invoke;
}
public static AParametersCollection GetParameters (TypeSpec delType)
{
var invoke_mb = GetInvokeMethod (delType);
return invoke_mb.Parameters;
}
//
// 15.2 Delegate compatibility
//
public static bool IsTypeCovariant (ResolveContext rc, TypeSpec a, TypeSpec b)
{
//
// For each value parameter (a parameter with no ref or out modifier), an
// identity conversion or implicit reference conversion exists from the
// parameter type in D to the corresponding parameter type in M
//
if (a == b)
return true;
if (rc.Module.Compiler.Settings.Version == LanguageVersion.ISO_1)
return false;
if (a.IsGenericParameter && b.IsGenericParameter)
return a == b;
return Convert.ImplicitReferenceConversionExists (a, b);
}
public static string FullDelegateDesc (MethodSpec invoke_method)
{
return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
}
public Expression InstanceExpression {
get {
return instance_expr;
}
set {
instance_expr = value;
}
}
}
//
// Base class for `NewDelegate' and `ImplicitDelegateCreation'
//
public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
{
protected MethodSpec constructor_method;
protected MethodGroupExpr method_group;
public bool AllowSpecialMethodsInvocation { get; set; }
public override bool ContainsEmitWithAwait ()
{
var instance = method_group.InstanceExpression;
return instance != null && instance.ContainsEmitWithAwait ();
}
public static Arguments CreateDelegateMethodArguments (ResolveContext rc, AParametersCollection pd, TypeSpec[] types, Location loc)
{
Arguments delegate_arguments = new Arguments (pd.Count);
for (int i = 0; i < pd.Count; ++i) {
Argument.AType atype_modifier;
switch (pd.FixedParameters [i].ModFlags & Parameter.Modifier.RefOutMask) {
case Parameter.Modifier.REF:
atype_modifier = Argument.AType.Ref;
break;
case Parameter.Modifier.OUT:
atype_modifier = Argument.AType.Out;
break;
default:
atype_modifier = 0;
break;
}
var ptype = types[i];
if (ptype.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
ptype = rc.BuiltinTypes.Object;
delegate_arguments.Add (new Argument (new TypeExpression (ptype, loc), atype_modifier));
}
return delegate_arguments;
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
Arguments args = new Arguments (2);
args.Add (new Argument (new TypeOf (type, loc)));
if (method_group.InstanceExpression == null)
args.Add (new Argument (new NullLiteral (loc)));
else
args.Add (new Argument (method_group.InstanceExpression));
Expression ma;
var create_v45 = ec.Module.PredefinedMembers.MethodInfoCreateDelegate.Get ();
if (create_v45 != null) {
//
// .NET 4.5 has better API but it produces different instance than Delegate::CreateDelegate
// and because csc uses this enhancement we have to as well to be fully compatible
//
var mg = MethodGroupExpr.CreatePredefined (create_v45, create_v45.DeclaringType, loc);
mg.InstanceExpression = method_group.CreateExpressionTree (ec);
ma = mg;
} else {
ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
args.Add (new Argument (method_group.CreateExpressionTree (ec)));
}
Expression e = new Invocation (ma, args).Resolve (ec);
if (e == null)
return null;
e = Convert.ExplicitConversion (ec, e, type, loc);
if (e == null)
return null;
return e.CreateExpressionTree (ec);
}
void ResolveConditionalAccessReceiver (ResolveContext rc)
{
// LAMESPEC: Not sure why this is explicitly disallowed with very odd error message
if (!rc.HasSet (ResolveContext.Options.DontSetConditionalAccessReceiver) && method_group.HasConditionalAccess ()) {
Error_OperatorCannotBeApplied (rc, loc, "?", method_group.Type);
}
}
protected override Expression DoResolve (ResolveContext ec)
{
constructor_method = Delegate.GetConstructor (type);
var invoke_method = Delegate.GetInvokeMethod (type);
ResolveConditionalAccessReceiver (ec);
Arguments arguments = CreateDelegateMethodArguments (ec, invoke_method.Parameters, invoke_method.Parameters.Types, loc);
method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
if (method_group == null)
return null;
var delegate_method = method_group.BestCandidate;
if (delegate_method.DeclaringType.IsNullableType) {
ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
delegate_method.GetSignatureForError ());
return null;
}
if (!AllowSpecialMethodsInvocation)
Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
if (emg != null) {
method_group.InstanceExpression = emg.ExtensionExpression;
TypeSpec e_type = emg.ExtensionExpression.Type;
if (TypeSpec.IsValueType (e_type)) {
ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
delegate_method.GetSignatureForError (), e_type.GetSignatureForError ());
}
}
TypeSpec rt = method_group.BestCandidateReturnType;
if (rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
rt = ec.BuiltinTypes.Object;
if (!Delegate.IsTypeCovariant (ec, rt, invoke_method.ReturnType)) {
Error_ConversionFailed (ec, delegate_method, delegate_method.ReturnType);
}
if (method_group.IsConditionallyExcluded) {
ec.Report.SymbolRelatedToPreviousError (delegate_method);
MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
if (m != null && m.IsPartialDefinition) {
ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
delegate_method.GetSignatureForError ());
} else {
ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
TypeManager.CSharpSignature (delegate_method));
}
}
var expr = method_group.InstanceExpression;
if (expr != null && (expr.Type.IsGenericParameter || !TypeSpec.IsReferenceType (expr.Type)))
method_group.InstanceExpression = new BoxedCast (expr, ec.BuiltinTypes.Object);
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
if (method_group.InstanceExpression == null) {
ec.EmitNull ();
} else {
var ie = new InstanceEmitter (method_group.InstanceExpression, false);
ie.Emit (ec, method_group.ConditionalAccess);
}
var delegate_method = method_group.BestCandidate;
// Any delegate must be sealed
if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
ec.Emit (OpCodes.Dup);
ec.Emit (OpCodes.Ldvirtftn, delegate_method);
} else {
ec.Emit (OpCodes.Ldftn, delegate_method);
}
ec.Emit (OpCodes.Newobj, constructor_method);
}
public override void FlowAnalysis (FlowAnalysisContext fc)
{
base.FlowAnalysis (fc);
method_group.FlowAnalysis (fc);
}
void Error_ConversionFailed (ResolveContext ec, MethodSpec method, TypeSpec return_type)
{
var invoke_method = Delegate.GetInvokeMethod (type);
string member_name = method_group.InstanceExpression != null ?
Delegate.FullDelegateDesc (method) :
TypeManager.GetFullNameSignature (method);
ec.Report.SymbolRelatedToPreviousError (type);
ec.Report.SymbolRelatedToPreviousError (method);
if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
ec.Report.Error (410, loc, "A method or delegate `{0} {1}' parameters and return type must be same as delegate `{2} {3}' parameters and return type",
method.ReturnType.GetSignatureForError (), member_name,
invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
return;
}
if (return_type == null) {
ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
member_name, Delegate.FullDelegateDesc (invoke_method));
return;
}
if (invoke_method.ReturnType.Kind == MemberKind.ByRef) {
ec.Report.Error (8189, loc, "By reference return delegate does not match `{0}' return type",
Delegate.FullDelegateDesc (invoke_method));
return;
}
ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
return_type.GetSignatureForError (), member_name,
invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
}
public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
{
// if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
// return false;
var invoke = Delegate.GetInvokeMethod (target_type);
Arguments arguments = CreateDelegateMethodArguments (ec, invoke.Parameters, invoke.Parameters.Types, mg.Location);
mg = mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
return mg != null && Delegate.IsTypeCovariant (ec, mg.BestCandidateReturnType, invoke.ReturnType);
}
#region IErrorHandler Members
bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
{
return false;
}
bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
{
Error_ConversionFailed (rc, best as MethodSpec, null);
return true;
}
bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
{
Error_ConversionFailed (rc, best as MethodSpec, null);
return true;
}
bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
{
return false;
}
#endregion
}
//
// Created from the conversion code
//
public class ImplicitDelegateCreation : DelegateCreation
{
Field mg_cache;
public ImplicitDelegateCreation (TypeSpec delegateType, MethodGroupExpr mg, Location loc)
{
type = delegateType;
this.method_group = mg;
this.loc = loc;
}
//
// Returns true when type is MVAR or has MVAR reference
//
public static bool ContainsMethodTypeParameter (TypeSpec type)
{
var tps = type as TypeParameterSpec;
if (tps != null)
return tps.IsMethodOwned;
var ec = type as ElementTypeSpec;
if (ec != null)
return ContainsMethodTypeParameter (ec.Element);
foreach (var t in type.TypeArguments) {
if (ContainsMethodTypeParameter (t)) {
return true;
}
}
if (type.IsNested)
return ContainsMethodTypeParameter (type.DeclaringType);
return false;
}
bool HasMvar ()
{
if (ContainsMethodTypeParameter (type))
return false;
var best = method_group.BestCandidate;
if (ContainsMethodTypeParameter (best.DeclaringType))
return false;
if (best.TypeArguments != null) {
foreach (var ta in best.TypeArguments) {
if (ContainsMethodTypeParameter (ta))
return false;
}
}
return true;
}
protected override Expression DoResolve (ResolveContext ec)
{
var expr = base.DoResolve (ec);
if (expr == null)
return ErrorExpression.Instance;
if (ec.IsInProbingMode)
return expr;
//
// Cache any static delegate creation
//
if (method_group.InstanceExpression != null)
return expr;
//
// Cannot easily cache types with MVAR
//
if (!HasMvar ())
return expr;
//
// Create type level cache for a delegate instance
//
var parent = ec.CurrentMemberDefinition.Parent.PartialContainer;
int id = parent.MethodGroupsCounter++;
mg_cache = new Field (parent, new TypeExpression (type, loc),
Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "mg$cache", id), loc), null);
mg_cache.Define ();
parent.AddField (mg_cache);
return expr;
}
public override void Emit (EmitContext ec)
{
Label l_initialized = ec.DefineLabel ();
if (mg_cache != null) {
ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
ec.Emit (OpCodes.Brtrue_S, l_initialized);
}
base.Emit (ec);
if (mg_cache != null) {
ec.Emit (OpCodes.Stsfld, mg_cache.Spec);
ec.MarkLabel (l_initialized);
ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
}
}
}
//
// A delegate-creation-expression, invoked from the `New' class
//
public class NewDelegate : DelegateCreation
{
public Arguments Arguments;
//
// This constructor is invoked from the `New' expression
//
public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
{
this.type = type;
this.Arguments = Arguments;
this.loc = loc;
}
protected override Expression DoResolve (ResolveContext ec)
{
if (Arguments == null || Arguments.Count != 1) {
ec.Report.Error (149, loc, "Method name expected");
return null;
}
Argument a = Arguments [0];
if (!a.ResolveMethodGroup (ec))
return null;
Expression e = a.Expr;
AnonymousMethodExpression ame = e as AnonymousMethodExpression;
if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
e = ame.Compatible (ec, type);
if (e == null)
return null;
return e.Resolve (ec);
}
method_group = e as MethodGroupExpr;
if (method_group == null) {
if (e.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
e = Convert.ImplicitConversionRequired (ec, e, type, loc);
} else if (!e.Type.IsDelegate) {
e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
return null;
}
//
// An argument is not a method but another delegate
//
method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (e.Type), e.Type, loc);
method_group.InstanceExpression = e;
}
return base.DoResolve (ec);
}
}
//
// Invocation converted to delegate Invoke call
//
class DelegateInvocation : ExpressionStatement
{
readonly Expression InstanceExpr;
readonly bool conditionalAccessReceiver;
Arguments arguments;
MethodSpec method;
public DelegateInvocation (Expression instance_expr, Arguments args, bool conditionalAccessReceiver, Location loc)
{
this.InstanceExpr = instance_expr;
this.arguments = args;
this.conditionalAccessReceiver = conditionalAccessReceiver;
this.loc = loc;
}
public override bool ContainsEmitWithAwait ()
{
return InstanceExpr.ContainsEmitWithAwait () || (arguments != null && arguments.ContainsEmitWithAwait ());
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
InstanceExpr.CreateExpressionTree (ec));
return CreateExpressionFactoryCall (ec, "Invoke", args);
}
public override void FlowAnalysis (FlowAnalysisContext fc)
{
InstanceExpr.FlowAnalysis (fc);
if (arguments != null)
arguments.FlowAnalysis (fc);
}
protected override Expression DoResolve (ResolveContext ec)
{
TypeSpec del_type = InstanceExpr.Type;
if (del_type == null)
return null;
//
// Do only core overload resolution the rest of the checks has been
// done on primary expression
//
method = Delegate.GetInvokeMethod (del_type);
var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
if (valid == null && !res.BestCandidateIsDynamic)
return null;
type = method.ReturnType;
if (conditionalAccessReceiver)
type = LiftMemberType (ec, type);
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
if (conditionalAccessReceiver) {
ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
}
//
// Invocation on delegates call the virtual Invoke member
// so we are always `instance' calls
//
var call = new CallEmitter ();
call.InstanceExpression = InstanceExpr;
call.Emit (ec, method, arguments, loc);
if (conditionalAccessReceiver)
ec.CloseConditionalAccess (type.IsNullableType && type != method.ReturnType ? type : null);
}
public override void EmitStatement (EmitContext ec)
{
if (conditionalAccessReceiver) {
ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()) {
Statement = true
};
}
var call = new CallEmitter ();
call.InstanceExpression = InstanceExpr;
call.EmitStatement (ec, method, arguments, loc);
if (conditionalAccessReceiver)
ec.CloseConditionalAccess (null);
}
public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
{
return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);
}
}
}
| |
#if UNITY_EDITOR
#define CACHE
#endif
using System;
using System.IO;
using System.Linq;
using UnityEngine;
using NodeEditorFramework.Utilities;
namespace NodeEditorFramework
{
public class NodeEditorUserCache
{
public NodeCanvas nodeCanvas;
public NodeEditorState editorState;
public string openedCanvasPath = "";
public Type defaultNodeCanvasType;
public NodeCanvasTypeData typeData;
private const string MainEditorStateIdentifier = "MainEditorState";
#if CACHE
private const bool cacheWorkingCopy = true;
private const bool cacheMemorySODump = true;
private const int cacheIntervalSec = 60;
private bool useCache = false;
private double lastCacheTime;
private string cachePath;
private string lastSessionPath { get { return cachePath + "LastSession.asset"; } }
private string SOMemoryDumpPath { get { return cachePath + "CurSession.asset"; } }
#endif
#region Setup
public NodeEditorUserCache(NodeCanvas loadedCanvas)
{
SetCanvas(loadedCanvas);
}
public NodeEditorUserCache()
{ }
public NodeEditorUserCache(string CachePath, NodeCanvas loadedCanvas)
{
#if CACHE
useCache = true;
cachePath = CachePath;
SetupCacheEvents();
#endif
SetCanvas(loadedCanvas);
}
public NodeEditorUserCache(string CachePath)
{
#if CACHE
useCache = true;
cachePath = CachePath;
SetupCacheEvents();
#endif
}
/// <summary>
/// Sets the cache path to a new location if cache is enabled. Does not check validity or moves files
/// </summary>
public void SetCachePath(string CachePath)
{
#if CACHE
if (useCache)
cachePath = CachePath;
#endif
}
/// <summary>
/// Returns the cache path if cache is enabled, else an empty string
/// </summary>
public string GetCachePath()
{
#if CACHE
if (useCache)
return cachePath;
#endif
return "";
}
/// <summary>
/// Assures a canvas is loaded, either from the cache or new
/// </summary>
public void AssureCanvas()
{
#if CACHE
if (nodeCanvas == null)
LoadCache ();
#endif
if (nodeCanvas == null)
NewNodeCanvas();
if (editorState == null)
NewEditorState();
}
#endregion
#region Cache
/// <summary>
/// Subscribes the cache events needed for the cache to work properly
/// </summary>
public void SetupCacheEvents ()
{
#if UNITY_EDITOR && CACHE
if (!useCache)
return;
UnityEditor.EditorApplication.update -= CheckCacheUpdate;
UnityEditor.EditorApplication.update += CheckCacheUpdate;
lastCacheTime = UnityEditor.EditorApplication.timeSinceStartup;
EditorLoadingControl.beforeEnteringPlayMode -= SaveCache;
EditorLoadingControl.beforeEnteringPlayMode += SaveCache;
EditorLoadingControl.beforeLeavingPlayMode -= SaveCache;
EditorLoadingControl.beforeLeavingPlayMode += SaveCache;
EditorLoadingControl.justEnteredPlayMode -= LoadCache;
EditorLoadingControl.justEnteredPlayMode += LoadCache;
#endif
}
/// <summary>
/// Unsubscribes all cache events
/// </summary>
public void ClearCacheEvents ()
{
#if UNITY_EDITOR && CACHE
SaveCache();
UnityEditor.EditorApplication.update -= CheckCacheUpdate;
EditorLoadingControl.beforeEnteringPlayMode -= SaveCache;
EditorLoadingControl.beforeLeavingPlayMode -= SaveCache;
EditorLoadingControl.justEnteredPlayMode -= LoadCache;
#endif
}
private void CheckCacheUpdate ()
{
#if UNITY_EDITOR && CACHE
if (UnityEditor.EditorApplication.timeSinceStartup-lastCacheTime > cacheIntervalSec)
{
AssureCanvas();
if (editorState.dragUserID == "" && editorState.connectKnob == null && GUIUtility.hotControl <= 0 && !OverlayGUI.HasPopupControl ())
{ // Only save when the user currently does not perform an action that could be interrupted by the save
lastCacheTime = UnityEditor.EditorApplication.timeSinceStartup;
SaveCache ();
}
}
#endif
}
/// <summary>
/// Creates a new cache save file for the currently loaded canvas
/// Only called when a new canvas is created or loaded
/// </summary>
private void RecreateCache ()
{
#if CACHE
if (!useCache)
return;
DeleteCache ();
SaveCache ();
#endif
}
/// <summary>
/// Saves the current canvas to the cache
/// </summary>
public void SaveCache ()
{
SaveCache(true);
}
/// <summary>
/// Saves the current canvas to the cache
/// </summary>
public void SaveCache (bool crashSafe = true)
{
#if CACHE
if (!useCache)
return;
if (!nodeCanvas || nodeCanvas.GetType () == typeof(NodeCanvas))
return;
UnityEditor.EditorUtility.SetDirty (nodeCanvas);
if (editorState != null)
UnityEditor.EditorUtility.SetDirty (editorState);
lastCacheTime = UnityEditor.EditorApplication.timeSinceStartup;
nodeCanvas.editorStates = new NodeEditorState[] { editorState };
if (nodeCanvas.livesInScene || nodeCanvas.allowSceneSaveOnly)
NodeEditorSaveManager.SaveSceneNodeCanvas ("lastSession", ref nodeCanvas, cacheWorkingCopy);
else if (crashSafe)
NodeEditorSaveManager.SaveNodeCanvas (lastSessionPath, ref nodeCanvas, cacheWorkingCopy, true);
if (cacheMemorySODump)
{ // Functionality for asset saves only
if (nodeCanvas.livesInScene || nodeCanvas.allowSceneSaveOnly)
{ // Delete for scene save so that next cache load, correct lastSession is used
UnityEditor.AssetDatabase.DeleteAsset(SOMemoryDumpPath);
}
else
{ // Dump all SOs used in this session (even if deleted) in this file to keep them alive for undo
NodeEditorUndoActions.CompleteSOMemoryDump(nodeCanvas);
NodeEditorSaveManager.ScriptableObjectReferenceDump(nodeCanvas.SOMemoryDump, SOMemoryDumpPath, false);
}
}
#endif
}
/// <summary>
/// Loads the canvas from the cache save file
/// Called whenever a reload was made
/// </summary>
public void LoadCache ()
{
#if CACHE
if (!useCache)
{ // Simply create a ne canvas
NewNodeCanvas ();
return;
}
bool skipLoad = false;
if (cacheMemorySODump)
{ // Check if a memory dump has been found, if so, load that
nodeCanvas = ResourceManager.LoadResource<NodeCanvas>(SOMemoryDumpPath);
if (nodeCanvas != null && !nodeCanvas.Validate(false))
{
Debug.LogWarning("Cache Dump corrupted! Loading crash-proof lastSession, you might have lost a bit of work. \n "
+ "To prevent this from happening in the future, allow the Node Editor to properly save the cache "
+ "by clicking out of the window before switching scenes, since there are no callbacks to facilitate this!");
nodeCanvas = null;
UnityEditor.AssetDatabase.DeleteAsset(SOMemoryDumpPath);
}
if (nodeCanvas != null)
skipLoad = true;
}
// Try to load the NodeCanvas
if (!skipLoad &&
(!File.Exists (lastSessionPath) || (nodeCanvas = NodeEditorSaveManager.LoadNodeCanvas (lastSessionPath, cacheWorkingCopy)) == null) && // Check for asset cache
(nodeCanvas = NodeEditorSaveManager.LoadSceneNodeCanvas ("lastSession", cacheWorkingCopy)) == null) // Check for scene cache
{
NewNodeCanvas ();
return;
}
// Fetch the associated MainEditorState
editorState = NodeEditorSaveManager.ExtractEditorState (nodeCanvas, MainEditorStateIdentifier);
UpdateCanvasInfo ();
nodeCanvas.Validate ();
nodeCanvas.TraverseAll ();
NodeEditor.RepaintClients ();
#endif
}
#if CACHE
/// <summary>
/// Makes sure the current canvas is saved to the cache
/// </summary>
private void CheckCurrentCache ()
{
if (!useCache)
return;
if (nodeCanvas.livesInScene)
{
if (!NodeEditorSaveManager.HasSceneSave ("lastSession"))
SaveCache ();
}
else if (UnityEditor.AssetDatabase.LoadAssetAtPath<NodeCanvas> (lastSessionPath) == null)
SaveCache ();
}
/// <summary>
/// Deletes the cache
/// </summary>
private void DeleteCache ()
{
if (!useCache)
return;
UnityEditor.AssetDatabase.DeleteAsset (SOMemoryDumpPath);
UnityEditor.AssetDatabase.DeleteAsset (lastSessionPath);
UnityEditor.AssetDatabase.Refresh ();
NodeEditorSaveManager.DeleteSceneNodeCanvas ("lastSession");
}
/// <summary>
/// Sets the cache dirty and as makes sure it's saved
/// </summary>
private void UpdateCacheFile ()
{
if (!useCache)
return;
UnityEditor.EditorUtility.SetDirty (nodeCanvas);
UnityEditor.AssetDatabase.SaveAssets ();
UnityEditor.AssetDatabase.Refresh ();
}
#endif
#endregion
#region Save/Load
/// <summary>
/// Sets the current canvas, handling all cache operations
/// </summary>
public void SetCanvas (NodeCanvas canvas)
{
if (canvas == null)
NewNodeCanvas();
else if (nodeCanvas != canvas)
{
canvas.Validate ();
nodeCanvas = canvas;
editorState = NodeEditorSaveManager.ExtractEditorState (nodeCanvas, MainEditorStateIdentifier);
RecreateCache ();
UpdateCanvasInfo ();
nodeCanvas.TraverseAll ();
NodeEditor.RepaintClients ();
}
}
/// <summary>
/// Saves the mainNodeCanvas and it's associated mainEditorState as an asset at path
/// </summary>
public void SaveSceneNodeCanvas (string path)
{
nodeCanvas.editorStates = new NodeEditorState[] { editorState };
bool switchedToScene = !nodeCanvas.livesInScene;
NodeEditorSaveManager.SaveSceneNodeCanvas (path, ref nodeCanvas, true);
editorState = NodeEditorSaveManager.ExtractEditorState (nodeCanvas, MainEditorStateIdentifier);
if (switchedToScene)
RecreateCache ();
NodeEditor.RepaintClients ();
}
/// <summary>
/// Loads the mainNodeCanvas and it's associated mainEditorState from an asset at path
/// </summary>
public void LoadSceneNodeCanvas (string path)
{
if (path.StartsWith ("SCENE/"))
path = path.Substring (6);
// Try to load the NodeCanvas
if ((nodeCanvas = NodeEditorSaveManager.LoadSceneNodeCanvas (path, true)) == null)
{
NewNodeCanvas ();
return;
}
editorState = NodeEditorSaveManager.ExtractEditorState (nodeCanvas, MainEditorStateIdentifier);
openedCanvasPath = path;
nodeCanvas.Validate();
RecreateCache ();
UpdateCanvasInfo ();
nodeCanvas.TraverseAll ();
NodeEditor.RepaintClients ();
}
/// <summary>
/// Saves the mainNodeCanvas and it's associated mainEditorState as an asset at path
/// </summary>
public void SaveNodeCanvas (string path)
{
nodeCanvas.editorStates = new NodeEditorState[] { editorState };
bool switchedToFile = nodeCanvas.livesInScene;
NodeEditorSaveManager.SaveNodeCanvas (path, ref nodeCanvas, true);
if (switchedToFile)
RecreateCache ();
else
SaveCache (false);
NodeEditor.RepaintClients ();
}
/// <summary>
/// Loads the mainNodeCanvas and it's associated mainEditorState from an asset at path
/// </summary>
public void LoadNodeCanvas (string path)
{
// Try to load the NodeCanvas
if (!File.Exists (path) || (nodeCanvas = NodeEditorSaveManager.LoadNodeCanvas (path, true)) == null)
{
NewNodeCanvas ();
return;
}
editorState = NodeEditorSaveManager.ExtractEditorState (nodeCanvas, MainEditorStateIdentifier);
openedCanvasPath = path;
nodeCanvas.Validate();
RecreateCache ();
UpdateCanvasInfo ();
nodeCanvas.TraverseAll ();
NodeEditor.RepaintClients ();
}
/// <summary>
/// Creates and loads a new NodeCanvas
/// </summary>
public void NewNodeCanvas (Type canvasType = null)
{
canvasType = canvasType ?? defaultNodeCanvasType ?? // Pick first canvas in alphabetical order (Calculation usually)
NodeCanvasManager.getCanvasDefinitions().OrderBy(c => c.DisplayString).First().CanvasType;
nodeCanvas = NodeCanvas.CreateCanvas (canvasType);
NewEditorState ();
openedCanvasPath = "";
RecreateCache ();
UpdateCanvasInfo ();
}
/// <summary>
/// Creates a new EditorState for the current NodeCanvas
/// </summary>
public void NewEditorState ()
{
editorState = ScriptableObject.CreateInstance<NodeEditorState> ();
if (!nodeCanvas) return;
editorState.canvas = nodeCanvas;
editorState.name = MainEditorStateIdentifier;
nodeCanvas.editorStates = new NodeEditorState[] { editorState };
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty (nodeCanvas);
#endif
}
#endregion
#region Utility
public void ConvertCanvasType(Type newType)
{
NodeCanvas canvas = NodeCanvasManager.ConvertCanvasType(nodeCanvas, newType);
if (canvas != nodeCanvas)
{
nodeCanvas = canvas;
RecreateCache();
UpdateCanvasInfo();
nodeCanvas.TraverseAll();
NodeEditor.RepaintClients();
}
}
private void UpdateCanvasInfo()
{
typeData = NodeCanvasManager.GetCanvasTypeData(nodeCanvas);
}
#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.
namespace System.Xml.Schema
{
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.Versioning;
/*
* The XdrBuilder class parses the XDR Schema and
* builds internal validation information
*/
internal sealed class XdrBuilder : SchemaBuilder
{
private const int XdrSchema = 1;
private const int XdrElementType = 2;
private const int XdrAttributeType = 3;
private const int XdrElement = 4;
private const int XdrAttribute = 5;
private const int XdrGroup = 6;
private const int XdrElementDatatype = 7;
private const int XdrAttributeDatatype = 8;
private const int SchemaFlagsNs = 0x0100;
private const int StackIncrement = 10;
private const int SchemaOrderNone = 0;
private const int SchemaOrderMany = 1;
private const int SchemaOrderSequence = 2;
private const int SchemaOrderChoice = 3;
private const int SchemaOrderAll = 4;
private const int SchemaContentNone = 0;
private const int SchemaContentEmpty = 1;
private const int SchemaContentText = 2;
private const int SchemaContentMixed = 3;
private const int SchemaContentElement = 4;
private sealed class DeclBaseInfo
{
// used for <element... or <attribute...
internal XmlQualifiedName _Name;
internal string _Prefix;
internal XmlQualifiedName _TypeName;
internal string _TypePrefix;
internal object _Default;
internal object _Revises;
internal uint _MaxOccurs;
internal uint _MinOccurs;
// used for checking undeclared attribute type
internal bool _Checking;
internal SchemaElementDecl _ElementDecl;
internal SchemaAttDef _Attdef;
internal DeclBaseInfo _Next;
internal DeclBaseInfo()
{
Reset();
}
internal void Reset()
{
_Name = XmlQualifiedName.Empty;
_Prefix = null;
_TypeName = XmlQualifiedName.Empty;
_TypePrefix = null;
_Default = null;
_Revises = null;
_MaxOccurs = 1;
_MinOccurs = 1;
_Checking = false;
_ElementDecl = null;
_Next = null;
_Attdef = null;
}
};
private sealed class GroupContent
{
internal uint _MinVal;
internal uint _MaxVal;
internal bool _HasMaxAttr;
internal bool _HasMinAttr;
internal int _Order;
internal static void Copy(GroupContent from, GroupContent to)
{
to._MinVal = from._MinVal;
to._MaxVal = from._MaxVal;
to._Order = from._Order;
}
internal static GroupContent Copy(GroupContent other)
{
GroupContent g = new GroupContent();
Copy(other, g);
return g;
}
};
private sealed class ElementContent
{
// for <ElementType ...
internal SchemaElementDecl _ElementDecl; // Element Information
internal int _ContentAttr; // content attribute
internal int _OrderAttr; // order attribute
internal bool _MasterGroupRequired; // In a situation like <!ELEMENT root (e1)> e1 has to have a ()
internal bool _ExistTerminal; // when there exist a terminal, we need to addOrder before
// we can add another terminal
internal bool _AllowDataType; // must have textOnly if we have datatype
internal bool _HasDataType; // got data type
// for <element ...
internal bool _HasType; // user must have a type attribute in <element ...
internal bool _EnumerationRequired;
internal uint _MinVal;
internal uint _MaxVal; // -1 means infinity
internal uint _MaxLength; // dt:maxLength
internal uint _MinLength; // dt:minLength
internal Hashtable _AttDefList; // a list of current AttDefs for the <ElementType ...
// only the used one will be added
};
private sealed class AttributeContent
{
// used for <AttributeType ...
internal SchemaAttDef _AttDef;
// used to store name & prefix for the AttributeType
internal XmlQualifiedName _Name;
internal string _Prefix;
internal bool _Required; // true: when the attribute required="yes"
// used for both AttributeType and attribute
internal uint _MinVal;
internal uint _MaxVal; // -1 means infinity
internal uint _MaxLength; // dt:maxLength
internal uint _MinLength; // dt:minLength
// used for datatype
internal bool _EnumerationRequired; // when we have dt:value then we must have dt:type="enumeration"
internal bool _HasDataType;
// used for <attribute ...
internal bool _Global;
internal object _Default;
};
private delegate void XdrBuildFunction(XdrBuilder builder, object obj, string prefix);
private delegate void XdrInitFunction(XdrBuilder builder, object obj);
private delegate void XdrBeginChildFunction(XdrBuilder builder);
private delegate void XdrEndChildFunction(XdrBuilder builder);
private sealed class XdrAttributeEntry
{
internal SchemaNames.Token _Attribute; // possible attribute names
internal int _SchemaFlags;
internal XmlSchemaDatatype _Datatype;
internal XdrBuildFunction _BuildFunc; // Corresponding build functions for attribute value
internal XdrAttributeEntry(SchemaNames.Token a, XmlTokenizedType ttype, XdrBuildFunction build)
{
_Attribute = a;
_Datatype = XmlSchemaDatatype.FromXmlTokenizedType(ttype);
_SchemaFlags = 0;
_BuildFunc = build;
}
internal XdrAttributeEntry(SchemaNames.Token a, XmlTokenizedType ttype, int schemaFlags, XdrBuildFunction build)
{
_Attribute = a;
_Datatype = XmlSchemaDatatype.FromXmlTokenizedType(ttype);
_SchemaFlags = schemaFlags;
_BuildFunc = build;
}
};
//
// XdrEntry controls the states of parsing a schema document
// and calls the corresponding "init", "end" and "build" functions when necessary
//
private sealed class XdrEntry
{
internal SchemaNames.Token _Name; // the name of the object it is comparing to
internal int[] _NextStates; // possible next states
internal XdrAttributeEntry[] _Attributes; // allowed attributes
internal XdrInitFunction _InitFunc; // "init" functions in XdrBuilder
internal XdrBeginChildFunction _BeginChildFunc; // "begin" functions in XdrBuilder for BeginChildren
internal XdrEndChildFunction _EndChildFunc; // "end" functions in XdrBuilder for EndChildren
internal bool _AllowText; // whether text content is allowed
internal XdrEntry(SchemaNames.Token n,
int[] states,
XdrAttributeEntry[] attributes,
XdrInitFunction init,
XdrBeginChildFunction begin,
XdrEndChildFunction end,
bool fText)
{
_Name = n;
_NextStates = states;
_Attributes = attributes;
_InitFunc = init;
_BeginChildFunc = begin;
_EndChildFunc = end;
_AllowText = fText;
}
};
/////////////////////////////////////////////////////////////////////////////
// Data structures for XML-Data Reduced (XDR Schema)
//
//
// Elements
//
private static readonly int[] s_XDR_Root_Element = { XdrSchema };
private static readonly int[] s_XDR_Root_SubElements = { XdrElementType, XdrAttributeType };
private static readonly int[] s_XDR_ElementType_SubElements = { XdrElement, XdrGroup, XdrAttributeType, XdrAttribute, XdrElementDatatype };
private static readonly int[] s_XDR_AttributeType_SubElements = { XdrAttributeDatatype };
private static readonly int[] s_XDR_Group_SubElements = { XdrElement, XdrGroup };
//
// Attributes
//
private static readonly XdrAttributeEntry[] s_XDR_Root_Attributes =
{
new XdrAttributeEntry(SchemaNames.Token.SchemaName, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildRoot_Name) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaId, XmlTokenizedType.QName, new XdrBuildFunction(XDR_BuildRoot_ID) )
};
private static readonly XdrAttributeEntry[] s_XDR_ElementType_Attributes =
{
new XdrAttributeEntry(SchemaNames.Token.SchemaName, XmlTokenizedType.QName, SchemaFlagsNs, new XdrBuildFunction(XDR_BuildElementType_Name) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaContent, XmlTokenizedType.QName, new XdrBuildFunction(XDR_BuildElementType_Content) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaModel, XmlTokenizedType.QName, new XdrBuildFunction(XDR_BuildElementType_Model) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaOrder, XmlTokenizedType.QName, new XdrBuildFunction(XDR_BuildElementType_Order) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtType, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildElementType_DtType) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtValues, XmlTokenizedType.NMTOKENS, new XdrBuildFunction(XDR_BuildElementType_DtValues) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtMaxLength, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildElementType_DtMaxLength) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtMinLength, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildElementType_DtMinLength) )
};
private static readonly XdrAttributeEntry[] s_XDR_AttributeType_Attributes =
{
new XdrAttributeEntry(SchemaNames.Token.SchemaName, XmlTokenizedType.QName, new XdrBuildFunction(XDR_BuildAttributeType_Name) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaRequired, XmlTokenizedType.QName, new XdrBuildFunction(XDR_BuildAttributeType_Required) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDefault, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildAttributeType_Default) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtType, XmlTokenizedType.QName, new XdrBuildFunction(XDR_BuildAttributeType_DtType) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtValues, XmlTokenizedType.NMTOKENS, new XdrBuildFunction(XDR_BuildAttributeType_DtValues) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtMaxLength, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildAttributeType_DtMaxLength) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtMinLength, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildAttributeType_DtMinLength) )
};
private static readonly XdrAttributeEntry[] s_XDR_Element_Attributes =
{
new XdrAttributeEntry(SchemaNames.Token.SchemaType, XmlTokenizedType.QName, SchemaFlagsNs, new XdrBuildFunction(XDR_BuildElement_Type) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaMinOccurs, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildElement_MinOccurs) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaMaxOccurs, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildElement_MaxOccurs) )
};
private static readonly XdrAttributeEntry[] s_XDR_Attribute_Attributes =
{
new XdrAttributeEntry(SchemaNames.Token.SchemaType, XmlTokenizedType.QName, new XdrBuildFunction(XDR_BuildAttribute_Type) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaRequired, XmlTokenizedType.QName, new XdrBuildFunction(XDR_BuildAttribute_Required) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDefault, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildAttribute_Default) )
};
private static readonly XdrAttributeEntry[] s_XDR_Group_Attributes =
{
new XdrAttributeEntry(SchemaNames.Token.SchemaOrder, XmlTokenizedType.QName, new XdrBuildFunction(XDR_BuildGroup_Order) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaMinOccurs, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildGroup_MinOccurs) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaMaxOccurs, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildGroup_MaxOccurs) )
};
private static readonly XdrAttributeEntry[] s_XDR_ElementDataType_Attributes =
{
new XdrAttributeEntry(SchemaNames.Token.SchemaDtType, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildElementType_DtType) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtValues, XmlTokenizedType.NMTOKENS, new XdrBuildFunction(XDR_BuildElementType_DtValues) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtMaxLength, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildElementType_DtMaxLength) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtMinLength, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildElementType_DtMinLength) )
};
private static readonly XdrAttributeEntry[] s_XDR_AttributeDataType_Attributes =
{
new XdrAttributeEntry(SchemaNames.Token.SchemaDtType, XmlTokenizedType.QName, new XdrBuildFunction(XDR_BuildAttributeType_DtType) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtValues, XmlTokenizedType.NMTOKENS, new XdrBuildFunction(XDR_BuildAttributeType_DtValues) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtMaxLength, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildAttributeType_DtMaxLength) ),
new XdrAttributeEntry(SchemaNames.Token.SchemaDtMinLength, XmlTokenizedType.CDATA, new XdrBuildFunction(XDR_BuildAttributeType_DtMinLength) )
};
//
// Schema entries
//
private static readonly XdrEntry[] s_schemaEntries =
{
new XdrEntry( SchemaNames.Token.Empty, s_XDR_Root_Element, null,
null,
null,
null,
false),
new XdrEntry( SchemaNames.Token.XdrRoot, s_XDR_Root_SubElements, s_XDR_Root_Attributes,
new XdrInitFunction(XDR_InitRoot),
new XdrBeginChildFunction(XDR_BeginRoot),
new XdrEndChildFunction(XDR_EndRoot),
false),
new XdrEntry( SchemaNames.Token.XdrElementType, s_XDR_ElementType_SubElements, s_XDR_ElementType_Attributes,
new XdrInitFunction(XDR_InitElementType),
new XdrBeginChildFunction(XDR_BeginElementType),
new XdrEndChildFunction(XDR_EndElementType),
false),
new XdrEntry( SchemaNames.Token.XdrAttributeType, s_XDR_AttributeType_SubElements, s_XDR_AttributeType_Attributes,
new XdrInitFunction(XDR_InitAttributeType),
new XdrBeginChildFunction(XDR_BeginAttributeType),
new XdrEndChildFunction(XDR_EndAttributeType),
false),
new XdrEntry( SchemaNames.Token.XdrElement, null, s_XDR_Element_Attributes,
new XdrInitFunction(XDR_InitElement),
null,
new XdrEndChildFunction(XDR_EndElement),
false),
new XdrEntry( SchemaNames.Token.XdrAttribute, null, s_XDR_Attribute_Attributes,
new XdrInitFunction(XDR_InitAttribute),
new XdrBeginChildFunction(XDR_BeginAttribute),
new XdrEndChildFunction(XDR_EndAttribute),
false),
new XdrEntry( SchemaNames.Token.XdrGroup, s_XDR_Group_SubElements, s_XDR_Group_Attributes,
new XdrInitFunction(XDR_InitGroup),
null,
new XdrEndChildFunction(XDR_EndGroup),
false),
new XdrEntry( SchemaNames.Token.XdrDatatype, null, s_XDR_ElementDataType_Attributes,
new XdrInitFunction(XDR_InitElementDtType),
null,
new XdrEndChildFunction(XDR_EndElementDtType),
true),
new XdrEntry( SchemaNames.Token.XdrDatatype, null, s_XDR_AttributeDataType_Attributes,
new XdrInitFunction(XDR_InitAttributeDtType),
null,
new XdrEndChildFunction(XDR_EndAttributeDtType),
true)
};
private SchemaInfo _SchemaInfo;
private string _TargetNamespace;
private XmlReader _reader;
private PositionInfo _positionInfo;
private ParticleContentValidator _contentValidator;
private XdrEntry _CurState;
private XdrEntry _NextState;
private HWStack _StateHistory;
private HWStack _GroupStack;
private string _XdrName;
private string _XdrPrefix;
private ElementContent _ElementDef;
private GroupContent _GroupDef;
private AttributeContent _AttributeDef;
private DeclBaseInfo _UndefinedAttributeTypes;
private DeclBaseInfo _BaseDecl;
private XmlNameTable _NameTable;
private SchemaNames _SchemaNames;
private XmlNamespaceManager _CurNsMgr;
private string _Text;
private ValidationEventHandler _validationEventHandler;
private Hashtable _UndeclaredElements = new Hashtable();
private const string x_schema = "x-schema:";
private XmlResolver _xmlResolver = null;
internal XdrBuilder(
XmlReader reader,
XmlNamespaceManager curmgr,
SchemaInfo sinfo,
string targetNamspace,
XmlNameTable nameTable,
SchemaNames schemaNames,
ValidationEventHandler eventhandler
)
{
_SchemaInfo = sinfo;
_TargetNamespace = targetNamspace;
_reader = reader;
_CurNsMgr = curmgr;
_validationEventHandler = eventhandler;
_StateHistory = new HWStack(StackIncrement);
_ElementDef = new ElementContent();
_AttributeDef = new AttributeContent();
_GroupStack = new HWStack(StackIncrement);
_GroupDef = new GroupContent();
_NameTable = nameTable;
_SchemaNames = schemaNames;
_CurState = s_schemaEntries[0];
_positionInfo = PositionInfo.GetPositionInfo(_reader);
_xmlResolver = null;
}
internal override bool ProcessElement(string prefix, string name, string ns)
{
XmlQualifiedName qname = new XmlQualifiedName(name, XmlSchemaDatatype.XdrCanonizeUri(ns, _NameTable, _SchemaNames));
if (GetNextState(qname))
{
Push();
if (_CurState._InitFunc != null)
{
(this._CurState._InitFunc)(this, qname);
}
return true;
}
else
{
if (!IsSkipableElement(qname))
{
SendValidationEvent(SR.Sch_UnsupportedElement, XmlQualifiedName.ToString(name, prefix));
}
return false;
}
}
// SxS: This method processes attribute from the source document and does not expose any resources to the caller
// It is fine to suppress the SxS warning.
internal override void ProcessAttribute(string prefix, string name, string ns, string value)
{
XmlQualifiedName qname = new XmlQualifiedName(name, XmlSchemaDatatype.XdrCanonizeUri(ns, _NameTable, _SchemaNames));
for (int i = 0; i < _CurState._Attributes.Length; i++)
{
XdrAttributeEntry a = _CurState._Attributes[i];
if (_SchemaNames.TokenToQName[(int)a._Attribute].Equals(qname))
{
XdrBuildFunction buildFunc = a._BuildFunc;
if (a._Datatype.TokenizedType == XmlTokenizedType.QName)
{
string prefixValue;
XmlQualifiedName qnameValue = XmlQualifiedName.Parse(value, _CurNsMgr, out prefixValue);
qnameValue.Atomize(_NameTable);
if (prefixValue.Length != 0)
{
if (a._Attribute != SchemaNames.Token.SchemaType)
{ // <attribute type= || <element type=
throw new XmlException(SR.Xml_UnexpectedToken, "NAME");
}
}
else if (IsGlobal(a._SchemaFlags))
{
qnameValue = new XmlQualifiedName(qnameValue.Name, _TargetNamespace);
}
else
{
qnameValue = new XmlQualifiedName(qnameValue.Name);
}
buildFunc(this, qnameValue, prefixValue);
}
else
{
buildFunc(this, a._Datatype.ParseValue(value, _NameTable, _CurNsMgr), string.Empty);
}
return;
}
}
if ((object)ns == (object)_SchemaNames.NsXmlNs && IsXdrSchema(value))
{
LoadSchema(value);
return;
}
// Check non-supported attribute
if (!IsSkipableAttribute(qname))
{
SendValidationEvent(SR.Sch_UnsupportedAttribute,
XmlQualifiedName.ToString(qname.Name, prefix));
}
}
internal XmlResolver XmlResolver
{
set
{
_xmlResolver = value;
}
}
private bool LoadSchema(string uri)
{
if (_xmlResolver == null)
{
return false;
}
uri = _NameTable.Add(uri);
if (_SchemaInfo.TargetNamespaces.ContainsKey(uri))
{
return false;
}
SchemaInfo schemaInfo = null;
Uri _baseUri = _xmlResolver.ResolveUri(null, _reader.BaseURI);
XmlReader reader = null;
try
{
Uri ruri = _xmlResolver.ResolveUri(_baseUri, uri.Substring(x_schema.Length));
Stream stm = (Stream)_xmlResolver.GetEntity(ruri, null, null);
reader = new XmlTextReader(ruri.ToString(), stm, _NameTable);
schemaInfo = new SchemaInfo();
Parser parser = new Parser(SchemaType.XDR, _NameTable, _SchemaNames, _validationEventHandler);
parser.XmlResolver = _xmlResolver;
parser.Parse(reader, uri);
schemaInfo = parser.XdrSchema;
}
catch (XmlException e)
{
SendValidationEvent(SR.Sch_CannotLoadSchema, new string[] { uri, e.Message }, XmlSeverityType.Warning);
schemaInfo = null;
}
finally
{
if (reader != null)
{
reader.Close();
}
}
if (schemaInfo != null && schemaInfo.ErrorCount == 0)
{
_SchemaInfo.Add(schemaInfo, _validationEventHandler);
return true;
}
return false;
}
internal static bool IsXdrSchema(string uri)
{
return uri.Length >= x_schema.Length &&
0 == string.Compare(uri, 0, x_schema, 0, x_schema.Length, StringComparison.Ordinal) &&
!uri.StartsWith("x-schema:#", StringComparison.Ordinal);
}
internal override bool IsContentParsed()
{
return true;
}
internal override void ProcessMarkup(XmlNode[] markup)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation); // should never be called
}
internal override void ProcessCData(string value)
{
if (_CurState._AllowText)
{
_Text = value;
}
else
{
SendValidationEvent(SR.Sch_TextNotAllowed, value);
}
}
internal override void StartChildren()
{
if (_CurState._BeginChildFunc != null)
{
(this._CurState._BeginChildFunc)(this);
}
}
internal override void EndChildren()
{
if (_CurState._EndChildFunc != null)
{
(this._CurState._EndChildFunc)(this);
}
Pop();
}
//
// State stack push & pop
//
private void Push()
{
_StateHistory.Push();
_StateHistory[_StateHistory.Length - 1] = _CurState;
_CurState = _NextState;
}
private void Pop()
{
_CurState = (XdrEntry)_StateHistory.Pop();
}
//
// Group stack push & pop
//
private void PushGroupInfo()
{
_GroupStack.Push();
_GroupStack[_GroupStack.Length - 1] = GroupContent.Copy(_GroupDef);
}
private void PopGroupInfo()
{
_GroupDef = (GroupContent)_GroupStack.Pop();
Debug.Assert(_GroupDef != null);
}
//
// XDR Schema
//
private static void XDR_InitRoot(XdrBuilder builder, object obj)
{
builder._SchemaInfo.SchemaType = SchemaType.XDR;
builder._ElementDef._ElementDecl = null;
builder._ElementDef._AttDefList = null;
builder._AttributeDef._AttDef = null;
}
private static void XDR_BuildRoot_Name(XdrBuilder builder, object obj, string prefix)
{
builder._XdrName = (string)obj;
builder._XdrPrefix = prefix;
}
private static void XDR_BuildRoot_ID(XdrBuilder builder, object obj, string prefix)
{
}
private static void XDR_BeginRoot(XdrBuilder builder)
{
if (builder._TargetNamespace == null)
{ // inline xdr schema
if (builder._XdrName != null)
{
builder._TargetNamespace = builder._NameTable.Add("x-schema:#" + builder._XdrName);
}
else
{
builder._TargetNamespace = String.Empty;
}
}
builder._SchemaInfo.TargetNamespaces.Add(builder._TargetNamespace, true);
}
private static void XDR_EndRoot(XdrBuilder builder)
{
//
// check undefined attribute types
// We already checked local attribute types, so only need to check global attribute types here
//
while (builder._UndefinedAttributeTypes != null)
{
XmlQualifiedName gname = builder._UndefinedAttributeTypes._TypeName;
// if there is no URN in this name then the name is local to the
// schema, but the global attribute was still URN qualified, so
// we need to qualify this name now.
if (gname.Namespace.Length == 0)
{
gname = new XmlQualifiedName(gname.Name, builder._TargetNamespace);
}
SchemaAttDef ad;
if (builder._SchemaInfo.AttributeDecls.TryGetValue(gname, out ad))
{
builder._UndefinedAttributeTypes._Attdef = (SchemaAttDef)ad.Clone();
builder._UndefinedAttributeTypes._Attdef.Name = gname;
builder.XDR_CheckAttributeDefault(builder._UndefinedAttributeTypes, builder._UndefinedAttributeTypes._Attdef);
}
else
{
builder.SendValidationEvent(SR.Sch_UndeclaredAttribute, gname.Name);
}
builder._UndefinedAttributeTypes = builder._UndefinedAttributeTypes._Next;
}
foreach (SchemaElementDecl ed in builder._UndeclaredElements.Values)
{
builder.SendValidationEvent(SR.Sch_UndeclaredElement, XmlQualifiedName.ToString(ed.Name.Name, ed.Prefix));
}
}
//
// XDR ElementType
//
private static void XDR_InitElementType(XdrBuilder builder, object obj)
{
builder._ElementDef._ElementDecl = new SchemaElementDecl();
builder._contentValidator = new ParticleContentValidator(XmlSchemaContentType.Mixed);
builder._contentValidator.IsOpen = true;
builder._ElementDef._ContentAttr = SchemaContentNone;
builder._ElementDef._OrderAttr = SchemaOrderNone;
builder._ElementDef._MasterGroupRequired = false;
builder._ElementDef._ExistTerminal = false;
builder._ElementDef._AllowDataType = true;
builder._ElementDef._HasDataType = false;
builder._ElementDef._EnumerationRequired = false;
builder._ElementDef._AttDefList = new Hashtable();
builder._ElementDef._MaxLength = uint.MaxValue;
builder._ElementDef._MinLength = uint.MaxValue;
// builder._AttributeDef._HasDataType = false;
// builder._AttributeDef._Default = null;
}
private static void XDR_BuildElementType_Name(XdrBuilder builder, object obj, string prefix)
{
XmlQualifiedName qname = (XmlQualifiedName)obj;
if (builder._SchemaInfo.ElementDecls.ContainsKey(qname))
{
builder.SendValidationEvent(SR.Sch_DupElementDecl, XmlQualifiedName.ToString(qname.Name, prefix));
}
builder._ElementDef._ElementDecl.Name = qname;
builder._ElementDef._ElementDecl.Prefix = prefix;
builder._SchemaInfo.ElementDecls.Add(qname, builder._ElementDef._ElementDecl);
if (builder._UndeclaredElements[qname] != null)
{
builder._UndeclaredElements.Remove(qname);
}
}
private static void XDR_BuildElementType_Content(XdrBuilder builder, object obj, string prefix)
{
builder._ElementDef._ContentAttr = builder.GetContent((XmlQualifiedName)obj);
}
private static void XDR_BuildElementType_Model(XdrBuilder builder, object obj, string prefix)
{
builder._contentValidator.IsOpen = builder.GetModel((XmlQualifiedName)obj);
}
private static void XDR_BuildElementType_Order(XdrBuilder builder, object obj, string prefix)
{
builder._ElementDef._OrderAttr = builder._GroupDef._Order = builder.GetOrder((XmlQualifiedName)obj);
}
private static void XDR_BuildElementType_DtType(XdrBuilder builder, object obj, string prefix)
{
builder._ElementDef._HasDataType = true;
string s = ((string)obj).Trim();
if (s.Length == 0)
{
builder.SendValidationEvent(SR.Sch_MissDtvalue);
}
else
{
XmlSchemaDatatype dtype = XmlSchemaDatatype.FromXdrName(s);
if (dtype == null)
{
builder.SendValidationEvent(SR.Sch_UnknownDtType, s);
}
builder._ElementDef._ElementDecl.Datatype = dtype;
}
}
private static void XDR_BuildElementType_DtValues(XdrBuilder builder, object obj, string prefix)
{
builder._ElementDef._EnumerationRequired = true;
builder._ElementDef._ElementDecl.Values = new List<string>((string[])obj);
}
private static void XDR_BuildElementType_DtMaxLength(XdrBuilder builder, object obj, string prefix)
{
ParseDtMaxLength(ref builder._ElementDef._MaxLength, obj, builder);
}
private static void XDR_BuildElementType_DtMinLength(XdrBuilder builder, object obj, string prefix)
{
ParseDtMinLength(ref builder._ElementDef._MinLength, obj, builder);
}
private static void XDR_BeginElementType(XdrBuilder builder)
{
string code = null;
string msg = null;
//
// check name attribute
//
if (builder._ElementDef._ElementDecl.Name.IsEmpty)
{
code = SR.Sch_MissAttribute;
msg = "name";
goto cleanup;
}
//
// check dt:type attribute
//
if (builder._ElementDef._HasDataType)
{
if (!builder._ElementDef._AllowDataType)
{
code = SR.Sch_DataTypeTextOnly;
goto cleanup;
}
else
{
builder._ElementDef._ContentAttr = SchemaContentText;
}
}
else if (builder._ElementDef._ContentAttr == SchemaContentNone)
{
switch (builder._ElementDef._OrderAttr)
{
case SchemaOrderNone:
builder._ElementDef._ContentAttr = SchemaContentMixed;
builder._ElementDef._OrderAttr = SchemaOrderMany;
break;
case SchemaOrderSequence:
builder._ElementDef._ContentAttr = SchemaContentElement;
break;
case SchemaOrderChoice:
builder._ElementDef._ContentAttr = SchemaContentElement;
break;
case SchemaOrderMany:
builder._ElementDef._ContentAttr = SchemaContentMixed;
break;
}
}
//save the model value from the base
bool tempOpen = builder._contentValidator.IsOpen;
ElementContent def = builder._ElementDef;
switch (builder._ElementDef._ContentAttr)
{
case SchemaContentText:
builder._ElementDef._ElementDecl.ContentValidator = ContentValidator.TextOnly;
builder._GroupDef._Order = SchemaOrderMany;
builder._contentValidator = null;
break;
case SchemaContentElement:
builder._contentValidator = new ParticleContentValidator(XmlSchemaContentType.ElementOnly);
if (def._OrderAttr == SchemaOrderNone)
{
builder._GroupDef._Order = SchemaOrderSequence;
}
def._MasterGroupRequired = true;
builder._contentValidator.IsOpen = tempOpen;
break;
case SchemaContentEmpty:
builder._ElementDef._ElementDecl.ContentValidator = ContentValidator.Empty;
builder._contentValidator = null;
break;
case SchemaContentMixed:
if (def._OrderAttr == SchemaOrderNone || def._OrderAttr == SchemaOrderMany)
{
builder._GroupDef._Order = SchemaOrderMany;
}
else
{
code = SR.Sch_MixedMany;
goto cleanup;
}
def._MasterGroupRequired = true;
builder._contentValidator.IsOpen = tempOpen;
break;
}
if (def._ContentAttr == SchemaContentMixed || def._ContentAttr == SchemaContentElement)
{
builder._contentValidator.Start();
builder._contentValidator.OpenGroup();
}
cleanup:
if (code != null)
{
builder.SendValidationEvent(code, msg);
}
}
private static void XDR_EndElementType(XdrBuilder builder)
{
SchemaElementDecl ed = builder._ElementDef._ElementDecl;
// check undefined attribute types first
if (builder._UndefinedAttributeTypes != null && builder._ElementDef._AttDefList != null)
{
DeclBaseInfo patt = builder._UndefinedAttributeTypes;
DeclBaseInfo p1 = patt;
while (patt != null)
{
SchemaAttDef pAttdef = null;
if (patt._ElementDecl == ed)
{
XmlQualifiedName pName = patt._TypeName;
pAttdef = (SchemaAttDef)builder._ElementDef._AttDefList[pName];
if (pAttdef != null)
{
patt._Attdef = (SchemaAttDef)pAttdef.Clone();
patt._Attdef.Name = pName;
builder.XDR_CheckAttributeDefault(patt, pAttdef);
// remove it from _pUndefinedAttributeTypes
if (patt == builder._UndefinedAttributeTypes)
{
patt = builder._UndefinedAttributeTypes = patt._Next;
p1 = patt;
}
else
{
p1._Next = patt._Next;
patt = p1._Next;
}
}
}
if (pAttdef == null)
{
if (patt != builder._UndefinedAttributeTypes)
p1 = p1._Next;
patt = patt._Next;
}
}
}
if (builder._ElementDef._MasterGroupRequired)
{
// if the content is mixed, there is a group that need to be closed
builder._contentValidator.CloseGroup();
if (!builder._ElementDef._ExistTerminal)
{
if (builder._contentValidator.IsOpen)
{
builder._ElementDef._ElementDecl.ContentValidator = ContentValidator.Any;
builder._contentValidator = null;
}
else
{
if (builder._ElementDef._ContentAttr != SchemaContentMixed)
builder.SendValidationEvent(SR.Sch_ElementMissing);
}
}
else
{
if (builder._GroupDef._Order == SchemaOrderMany)
{
builder._contentValidator.AddStar();
}
}
}
if (ed.Datatype != null)
{
XmlTokenizedType ttype = ed.Datatype.TokenizedType;
if (ttype == XmlTokenizedType.ENUMERATION &&
!builder._ElementDef._EnumerationRequired)
{
builder.SendValidationEvent(SR.Sch_MissDtvaluesAttribute);
}
if (ttype != XmlTokenizedType.ENUMERATION &&
builder._ElementDef._EnumerationRequired)
{
builder.SendValidationEvent(SR.Sch_RequireEnumeration);
}
}
CompareMinMaxLength(builder._ElementDef._MinLength, builder._ElementDef._MaxLength, builder);
ed.MaxLength = (long)builder._ElementDef._MaxLength;
ed.MinLength = (long)builder._ElementDef._MinLength;
if (builder._contentValidator != null)
{
builder._ElementDef._ElementDecl.ContentValidator = builder._contentValidator.Finish(true);
builder._contentValidator = null;
}
builder._ElementDef._ElementDecl = null;
builder._ElementDef._AttDefList = null;
}
//
// XDR AttributeType
//
private static void XDR_InitAttributeType(XdrBuilder builder, object obj)
{
AttributeContent ad = builder._AttributeDef;
ad._AttDef = new SchemaAttDef(XmlQualifiedName.Empty, null);
ad._Required = false;
ad._Prefix = null;
ad._Default = null;
ad._MinVal = 0; // optional by default.
ad._MaxVal = 1;
// used for datatype
ad._EnumerationRequired = false;
ad._HasDataType = false;
ad._Global = (builder._StateHistory.Length == 2);
ad._MaxLength = uint.MaxValue;
ad._MinLength = uint.MaxValue;
}
private static void XDR_BuildAttributeType_Name(XdrBuilder builder, object obj, string prefix)
{
XmlQualifiedName qname = (XmlQualifiedName)obj;
builder._AttributeDef._Name = qname;
builder._AttributeDef._Prefix = prefix;
builder._AttributeDef._AttDef.Name = qname;
if (builder._ElementDef._ElementDecl != null)
{ // Local AttributeType
if (builder._ElementDef._AttDefList[qname] == null)
{
builder._ElementDef._AttDefList.Add(qname, builder._AttributeDef._AttDef);
}
else
{
builder.SendValidationEvent(SR.Sch_DupAttribute, XmlQualifiedName.ToString(qname.Name, prefix));
}
}
else
{ // Global AttributeType
// Global AttributeTypes are URN qualified so that we can look them up across schemas.
qname = new XmlQualifiedName(qname.Name, builder._TargetNamespace);
builder._AttributeDef._AttDef.Name = qname;
if (!builder._SchemaInfo.AttributeDecls.ContainsKey(qname))
{
builder._SchemaInfo.AttributeDecls.Add(qname, builder._AttributeDef._AttDef);
}
else
{
builder.SendValidationEvent(SR.Sch_DupAttribute, XmlQualifiedName.ToString(qname.Name, prefix));
}
}
}
private static void XDR_BuildAttributeType_Required(XdrBuilder builder, object obj, string prefix)
{
builder._AttributeDef._Required = IsYes(obj, builder);
}
private static void XDR_BuildAttributeType_Default(XdrBuilder builder, object obj, string prefix)
{
builder._AttributeDef._Default = obj;
}
private static void XDR_BuildAttributeType_DtType(XdrBuilder builder, object obj, string prefix)
{
XmlQualifiedName qname = (XmlQualifiedName)obj;
builder._AttributeDef._HasDataType = true;
builder._AttributeDef._AttDef.Datatype = builder.CheckDatatype(qname.Name);
}
private static void XDR_BuildAttributeType_DtValues(XdrBuilder builder, object obj, string prefix)
{
builder._AttributeDef._EnumerationRequired = true;
builder._AttributeDef._AttDef.Values = new List<string>((string[])obj);
}
private static void XDR_BuildAttributeType_DtMaxLength(XdrBuilder builder, object obj, string prefix)
{
ParseDtMaxLength(ref builder._AttributeDef._MaxLength, obj, builder);
}
private static void XDR_BuildAttributeType_DtMinLength(XdrBuilder builder, object obj, string prefix)
{
ParseDtMinLength(ref builder._AttributeDef._MinLength, obj, builder);
}
private static void XDR_BeginAttributeType(XdrBuilder builder)
{
if (builder._AttributeDef._Name.IsEmpty)
{
builder.SendValidationEvent(SR.Sch_MissAttribute);
}
}
private static void XDR_EndAttributeType(XdrBuilder builder)
{
string code = null;
if (builder._AttributeDef._HasDataType && builder._AttributeDef._AttDef.Datatype != null)
{
XmlTokenizedType ttype = builder._AttributeDef._AttDef.Datatype.TokenizedType;
if (ttype == XmlTokenizedType.ENUMERATION && !builder._AttributeDef._EnumerationRequired)
{
code = SR.Sch_MissDtvaluesAttribute;
goto cleanup;
}
if (ttype != XmlTokenizedType.ENUMERATION && builder._AttributeDef._EnumerationRequired)
{
code = SR.Sch_RequireEnumeration;
goto cleanup;
}
// an attribute of type id is not supposed to have a default value
if (builder._AttributeDef._Default != null && ttype == XmlTokenizedType.ID)
{
code = SR.Sch_DefaultIdValue;
goto cleanup;
}
}
else
{
builder._AttributeDef._AttDef.Datatype = XmlSchemaDatatype.FromXmlTokenizedType(XmlTokenizedType.CDATA);
}
//
// constraints
//
CompareMinMaxLength(builder._AttributeDef._MinLength, builder._AttributeDef._MaxLength, builder);
builder._AttributeDef._AttDef.MaxLength = builder._AttributeDef._MaxLength;
builder._AttributeDef._AttDef.MinLength = builder._AttributeDef._MinLength;
//
// checkAttributeType
//
if (builder._AttributeDef._Default != null)
{
builder._AttributeDef._AttDef.DefaultValueRaw = builder._AttributeDef._AttDef.DefaultValueExpanded = (string)builder._AttributeDef._Default;
builder.CheckDefaultAttValue(builder._AttributeDef._AttDef);
}
builder.SetAttributePresence(builder._AttributeDef._AttDef, builder._AttributeDef._Required);
cleanup:
if (code != null)
{
builder.SendValidationEvent(code);
}
}
//
// XDR Element
//
private static void XDR_InitElement(XdrBuilder builder, object obj)
{
if (builder._ElementDef._HasDataType ||
(builder._ElementDef._ContentAttr == SchemaContentEmpty) ||
(builder._ElementDef._ContentAttr == SchemaContentText))
{
builder.SendValidationEvent(SR.Sch_ElementNotAllowed);
}
builder._ElementDef._AllowDataType = false;
builder._ElementDef._HasType = false;
builder._ElementDef._MinVal = 1;
builder._ElementDef._MaxVal = 1;
}
private static void XDR_BuildElement_Type(XdrBuilder builder, object obj, string prefix)
{
XmlQualifiedName qname = (XmlQualifiedName)obj;
if (!builder._SchemaInfo.ElementDecls.ContainsKey(qname))
{
SchemaElementDecl ed = (SchemaElementDecl)builder._UndeclaredElements[qname];
if (ed == null)
{
ed = new SchemaElementDecl(qname, prefix);
builder._UndeclaredElements.Add(qname, ed);
}
}
builder._ElementDef._HasType = true;
if (builder._ElementDef._ExistTerminal)
builder.AddOrder();
else
builder._ElementDef._ExistTerminal = true;
builder._contentValidator.AddName(qname, null);
}
private static void XDR_BuildElement_MinOccurs(XdrBuilder builder, object obj, string prefix)
{
builder._ElementDef._MinVal = ParseMinOccurs(obj, builder);
}
private static void XDR_BuildElement_MaxOccurs(XdrBuilder builder, object obj, string prefix)
{
builder._ElementDef._MaxVal = ParseMaxOccurs(obj, builder);
}
// private static void XDR_BeginElement(XdrBuilder builder)
// {
//
// }
private static void XDR_EndElement(XdrBuilder builder)
{
if (builder._ElementDef._HasType)
{
HandleMinMax(builder._contentValidator,
builder._ElementDef._MinVal,
builder._ElementDef._MaxVal);
}
else
{
builder.SendValidationEvent(SR.Sch_MissAttribute);
}
}
//
// XDR Attribute
//
private static void XDR_InitAttribute(XdrBuilder builder, object obj)
{
if (builder._BaseDecl == null)
builder._BaseDecl = new DeclBaseInfo();
builder._BaseDecl._MinOccurs = 0;
}
private static void XDR_BuildAttribute_Type(XdrBuilder builder, object obj, string prefix)
{
builder._BaseDecl._TypeName = (XmlQualifiedName)obj;
builder._BaseDecl._Prefix = prefix;
}
private static void XDR_BuildAttribute_Required(XdrBuilder builder, object obj, string prefix)
{
if (IsYes(obj, builder))
{
builder._BaseDecl._MinOccurs = 1;
}
}
private static void XDR_BuildAttribute_Default(XdrBuilder builder, object obj, string prefix)
{
builder._BaseDecl._Default = obj;
}
private static void XDR_BeginAttribute(XdrBuilder builder)
{
if (builder._BaseDecl._TypeName.IsEmpty)
{
builder.SendValidationEvent(SR.Sch_MissAttribute);
}
SchemaAttDef attdef = null;
XmlQualifiedName qname = builder._BaseDecl._TypeName;
string prefix = builder._BaseDecl._Prefix;
// local?
if (builder._ElementDef._AttDefList != null)
{
attdef = (SchemaAttDef)builder._ElementDef._AttDefList[qname];
}
// global?
if (attdef == null)
{
// if there is no URN in this name then the name is local to the
// schema, but the global attribute was still URN qualified, so
// we need to qualify this name now.
XmlQualifiedName gname = qname;
if (prefix.Length == 0)
gname = new XmlQualifiedName(qname.Name, builder._TargetNamespace);
SchemaAttDef ad;
if (builder._SchemaInfo.AttributeDecls.TryGetValue(gname, out ad))
{
attdef = (SchemaAttDef)ad.Clone();
attdef.Name = qname;
}
else if (prefix.Length != 0)
{
builder.SendValidationEvent(SR.Sch_UndeclaredAttribute, XmlQualifiedName.ToString(qname.Name, prefix));
}
}
if (attdef != null)
{
builder.XDR_CheckAttributeDefault(builder._BaseDecl, attdef);
}
else
{
// will process undeclared types later
attdef = new SchemaAttDef(qname, prefix);
DeclBaseInfo decl = new DeclBaseInfo();
decl._Checking = true;
decl._Attdef = attdef;
decl._TypeName = builder._BaseDecl._TypeName;
decl._ElementDecl = builder._ElementDef._ElementDecl;
decl._MinOccurs = builder._BaseDecl._MinOccurs;
decl._Default = builder._BaseDecl._Default;
// add undefined attribute types
decl._Next = builder._UndefinedAttributeTypes;
builder._UndefinedAttributeTypes = decl;
}
builder._ElementDef._ElementDecl.AddAttDef(attdef);
}
private static void XDR_EndAttribute(XdrBuilder builder)
{
builder._BaseDecl.Reset();
}
//
// XDR Group
//
private static void XDR_InitGroup(XdrBuilder builder, object obj)
{
if (builder._ElementDef._ContentAttr == SchemaContentEmpty ||
builder._ElementDef._ContentAttr == SchemaContentText)
{
builder.SendValidationEvent(SR.Sch_GroupDisabled);
}
builder.PushGroupInfo();
builder._GroupDef._MinVal = 1;
builder._GroupDef._MaxVal = 1;
builder._GroupDef._HasMaxAttr = false;
builder._GroupDef._HasMinAttr = false;
if (builder._ElementDef._ExistTerminal)
builder.AddOrder();
// now we are in a group so we reset fExistTerminal
builder._ElementDef._ExistTerminal = false;
builder._contentValidator.OpenGroup();
}
private static void XDR_BuildGroup_Order(XdrBuilder builder, object obj, string prefix)
{
builder._GroupDef._Order = builder.GetOrder((XmlQualifiedName)obj);
if (builder._ElementDef._ContentAttr == SchemaContentMixed && builder._GroupDef._Order != SchemaOrderMany)
{
builder.SendValidationEvent(SR.Sch_MixedMany);
}
}
private static void XDR_BuildGroup_MinOccurs(XdrBuilder builder, object obj, string prefix)
{
builder._GroupDef._MinVal = ParseMinOccurs(obj, builder);
builder._GroupDef._HasMinAttr = true;
}
private static void XDR_BuildGroup_MaxOccurs(XdrBuilder builder, object obj, string prefix)
{
builder._GroupDef._MaxVal = ParseMaxOccurs(obj, builder);
builder._GroupDef._HasMaxAttr = true;
}
// private static void XDR_BeginGroup(XdrBuilder builder)
// {
//
// }
private static void XDR_EndGroup(XdrBuilder builder)
{
if (!builder._ElementDef._ExistTerminal)
{
builder.SendValidationEvent(SR.Sch_ElementMissing);
}
builder._contentValidator.CloseGroup();
if (builder._GroupDef._Order == SchemaOrderMany)
{
builder._contentValidator.AddStar();
}
if (SchemaOrderMany == builder._GroupDef._Order &&
builder._GroupDef._HasMaxAttr &&
builder._GroupDef._MaxVal != uint.MaxValue)
{
builder.SendValidationEvent(SR.Sch_ManyMaxOccurs);
}
HandleMinMax(builder._contentValidator,
builder._GroupDef._MinVal,
builder._GroupDef._MaxVal);
builder.PopGroupInfo();
}
//
// DataType
//
private static void XDR_InitElementDtType(XdrBuilder builder, object obj)
{
if (builder._ElementDef._HasDataType)
{
builder.SendValidationEvent(SR.Sch_DupDtType);
}
if (!builder._ElementDef._AllowDataType)
{
builder.SendValidationEvent(SR.Sch_DataTypeTextOnly);
}
}
private static void XDR_EndElementDtType(XdrBuilder builder)
{
if (!builder._ElementDef._HasDataType)
{
builder.SendValidationEvent(SR.Sch_MissAttribute);
}
builder._ElementDef._ElementDecl.ContentValidator = ContentValidator.TextOnly;
builder._ElementDef._ContentAttr = SchemaContentText;
builder._ElementDef._MasterGroupRequired = false;
builder._contentValidator = null;
}
private static void XDR_InitAttributeDtType(XdrBuilder builder, object obj)
{
if (builder._AttributeDef._HasDataType)
{
builder.SendValidationEvent(SR.Sch_DupDtType);
}
}
private static void XDR_EndAttributeDtType(XdrBuilder builder)
{
string code = null;
if (!builder._AttributeDef._HasDataType)
{
code = SR.Sch_MissAttribute;
}
else
{
if (builder._AttributeDef._AttDef.Datatype != null)
{
XmlTokenizedType ttype = builder._AttributeDef._AttDef.Datatype.TokenizedType;
if (ttype == XmlTokenizedType.ENUMERATION && !builder._AttributeDef._EnumerationRequired)
{
code = SR.Sch_MissDtvaluesAttribute;
}
else if (ttype != XmlTokenizedType.ENUMERATION && builder._AttributeDef._EnumerationRequired)
{
code = SR.Sch_RequireEnumeration;
}
}
}
if (code != null)
{
builder.SendValidationEvent(code);
}
}
//
// private utility methods
//
private bool GetNextState(XmlQualifiedName qname)
{
if (_CurState._NextStates != null)
{
for (int i = 0; i < _CurState._NextStates.Length; i++)
{
if (_SchemaNames.TokenToQName[(int)s_schemaEntries[_CurState._NextStates[i]]._Name].Equals(qname))
{
_NextState = s_schemaEntries[_CurState._NextStates[i]];
return true;
}
}
}
return false;
}
private bool IsSkipableElement(XmlQualifiedName qname)
{
string ns = qname.Namespace;
if (ns != null && !Ref.Equal(ns, _SchemaNames.NsXdr))
return true;
// skip description && extends
if (_SchemaNames.TokenToQName[(int)SchemaNames.Token.XdrDescription].Equals(qname) ||
_SchemaNames.TokenToQName[(int)SchemaNames.Token.XdrExtends].Equals(qname))
return true;
return false;
}
private bool IsSkipableAttribute(XmlQualifiedName qname)
{
string ns = qname.Namespace;
if (
ns.Length != 0 &&
!Ref.Equal(ns, _SchemaNames.NsXdr) &&
!Ref.Equal(ns, _SchemaNames.NsDataType)
)
{
return true;
}
if (Ref.Equal(ns, _SchemaNames.NsDataType) &&
_CurState._Name == SchemaNames.Token.XdrDatatype &&
(_SchemaNames.QnDtMax.Equals(qname) ||
_SchemaNames.QnDtMin.Equals(qname) ||
_SchemaNames.QnDtMaxExclusive.Equals(qname) ||
_SchemaNames.QnDtMinExclusive.Equals(qname)))
{
return true;
}
return false;
}
private int GetOrder(XmlQualifiedName qname)
{
int order = 0;
if (_SchemaNames.TokenToQName[(int)SchemaNames.Token.SchemaSeq].Equals(qname))
{
order = SchemaOrderSequence;
}
else if (_SchemaNames.TokenToQName[(int)SchemaNames.Token.SchemaOne].Equals(qname))
{
order = SchemaOrderChoice;
}
else if (_SchemaNames.TokenToQName[(int)SchemaNames.Token.SchemaMany].Equals(qname))
{
order = SchemaOrderMany;
}
else
{
SendValidationEvent(SR.Sch_UnknownOrder, qname.Name);
}
return order;
}
private void AddOrder()
{
// additional order can be add on by changing the setOrder and addOrder
switch (_GroupDef._Order)
{
case SchemaOrderSequence:
_contentValidator.AddSequence();
break;
case SchemaOrderChoice:
case SchemaOrderMany:
_contentValidator.AddChoice();
break;
default:
case SchemaOrderAll:
throw new XmlException(SR.Xml_UnexpectedToken, "NAME");
}
}
private static bool IsYes(object obj, XdrBuilder builder)
{
XmlQualifiedName qname = (XmlQualifiedName)obj;
bool fYes = false;
if (qname.Name == "yes")
{
fYes = true;
}
else if (qname.Name != "no")
{
builder.SendValidationEvent(SR.Sch_UnknownRequired);
}
return fYes;
}
private static uint ParseMinOccurs(object obj, XdrBuilder builder)
{
uint cVal = 1;
if (!ParseInteger((string)obj, ref cVal) || (cVal != 0 && cVal != 1))
{
builder.SendValidationEvent(SR.Sch_MinOccursInvalid);
}
return cVal;
}
private static uint ParseMaxOccurs(object obj, XdrBuilder builder)
{
uint cVal = uint.MaxValue;
string s = (string)obj;
if (!s.Equals("*") &&
(!ParseInteger(s, ref cVal) || (cVal != uint.MaxValue && cVal != 1)))
{
builder.SendValidationEvent(SR.Sch_MaxOccursInvalid);
}
return cVal;
}
private static void HandleMinMax(ParticleContentValidator pContent, uint cMin, uint cMax)
{
if (pContent != null)
{
if (cMax == uint.MaxValue)
{
if (cMin == 0)
pContent.AddStar(); // minOccurs="0" and maxOccurs="infinite"
else
pContent.AddPlus(); // minOccurs="1" and maxOccurs="infinite"
}
else if (cMin == 0)
{ // minOccurs="0" and maxOccurs="1")
pContent.AddQMark();
}
}
}
private static void ParseDtMaxLength(ref uint cVal, object obj, XdrBuilder builder)
{
if (uint.MaxValue != cVal)
{
builder.SendValidationEvent(SR.Sch_DupDtMaxLength);
}
if (!ParseInteger((string)obj, ref cVal) || cVal < 0)
{
builder.SendValidationEvent(SR.Sch_DtMaxLengthInvalid, obj.ToString());
}
}
private static void ParseDtMinLength(ref uint cVal, object obj, XdrBuilder builder)
{
if (uint.MaxValue != cVal)
{
builder.SendValidationEvent(SR.Sch_DupDtMinLength);
}
if (!ParseInteger((string)obj, ref cVal) || cVal < 0)
{
builder.SendValidationEvent(SR.Sch_DtMinLengthInvalid, obj.ToString());
}
}
private static void CompareMinMaxLength(uint cMin, uint cMax, XdrBuilder builder)
{
if (cMin != uint.MaxValue && cMax != uint.MaxValue && cMin > cMax)
{
builder.SendValidationEvent(SR.Sch_DtMinMaxLength);
}
}
private static bool ParseInteger(string str, ref uint n)
{
return UInt32.TryParse(str, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out n);
}
private void XDR_CheckAttributeDefault(DeclBaseInfo decl, SchemaAttDef pAttdef)
{
if (decl._Default != null || pAttdef.DefaultValueTyped != null)
{
if (decl._Default != null)
{
pAttdef.DefaultValueRaw = pAttdef.DefaultValueExpanded = (string)decl._Default;
CheckDefaultAttValue(pAttdef);
}
}
SetAttributePresence(pAttdef, 1 == decl._MinOccurs);
}
private void SetAttributePresence(SchemaAttDef pAttdef, bool fRequired)
{
if (SchemaDeclBase.Use.Fixed != pAttdef.Presence)
{
if (fRequired || SchemaDeclBase.Use.Required == pAttdef.Presence)
{
// If it is required and it has a default value then it is a FIXED attribute.
if (pAttdef.DefaultValueTyped != null)
pAttdef.Presence = SchemaDeclBase.Use.Fixed;
else
pAttdef.Presence = SchemaDeclBase.Use.Required;
}
else if (pAttdef.DefaultValueTyped != null)
{
pAttdef.Presence = SchemaDeclBase.Use.Default;
}
else
{
pAttdef.Presence = SchemaDeclBase.Use.Implied;
}
}
}
private int GetContent(XmlQualifiedName qname)
{
int content = 0;
if (_SchemaNames.TokenToQName[(int)SchemaNames.Token.SchemaEmpty].Equals(qname))
{
content = SchemaContentEmpty;
_ElementDef._AllowDataType = false;
}
else if (_SchemaNames.TokenToQName[(int)SchemaNames.Token.SchemaElementOnly].Equals(qname))
{
content = SchemaContentElement;
_ElementDef._AllowDataType = false;
}
else if (_SchemaNames.TokenToQName[(int)SchemaNames.Token.SchemaMixed].Equals(qname))
{
content = SchemaContentMixed;
_ElementDef._AllowDataType = false;
}
else if (_SchemaNames.TokenToQName[(int)SchemaNames.Token.SchemaTextOnly].Equals(qname))
{
content = SchemaContentText;
}
else
{
SendValidationEvent(SR.Sch_UnknownContent, qname.Name);
}
return content;
}
private bool GetModel(XmlQualifiedName qname)
{
bool fOpen = false;
if (_SchemaNames.TokenToQName[(int)SchemaNames.Token.SchemaOpen].Equals(qname))
fOpen = true;
else if (_SchemaNames.TokenToQName[(int)SchemaNames.Token.SchemaClosed].Equals(qname))
fOpen = false;
else
SendValidationEvent(SR.Sch_UnknownModel, qname.Name);
return fOpen;
}
private XmlSchemaDatatype CheckDatatype(string str)
{
XmlSchemaDatatype dtype = XmlSchemaDatatype.FromXdrName(str);
if (dtype == null)
{
SendValidationEvent(SR.Sch_UnknownDtType, str);
}
else if (dtype.TokenizedType == XmlTokenizedType.ID)
{
if (!_AttributeDef._Global)
{
if (_ElementDef._ElementDecl.IsIdDeclared)
{
SendValidationEvent(SR.Sch_IdAttrDeclared,
XmlQualifiedName.ToString(_ElementDef._ElementDecl.Name.Name, _ElementDef._ElementDecl.Prefix));
}
_ElementDef._ElementDecl.IsIdDeclared = true;
}
}
return dtype;
}
private void CheckDefaultAttValue(SchemaAttDef attDef)
{
string str = (attDef.DefaultValueRaw).Trim();
XdrValidator.CheckDefaultValue(str, attDef, _SchemaInfo, _CurNsMgr, _NameTable, null, _validationEventHandler, _reader.BaseURI, _positionInfo.LineNumber, _positionInfo.LinePosition);
}
private bool IsGlobal(int flags)
{
return flags == SchemaFlagsNs;
}
private void SendValidationEvent(string code, string[] args, XmlSeverityType severity)
{
SendValidationEvent(new XmlSchemaException(code, args, _reader.BaseURI, _positionInfo.LineNumber, _positionInfo.LinePosition), severity);
}
private void SendValidationEvent(string code)
{
SendValidationEvent(code, string.Empty);
}
private void SendValidationEvent(string code, string msg)
{
SendValidationEvent(new XmlSchemaException(code, msg, _reader.BaseURI, _positionInfo.LineNumber, _positionInfo.LinePosition), XmlSeverityType.Error);
}
private void SendValidationEvent(XmlSchemaException e, XmlSeverityType severity)
{
_SchemaInfo.ErrorCount++;
if (_validationEventHandler != null)
{
_validationEventHandler(this, new ValidationEventArgs(e, severity));
}
else if (severity == XmlSeverityType.Error)
{
throw e;
}
}
}; // class XdrBuilder
} // namespace System.Xml
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: TextProperties.cs
//
// Description: Text run properties provider.
//
// History:
// 04/25/2003 : [....] - moving from Avalon branch.
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
namespace MS.Internal.Text
{
// ----------------------------------------------------------------------
// Text run properties provider.
// ----------------------------------------------------------------------
internal sealed class TextProperties : TextRunProperties
{
// ------------------------------------------------------------------
//
// TextRunProperties Implementation
//
// ------------------------------------------------------------------
#region TextRunProperties Implementation
// ------------------------------------------------------------------
// Typeface used to format and display text.
// ------------------------------------------------------------------
public override Typeface Typeface { get { return _typeface; } }
// ------------------------------------------------------------------
// Em size of font used to format and display text.
// ------------------------------------------------------------------
public override double FontRenderingEmSize
{
get
{
double emSize = _fontSize;
// Make sure that TextFormatter limitations are not exceeded.
TextDpi.EnsureValidLineOffset(ref emSize);
return emSize;
}
}
// ------------------------------------------------------------------
// Em size of font to determine subtle change in font hinting.
// ------------------------------------------------------------------
public override double FontHintingEmSize { get { return 12.0; } }
// ------------------------------------------------------------------
// Text decorations.
// ------------------------------------------------------------------
public override TextDecorationCollection TextDecorations { get { return _textDecorations; } }
// ------------------------------------------------------------------
// Text foreground bursh.
// ------------------------------------------------------------------
public override Brush ForegroundBrush { get { return _foreground; } }
// ------------------------------------------------------------------
// Text background brush.
// ------------------------------------------------------------------
public override Brush BackgroundBrush { get { return _backgroundBrush; } }
// ------------------------------------------------------------------
// Text vertical alignment.
// ------------------------------------------------------------------
public override BaselineAlignment BaselineAlignment { get { return _baselineAlignment; } }
// ------------------------------------------------------------------
// Text culture info.
// ------------------------------------------------------------------
public override CultureInfo CultureInfo { get { return _cultureInfo; } }
// ------------------------------------------------------------------
// Number substitution
// ------------------------------------------------------------------
public override NumberSubstitution NumberSubstitution { get { return _numberSubstitution; } }
// ------------------------------------------------------------------
// Typography properties
// ------------------------------------------------------------------
public override TextRunTypographyProperties TypographyProperties{ get { return _typographyProperties; } }
// ------------------------------------------------------------------
// TextEffects property
// ------------------------------------------------------------------
public override TextEffectCollection TextEffects { get { return _textEffects; } }
#endregion TextRunProperties Implementation
// ------------------------------------------------------------------
// Constructor.
// ------------------------------------------------------------------
internal TextProperties(FrameworkElement target, bool isTypographyDefaultValue)
{
// if none of the number substitution properties have changed, initialize the
// _numberSubstitution field to a known default value
if (!target.HasNumberSubstitutionChanged)
{
_numberSubstitution = FrameworkElement.DefaultNumberSubstitution;
}
InitCommon(target);
if (!isTypographyDefaultValue)
{
_typographyProperties = TextElement.GetTypographyProperties(target);
}
else
{
_typographyProperties = Typography.Default;
}
_baselineAlignment = BaselineAlignment.Baseline;
}
internal TextProperties(DependencyObject target, StaticTextPointer position, bool inlineObjects, bool getBackground)
{
// if none of the number substitution properties have changed, we may be able to
// initialize the _numberSubstitution field to a known default value
FrameworkContentElement fce = target as FrameworkContentElement;
if (fce != null)
{
if (!fce.HasNumberSubstitutionChanged)
{
_numberSubstitution = FrameworkContentElement.DefaultNumberSubstitution;
}
}
else
{
FrameworkElement fe = target as FrameworkElement;
if (fe != null && !fe.HasNumberSubstitutionChanged)
{
_numberSubstitution = FrameworkElement.DefaultNumberSubstitution;
}
}
InitCommon(target);
_typographyProperties = GetTypographyProperties(target);
if (!inlineObjects)
{
_baselineAlignment = DynamicPropertyReader.GetBaselineAlignment(target);
if (!position.IsNull)
{
TextDecorationCollection highlightDecorations = GetHighlightTextDecorations(position);
if (highlightDecorations != null)
{
// Highlights (if present) take precedence over property value TextDecorations.
_textDecorations = highlightDecorations;
}
}
if (getBackground)
{
_backgroundBrush = DynamicPropertyReader.GetBackgroundBrush(target);
}
}
else
{
_baselineAlignment = DynamicPropertyReader.GetBaselineAlignmentForInlineObject(target);
_textDecorations = DynamicPropertyReader.GetTextDecorationsForInlineObject(target, _textDecorations);
if (getBackground)
{
_backgroundBrush = DynamicPropertyReader.GetBackgroundBrushForInlineObject(position);
}
}
}
// Copy constructor, with override for default TextDecorationCollection value.
internal TextProperties(TextProperties source, TextDecorationCollection textDecorations)
{
_backgroundBrush = source._backgroundBrush;
_typeface = source._typeface;
_fontSize = source._fontSize;
_foreground = source._foreground;
_textEffects = source._textEffects;
_cultureInfo = source._cultureInfo;
_numberSubstitution = source._numberSubstitution;
_typographyProperties = source._typographyProperties;
_baselineAlignment = source._baselineAlignment;
_textDecorations = textDecorations;
}
// assigns values to all fields except for _typographyProperties, _baselineAlignment,
// and _background, which are set appropriately in each constructor
private void InitCommon(DependencyObject target)
{
_typeface = DynamicPropertyReader.GetTypeface(target);
_fontSize = (double)target.GetValue(TextElement.FontSizeProperty);
_foreground = (Brush) target.GetValue(TextElement.ForegroundProperty);
_textEffects = DynamicPropertyReader.GetTextEffects(target);
_cultureInfo = DynamicPropertyReader.GetCultureInfo(target);
_textDecorations = DynamicPropertyReader.GetTextDecorations(target);
// as an optimization, we may have already initialized _numberSubstitution to a default
// value if none of the NumberSubstitution dependency properties have changed
if (_numberSubstitution == null)
{
_numberSubstitution = DynamicPropertyReader.GetNumberSubstitution(target);
}
}
// Gathers text decorations set on scoping highlights.
// If no highlight properties are found, returns null
private static TextDecorationCollection GetHighlightTextDecorations(StaticTextPointer highlightPosition)
{
TextDecorationCollection textDecorations = null;
Highlights highlights = highlightPosition.TextContainer.Highlights;
if (highlights == null)
{
return textDecorations;
}
//
// Speller
//
textDecorations = highlights.GetHighlightValue(highlightPosition, LogicalDirection.Forward, typeof(SpellerHighlightLayer)) as TextDecorationCollection;
//
// IME composition
//
//
#if UNUSED_IME_HIGHLIGHT_LAYER
TextDecorationCollection imeTextDecorations = highlights.GetHighlightValue(highlightPosition, LogicalDirection.Forward, typeof(FrameworkTextComposition)) as TextDecorationCollection;
if (imeTextDecorations != null)
{
textDecorations = imeTextDecorations;
}
#endif
return textDecorations;
}
// ------------------------------------------------------------------
// Retrieve typography properties from specified element.
// ------------------------------------------------------------------
private static TypographyProperties GetTypographyProperties(DependencyObject element)
{
Debug.Assert(element != null);
TextBlock tb = element as TextBlock;
if (tb != null)
{
if(!tb.IsTypographyDefaultValue)
{
return TextElement.GetTypographyProperties(element);
}
else
{
return Typography.Default;
}
}
TextBox textBox = element as TextBox;
if (textBox != null)
{
if (!textBox.IsTypographyDefaultValue)
{
return TextElement.GetTypographyProperties(element);
}
else
{
return Typography.Default;
}
}
TextElement te = element as TextElement;
if (te != null)
{
return te.TypographyPropertiesGroup;
}
FlowDocument fd = element as FlowDocument;
if (fd != null)
{
return fd.TypographyPropertiesGroup;
}
// return default typography properties group
return Typography.Default;
}
// ------------------------------------------------------------------
// Typeface.
// ------------------------------------------------------------------
private Typeface _typeface;
// ------------------------------------------------------------------
// Font size.
// ------------------------------------------------------------------
private double _fontSize;
// ------------------------------------------------------------------
// Foreground brush.
// ------------------------------------------------------------------
private Brush _foreground;
// ------------------------------------------------------------------
// Text effects flags.
// ------------------------------------------------------------------
private TextEffectCollection _textEffects;
// ------------------------------------------------------------------
// Text decorations.
// ------------------------------------------------------------------
private TextDecorationCollection _textDecorations;
// ------------------------------------------------------------------
// Baseline alignment.
// ------------------------------------------------------------------
private BaselineAlignment _baselineAlignment;
// ------------------------------------------------------------------
// Text background brush.
// ------------------------------------------------------------------
private Brush _backgroundBrush;
// ------------------------------------------------------------------
// Culture info.
// ------------------------------------------------------------------
private CultureInfo _cultureInfo;
// ------------------------------------------------------------------
// Number Substitution
// ------------------------------------------------------------------
private NumberSubstitution _numberSubstitution;
// ------------------------------------------------------------------
// Typography properties group.
// ------------------------------------------------------------------
private TextRunTypographyProperties _typographyProperties;
}
}
| |
using System;
using NUnit.Framework;
using Whois.Parsers;
namespace Whois.Parsing.Whois.Cat.Cat
{
[TestFixture]
public class CatParsingTests : ParsingTests
{
private WhoisParser parser;
[SetUp]
public void SetUp()
{
SerilogConfig.Init();
parser = new WhoisParser();
}
[Test]
public void Test_not_found()
{
var sample = SampleReader.Read("whois.cat", "cat", "not_found.txt");
var response = parser.Parse("whois.cat", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.NotFound, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cat/cat/NotFound", response.TemplateName);
Assert.AreEqual("u34jedzcq.cat", response.DomainName.ToString());
Assert.AreEqual(2, response.FieldsParsed);
}
[Test]
public void Test_found()
{
var sample = SampleReader.Read("whois.cat", "cat", "found.txt");
var response = parser.Parse("whois.cat", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Found, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cat/cat/Found", response.TemplateName);
Assert.AreEqual("abril.cat", response.DomainName.ToString());
Assert.AreEqual("REG-D42136", response.RegistryDomainId);
Assert.AreEqual(new DateTime(2011, 1, 12, 16, 50, 9, DateTimeKind.Utc), response.Updated);
Assert.AreEqual(new DateTime(2006, 4, 22, 09, 48, 30, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2011, 4, 22, 09, 48, 30, DateTimeKind.Utc), response.Expiration);
// Registrant Details
Assert.AreEqual("edig-001455", response.Registrant.RegistryId);
Assert.AreEqual("Amadeu Abril i Abril", response.Registrant.Name);
// Registrant Address
Assert.AreEqual(4, response.Registrant.Address.Count);
Assert.AreEqual("Carrer del carme 47", response.Registrant.Address[0]);
Assert.AreEqual("Barcelona", response.Registrant.Address[1]);
Assert.AreEqual("08001", response.Registrant.Address[2]);
Assert.AreEqual("ES", response.Registrant.Address[3]);
Assert.AreEqual("+34.932701520", response.Registrant.TelephoneNumber);
Assert.AreEqual("Amadeu@abril.info", response.Registrant.Email);
// AdminContact Details
Assert.AreEqual("ento0027519", response.AdminContact.RegistryId);
Assert.AreEqual("Amadeu Abril i Abril", response.AdminContact.Name);
// AdminContact Address
Assert.AreEqual(5, response.AdminContact.Address.Count);
Assert.AreEqual("Carrer del Carme 47", response.AdminContact.Address[0]);
Assert.AreEqual("Barcelona", response.AdminContact.Address[1]);
Assert.AreEqual("BARCELONA", response.AdminContact.Address[2]);
Assert.AreEqual("08001", response.AdminContact.Address[3]);
Assert.AreEqual("ES", response.AdminContact.Address[4]);
Assert.AreEqual("+34.932701520", response.AdminContact.TelephoneNumber);
Assert.AreEqual("dominisadmin@mac.com", response.AdminContact.Email);
// BillingContact Details
Assert.AreEqual("ento0027519", response.BillingContact.RegistryId);
Assert.AreEqual("Amadeu Abril i Abril", response.BillingContact.Name);
// BillingContact Address
Assert.AreEqual(5, response.BillingContact.Address.Count);
Assert.AreEqual("Carrer del Carme 47", response.BillingContact.Address[0]);
Assert.AreEqual("Barcelona", response.BillingContact.Address[1]);
Assert.AreEqual("BARCELONA", response.BillingContact.Address[2]);
Assert.AreEqual("08001", response.BillingContact.Address[3]);
Assert.AreEqual("ES", response.BillingContact.Address[4]);
Assert.AreEqual("+34.932701520", response.BillingContact.TelephoneNumber);
Assert.AreEqual("dominisadmin@mac.com", response.BillingContact.Email);
// TechnicalContact Details
Assert.AreEqual("ento0027519", response.TechnicalContact.RegistryId);
Assert.AreEqual("Amadeu Abril i Abril", response.TechnicalContact.Name);
// TechnicalContact Address
Assert.AreEqual(5, response.TechnicalContact.Address.Count);
Assert.AreEqual("Carrer del Carme 47", response.TechnicalContact.Address[0]);
Assert.AreEqual("Barcelona", response.TechnicalContact.Address[1]);
Assert.AreEqual("BARCELONA", response.TechnicalContact.Address[2]);
Assert.AreEqual("08001", response.TechnicalContact.Address[3]);
Assert.AreEqual("ES", response.TechnicalContact.Address[4]);
Assert.AreEqual("+34.932701520", response.TechnicalContact.TelephoneNumber);
Assert.AreEqual("dominisadmin@mac.com", response.TechnicalContact.Email);
// Nameservers
Assert.AreEqual(2, response.NameServers.Count);
Assert.AreEqual("ns14.zoneedit.com", response.NameServers[0]);
Assert.AreEqual("ns12.zoneedit.com", response.NameServers[1]);
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("clientTransferProhibited, clientDeleteProhibited", response.DomainStatus[0]);
Assert.AreEqual(48, response.FieldsParsed);
}
[Test]
public void Test_found_status_ok()
{
var sample = SampleReader.Read("whois.cat", "cat", "found_status_ok.txt");
var response = parser.Parse("whois.cat", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Found, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cat/cat/Found", response.TemplateName);
Assert.AreEqual("gencat.cat", response.DomainName.ToString());
Assert.AreEqual("REG-D3862", response.RegistryDomainId);
Assert.AreEqual(new DateTime(2009, 3, 31, 16, 22, 42, DateTimeKind.Utc), response.Updated);
Assert.AreEqual(new DateTime(2006, 2, 14, 9, 12, 37, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2010, 2, 14, 9, 12, 37, DateTimeKind.Utc), response.Expiration);
// Registrant Details
Assert.AreEqual("NOM_P_15605701", response.Registrant.RegistryId);
Assert.AreEqual("Generalitat de Catalunya Departament de la Presidencia", response.Registrant.Name);
// Registrant Address
Assert.AreEqual(5, response.Registrant.Address.Count);
Assert.AreEqual("Via Laietana, 14", response.Registrant.Address[0]);
Assert.AreEqual("Barcelona", response.Registrant.Address[1]);
Assert.AreEqual("BARCELONA", response.Registrant.Address[2]);
Assert.AreEqual("08003", response.Registrant.Address[3]);
Assert.AreEqual("ES", response.Registrant.Address[4]);
Assert.AreEqual("+34.935676330", response.Registrant.TelephoneNumber);
Assert.AreEqual("jcolomer@gencat.net", response.Registrant.Email);
// AdminContact Details
Assert.AreEqual("NOM_8727301", response.AdminContact.RegistryId);
Assert.AreEqual("Marta Continente Gonzalo", response.AdminContact.Name);
Assert.AreEqual("Generalitat de Catalunya Departament de la Presidencia (2)", response.AdminContact.Organization);
// AdminContact Address
Assert.AreEqual(5, response.AdminContact.Address.Count);
Assert.AreEqual("Via Laietana, 14", response.AdminContact.Address[0]);
Assert.AreEqual("Barcelona", response.AdminContact.Address[1]);
Assert.AreEqual("BARCELONA", response.AdminContact.Address[2]);
Assert.AreEqual("08003", response.AdminContact.Address[3]);
Assert.AreEqual("ES", response.AdminContact.Address[4]);
Assert.AreEqual("+34.935676330", response.AdminContact.TelephoneNumber);
Assert.AreEqual("+34.935676331", response.AdminContact.FaxNumber);
Assert.AreEqual("dominisgencat@gencat.net", response.AdminContact.Email);
// BillingContact Details
Assert.AreEqual("NOM_8727401", response.BillingContact.RegistryId);
Assert.AreEqual("Jaume Colomer Garcia", response.BillingContact.Name);
Assert.AreEqual("Generalitat de Catalunya - Departament de la Presidencia", response.BillingContact.Organization);
// BillingContact Address
Assert.AreEqual(5, response.BillingContact.Address.Count);
Assert.AreEqual("Via Laietana, 14", response.BillingContact.Address[0]);
Assert.AreEqual("Barcelona", response.BillingContact.Address[1]);
Assert.AreEqual("BARCELONA", response.BillingContact.Address[2]);
Assert.AreEqual("08003", response.BillingContact.Address[3]);
Assert.AreEqual("ES", response.BillingContact.Address[4]);
Assert.AreEqual("+34.935676330", response.BillingContact.TelephoneNumber);
Assert.AreEqual("+34.935676331", response.BillingContact.FaxNumber);
Assert.AreEqual("dominisgencat@gencat.net", response.BillingContact.Email);
// TechnicalContact Details
Assert.AreEqual("NOM_8727401", response.TechnicalContact.RegistryId);
Assert.AreEqual("Jaume Colomer Garcia", response.TechnicalContact.Name);
Assert.AreEqual("Generalitat de Catalunya - Departament de la Presidencia", response.TechnicalContact.Organization);
// TechnicalContact Address
Assert.AreEqual(5, response.TechnicalContact.Address.Count);
Assert.AreEqual("Via Laietana, 14", response.TechnicalContact.Address[0]);
Assert.AreEqual("Barcelona", response.TechnicalContact.Address[1]);
Assert.AreEqual("BARCELONA", response.TechnicalContact.Address[2]);
Assert.AreEqual("08003", response.TechnicalContact.Address[3]);
Assert.AreEqual("ES", response.TechnicalContact.Address[4]);
Assert.AreEqual("+34.935676330", response.TechnicalContact.TelephoneNumber);
Assert.AreEqual("+34.935676331", response.TechnicalContact.FaxNumber);
Assert.AreEqual("dominisgencat@gencat.net", response.TechnicalContact.Email);
// Nameservers
Assert.AreEqual(1, response.NameServers.Count);
Assert.AreEqual("dns.gencat.net", response.NameServers[0]);
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("ok", response.DomainStatus[0]);
Assert.AreEqual(51, response.FieldsParsed);
}
[Test]
public void Test_not_found_status_available()
{
var sample = SampleReader.Read("whois.cat", "cat", "not_found_status_available.txt");
var response = parser.Parse("whois.cat", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.NotFound, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cat/cat/NotFound", response.TemplateName);
Assert.AreEqual("u34jedzcq.cat", response.DomainName.ToString());
Assert.AreEqual(2, response.FieldsParsed);
}
[Test]
public void Test_found_status_registered()
{
var sample = SampleReader.Read("whois.cat", "cat", "found_status_registered.txt");
var response = parser.Parse("whois.cat", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Found, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cat/cat/Found", response.TemplateName);
Assert.AreEqual("gencat.cat", response.DomainName.ToString());
Assert.AreEqual("REG-D3862", response.RegistryDomainId);
Assert.AreEqual(new DateTime(2013, 11, 27, 17, 30, 59, DateTimeKind.Utc), response.Updated);
Assert.AreEqual(new DateTime(2006, 2, 14, 9, 12, 37, DateTimeKind.Utc), response.Registered);
Assert.AreEqual(new DateTime(2020, 2, 14, 9, 12, 37, DateTimeKind.Utc), response.Expiration);
// Registrant Details
Assert.AreEqual("CD126562321349", response.Registrant.RegistryId);
Assert.AreEqual("Departament de la Presidencia - Generalitat de Catalunya", response.Registrant.Name);
Assert.AreEqual("Departament de la Presidencia - Generalitat de Catalunya", response.Registrant.Organization);
// Registrant Address
Assert.AreEqual(5, response.Registrant.Address.Count);
Assert.AreEqual("Via Laietana, 14", response.Registrant.Address[0]);
Assert.AreEqual("Barcelona", response.Registrant.Address[1]);
Assert.AreEqual("Barcelona", response.Registrant.Address[2]);
Assert.AreEqual("08003", response.Registrant.Address[3]);
Assert.AreEqual("ES", response.Registrant.Address[4]);
Assert.AreEqual("+34.935676330", response.Registrant.TelephoneNumber);
Assert.AreEqual("dominisgencat@gencat.cat", response.Registrant.Email);
// AdminContact Details
Assert.AreEqual("CD126562321411", response.AdminContact.RegistryId);
Assert.AreEqual("Direccio General Atencio Ciutadana i Difusio (Generalitat de Catalunya)", response.AdminContact.Name);
// AdminContact Address
Assert.AreEqual(5, response.AdminContact.Address.Count);
Assert.AreEqual("Via Laietana, 14", response.AdminContact.Address[0]);
Assert.AreEqual("Barcelona", response.AdminContact.Address[1]);
Assert.AreEqual("BARCELONA", response.AdminContact.Address[2]);
Assert.AreEqual("08003", response.AdminContact.Address[3]);
Assert.AreEqual("ES", response.AdminContact.Address[4]);
Assert.AreEqual("+34.935676330", response.AdminContact.TelephoneNumber);
Assert.AreEqual("dominisgencat@gencat.cat", response.AdminContact.Email);
// BillingContact Details
Assert.AreEqual("CD126562321532", response.BillingContact.RegistryId);
Assert.AreEqual("DGAC Direccio General Atencio Ciutadana", response.BillingContact.Name);
Assert.AreEqual("DGAC Direccio General Atencio Ciutadana", response.BillingContact.Organization);
// BillingContact Address
Assert.AreEqual(5, response.BillingContact.Address.Count);
Assert.AreEqual("Via Laietana, 14", response.BillingContact.Address[0]);
Assert.AreEqual("Barcelona", response.BillingContact.Address[1]);
Assert.AreEqual("Barcelona", response.BillingContact.Address[2]);
Assert.AreEqual("08003", response.BillingContact.Address[3]);
Assert.AreEqual("ES", response.BillingContact.Address[4]);
Assert.AreEqual("+34.935676330", response.BillingContact.TelephoneNumber);
Assert.AreEqual("dominisgencat@gencat.cat", response.BillingContact.Email);
// TechnicalContact Details
Assert.AreEqual("CD126562321482", response.TechnicalContact.RegistryId);
Assert.AreEqual("Carles Corcoll Lopez", response.TechnicalContact.Name);
Assert.AreEqual("Carles Corcoll Lopez", response.TechnicalContact.Organization);
// TechnicalContact Address
Assert.AreEqual(5, response.TechnicalContact.Address.Count);
Assert.AreEqual("Via Laietana 14 3a planta", response.TechnicalContact.Address[0]);
Assert.AreEqual("Barcelona", response.TechnicalContact.Address[1]);
Assert.AreEqual("BARCELONA", response.TechnicalContact.Address[2]);
Assert.AreEqual("08003", response.TechnicalContact.Address[3]);
Assert.AreEqual("ES", response.TechnicalContact.Address[4]);
Assert.AreEqual("+34.935676330", response.TechnicalContact.TelephoneNumber);
Assert.AreEqual("dominisgencat@gencat.cat", response.TechnicalContact.Email);
// Nameservers
Assert.AreEqual(1, response.NameServers.Count);
Assert.AreEqual("dns.gencat.net", response.NameServers[0]);
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("ok", response.DomainStatus[0]);
Assert.AreEqual(48, response.FieldsParsed);
}
}
}
| |
// EasyButton library is copyright (c) of Hedgehog Team
// Please send feedback or bug reports to the.hedgehog.team@gmail.com
using UnityEngine;
using System.Collections;
/// <summary>
/// Release notes:
/// EasyButton V1.3 October 2013
/// =============================
/// * Bugs fixed
/// ------------
/// - Fix debug area
///
/// EasyButton V1.2 Septembre 2013
/// =============================
/// * Fixe On_ButtonUp event that didn't allow you to use joystick in the same time
///
/// EasyButton V1.1 August 2013
/// =============================
/// * Fixe On_ButtonUp event that didn't allow you to use joystick in the same time
///
/// EasyButton V1.0 April 2013
/// =============================
/// * Bugs fixed
/// ------------
/// - Fixe Normaltexture property, if you changes the texture during runtime, it taken into account after une first click on a button
///
/// EasyButton V1.0 April 2013
/// =============================
/// - First release
///
/// <summary>
/// This is the main class of EasyButton engine.
///
/// For add EasyButton to your scene, use the menu Hedgehog Team<br>
/// </summary>
[ExecuteInEditMode]
public class EasyButton : MonoBehaviour {
#region Delegate
public delegate void ButtonUpHandler(string buttonName);
public delegate void ButtonPressHandler(string buttonName);
public delegate void ButtonDownHandler(string buttonName);
#endregion
#region Event
/// <summary>
/// Occurs when the button is down for the first time.
/// </summary>
public static event ButtonDownHandler On_ButtonDown;
/// <summary>
/// Occurs when the button is pressed.
/// </summary>
public static event ButtonPressHandler On_ButtonPress;
/// <summary>
/// Occurs when the button is up
/// </summary>
public static event ButtonUpHandler On_ButtonUp;
#endregion
#region Enumerations
/// <summary>
/// Button anchor.
/// </summary>
public enum ButtonAnchor {UpperLeft, UpperCenter, UpperRight, MiddleLeft, MiddleCenter, MiddleRight, LowerLeft, LowerCenter, LowerRight};
/// <summary>
/// Broadcast mode for javascript
/// </summary>
public enum Broadcast {SendMessage,SendMessageUpwards,BroadcastMessage }
/// <summary>
/// Button state, for include mode
/// </summary>
public enum ButtonState { Down, Press, Up, None};
/// <summary>
/// Interaction type.
/// </summary>
public enum InteractionType {Event, Include}
private enum MessageName{On_ButtonDown, On_ButtonPress,On_ButtonUp};
#endregion
#region Members
#region public members
#region Button properties
/// <summary>
/// Enable or disable the button.
/// </summary>
public bool enable = true;
/// <summary>
/// Activacte or deactivate the button
/// </summary>
public bool isActivated = true;
public bool showDebugArea=true;
public bool selected=false;
/// <summary>
/// Disable this lets you skip the GUI layout phase.
/// </summary>
public bool isUseGuiLayout=true;
/// <summary>
/// The state of the button
/// </summary>
public ButtonState buttonState = ButtonState.None;
#endregion
#region Button position & size
[SerializeField]
private ButtonAnchor anchor = ButtonAnchor.LowerRight;
/// <summary>
/// Gets or sets the anchor.
/// </summary>
/// <value>
/// The anchor.
/// </value>
public ButtonAnchor Anchor {
get {
return this.anchor;
}
set {
anchor = value;
ComputeButtonAnchor( anchor);
}
}
[SerializeField]
private Vector2 offset = Vector2.zero;
/// <summary>
/// Gets or sets the offset.
/// </summary>
/// <value>
/// The offset.
/// </value>
public Vector2 Offset {
get {
return this.offset;
}
set {
offset = value;
ComputeButtonAnchor( anchor);
}
}
[SerializeField]
private Vector2 scale = Vector2.one;
/// <summary>
/// Gets or sets the scale.
/// </summary>
/// <value>
/// The scale.
/// </value>
public Vector2 Scale {
get {
return this.scale;
}
set {
scale = value;
ComputeButtonAnchor( anchor);
}
}
/// <summary>
/// Enable or disable swipe in option
/// </summary>
public bool isSwipeIn = false;
/// <summary>
/// enable or disable siwpe out
/// </summary>
public bool isSwipeOut = false;
#endregion
#region Interaction & Events
/// <summary>
/// The interaction.
/// </summary>/
public InteractionType interaction = InteractionType.Event;
/// <summary>
/// Enable or disable Broadcast message mode.
/// </summary>
public bool useBroadcast = false;
// Messaging
/// <summary>
/// The receiver gameobject when you're in broacast mode for events
/// </summary>
public GameObject receiverGameObject;
/// <summary>
/// The message sending mode for broacast
/// </summary>
public Broadcast messageMode;
/// <summary>
/// The use specifical method.
/// </summary>
public bool useSpecificalMethod=false;
/// <summary>
/// The name of the method.
/// </summary>
/// <summary>
/// The name of the down method.
/// </summary>
public string downMethodName;
/// <summary>
/// The name of the press method.
/// </summary>
public string pressMethodName;
/// <summary>
/// The name of the up method.
/// </summary>
public string upMethodName;
#endregion
#region Button texture & color
/// <summary>
/// The GUI depth.
/// </summary>
public int guiDepth = 0;
// Normal
[SerializeField]
private Texture2D normalTexture;
/// <summary>
/// Gets or sets the normal texture.
/// </summary>
/// <value>
/// The normal texture.
/// </value>
public Texture2D NormalTexture {
get {
return this.normalTexture;
}
set {
normalTexture = value;
if (normalTexture!=null){
ComputeButtonAnchor( anchor);
currentTexture = normalTexture;
}
}
}
/// <summary>
/// The color of the button normal.
/// </summary>
public Color buttonNormalColor = Color.white;
// Active
[SerializeField]
private Texture2D activeTexture;
/// <summary>
/// Gets or sets the active texture.
/// </summary>
/// <value>
/// The active texture.
/// </value>
public Texture2D ActiveTexture {
get {
return this.activeTexture;
}
set {
activeTexture = value;
}
}
/// <summary>
/// The color of the button active.
/// </summary>
public Color buttonActiveColor = Color.white;
#endregion
#region Inspector
public bool showInspectorProperties=true;
public bool showInspectorPosition=true;
public bool showInspectorEvent=false;
public bool showInspectorTexture=false;
#endregion
#endregion
#region Private member
private Rect buttonRect;
private int buttonFingerIndex=-1;
private Texture2D currentTexture;
private Color currentColor;
private int frame=0;
#endregion
#endregion
#region MonoBehaviour methods
void OnEnable(){
EasyTouch.On_TouchStart += On_TouchStart;
EasyTouch.On_TouchDown += On_TouchDown;
EasyTouch.On_TouchUp += On_TouchUp;
}
void OnDisable(){
EasyTouch.On_TouchStart -= On_TouchStart;
EasyTouch.On_TouchDown -= On_TouchDown;
EasyTouch.On_TouchUp -= On_TouchUp;
if (Application.isPlaying){
if (EasyTouch.instance != null){
EasyTouch.instance.reservedVirtualAreas.Remove( buttonRect);
}
}
}
void OnDestroy(){
EasyTouch.On_TouchStart -= On_TouchStart;
EasyTouch.On_TouchDown -= On_TouchDown;
EasyTouch.On_TouchUp -= On_TouchUp;
if (Application.isPlaying){
if (EasyTouch.instance != null){
EasyTouch.instance.reservedVirtualAreas.Remove( buttonRect);
}
}
}
void Start(){
currentTexture = normalTexture;
currentColor = buttonNormalColor;
buttonState = ButtonState.None;
VirtualScreen.ComputeVirtualScreen();
ComputeButtonAnchor(anchor);
}
void OnGUI(){
if (enable){
GUI.depth = guiDepth;
useGUILayout = isUseGuiLayout;
VirtualScreen.ComputeVirtualScreen();
VirtualScreen.SetGuiScaleMatrix();
if (normalTexture!=null && activeTexture!=null){
ComputeButtonAnchor(anchor);
if (normalTexture!=null){
if (Application.isEditor && !Application.isPlaying){
currentTexture = normalTexture;
}
if (showDebugArea && Application.isEditor && selected && !Application.isPlaying){
GUI.Box( buttonRect,"");
}
if (currentTexture!=null){
if (isActivated){
GUI.color = currentColor;
if (Application.isPlaying){
EasyTouch.instance.reservedVirtualAreas.Remove( buttonRect);
EasyTouch.instance.reservedVirtualAreas.Add( buttonRect);
}
}
else{
GUI.color = new Color(currentColor.r,currentColor.g,currentColor.b,0.2f);
if (Application.isPlaying){
EasyTouch.instance.reservedVirtualAreas.Remove( buttonRect);
}
}
GUI.DrawTexture( buttonRect,currentTexture);
GUI.color = Color.white;
}
}
}
}
else{
if (Application.isPlaying){
EasyTouch.instance.reservedVirtualAreas.Remove( buttonRect);
}
}
}
void Update(){
if (buttonState == ButtonState.Up){
buttonState = ButtonState.None;
}
if (EasyTouch.GetTouchCount()==0){
buttonFingerIndex=-1;
currentTexture = normalTexture;
currentColor = buttonNormalColor;
buttonState = ButtonState.None;
}
}
void OnDrawGizmos(){
}
#endregion
#region Private methods
void ComputeButtonAnchor(ButtonAnchor anchor){
if (normalTexture!=null){
Vector2 buttonSize = new Vector2(normalTexture.width*scale.x, normalTexture.height*scale.y);
Vector2 anchorPosition = Vector2.zero;
// Anchor position
switch (anchor){
case ButtonAnchor.UpperLeft:
anchorPosition = new Vector2( 0, 0);
break;
case ButtonAnchor.UpperCenter:
anchorPosition = new Vector2( VirtualScreen.width/2- buttonSize.x/2, offset.y);
break;
case ButtonAnchor.UpperRight:
anchorPosition = new Vector2( VirtualScreen.width-buttonSize.x ,0);
break;
case ButtonAnchor.MiddleLeft:
anchorPosition = new Vector2( 0, VirtualScreen.height/2- buttonSize.y/2);
break;
case ButtonAnchor.MiddleCenter:
anchorPosition = new Vector2( VirtualScreen.width/2- buttonSize.x/2, VirtualScreen.height/2- buttonSize.y/2);
break;
case ButtonAnchor.MiddleRight:
anchorPosition = new Vector2( VirtualScreen.width-buttonSize.x,VirtualScreen.height/2- buttonSize.y/2);
break;
case ButtonAnchor.LowerLeft:
anchorPosition = new Vector2( 0, VirtualScreen.height- buttonSize.y);
break;
case ButtonAnchor.LowerCenter:
anchorPosition = new Vector2( VirtualScreen.width/2- buttonSize.x/2, VirtualScreen.height- buttonSize.y);
break;
case ButtonAnchor.LowerRight:
anchorPosition = new Vector2( VirtualScreen.width-buttonSize.x,VirtualScreen.height- buttonSize.y);
break;
}
//button rect
buttonRect = new Rect(anchorPosition.x + offset.x, anchorPosition.y + offset.y ,buttonSize.x,buttonSize.y);
}
}
void RaiseEvent(MessageName msg){
if (interaction == InteractionType.Event){
if (!useBroadcast){
switch (msg){
case MessageName.On_ButtonDown:
if (On_ButtonDown!=null){
On_ButtonDown( gameObject.name);
}
break;
case MessageName.On_ButtonUp:
if (On_ButtonUp!=null){
On_ButtonUp( gameObject.name);
}
break;
case MessageName.On_ButtonPress:
if (On_ButtonPress!=null){
On_ButtonPress( gameObject.name);
}
break;
}
}
else{
string method = msg.ToString();
if (msg == MessageName.On_ButtonDown && downMethodName!="" && useSpecificalMethod){
method = downMethodName;
}
if (msg == MessageName.On_ButtonPress && pressMethodName!="" && useSpecificalMethod){
method = pressMethodName;
}
if (msg == MessageName.On_ButtonUp && upMethodName!="" && useSpecificalMethod){
method = upMethodName;
}
if (receiverGameObject!=null){
switch(messageMode){
case Broadcast.BroadcastMessage:
receiverGameObject.BroadcastMessage( method,name,SendMessageOptions.DontRequireReceiver);
break;
case Broadcast.SendMessage:
receiverGameObject.SendMessage( method,name,SendMessageOptions.DontRequireReceiver);
break;
case Broadcast.SendMessageUpwards:
receiverGameObject.SendMessageUpwards( method,name,SendMessageOptions.DontRequireReceiver);
break;
}
}
else{
//Debug.LogError("Button : " + gameObject.name + " : you must setup receiver gameobject");
}
}
}
}
#endregion
#region EasyTouch Event
void On_TouchStart (Gesture gesture){
if (gesture.IsInRect( VirtualScreen.GetRealRect(buttonRect),true) && enable && isActivated){
buttonFingerIndex = gesture.fingerIndex;
currentTexture = activeTexture;
currentColor = buttonActiveColor;
buttonState = ButtonState.Down;
frame=0;
RaiseEvent( MessageName.On_ButtonDown);
}
}
void On_TouchDown (Gesture gesture){
if (gesture.fingerIndex == buttonFingerIndex || (isSwipeIn && buttonState==ButtonState.None) ){
if (gesture.IsInRect( VirtualScreen.GetRealRect(buttonRect),true) && enable && isActivated){
currentTexture = activeTexture;
currentColor = buttonActiveColor;
frame++;
if ((buttonState == ButtonState.Down || buttonState == ButtonState.Press) && frame>=2){
RaiseEvent(MessageName.On_ButtonPress);
buttonState = ButtonState.Press;
}
if (buttonState == ButtonState.None){
buttonFingerIndex = gesture.fingerIndex;
buttonState = ButtonState.Down;
frame=0;
RaiseEvent( MessageName.On_ButtonDown);
}
}
else {
if (((isSwipeIn || !isSwipeIn ) && !isSwipeOut) && buttonState == ButtonState.Press){
buttonFingerIndex=-1;
currentTexture = normalTexture;
currentColor = buttonNormalColor;
buttonState = ButtonState.None;
}
else if (isSwipeOut && buttonState == ButtonState.Press) {
RaiseEvent(MessageName.On_ButtonPress);
buttonState = ButtonState.Press;
}
}
}
}
void On_TouchUp (Gesture gesture){
if (gesture.fingerIndex == buttonFingerIndex){
if ((gesture.IsInRect(VirtualScreen.GetRealRect(buttonRect),true) || (isSwipeOut && buttonState == ButtonState.Press)) && enable && isActivated){
RaiseEvent(MessageName.On_ButtonUp);
}
buttonState = ButtonState.Up;
buttonFingerIndex=-1;
currentTexture = normalTexture;
currentColor = buttonNormalColor;
}
}
#endregion
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Conn.Scheme.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Org.Apache.Http.Conn.Scheme
{
/// <summary>
/// <para>A set of supported protocol schemes. Schemes are identified by lowercase names.</para><para><para></para><para></para><title>Revision:</title><para>648356 </para><title>Date:</title><para>2008-04-15 10:57:53 -0700 (Tue, 15 Apr 2008) </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/scheme/SchemeRegistry
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/scheme/SchemeRegistry", AccessFlags = 49)]
public sealed partial class SchemeRegistry
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new, empty scheme registry. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public SchemeRegistry() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the scheme for a host. Convenience method for <code>getScheme(host.getSchemeName())</code></para><para><code> </code></para>
/// </summary>
/// <returns>
/// <para>the scheme for the given host, never <code>null</code></para>
/// </returns>
/// <java-name>
/// getScheme
/// </java-name>
[Dot42.DexImport("getScheme", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)]
public global::Org.Apache.Http.Conn.Scheme.Scheme GetScheme(string host) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.Scheme);
}
/// <summary>
/// <para>Obtains the scheme for a host. Convenience method for <code>getScheme(host.getSchemeName())</code></para><para><code> </code></para>
/// </summary>
/// <returns>
/// <para>the scheme for the given host, never <code>null</code></para>
/// </returns>
/// <java-name>
/// getScheme
/// </java-name>
[Dot42.DexImport("getScheme", "(Lorg/apache/http/HttpHost;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)]
public global::Org.Apache.Http.Conn.Scheme.Scheme GetScheme(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.Scheme);
}
/// <summary>
/// <para>Obtains a scheme by name, if registered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the scheme, or <code>null</code> if there is none by this name </para>
/// </returns>
/// <java-name>
/// get
/// </java-name>
[Dot42.DexImport("get", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)]
public global::Org.Apache.Http.Conn.Scheme.Scheme Get(string name) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.Scheme);
}
/// <summary>
/// <para>Registers a scheme. The scheme can later be retrieved by its name using getScheme or get.</para><para></para>
/// </summary>
/// <returns>
/// <para>the scheme previously registered with that name, or <code>null</code> if none was registered </para>
/// </returns>
/// <java-name>
/// register
/// </java-name>
[Dot42.DexImport("register", "(Lorg/apache/http/conn/scheme/Scheme;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)]
public global::Org.Apache.Http.Conn.Scheme.Scheme Register(global::Org.Apache.Http.Conn.Scheme.Scheme sch) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.Scheme);
}
/// <summary>
/// <para>Unregisters a scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para>the unregistered scheme, or <code>null</code> if there was none </para>
/// </returns>
/// <java-name>
/// unregister
/// </java-name>
[Dot42.DexImport("unregister", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)]
public global::Org.Apache.Http.Conn.Scheme.Scheme Unregister(string name) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.Scheme);
}
/// <summary>
/// <para>Obtains the names of the registered schemes in their default order.</para><para></para>
/// </summary>
/// <returns>
/// <para>List containing registered scheme names. </para>
/// </returns>
/// <java-name>
/// getSchemeNames
/// </java-name>
[Dot42.DexImport("getSchemeNames", "()Ljava/util/List;", AccessFlags = 49, Signature = "()Ljava/util/List<Ljava/lang/String;>;")]
public global::Java.Util.IList<string> GetSchemeNames() /* MethodBuilder.Create */
{
return default(global::Java.Util.IList<string>);
}
/// <summary>
/// <para>Populates the internal collection of registered protocol schemes with the content of the map passed as a parameter.</para><para></para>
/// </summary>
/// <java-name>
/// setItems
/// </java-name>
[Dot42.DexImport("setItems", "(Ljava/util/Map;)V", AccessFlags = 33, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/conn/scheme/Scheme;>;)V")]
public void SetItems(global::Java.Util.IMap<string, global::Org.Apache.Http.Conn.Scheme.Scheme> map) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the names of the registered schemes in their default order.</para><para></para>
/// </summary>
/// <returns>
/// <para>List containing registered scheme names. </para>
/// </returns>
/// <java-name>
/// getSchemeNames
/// </java-name>
public global::Java.Util.IList<string> SchemeNames
{
[Dot42.DexImport("getSchemeNames", "()Ljava/util/List;", AccessFlags = 49, Signature = "()Ljava/util/List<Ljava/lang/String;>;")]
get{ return GetSchemeNames(); }
}
}
/// <java-name>
/// org/apache/http/conn/scheme/HostNameResolver
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/scheme/HostNameResolver", AccessFlags = 1537)]
public partial interface IHostNameResolver
/* scope: __dot42__ */
{
/// <java-name>
/// resolve
/// </java-name>
[Dot42.DexImport("resolve", "(Ljava/lang/String;)Ljava/net/InetAddress;", AccessFlags = 1025)]
global::Java.Net.InetAddress Resolve(string hostname) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>A factory for creating and connecting sockets. The factory encapsulates the logic for establishing a socket connection. <br></br> Both Object.equals() and Object.hashCode() must be overridden for the correct operation of some connection managers.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/scheme/SocketFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/scheme/SocketFactory", AccessFlags = 1537)]
public partial interface ISocketFactory
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new, unconnected socket. The socket should subsequently be passed to connectSocket.</para><para></para>
/// </summary>
/// <returns>
/// <para>a new socket</para>
/// </returns>
/// <java-name>
/// createSocket
/// </java-name>
[Dot42.DexImport("createSocket", "()Ljava/net/Socket;", AccessFlags = 1025)]
global::Java.Net.Socket CreateSocket() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Connects a socket to the given host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the connected socket. The returned object may be different from the <code>sock</code> argument if this factory supports a layered protocol.</para>
/// </returns>
/// <java-name>
/// connectSocket
/// </java-name>
[Dot42.DexImport("connectSocket", "(Ljava/net/Socket;Ljava/lang/String;ILjava/net/InetAddress;ILorg/apache/http/para" +
"ms/HttpParams;)Ljava/net/Socket;", AccessFlags = 1025)]
global::Java.Net.Socket ConnectSocket(global::Java.Net.Socket sock, string host, int port, global::Java.Net.InetAddress localAddress, int localPort, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks whether a socket provides a secure connection. The socket must be connected by this factory. The factory will <b>not</b> perform I/O operations in this method. <br></br> As a rule of thumb, plain sockets are not secure and TLS/SSL sockets are secure. However, there may be application specific deviations. For example, a plain socket to a host in the same intranet ("trusted zone") could be considered secure. On the other hand, a TLS/SSL socket could be considered insecure based on the cypher suite chosen for the connection.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the connection of the socket should be considered secure, or <code>false</code> if it should not</para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "(Ljava/net/Socket;)Z", AccessFlags = 1025)]
bool IsSecure(global::Java.Net.Socket sock) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Encapsulates specifics of a protocol scheme such as "http" or "https". Schemes are identified by lowercase names. Supported schemes are typically collected in a SchemeRegistry.</para><para>For example, to configure support for "https://" URLs, you could write code like the following: </para><para><pre>
/// Scheme https = new Scheme("https", new MySecureSocketFactory(), 443);
/// SchemeRegistry.DEFAULT.register(https);
/// </pre></para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para><simplesectsep></simplesectsep><para>Jeff Dever </para><simplesectsep></simplesectsep><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/scheme/Scheme
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/scheme/Scheme", AccessFlags = 49)]
public sealed partial class Scheme
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new scheme. Whether the created scheme allows for layered connections depends on the class of <code>factory</code>.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Lorg/apache/http/conn/scheme/SocketFactory;I)V", AccessFlags = 1)]
public Scheme(string name, global::Org.Apache.Http.Conn.Scheme.ISocketFactory factory, int port) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the default port.</para><para></para>
/// </summary>
/// <returns>
/// <para>the default port for this scheme </para>
/// </returns>
/// <java-name>
/// getDefaultPort
/// </java-name>
[Dot42.DexImport("getDefaultPort", "()I", AccessFlags = 17)]
public int GetDefaultPort() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Obtains the socket factory. If this scheme is layered, the factory implements LayeredSocketFactory.</para><para></para>
/// </summary>
/// <returns>
/// <para>the socket factory for this scheme </para>
/// </returns>
/// <java-name>
/// getSocketFactory
/// </java-name>
[Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/SocketFactory;", AccessFlags = 17)]
public global::Org.Apache.Http.Conn.Scheme.ISocketFactory GetSocketFactory() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.ISocketFactory);
}
/// <summary>
/// <para>Obtains the scheme name.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of this scheme, in lowercase </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 17)]
public string GetName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Indicates whether this scheme allows for layered connections.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if layered connections are possible, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isLayered
/// </java-name>
[Dot42.DexImport("isLayered", "()Z", AccessFlags = 17)]
public bool IsLayered() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Resolves the correct port for this scheme. Returns the given port if it is valid, the default port otherwise.</para><para></para>
/// </summary>
/// <returns>
/// <para>the given port or the defaultPort </para>
/// </returns>
/// <java-name>
/// resolvePort
/// </java-name>
[Dot42.DexImport("resolvePort", "(I)I", AccessFlags = 17)]
public int ResolvePort(int port) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Return a string representation of this object.</para><para></para>
/// </summary>
/// <returns>
/// <para>a human-readable string description of this scheme </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 17)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Compares this scheme to an object.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> iff the argument is equal to this scheme </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 17)]
public override bool Equals(object obj) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Obtains a hash code for this scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para>the hash code </para>
/// </returns>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal Scheme() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Obtains the default port.</para><para></para>
/// </summary>
/// <returns>
/// <para>the default port for this scheme </para>
/// </returns>
/// <java-name>
/// getDefaultPort
/// </java-name>
public int DefaultPort
{
[Dot42.DexImport("getDefaultPort", "()I", AccessFlags = 17)]
get{ return GetDefaultPort(); }
}
/// <summary>
/// <para>Obtains the socket factory. If this scheme is layered, the factory implements LayeredSocketFactory.</para><para></para>
/// </summary>
/// <returns>
/// <para>the socket factory for this scheme </para>
/// </returns>
/// <java-name>
/// getSocketFactory
/// </java-name>
public global::Org.Apache.Http.Conn.Scheme.ISocketFactory SocketFactory
{
[Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/SocketFactory;", AccessFlags = 17)]
get{ return GetSocketFactory(); }
}
/// <summary>
/// <para>Obtains the scheme name.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of this scheme, in lowercase </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
public string Name
{
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 17)]
get{ return GetName(); }
}
}
/// <summary>
/// <para>A SocketFactory for layered sockets (SSL/TLS). See there for things to consider when implementing a socket factory.</para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/scheme/LayeredSocketFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/scheme/LayeredSocketFactory", AccessFlags = 1537)]
public partial interface ILayeredSocketFactory : global::Org.Apache.Http.Conn.Scheme.ISocketFactory
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns a socket connected to the given host that is layered over an existing socket. Used primarily for creating secure sockets through proxies.</para><para></para>
/// </summary>
/// <returns>
/// <para>Socket a new socket</para>
/// </returns>
/// <java-name>
/// createSocket
/// </java-name>
[Dot42.DexImport("createSocket", "(Ljava/net/Socket;Ljava/lang/String;IZ)Ljava/net/Socket;", AccessFlags = 1025)]
global::Java.Net.Socket CreateSocket(global::Java.Net.Socket socket, string host, int port, bool autoClose) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The default class for creating sockets.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/scheme/PlainSocketFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/scheme/PlainSocketFactory", AccessFlags = 49)]
public sealed partial class PlainSocketFactory : global::Org.Apache.Http.Conn.Scheme.ISocketFactory
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/conn/scheme/HostNameResolver;)V", AccessFlags = 1)]
public PlainSocketFactory(global::Org.Apache.Http.Conn.Scheme.IHostNameResolver nameResolver) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public PlainSocketFactory() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the singleton instance of this class. </para>
/// </summary>
/// <returns>
/// <para>the one and only plain socket factory </para>
/// </returns>
/// <java-name>
/// getSocketFactory
/// </java-name>
[Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/PlainSocketFactory;", AccessFlags = 9)]
public static global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory GetSocketFactory() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory);
}
/// <summary>
/// <para>Creates a new, unconnected socket. The socket should subsequently be passed to connectSocket.</para><para></para>
/// </summary>
/// <returns>
/// <para>a new socket</para>
/// </returns>
/// <java-name>
/// createSocket
/// </java-name>
[Dot42.DexImport("createSocket", "()Ljava/net/Socket;", AccessFlags = 1)]
public global::Java.Net.Socket CreateSocket() /* MethodBuilder.Create */
{
return default(global::Java.Net.Socket);
}
/// <summary>
/// <para>Connects a socket to the given host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the connected socket. The returned object may be different from the <code>sock</code> argument if this factory supports a layered protocol.</para>
/// </returns>
/// <java-name>
/// connectSocket
/// </java-name>
[Dot42.DexImport("connectSocket", "(Ljava/net/Socket;Ljava/lang/String;ILjava/net/InetAddress;ILorg/apache/http/para" +
"ms/HttpParams;)Ljava/net/Socket;", AccessFlags = 1)]
public global::Java.Net.Socket ConnectSocket(global::Java.Net.Socket sock, string host, int port, global::Java.Net.InetAddress localAddress, int localPort, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Java.Net.Socket);
}
/// <summary>
/// <para>Checks whether a socket connection is secure. This factory creates plain socket connections which are not considered secure.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>false</code></para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "(Ljava/net/Socket;)Z", AccessFlags = 17)]
public bool IsSecure(global::Java.Net.Socket sock) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Compares this factory with an object. There is only one instance of this class.</para><para></para>
/// </summary>
/// <returns>
/// <para>iff the argument is this object </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object obj) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Obtains a hash code for this object. All instances of this class have the same hash code. There is only one instance of this class. </para>
/// </summary>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Gets the singleton instance of this class. </para>
/// </summary>
/// <returns>
/// <para>the one and only plain socket factory </para>
/// </returns>
/// <java-name>
/// getSocketFactory
/// </java-name>
public static global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory SocketFactory
{
[Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/PlainSocketFactory;", AccessFlags = 9)]
get{ return GetSocketFactory(); }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using ASP.NET_Web_API_application.Areas.HelpPage.ModelDescriptions;
using ASP.NET_Web_API_application.Areas.HelpPage.Models;
namespace ASP.NET_Web_API_application.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/***************************************************************************
* World.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id: World.cs 844 2012-03-07 13:47:33Z mark $
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using Server;
using Server.Mobiles;
using Server.Accounting;
using Server.Network;
using Server.Guilds;
namespace Server {
public static class World {
private static Dictionary<Serial, Mobile> m_Mobiles;
private static Dictionary<Serial, Item> m_Items;
private static bool m_Loading;
private static bool m_Loaded;
private static bool m_Saving;
private static ManualResetEvent m_DiskWriteHandle = new ManualResetEvent(true);
private static Queue<IEntity> _addQueue, _deleteQueue;
public static bool Saving { get { return m_Saving; } }
public static bool Loaded { get { return m_Loaded; } }
public static bool Loading { get { return m_Loading; } }
public readonly static string MobileIndexPath = Path.Combine( "Saves/Mobiles/", "Mobiles.idx" );
public readonly static string MobileTypesPath = Path.Combine( "Saves/Mobiles/", "Mobiles.tdb" );
public readonly static string MobileDataPath = Path.Combine( "Saves/Mobiles/", "Mobiles.bin" );
public readonly static string ItemIndexPath = Path.Combine( "Saves/Items/", "Items.idx" );
public readonly static string ItemTypesPath = Path.Combine( "Saves/Items/", "Items.tdb" );
public readonly static string ItemDataPath = Path.Combine( "Saves/Items/", "Items.bin" );
public readonly static string GuildIndexPath = Path.Combine( "Saves/Guilds/", "Guilds.idx" );
public readonly static string GuildDataPath = Path.Combine( "Saves/Guilds/", "Guilds.bin" );
public static void NotifyDiskWriteComplete()
{
if( m_DiskWriteHandle.Set())
{
Console.WriteLine("Closing Save Files. ");
}
}
public static void WaitForWriteCompletion()
{
m_DiskWriteHandle.WaitOne();
}
public static Dictionary<Serial, Mobile> Mobiles {
get { return m_Mobiles; }
}
public static Dictionary<Serial, Item> Items {
get { return m_Items; }
}
public static bool OnDelete( IEntity entity ) {
if ( m_Saving || m_Loading ) {
if ( m_Saving ) {
AppendSafetyLog( "delete", entity );
}
_deleteQueue.Enqueue( entity );
return false;
}
return true;
}
public static void Broadcast( int hue, bool ascii, string text ) {
Packet p;
if ( ascii )
p = new AsciiMessage( Serial.MinusOne, -1, MessageType.Regular, hue, 3, "System", text );
else
p = new UnicodeMessage( Serial.MinusOne, -1, MessageType.Regular, hue, 3, "ENU", "System", text );
List<NetState> list = NetState.Instances;
p.Acquire();
for ( int i = 0; i < list.Count; ++i ) {
if ( list[i].Mobile != null )
list[i].Send( p );
}
p.Release();
NetState.FlushAll();
}
public static void Broadcast( int hue, bool ascii, string format, params object[] args ) {
Broadcast( hue, ascii, String.Format( format, args ) );
}
private interface IEntityEntry {
Serial Serial { get; }
int TypeID { get; }
long Position { get; }
int Length { get; }
}
private sealed class GuildEntry : IEntityEntry {
private BaseGuild m_Guild;
private long m_Position;
private int m_Length;
public BaseGuild Guild {
get {
return m_Guild;
}
}
public Serial Serial {
get {
return m_Guild == null ? 0 : m_Guild.Id;
}
}
public int TypeID {
get {
return 0;
}
}
public long Position {
get {
return m_Position;
}
}
public int Length {
get {
return m_Length;
}
}
public GuildEntry( BaseGuild g, long pos, int length ) {
m_Guild = g;
m_Position = pos;
m_Length = length;
}
}
private sealed class ItemEntry : IEntityEntry {
private Item m_Item;
private int m_TypeID;
private string m_TypeName;
private long m_Position;
private int m_Length;
public Item Item {
get {
return m_Item;
}
}
public Serial Serial {
get {
return m_Item == null ? Serial.MinusOne : m_Item.Serial;
}
}
public int TypeID {
get {
return m_TypeID;
}
}
public string TypeName {
get {
return m_TypeName;
}
}
public long Position {
get {
return m_Position;
}
}
public int Length {
get {
return m_Length;
}
}
public ItemEntry( Item item, int typeID, string typeName, long pos, int length ) {
m_Item = item;
m_TypeID = typeID;
m_TypeName = typeName;
m_Position = pos;
m_Length = length;
}
}
private sealed class MobileEntry : IEntityEntry {
private Mobile m_Mobile;
private int m_TypeID;
private string m_TypeName;
private long m_Position;
private int m_Length;
public Mobile Mobile {
get {
return m_Mobile;
}
}
public Serial Serial {
get {
return m_Mobile == null ? Serial.MinusOne : m_Mobile.Serial;
}
}
public int TypeID {
get {
return m_TypeID;
}
}
public string TypeName {
get {
return m_TypeName;
}
}
public long Position {
get {
return m_Position;
}
}
public int Length {
get {
return m_Length;
}
}
public MobileEntry( Mobile mobile, int typeID, string typeName, long pos, int length ) {
m_Mobile = mobile;
m_TypeID = typeID;
m_TypeName = typeName;
m_Position = pos;
m_Length = length;
}
}
private static string m_LoadingType;
public static string LoadingType {
get { return m_LoadingType; }
}
private static readonly Type[] m_SerialTypeArray = new Type[1] { typeof(Serial) };
#if Framework_4_0
private static List<Tuple<ConstructorInfo, string>> ReadTypes( BinaryReader tdbReader )
{
int count = tdbReader.ReadInt32();
List<Tuple<ConstructorInfo, string>> types = new List<Tuple<ConstructorInfo, string>>( count );
for (int i = 0; i < count; ++i)
{
string typeName = tdbReader.ReadString();
Type t = ScriptCompiler.FindTypeByFullName(typeName);
if (t == null)
{
Console.WriteLine("failed");
if (!Core.Service)
{
Console.WriteLine("Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName);
if (Console.ReadKey(true).Key == ConsoleKey.Y)
{
types.Add(null);
Console.Write("World: Loading...");
continue;
}
Console.WriteLine("Types will not be deleted. An exception will be thrown.");
}
else
{
Console.WriteLine("Error: Type '{0}' was not found.", typeName);
}
throw new Exception(String.Format("Bad type '{0}'", typeName));
}
ConstructorInfo ctor = t.GetConstructor(m_SerialTypeArray);
if (ctor != null)
{
types.Add( new Tuple<ConstructorInfo, string>( ctor, typeName ) );
}
else
{
throw new Exception(String.Format("Type '{0}' does not have a serialization constructor", t));
}
}
return types;
}
public static void Load() {
if ( m_Loaded )
return;
m_Loaded = true;
m_LoadingType = null;
Console.Write( "World: Loading..." );
Stopwatch watch = Stopwatch.StartNew();
m_Loading = true;
_addQueue = new Queue<IEntity>();
_deleteQueue = new Queue<IEntity>();
int mobileCount = 0, itemCount = 0, guildCount = 0;
object[] ctorArgs = new object[1];
List<ItemEntry> items = new List<ItemEntry>();
List<MobileEntry> mobiles = new List<MobileEntry>();
List<GuildEntry> guilds = new List<GuildEntry>();
if ( File.Exists( MobileIndexPath ) && File.Exists( MobileTypesPath ) ) {
using ( FileStream idx = new FileStream( MobileIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryReader idxReader = new BinaryReader( idx );
using ( FileStream tdb = new FileStream( MobileTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryReader tdbReader = new BinaryReader( tdb );
List<Tuple<ConstructorInfo, string>> types = ReadTypes( tdbReader );
mobileCount = idxReader.ReadInt32();
m_Mobiles = new Dictionary<Serial, Mobile>( mobileCount );
for ( int i = 0; i < mobileCount; ++i ) {
int typeID = idxReader.ReadInt32();
int serial = idxReader.ReadInt32();
long pos = idxReader.ReadInt64();
int length = idxReader.ReadInt32();
Tuple<ConstructorInfo, string> objs = types[typeID];
if ( objs == null )
continue;
Mobile m = null;
ConstructorInfo ctor = objs.Item1;
string typeName = objs.Item2;
try {
ctorArgs[0] = ( Serial ) serial;
m = ( Mobile ) ( ctor.Invoke( ctorArgs ) );
} catch {
}
if ( m != null ) {
mobiles.Add( new MobileEntry( m, typeID, typeName, pos, length ) );
AddMobile( m );
}
}
tdbReader.Close();
}
idxReader.Close();
}
} else {
m_Mobiles = new Dictionary<Serial, Mobile>();
}
if ( File.Exists( ItemIndexPath ) && File.Exists( ItemTypesPath ) ) {
using ( FileStream idx = new FileStream( ItemIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryReader idxReader = new BinaryReader( idx );
using ( FileStream tdb = new FileStream( ItemTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryReader tdbReader = new BinaryReader( tdb );
List<Tuple<ConstructorInfo, string>> types = ReadTypes( tdbReader );
itemCount = idxReader.ReadInt32();
m_Items = new Dictionary<Serial, Item>( itemCount );
for ( int i = 0; i < itemCount; ++i ) {
int typeID = idxReader.ReadInt32();
int serial = idxReader.ReadInt32();
long pos = idxReader.ReadInt64();
int length = idxReader.ReadInt32();
Tuple<ConstructorInfo, string> objs = types[typeID];
if ( objs == null )
continue;
Item item = null;
ConstructorInfo ctor = objs.Item1;
string typeName = objs.Item2;
try {
ctorArgs[0] = ( Serial ) serial;
item = ( Item ) ( ctor.Invoke( ctorArgs ) );
} catch {
}
if ( item != null ) {
items.Add( new ItemEntry( item, typeID, typeName, pos, length ) );
AddItem( item );
}
}
tdbReader.Close();
}
idxReader.Close();
}
} else {
m_Items = new Dictionary<Serial, Item>();
}
if ( File.Exists( GuildIndexPath ) ) {
using ( FileStream idx = new FileStream( GuildIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryReader idxReader = new BinaryReader( idx );
guildCount = idxReader.ReadInt32();
CreateGuildEventArgs createEventArgs = new CreateGuildEventArgs( -1 );
for ( int i = 0; i < guildCount; ++i ) {
idxReader.ReadInt32();//no typeid for guilds
int id = idxReader.ReadInt32();
long pos = idxReader.ReadInt64();
int length = idxReader.ReadInt32();
createEventArgs.Id = id;
BaseGuild guild = EventSink.InvokeCreateGuild( createEventArgs );
if ( guild != null )
guilds.Add( new GuildEntry( guild, pos, length ) );
}
idxReader.Close();
}
}
bool failedMobiles = false, failedItems = false, failedGuilds = false;
Type failedType = null;
Serial failedSerial = Serial.Zero;
Exception failed = null;
int failedTypeID = 0;
if ( File.Exists( MobileDataPath ) ) {
using ( FileStream bin = new FileStream( MobileDataPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) );
for ( int i = 0; i < mobiles.Count; ++i ) {
MobileEntry entry = mobiles[i];
Mobile m = entry.Mobile;
if ( m != null ) {
reader.Seek( entry.Position, SeekOrigin.Begin );
try {
m_LoadingType = entry.TypeName;
m.Deserialize( reader );
if ( reader.Position != ( entry.Position + entry.Length ) )
throw new Exception( String.Format( "***** Bad serialize on {0} *****", m.GetType() ) );
} catch ( Exception e ) {
mobiles.RemoveAt( i );
failed = e;
failedMobiles = true;
failedType = m.GetType();
failedTypeID = entry.TypeID;
failedSerial = m.Serial;
break;
}
}
}
reader.Close();
}
}
if ( !failedMobiles && File.Exists( ItemDataPath ) ) {
using ( FileStream bin = new FileStream( ItemDataPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) );
for ( int i = 0; i < items.Count; ++i ) {
ItemEntry entry = items[i];
Item item = entry.Item;
if ( item != null ) {
reader.Seek( entry.Position, SeekOrigin.Begin );
try {
m_LoadingType = entry.TypeName;
item.Deserialize( reader );
if ( reader.Position != ( entry.Position + entry.Length ) )
throw new Exception( String.Format( "***** Bad serialize on {0} *****", item.GetType() ) );
} catch ( Exception e ) {
items.RemoveAt( i );
failed = e;
failedItems = true;
failedType = item.GetType();
failedTypeID = entry.TypeID;
failedSerial = item.Serial;
break;
}
}
}
reader.Close();
}
}
m_LoadingType = null;
if ( !failedMobiles && !failedItems && File.Exists( GuildDataPath ) ) {
using ( FileStream bin = new FileStream( GuildDataPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) );
for ( int i = 0; i < guilds.Count; ++i ) {
GuildEntry entry = guilds[i];
BaseGuild g = entry.Guild;
if ( g != null ) {
reader.Seek( entry.Position, SeekOrigin.Begin );
try {
g.Deserialize( reader );
if ( reader.Position != ( entry.Position + entry.Length ) )
throw new Exception( String.Format( "***** Bad serialize on Guild {0} *****", g.Id ) );
} catch ( Exception e ) {
guilds.RemoveAt( i );
failed = e;
failedGuilds = true;
failedType = typeof( BaseGuild );
failedTypeID = g.Id;
failedSerial = g.Id;
break;
}
}
}
reader.Close();
}
}
if ( failedItems || failedMobiles || failedGuilds ) {
Console.WriteLine( "An error was encountered while loading a saved object" );
Console.WriteLine( " - Type: {0}", failedType );
Console.WriteLine( " - Serial: {0}", failedSerial );
if ( !Core.Service ) {
Console.WriteLine( "Delete the object? (y/n)" );
if ( Console.ReadKey( true ).Key == ConsoleKey.Y ) {
if ( failedType != typeof( BaseGuild ) ) {
Console.WriteLine( "Delete all objects of that type? (y/n)" );
if ( Console.ReadKey( true ).Key == ConsoleKey.Y ) {
if ( failedMobiles ) {
for ( int i = 0; i < mobiles.Count; ) {
if ( mobiles[i].TypeID == failedTypeID )
mobiles.RemoveAt( i );
else
++i;
}
} else if ( failedItems ) {
for ( int i = 0; i < items.Count; ) {
if ( items[i].TypeID == failedTypeID )
items.RemoveAt( i );
else
++i;
}
}
}
}
SaveIndex<MobileEntry>( mobiles, MobileIndexPath );
SaveIndex<ItemEntry>( items, ItemIndexPath );
SaveIndex<GuildEntry>( guilds, GuildIndexPath );
}
Console.WriteLine( "After pressing return an exception will be thrown and the server will terminate." );
Console.ReadLine();
} else {
Console.WriteLine( "An exception will be thrown and the server will terminate." );
}
throw new Exception( String.Format( "Load failed (items={0}, mobiles={1}, guilds={2}, type={3}, serial={4})", failedItems, failedMobiles, failedGuilds, failedType, failedSerial ), failed );
}
EventSink.InvokeWorldLoad();
m_Loading = false;
ProcessSafetyQueues();
foreach ( Item item in m_Items.Values ) {
if ( item.Parent == null )
item.UpdateTotals();
item.ClearProperties();
}
foreach ( Mobile m in m_Mobiles.Values ) {
m.UpdateRegion(); // Is this really needed?
m.UpdateTotals();
m.ClearProperties();
}
watch.Stop();
Console.WriteLine( "done ({1} items, {2} mobiles) ({0:F2} seconds)", watch.Elapsed.TotalSeconds, m_Items.Count, m_Mobiles.Count );
}
#else
private static List<object[]> ReadTypes( BinaryReader tdbReader )
{
int count = tdbReader.ReadInt32();
List<object[]> types = new List<object[]>(count);
for (int i = 0; i < count; ++i)
{
string typeName = tdbReader.ReadString();
Type t = ScriptCompiler.FindTypeByFullName(typeName);
if (t == null)
{
Console.WriteLine("failed");
if (!Core.Service)
{
Console.WriteLine("Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName);
if (Console.ReadKey(true).Key == ConsoleKey.Y)
{
types.Add(null);
Console.Write("World: Loading...");
continue;
}
Console.WriteLine("Types will not be deleted. An exception will be thrown.");
}
else
{
Console.WriteLine("Error: Type '{0}' was not found.", typeName);
}
throw new Exception(String.Format("Bad type '{0}'", typeName));
}
ConstructorInfo ctor = t.GetConstructor(m_SerialTypeArray);
if (ctor != null)
{
types.Add(new object[] { ctor, typeName });
}
else
{
throw new Exception(String.Format("Type '{0}' does not have a serialization constructor", t));
}
}
return types;
}
public static void Load() {
if ( m_Loaded )
return;
m_Loaded = true;
m_LoadingType = null;
Console.Write( "World: Loading..." );
Stopwatch watch = Stopwatch.StartNew();
m_Loading = true;
_addQueue = new Queue<IEntity>();
_deleteQueue = new Queue<IEntity>();
int mobileCount = 0, itemCount = 0, guildCount = 0;
object[] ctorArgs = new object[1];
List<ItemEntry> items = new List<ItemEntry>();
List<MobileEntry> mobiles = new List<MobileEntry>();
List<GuildEntry> guilds = new List<GuildEntry>();
if ( File.Exists( MobileIndexPath ) && File.Exists( MobileTypesPath ) ) {
using ( FileStream idx = new FileStream( MobileIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryReader idxReader = new BinaryReader( idx );
using ( FileStream tdb = new FileStream( MobileTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryReader tdbReader = new BinaryReader( tdb );
List<object[]> types = ReadTypes( tdbReader );
mobileCount = idxReader.ReadInt32();
m_Mobiles = new Dictionary<Serial, Mobile>( mobileCount );
for ( int i = 0; i < mobileCount; ++i ) {
int typeID = idxReader.ReadInt32();
int serial = idxReader.ReadInt32();
long pos = idxReader.ReadInt64();
int length = idxReader.ReadInt32();
object[] objs = types[typeID];
if ( objs == null )
continue;
Mobile m = null;
ConstructorInfo ctor = ( ConstructorInfo ) objs[0];
string typeName = ( string ) objs[1];
try {
ctorArgs[0] = ( Serial ) serial;
m = ( Mobile ) ( ctor.Invoke( ctorArgs ) );
} catch {
}
if ( m != null ) {
mobiles.Add( new MobileEntry( m, typeID, typeName, pos, length ) );
AddMobile( m );
}
}
tdbReader.Close();
}
idxReader.Close();
}
} else {
m_Mobiles = new Dictionary<Serial, Mobile>();
}
if ( File.Exists( ItemIndexPath ) && File.Exists( ItemTypesPath ) ) {
using ( FileStream idx = new FileStream( ItemIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryReader idxReader = new BinaryReader( idx );
using ( FileStream tdb = new FileStream( ItemTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryReader tdbReader = new BinaryReader( tdb );
List<object[]> types = ReadTypes( tdbReader );
itemCount = idxReader.ReadInt32();
m_Items = new Dictionary<Serial, Item>( itemCount );
for ( int i = 0; i < itemCount; ++i ) {
int typeID = idxReader.ReadInt32();
int serial = idxReader.ReadInt32();
long pos = idxReader.ReadInt64();
int length = idxReader.ReadInt32();
object[] objs = types[typeID];
if ( objs == null )
continue;
Item item = null;
ConstructorInfo ctor = ( ConstructorInfo ) objs[0];
string typeName = ( string ) objs[1];
try {
ctorArgs[0] = ( Serial ) serial;
item = ( Item ) ( ctor.Invoke( ctorArgs ) );
} catch {
}
if ( item != null ) {
items.Add( new ItemEntry( item, typeID, typeName, pos, length ) );
AddItem( item );
}
}
tdbReader.Close();
}
idxReader.Close();
}
} else {
m_Items = new Dictionary<Serial, Item>();
}
if ( File.Exists( GuildIndexPath ) ) {
using ( FileStream idx = new FileStream( GuildIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryReader idxReader = new BinaryReader( idx );
guildCount = idxReader.ReadInt32();
CreateGuildEventArgs createEventArgs = new CreateGuildEventArgs( -1 );
for ( int i = 0; i < guildCount; ++i ) {
idxReader.ReadInt32();//no typeid for guilds
int id = idxReader.ReadInt32();
long pos = idxReader.ReadInt64();
int length = idxReader.ReadInt32();
createEventArgs.Id = id;
BaseGuild guild = EventSink.InvokeCreateGuild( createEventArgs );
if ( guild != null )
guilds.Add( new GuildEntry( guild, pos, length ) );
}
idxReader.Close();
}
}
bool failedMobiles = false, failedItems = false, failedGuilds = false;
Type failedType = null;
Serial failedSerial = Serial.Zero;
Exception failed = null;
int failedTypeID = 0;
if ( File.Exists( MobileDataPath ) ) {
using ( FileStream bin = new FileStream( MobileDataPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) );
for ( int i = 0; i < mobiles.Count; ++i ) {
MobileEntry entry = mobiles[i];
Mobile m = entry.Mobile;
if ( m != null ) {
reader.Seek( entry.Position, SeekOrigin.Begin );
try {
m_LoadingType = entry.TypeName;
m.Deserialize( reader );
if ( reader.Position != ( entry.Position + entry.Length ) )
throw new Exception( String.Format( "***** Bad serialize on {0} *****", m.GetType() ) );
} catch ( Exception e ) {
mobiles.RemoveAt( i );
failed = e;
failedMobiles = true;
failedType = m.GetType();
failedTypeID = entry.TypeID;
failedSerial = m.Serial;
break;
}
}
}
reader.Close();
}
}
if ( !failedMobiles && File.Exists( ItemDataPath ) ) {
using ( FileStream bin = new FileStream( ItemDataPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) );
for ( int i = 0; i < items.Count; ++i ) {
ItemEntry entry = items[i];
Item item = entry.Item;
if ( item != null ) {
reader.Seek( entry.Position, SeekOrigin.Begin );
try {
m_LoadingType = entry.TypeName;
item.Deserialize( reader );
if ( reader.Position != ( entry.Position + entry.Length ) )
throw new Exception( String.Format( "***** Bad serialize on {0} *****", item.GetType() ) );
} catch ( Exception e ) {
items.RemoveAt( i );
failed = e;
failedItems = true;
failedType = item.GetType();
failedTypeID = entry.TypeID;
failedSerial = item.Serial;
break;
}
}
}
reader.Close();
}
}
m_LoadingType = null;
if ( !failedMobiles && !failedItems && File.Exists( GuildDataPath ) ) {
using ( FileStream bin = new FileStream( GuildDataPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) );
for ( int i = 0; i < guilds.Count; ++i ) {
GuildEntry entry = guilds[i];
BaseGuild g = entry.Guild;
if ( g != null ) {
reader.Seek( entry.Position, SeekOrigin.Begin );
try {
g.Deserialize( reader );
if ( reader.Position != ( entry.Position + entry.Length ) )
throw new Exception( String.Format( "***** Bad serialize on Guild {0} *****", g.Id ) );
} catch ( Exception e ) {
guilds.RemoveAt( i );
failed = e;
failedGuilds = true;
failedType = typeof( BaseGuild );
failedTypeID = g.Id;
failedSerial = g.Id;
break;
}
}
}
reader.Close();
}
}
if ( failedItems || failedMobiles || failedGuilds ) {
Console.WriteLine( "An error was encountered while loading a saved object" );
Console.WriteLine( " - Type: {0}", failedType );
Console.WriteLine( " - Serial: {0}", failedSerial );
if ( !Core.Service ) {
Console.WriteLine( "Delete the object? (y/n)" );
if ( Console.ReadKey( true ).Key == ConsoleKey.Y ) {
if ( failedType != typeof( BaseGuild ) ) {
Console.WriteLine( "Delete all objects of that type? (y/n)" );
if ( Console.ReadKey( true ).Key == ConsoleKey.Y ) {
if ( failedMobiles ) {
for ( int i = 0; i < mobiles.Count; ) {
if ( mobiles[i].TypeID == failedTypeID )
mobiles.RemoveAt( i );
else
++i;
}
} else if ( failedItems ) {
for ( int i = 0; i < items.Count; ) {
if ( items[i].TypeID == failedTypeID )
items.RemoveAt( i );
else
++i;
}
}
}
}
SaveIndex<MobileEntry>( mobiles, MobileIndexPath );
SaveIndex<ItemEntry>( items, ItemIndexPath );
SaveIndex<GuildEntry>( guilds, GuildIndexPath );
}
Console.WriteLine( "After pressing return an exception will be thrown and the server will terminate." );
Console.ReadLine();
} else {
Console.WriteLine( "An exception will be thrown and the server will terminate." );
}
throw new Exception( String.Format( "Load failed (items={0}, mobiles={1}, guilds={2}, type={3}, serial={4})", failedItems, failedMobiles, failedGuilds, failedType, failedSerial ), failed );
}
EventSink.InvokeWorldLoad();
m_Loading = false;
ProcessSafetyQueues();
foreach ( Item item in m_Items.Values ) {
if ( item.Parent == null )
item.UpdateTotals();
item.ClearProperties();
}
foreach ( Mobile m in m_Mobiles.Values ) {
m.UpdateRegion(); // Is this really needed?
m.UpdateTotals();
m.ClearProperties();
}
watch.Stop();
Console.WriteLine( "done ({1} items, {2} mobiles) ({0:F2} seconds)", watch.Elapsed.TotalSeconds, m_Items.Count, m_Mobiles.Count );
}
#endif
private static void ProcessSafetyQueues() {
while ( _addQueue.Count > 0 ) {
IEntity entity = _addQueue.Dequeue();
Item item = entity as Item;
if ( item != null ) {
AddItem( item );
} else {
Mobile mob = entity as Mobile;
if ( mob != null ) {
AddMobile( mob );
}
}
}
while ( _deleteQueue.Count > 0 ) {
IEntity entity = _deleteQueue.Dequeue();
Item item = entity as Item;
if ( item != null ) {
item.Delete();
} else {
Mobile mob = entity as Mobile;
if ( mob != null ) {
mob.Delete();
}
}
}
}
private static void AppendSafetyLog( string action, IEntity entity ) {
string message = String.Format( "Warning: Attempted to {1} {2} during world save." +
"{0}This action could cause inconsistent state." +
"{0}It is strongly advised that the offending scripts be corrected.",
Environment.NewLine,
action, entity
);
Console.WriteLine( message );
try {
using ( StreamWriter op = new StreamWriter( "world-save-errors.log", true ) ) {
op.WriteLine( "{0}\t{1}", DateTime.Now, message );
op.WriteLine( new StackTrace( 2 ).ToString() );
op.WriteLine();
}
} catch {
}
}
private static void SaveIndex<T>( List<T> list, string path ) where T : IEntityEntry {
if ( !Directory.Exists( "Saves/Mobiles/" ) )
Directory.CreateDirectory( "Saves/Mobiles/" );
if ( !Directory.Exists( "Saves/Items/" ) )
Directory.CreateDirectory( "Saves/Items/" );
if ( !Directory.Exists( "Saves/Guilds/" ) )
Directory.CreateDirectory( "Saves/Guilds/" );
using ( FileStream idx = new FileStream( path, FileMode.Create, FileAccess.Write, FileShare.None ) ) {
BinaryWriter idxWriter = new BinaryWriter( idx );
idxWriter.Write( list.Count );
for ( int i = 0; i < list.Count; ++i ) {
T e = list[i];
idxWriter.Write( e.TypeID );
idxWriter.Write( e.Serial );
idxWriter.Write( e.Position );
idxWriter.Write( e.Length );
}
idxWriter.Close();
}
}
internal static int m_Saves;
public static void Save() {
Save( true, false );
}
public static void Save( bool message, bool permitBackgroundWrite ) {
if ( m_Saving )
return;
++m_Saves;
NetState.FlushAll();
NetState.Pause();
World.WaitForWriteCompletion();//Blocks Save until current disk flush is done.
m_Saving = true;
m_DiskWriteHandle.Reset();
if ( message )
Broadcast( 0x35, true, "The world is saving, please wait." );
SaveStrategy strategy = SaveStrategy.Acquire();
Console.WriteLine( "Core: Using {0} save strategy", strategy.Name.ToLowerInvariant() );
Console.Write( "World: Saving..." );
Stopwatch watch = Stopwatch.StartNew();
if ( !Directory.Exists( "Saves/Mobiles/" ) )
Directory.CreateDirectory( "Saves/Mobiles/" );
if ( !Directory.Exists( "Saves/Items/" ) )
Directory.CreateDirectory( "Saves/Items/" );
if ( !Directory.Exists( "Saves/Guilds/" ) )
Directory.CreateDirectory( "Saves/Guilds/" );
/*using ( SaveMetrics metrics = new SaveMetrics() ) {*/
strategy.Save( null, permitBackgroundWrite );
/*}*/
try {
EventSink.InvokeWorldSave( new WorldSaveEventArgs( message ) );
} catch ( Exception e ) {
throw new Exception( "World Save event threw an exception. Save failed!", e );
}
watch.Stop();
m_Saving = false;
if (!permitBackgroundWrite)
World.NotifyDiskWriteComplete(); //Sets the DiskWriteHandle. If we allow background writes, we leave this upto the individual save strategies.
ProcessSafetyQueues();
strategy.ProcessDecay();
Console.WriteLine( "Save done in {0:F2} seconds.", watch.Elapsed.TotalSeconds );
if ( message )
Broadcast( 0x35, true, "World save complete. The entire process took {0:F1} seconds.", watch.Elapsed.TotalSeconds );
NetState.Resume();
}
internal static List<Type> m_ItemTypes = new List<Type>();
internal static List<Type> m_MobileTypes = new List<Type>();
public static IEntity FindEntity( Serial serial ) {
if ( serial.IsItem )
return FindItem( serial );
else if ( serial.IsMobile )
return FindMobile( serial );
return null;
}
public static Mobile FindMobile( Serial serial ) {
Mobile mob;
m_Mobiles.TryGetValue( serial, out mob );
return mob;
}
public static void AddMobile( Mobile m ) {
if ( m_Saving ) {
AppendSafetyLog( "add", m );
_addQueue.Enqueue( m );
} else {
m_Mobiles[m.Serial] = m;
}
}
public static Item FindItem( Serial serial ) {
Item item;
m_Items.TryGetValue( serial, out item );
return item;
}
public static void AddItem( Item item ) {
if ( m_Saving ) {
AppendSafetyLog( "add", item );
_addQueue.Enqueue( item );
} else {
m_Items[item.Serial] = item;
}
}
public static void RemoveMobile( Mobile m ) {
m_Mobiles.Remove( m.Serial );
}
public static void RemoveItem( Item item ) {
m_Items.Remove( item.Serial );
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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.Targets.Wrappers
{
using System;
using System.ComponentModel;
using System.Threading;
using Common;
using Internal;
using System.Collections.Generic;
/// <summary>
/// Provides asynchronous, buffered execution of target writes.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/AsyncWrapper-target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// <p>
/// Asynchronous target wrapper allows the logger code to execute more quickly, by queueing
/// messages and processing them in a separate thread. You should wrap targets
/// that spend a non-trivial amount of time in their Write() method with asynchronous
/// target to speed up logging.
/// </p>
/// <p>
/// Because asynchronous logging is quite a common scenario, NLog supports a
/// shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to
/// the <targets/> element in the configuration file.
/// </p>
/// <code lang="XML">
/// <![CDATA[
/// <targets async="true">
/// ... your targets go here ...
/// </targets>
/// ]]></code>
/// </remarks>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/AsyncWrapper/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule. See below for
/// a programmatic configuration that's equivalent to the above config file:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/AsyncWrapper/Wrapping File/Example.cs" />
/// </example>
[Target("AsyncWrapper", IsWrapper = true)]
public class AsyncTargetWrapper : WrapperTargetBase
{
private readonly object lockObject = new object();
private Timer lazyWriterTimer;
private readonly Queue<AsyncContinuation> flushAllContinuations = new Queue<AsyncContinuation>();
private readonly object continuationQueueLock = new object();
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
public AsyncTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public AsyncTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="queueLimit">Maximum number of requests in the queue.</param>
/// <param name="overflowAction">The action to be taken when the queue overflows.</param>
public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction)
{
this.RequestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard);
this.TimeToSleepBetweenBatches = 50;
this.BatchSize = 100;
this.WrappedTarget = wrappedTarget;
this.QueueLimit = queueLimit;
this.OverflowAction = overflowAction;
}
/// <summary>
/// Gets or sets the number of log events that should be processed in a batch
/// by the lazy writer thread.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(100)]
public int BatchSize { get; set; }
/// <summary>
/// Gets or sets the time in milliseconds to sleep between batches.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(50)]
public int TimeToSleepBetweenBatches { get; set; }
/// <summary>
/// Gets or sets the action to be taken when the lazy writer thread request queue count
/// exceeds the set limit.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue("Discard")]
public AsyncTargetWrapperOverflowAction OverflowAction
{
get { return this.RequestQueue.OnOverflow; }
set { this.RequestQueue.OnOverflow = value; }
}
/// <summary>
/// Gets or sets the limit on the number of requests in the lazy writer thread request queue.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(10000)]
public int QueueLimit
{
get { return this.RequestQueue.RequestLimit; }
set { this.RequestQueue.RequestLimit = value; }
}
/// <summary>
/// Gets the queue of lazy writer thread requests.
/// </summary>
internal AsyncRequestQueue RequestQueue { get; private set; }
/// <summary>
/// Waits for the lazy writer thread to finish writing messages.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
lock (continuationQueueLock)
{
this.flushAllContinuations.Enqueue(asyncContinuation);
}
}
/// <summary>
/// Initializes the target by starting the lazy writer timer.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
this.RequestQueue.Clear();
this.lazyWriterTimer = new Timer(this.ProcessPendingEvents, null, Timeout.Infinite, Timeout.Infinite);
this.StartLazyWriterTimer();
}
/// <summary>
/// Shuts down the lazy writer timer.
/// </summary>
protected override void CloseTarget()
{
this.StopLazyWriterThread();
if (this.RequestQueue.RequestCount > 0)
{
ProcessPendingEvents(null);
}
base.CloseTarget();
}
/// <summary>
/// Starts the lazy writer thread which periodically writes
/// queued log messages.
/// </summary>
protected virtual void StartLazyWriterTimer()
{
lock (this.lockObject)
{
if (this.lazyWriterTimer != null)
{
this.lazyWriterTimer.Change(this.TimeToSleepBetweenBatches, Timeout.Infinite);
}
}
}
/// <summary>
/// Starts the lazy writer thread.
/// </summary>
protected virtual void StopLazyWriterThread()
{
lock (this.lockObject)
{
if (this.lazyWriterTimer != null)
{
this.lazyWriterTimer.Change(Timeout.Infinite, Timeout.Infinite);
this.lazyWriterTimer = null;
}
}
}
/// <summary>
/// Adds the log event to asynchronous queue to be processed by
/// the lazy writer thread.
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <remarks>
/// The <see cref="Target.PrecalculateVolatileLayouts"/> is called
/// to ensure that the log event can be processed in another thread.
/// </remarks>
protected override void Write(AsyncLogEventInfo logEvent)
{
this.MergeEventProperties(logEvent.LogEvent);
this.PrecalculateVolatileLayouts(logEvent.LogEvent);
this.RequestQueue.Enqueue(logEvent);
}
private void ProcessPendingEvents(object state)
{
AsyncContinuation[] continuations;
lock (this.continuationQueueLock)
{
continuations = this.flushAllContinuations.Count > 0
? this.flushAllContinuations.ToArray()
: new AsyncContinuation[] { null };
this.flushAllContinuations.Clear();
}
try
{
foreach (var continuation in continuations)
{
int count = this.BatchSize;
if (continuation != null)
{
count = this.RequestQueue.RequestCount;
InternalLogger.Trace("Flushing {0} events.", count);
}
if (this.RequestQueue.RequestCount == 0)
{
if (continuation != null)
{
continuation(null);
}
}
AsyncLogEventInfo[] logEventInfos = this.RequestQueue.DequeueBatch(count);
if (continuation != null)
{
// write all events, then flush, then call the continuation
this.WrappedTarget.WriteAsyncLogEvents(logEventInfos, ex => this.WrappedTarget.Flush(continuation));
}
else
{
// just write all events
this.WrappedTarget.WriteAsyncLogEvents(logEventInfos);
}
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error in lazy writer timer procedure.");
if (exception.MustBeRethrown())
{
throw;
}
}
finally
{
this.StartLazyWriterTimer();
}
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Transactions;
using ApprovalTests;
using NUnit.Framework;
namespace AsyncTransactions
{
/// <summary>
/// Contains a lot of white space. Optimized for Consolas 14 pt
/// and Full HD resolution
/// </summary>
[TestFixture]
public class Script
{
[SetUp]
public void SetUp()
{
Transaction.Current = null;
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
[TestCase("EntityFramework")]
public void TheStart(string EntityFramework = null)
{
var daniel = new DanielMarbach();
daniel
.Is("CEO").Of("tracelight Gmbh").In("Switzerland")
.and
.WorkingFor("Particular Software").TheFolksBehind("NServiceBus");
throw new ArgumentOutOfRangeException(nameof(EntityFramework),
"Sorry this presentation is not about Entity Framework");
}
[Test]
public async Task TransactionScopeIntroOrRefresh()
{
var slide = new Slide(title: "Transaction Scope Intro");
await slide
.BulletPoint("System.Transactions.TransactionScope")
.BulletPoint("Implicit programing model / Ambient Transactions")
.BulletPoint("Only works with async/await in .NET 4.5.1")
.BulletPoint("Limited usefulness in cloud scenarios")
.BulletPoint("Upgrades a local transaction to a distributed transaction")
.BulletPoint("Ease of coding - If you prefer implicit over explicit")
.Sample(() =>
{
Assert.Null(Transaction.Current);
using (var tx = new TransactionScope())
{
Assert.NotNull(Transaction.Current);
SomeMethodInTheCallStack();
tx.Complete();
}
Assert.Null(Transaction.Current);
});
}
private static void SomeMethodInTheCallStack()
{
Assert.NotNull(Transaction.Current);
}
[Test]
[ExpectedException(typeof(InvalidOperationException))] // Normally never use those
public async Task TransactionScopeAsync()
{
var slide = new Slide(title: "Transaction Scope Async");
await slide
.Sample(async () =>
{
Assert.Null(Transaction.Current);
using (var tx = new TransactionScope())
{
Assert.NotNull(Transaction.Current);
await SomeMethodInTheCallStackAsync()
.ConfigureAwait(false);
tx.Complete();
}
Assert.Null(Transaction.Current);
});
}
[Test]
public async Task TransactionScopeAsyncProper()
{
var slide = new Slide(title: "Transaction Scope Async");
await slide
.Sample(async () =>
{
Assert.Null(Transaction.Current);
using (var tx =
new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
Assert.NotNull(Transaction.Current);
await SomeMethodInTheCallStackAsync()
.ConfigureAwait(false);
tx.Complete();
}
Assert.Null(Transaction.Current);
});
}
private static async Task SomeMethodInTheCallStackAsync()
{
await Task.Delay(500).ConfigureAwait(false);
Assert.NotNull(Transaction.Current);
}
[Test]
[MethodImpl(MethodImplOptions.NoInlining)]
[TestCase(DatabaseMode.Synchronous)]
[TestCase(DatabaseMode.Dangerous)]
[TestCase(DatabaseMode.AsyncBlocking)]
public async Task StoreAsync(DatabaseMode mode)
{
var slide = new Slide(title: "Store Async");
await slide
.BulletPoint("OMG! You just rolled your own NoSQL database, right?")
.Sample(async () =>
{
var database = new Database("StoreAsync.received.txt", mode);
StoringTenSwissGuysInTheDatabase(database);
try
{
await database.SaveAsync().ConfigureAwait(false);
}
finally
{
database.Close();
}
});
}
[Test]
[MethodImpl(MethodImplOptions.NoInlining)]
[TestCase(DatabaseMode.Synchronous)]
[TestCase(DatabaseMode.Dangerous)]
[TestCase(DatabaseMode.AsyncBlocking)]
public async Task StoreAsyncSupportsAmbientTransactionComplete(DatabaseMode mode)
{
var slide = new Slide(title: "Store Async supports ambient transactions - complete");
await slide
.Sample(async () =>
{
var database = new Database("StoreAsyncSupportsAmbientTransactionComplete.received.txt", mode);
StoringTenSwissGuysInTheDatabase(database);
using (var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
await database.SaveAsync().ConfigureAwait(false);
tx.Complete();
}
database.Close();
});
}
[Test]
[MethodImpl(MethodImplOptions.NoInlining)]
[TestCase(DatabaseMode.Synchronous)]
[TestCase(DatabaseMode.Dangerous)]
[TestCase(DatabaseMode.AsyncBlocking)]
public async Task StoreAsyncSupportsAmbientTransactionRollback(DatabaseMode mode)
{
var slide = new Slide(title: "Store Async supports ambient transactions - rollback");
await slide
.Sample(async () =>
{
var database = new Database("StoreAsyncSupportsAmbientTransactionRollback.received.txt", mode);
StoringTenSwissGuysInTheDatabase(database);
using (var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
await database.SaveAsync().ConfigureAwait(false);
// Rollback
}
database.Close();
});
}
[Test]
public async Task WhatDidWeJustLearn()
{
var slide = new Slide(title: "What did we just learn?");
await slide
.BulletPoint("Async void is evil! Use carefully.")
.BulletPoint("Async all the way.")
.BulletPoint("In a cloud first and async world try to avoid TransactionScope")
.BulletPoint("Modern frameworks like EF6 (and higher) support own transactions")
.BulletPoint("Use AsyncPump if you need TxScope and enlist your own stuff.")
.BulletPoint("Write an async enabled library? ConfigureAwait(false) is your friend");
}
[Test]
[Explicit]
public async Task TheEnd()
{
var giveAway = new GiveAway();
await giveAway.WorthThousandDollars();
}
[Test]
public async Task Links()
{
var slide = new Slide(title: "Useful links");
await slide
.BulletPoint("Sample Code including Transcript of what I explained" +
"https://github.com/danielmarbach/AsyncTransactions")
.BulletPoint("Six Essential Tips for Async - " +
"http://channel9.msdn.com/Series/Three-Essential-Tips-for-Async")
.BulletPoint("Best Practices in Asynchronous Programming" +
"https://msdn.microsoft.com/en-us/magazine/jj991977.aspx")
.BulletPoint("Participating in TransactionScopes and Async/Await" +
"http://www.planetgeek.ch/2014/12/07/participating-in-transactionscopes-and-asyncawait-introduction/")
.BulletPoint("Working with Transactions (EF6 Onwards)" +
"https://msdn.microsoft.com/en-us/data/dn456843.aspx")
.BulletPoint("Enlisting Resources as Participants in a Transaction" +
"https://msdn.microsoft.com/en-us/library/ms172153.aspx");
}
private static void StoringTenSwissGuysInTheDatabase(Database database)
{
for (int i = 0; i < 10; i++)
{
database.Store(new Customer {Name = "Daniel" + i});
}
}
}
}
| |
namespace StripeTests
{
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Stripe;
using Xunit;
public class StripeClientTest : BaseStripeTest
{
private readonly DummyHttpClient httpClient;
private readonly StripeClient stripeClient;
private readonly BaseOptions options;
private readonly RequestOptions requestOptions;
public StripeClientTest()
{
this.httpClient = new DummyHttpClient();
this.stripeClient = new StripeClient(
"sk_test_123",
httpClient: this.httpClient);
this.options = new ChargeCreateOptions
{
Amount = 123,
Currency = "usd",
Source = "tok_visa",
};
this.requestOptions = new RequestOptions();
}
[Fact]
public void Ctor_DoesNotThrowsIfApiKeyIsNull()
{
var client = new StripeClient(null);
Assert.NotNull(client);
Assert.Null(client.ApiKey);
}
[Fact]
public void Ctor_ThrowsIfApiKeyIsEmpty()
{
var exception = Assert.Throws<ArgumentException>(() => new StripeClient(string.Empty));
Assert.Contains("API key cannot be the empty string.", exception.Message);
}
[Fact]
public void Ctor_ThrowsIfApiKeyContainsWhitespace()
{
var exception = Assert.Throws<ArgumentException>(() => new StripeClient("sk_test_123\n"));
Assert.Contains("API key cannot contain whitespace.", exception.Message);
}
[Fact]
public async Task RequestAsync_OkResponse()
{
var response = new StripeResponse(HttpStatusCode.OK, null, "{\"id\": \"ch_123\"}");
this.httpClient.Response = response;
var charge = await this.stripeClient.RequestAsync<Charge>(
HttpMethod.Post,
"/v1/charges",
this.options,
this.requestOptions);
Assert.NotNull(charge);
Assert.Equal("ch_123", charge.Id);
Assert.Equal(response, charge.StripeResponse);
}
[Fact]
public async Task RequestAsync_OkResponse_InvalidJson()
{
var response = new StripeResponse(HttpStatusCode.OK, null, "this isn't JSON");
this.httpClient.Response = response;
var exception = await Assert.ThrowsAsync<StripeException>(async () =>
await this.stripeClient.RequestAsync<Charge>(
HttpMethod.Post,
"/v1/charges",
this.options,
this.requestOptions));
Assert.NotNull(exception);
Assert.Equal(HttpStatusCode.OK, exception.HttpStatusCode);
Assert.Equal("Invalid response object from API: \"this isn't JSON\"", exception.Message);
Assert.Equal(response, exception.StripeResponse);
}
[Fact]
public async Task RequestAsync_ApiError()
{
var response = new StripeResponse(
HttpStatusCode.PaymentRequired,
null,
"{\"error\": {\"type\": \"card_error\"}}");
this.httpClient.Response = response;
var exception = await Assert.ThrowsAsync<StripeException>(async () =>
await this.stripeClient.RequestAsync<Charge>(
HttpMethod.Post,
"/v1/charges",
this.options,
this.requestOptions));
Assert.NotNull(exception);
Assert.Equal(HttpStatusCode.PaymentRequired, exception.HttpStatusCode);
Assert.Equal("card_error", exception.StripeError.Type);
Assert.Equal(response, exception.StripeResponse);
}
[Fact]
public async Task RequestAsync_OAuthError()
{
var response = new StripeResponse(
HttpStatusCode.BadRequest,
null,
"{\"error\": \"invalid_request\"}");
this.httpClient.Response = response;
var exception = await Assert.ThrowsAsync<StripeException>(async () =>
await this.stripeClient.RequestAsync<OAuthToken>(
HttpMethod.Post,
"/oauth/token",
this.options,
this.requestOptions));
Assert.NotNull(exception);
Assert.Equal(HttpStatusCode.BadRequest, exception.HttpStatusCode);
Assert.Equal("invalid_request", exception.StripeError.Error);
Assert.Equal(response, exception.StripeResponse);
}
[Fact]
public async Task RequestAsync_Error_InvalidJson()
{
var response = new StripeResponse(
HttpStatusCode.InternalServerError,
null,
"this isn't JSON");
this.httpClient.Response = response;
var exception = await Assert.ThrowsAsync<StripeException>(async () =>
await this.stripeClient.RequestAsync<Charge>(
HttpMethod.Post,
"/v1/charges",
this.options,
this.requestOptions));
Assert.NotNull(exception);
Assert.Equal(HttpStatusCode.InternalServerError, exception.HttpStatusCode);
Assert.Equal("Invalid response object from API: \"this isn't JSON\"", exception.Message);
Assert.Equal(response, exception.StripeResponse);
}
[Fact]
public async Task RequestAsync_Error_InvalidErrorObject()
{
var response = new StripeResponse(
HttpStatusCode.InternalServerError,
null,
"{}");
this.httpClient.Response = response;
var exception = await Assert.ThrowsAsync<StripeException>(async () =>
await this.stripeClient.RequestAsync<Charge>(
HttpMethod.Post,
"/v1/charges",
this.options,
this.requestOptions));
Assert.NotNull(exception);
Assert.Equal(HttpStatusCode.InternalServerError, exception.HttpStatusCode);
Assert.Equal("Invalid response object from API: \"{}\"", exception.Message);
Assert.Equal(response, exception.StripeResponse);
}
[Fact]
public async Task RequestStreamingAsync_OkResponse_InvalidJson()
{
var streamedResponse = new StripeStreamedResponse(
HttpStatusCode.OK,
null,
StringToStream("this isn't JSON"));
this.httpClient.StreamedResponse = streamedResponse;
var stream = await this.stripeClient.RequestStreamingAsync(
HttpMethod.Post,
"/v1/charges",
this.options,
this.requestOptions);
Assert.NotNull(stream);
Assert.Equal("this isn't JSON", StreamToString(stream));
}
[Fact]
public async Task RequestStreamingAsync_ApiError()
{
var streamedResponse = new StripeStreamedResponse(
HttpStatusCode.PaymentRequired,
null,
StringToStream("{\"error\": {\"type\": \"card_error\"}}"));
this.httpClient.StreamedResponse = streamedResponse;
var exception = await Assert.ThrowsAsync<StripeException>(async () =>
await this.stripeClient.RequestStreamingAsync(
HttpMethod.Post,
"/v1/charges",
this.options,
this.requestOptions));
Assert.NotNull(exception);
Assert.Equal(HttpStatusCode.PaymentRequired, exception.HttpStatusCode);
Assert.Equal("card_error", exception.StripeError.Type);
Assert.Equal(await streamedResponse.ToStripeResponseAsync(), exception.StripeResponse);
}
[Fact]
public async Task RequestStreamingAsync_OAuthError()
{
var streamedResponse = new StripeStreamedResponse(
HttpStatusCode.BadRequest,
null,
StringToStream("{\"error\": \"invalid_request\"}"));
this.httpClient.StreamedResponse = streamedResponse;
var exception = await Assert.ThrowsAsync<StripeException>(async () =>
await this.stripeClient.RequestStreamingAsync(
HttpMethod.Post,
"/oauth/token",
this.options,
this.requestOptions));
Assert.NotNull(exception);
Assert.Equal(HttpStatusCode.BadRequest, exception.HttpStatusCode);
Assert.Equal("invalid_request", exception.StripeError.Error);
Assert.Equal(await streamedResponse.ToStripeResponseAsync(), exception.StripeResponse);
}
[Fact]
public async Task RequestStreamingAsync_Error_InvalidErrorObject()
{
var streamedResponse = new StripeStreamedResponse(
HttpStatusCode.InternalServerError,
null,
StringToStream("{}"));
this.httpClient.StreamedResponse = streamedResponse;
var exception = await Assert.ThrowsAsync<StripeException>(async () =>
await this.stripeClient.RequestStreamingAsync(
HttpMethod.Post,
"/v1/charges",
this.options,
this.requestOptions));
Assert.NotNull(exception);
Assert.Equal(HttpStatusCode.InternalServerError, exception.HttpStatusCode);
Assert.Equal("Invalid response object from API: \"{}\"", exception.Message);
Assert.Equal(await streamedResponse.ToStripeResponseAsync(), exception.StripeResponse);
}
private static Stream StringToStream(string content)
{
return new MemoryStream(Encoding.UTF8.GetBytes(content));
}
private static string StreamToString(Stream stream)
{
return new StreamReader(stream, Encoding.UTF8).ReadToEnd();
}
private class DummyHttpClient : IHttpClient
{
public StripeResponse Response { get; set; }
public StripeStreamedResponse StreamedResponse { get; set; }
public Task<StripeResponse> MakeRequestAsync(
StripeRequest request,
CancellationToken cancellationToken = default)
{
if (this.Response == null)
{
throw new StripeTestException("Response is null");
}
return Task.FromResult<StripeResponse>(this.Response);
}
public Task<StripeStreamedResponse> MakeStreamingRequestAsync(
StripeRequest request,
CancellationToken cancellationToken = default)
{
if (this.StreamedResponse == null)
{
throw new StripeTestException("StreamedResponse is null");
}
return Task.FromResult(this.StreamedResponse);
}
}
}
}
| |
namespace TheArtOfDev.HtmlRenderer.Core.Utils
{
/// <summary>
/// Defines HTML strings
/// </summary>
internal static class HtmlConstants
{
public const string A = "a";
// public const string ABBR = "ABBR";
// public const string ACRONYM = "ACRONYM";
// public const string ADDRESS = "ADDRESS";
// public const string APPLET = "APPLET";
// public const string AREA = "AREA";
// public const string B = "B";
// public const string BASE = "BASE";
// public const string BASEFONT = "BASEFONT";
// public const string BDO = "BDO";
// public const string BIG = "BIG";
// public const string BLOCKQUOTE = "BLOCKQUOTE";
// public const string BODY = "BODY";
// public const string BR = "BR";
// public const string BUTTON = "BUTTON";
public const string Caption = "caption";
// public const string CENTER = "CENTER";
// public const string CITE = "CITE";
// public const string CODE = "CODE";
public const string Col = "col";
public const string Colgroup = "colgroup";
public const string Display = "display";
// public const string DD = "DD";
// public const string DEL = "DEL";
// public const string DFN = "DFN";
// public const string DIR = "DIR";
// public const string DIV = "DIV";
// public const string DL = "DL";
// public const string DT = "DT";
// public const string EM = "EM";
// public const string FIELDSET = "FIELDSET";
public const string Font = "font";
// public const string FORM = "FORM";
// public const string FRAME = "FRAME";
// public const string FRAMESET = "FRAMESET";
// public const string H1 = "H1";
// public const string H2 = "H2";
// public const string H3 = "H3";
// public const string H4 = "H4";
// public const string H5 = "H5";
// public const string H6 = "H6";
// public const string HEAD = "HEAD";
public const string Hr = "hr";
// public const string HTML = "HTML";
// public const string I = "I";
public const string Iframe = "iframe";
public const string Img = "img";
// public const string INPUT = "INPUT";
// public const string INS = "INS";
// public const string ISINDEX = "ISINDEX";
// public const string KBD = "KBD";
// public const string LABEL = "LABEL";
// public const string LEGEND = "LEGEND";
public const string Li = "li";
// public const string LINK = "LINK";
// public const string MAP = "MAP";
// public const string MENU = "MENU";
// public const string META = "META";
// public const string NOFRAMES = "NOFRAMES";
// public const string NOSCRIPT = "NOSCRIPT";
// public const string OBJECT = "OBJECT";
// public const string OL = "OL";
// public const string OPTGROUP = "OPTGROUP";
// public const string OPTION = "OPTION";
// public const string P = "P";
// public const string PARAM = "PARAM";
// public const string PRE = "PRE";
// public const string Q = "Q";
// public const string S = "S";
// public const string SAMP = "SAMP";
// public const string SCRIPT = "SCRIPT";
// public const string SELECT = "SELECT";
// public const string SMALL = "SMALL";
// public const string SPAN = "SPAN";
// public const string STRIKE = "STRIKE";
// public const string STRONG = "STRONG";
public const string Style = "style";
// public const string SUB = "SUB";
// public const string SUP = "SUP";
public const string Table = "table";
public const string Tbody = "tbody";
public const string Td = "td";
// public const string TEXTAREA = "TEXTAREA";
public const string Tfoot = "tfoot";
public const string Th = "th";
public const string Thead = "thead";
// public const string TITLE = "TITLE";
public const string Tr = "tr";
// public const string TT = "TT";
// public const string U = "U";
// public const string UL = "UL";
// public const string VAR = "VAR";
// public const string abbr = "abbr";
// public const string accept = "accept";
// public const string accesskey = "accesskey";
// public const string action = "action";
public const string Align = "align";
// public const string alink = "alink";
// public const string alt = "alt";
// public const string archive = "archive";
// public const string axis = "axis";
public const string Background = "background";
public const string Bgcolor = "bgcolor";
public const string Border = "border";
public const string Bordercolor = "bordercolor";
public const string Cellpadding = "cellpadding";
public const string Cellspacing = "cellspacing";
// public const string char_ = "char";
// public const string charoff = "charoff";
// public const string charset = "charset";
// public const string checked_ = "checked";
// public const string cite = "cite";
public const string Class = "class";
// public const string classid = "classid";
// public const string clear = "clear";
// public const string code = "code";
// public const string codebase = "codebase";
// public const string codetype = "codetype";
public const string Color = "color";
// public const string cols = "cols";
// public const string colspan = "colspan";
// public const string compact = "compact";
// public const string content = "content";
// public const string coords = "coords";
// public const string data = "data";
// public const string datetime = "datetime";
// public const string declare = "declare";
// public const string defer = "defer";
public const string Dir = "dir";
// public const string disabled = "disabled";
// public const string enctype = "enctype";
public const string Face = "face";
// public const string for_ = "for";
// public const string frame = "frame";
// public const string frameborder = "frameborder";
// public const string headers = "headers";
public const string Height = "height";
public const string Href = "href";
// public const string hreflang = "hreflang";
public const string Hspace = "hspace";
// public const string http_equiv = "http-equiv";
// public const string id = "id";
// public const string ismap = "ismap";
// public const string label = "label";
// public const string lang = "lang";
// public const string language = "language";
// public const string link = "link";
// public const string longdesc = "longdesc";
// public const string marginheight = "marginheight";
// public const string marginwidth = "marginwidth";
// public const string maxlength = "maxlength";
// public const string media = "media";
// public const string method = "method";
// public const string multiple = "multiple";
// public const string name = "name";
// public const string nohref = "nohref";
// public const string noresize = "noresize";
// public const string noshade = "noshade";
public const string Nowrap = "nowrap";
// public const string object_ = "object";
// public const string onblur = "onblur";
// public const string onchange = "onchange";
// public const string onclick = "onclick";
// public const string ondblclick = "ondblclick";
// public const string onfocus = "onfocus";
// public const string onkeydown = "onkeydown";
// public const string onkeypress = "onkeypress";
// public const string onkeyup = "onkeyup";
// public const string onload = "onload";
// public const string onmousedown = "onmousedown";
// public const string onmousemove = "onmousemove";
// public const string onmouseout = "onmouseout";
// public const string onmouseover = "onmouseover";
// public const string onmouseup = "onmouseup";
// public const string onreset = "onreset";
// public const string onselect = "onselect";
// public const string onsubmit = "onsubmit";
// public const string onunload = "onunload";
// public const string profile = "profile";
// public const string prompt = "prompt";
// public const string readonly_ = "readonly";
// public const string rel = "rel";
// public const string rev = "rev";
// public const string rows = "rows";
// public const string rowspan = "rowspan";
// public const string rules = "rules";
// public const string scheme = "scheme";
// public const string scope = "scope";
// public const string scrolling = "scrolling";
// public const string selected = "selected";
// public const string shape = "shape";
public const string Size = "size";
// public const string span = "span";
// public const string src = "src";
// public const string standby = "standby";
// public const string start = "start";
// public const string style = "style";
// public const string summary = "summary";
// public const string tabindex = "tabindex";
// public const string target = "target";
// public const string text = "text";
// public const string title = "title";
// public const string type = "type";
// public const string usemap = "usemap";
public const string Valign = "valign";
// public const string value = "value";
// public const string valuetype = "valuetype";
// public const string version = "version";
// public const string vlink = "vlink";
public const string Vspace = "vspace";
public const string Width = "width";
public const string Left = "left";
public const string Right = "right";
// public const string top = "top";
public const string Center = "center";
// public const string middle = "middle";
// public const string bottom = "bottom";
public const string Justify = "justify";
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using NSubstitute;
using Octokit.Helpers;
using Xunit;
namespace Octokit.Tests.Clients
{
public class StatisticsClientTests
{
public class TheCtor
{
[Fact]
public void EnsuresNonNullArguments()
{
Assert.Throws<ArgumentNullException>(() => new StatisticsClient(null));
}
}
public class TheGetContributorsMethod
{
[Fact]
public async Task RetrievesContributorsForCorrectUrl()
{
var expectedEndPoint = new Uri("repos/username/repositoryName/stats/contributors", UriKind.Relative);
var client = Substitute.For<IApiConnection>();
IReadOnlyList<Contributor> contributors = new ReadOnlyCollection<Contributor>(new[] { new Contributor() });
client.GetQueuedOperation<Contributor>(expectedEndPoint, Args.CancellationToken)
.Returns(Task.FromResult(contributors));
var statisticsClient = new StatisticsClient(client);
var result = await statisticsClient.GetContributors("username", "repositoryName");
Assert.Equal(1, result.Count);
}
[Fact]
public async Task ThrowsIfGivenNullOwner()
{
var statisticsClient = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => statisticsClient.GetContributors(null, "repositoryName"));
}
[Fact]
public async Task ThrowsIfGivenNullRepositoryName()
{
var statisticsClient = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => statisticsClient.GetContributors("owner", null));
}
}
public class TheGetCommitActivityForTheLastYearMethod
{
[Fact]
public async Task RequestsCorrectUrl()
{
var expectedEndPoint = new Uri("repos/username/repositoryName/stats/commit_activity", UriKind.Relative);
var data = new WeeklyCommitActivity(new[] { 1, 2 }, 100, 42);
IReadOnlyList<WeeklyCommitActivity> response = new ReadOnlyCollection<WeeklyCommitActivity>(new[] { data });
var client = Substitute.For<IApiConnection>();
client.GetQueuedOperation<WeeklyCommitActivity>(expectedEndPoint, Args.CancellationToken)
.Returns(Task.FromResult(response));
var statisticsClient = new StatisticsClient(client);
var result = await statisticsClient.GetCommitActivity("username", "repositoryName");
Assert.Equal(2, result.Activity[0].Days.Count);
Assert.Equal(1, result.Activity[0].Days[0]);
Assert.Equal(2, result.Activity[0].Days[1]);
Assert.Equal(100, result.Activity[0].Total);
Assert.Equal(42, result.Activity[0].Week);
}
[Fact]
public async Task ThrowsIfGivenNullOwner()
{
var statisticsClient = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => statisticsClient.GetCommitActivity(null, "repositoryName"));
}
[Fact]
public async Task ThrowsIfGivenNullRepositoryName()
{
var statisticsClient = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => statisticsClient.GetCommitActivity("owner", null));
}
}
public class TheGetAdditionsAndDeletionsPerWeekMethod
{
[Fact]
public async Task RequestsCorrectUrl()
{
var expectedEndPoint = new Uri("repos/username/repositoryName/stats/code_frequency", UriKind.Relative);
long firstTimestamp = 159670861;
long secondTimestamp = 0;
IReadOnlyList<long[]> data = new ReadOnlyCollection<long[]>(new[]
{
new[] { firstTimestamp, 10, 52 },
new[] { secondTimestamp, 0, 9 }
});
var client = Substitute.For<IApiConnection>();
client.GetQueuedOperation<long[]>(expectedEndPoint, Args.CancellationToken)
.Returns(Task.FromResult(data));
var statisticsClient = new StatisticsClient(client);
var codeFrequency = await statisticsClient.GetCodeFrequency("username", "repositoryName");
Assert.Equal(2, codeFrequency.AdditionsAndDeletionsByWeek.Count);
Assert.Equal(firstTimestamp.FromUnixTime(), codeFrequency.AdditionsAndDeletionsByWeek[0].Timestamp);
Assert.Equal(10, codeFrequency.AdditionsAndDeletionsByWeek[0].Additions);
Assert.Equal(52, codeFrequency.AdditionsAndDeletionsByWeek[0].Deletions);
Assert.Equal(secondTimestamp.FromUnixTime(), codeFrequency.AdditionsAndDeletionsByWeek[1].Timestamp);
Assert.Equal(0, codeFrequency.AdditionsAndDeletionsByWeek[1].Additions);
Assert.Equal(9, codeFrequency.AdditionsAndDeletionsByWeek[1].Deletions);
}
[Fact]
public async Task ThrowsIfGivenNullOwner()
{
var statisticsClient = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => statisticsClient.GetCodeFrequency(null, "repositoryName"));
}
[Fact]
public async Task ThrowsIfGivenNullRepositoryName()
{
var statisticsClient = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => statisticsClient.GetCodeFrequency("owner", null));
}
}
public class TheGetWeeklyCommitCountsMethod
{
[Fact]
public void RequestsCorrectUrl()
{
var expectedEndPoint = new Uri("repos/username/repositoryName/stats/participation", UriKind.Relative);
var client = Substitute.For<IApiConnection>();
var statisticsClient = new StatisticsClient(client);
statisticsClient.GetParticipation("username", "repositoryName");
client.Received().GetQueuedOperation<Participation>(expectedEndPoint, Args.CancellationToken);
}
[Fact]
public async Task ThrowsIfGivenNullOwner()
{
var statisticsClient = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => statisticsClient.GetParticipation(null, "repositoryName"));
}
[Fact]
public async Task ThrowsIfGivenNullRepositoryName()
{
var statisticsClient = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => statisticsClient.GetParticipation("owner", null));
}
}
public class TheGetHourlyCommitCountsMethod
{
[Fact]
public async Task RetrievesPunchCard()
{
var expectedEndPoint = new Uri("repos/username/repositoryName/stats/punch_card", UriKind.Relative);
var client = Substitute.For<IApiConnection>();
IReadOnlyList<int[]> data = new ReadOnlyCollection<int[]>(new[] { new[] { 2, 8, 42 } });
client.GetQueuedOperation<int[]>(expectedEndPoint, Args.CancellationToken)
.Returns(Task.FromResult(data));
var statisticsClient = new StatisticsClient(client);
var result = await statisticsClient.GetPunchCard("username", "repositoryName");
Assert.Equal(1, result.PunchPoints.Count);
Assert.Equal(DayOfWeek.Tuesday, result.PunchPoints[0].DayOfWeek);
Assert.Equal(8, result.PunchPoints[0].HourOfTheDay);
Assert.Equal(42, result.PunchPoints[0].CommitCount);
}
[Fact]
public async Task ThrowsIfGivenNullOwner()
{
var statisticsClient = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => statisticsClient.GetPunchCard(null, "repositoryName"));
}
[Fact]
public async Task ThrowsIfGivenNullRepositoryName()
{
var statisticsClient = new StatisticsClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => statisticsClient.GetPunchCard("owner", null));
}
}
}
}
| |
using System;
using BigMath;
using Raksha.Crypto.Parameters;
using Raksha.Math;
using Raksha.Security;
namespace Raksha.Crypto.Generators
{
/**
* generate suitable parameters for GOST3410.
*/
public class Gost3410ParametersGenerator
{
private int size;
private int typeproc;
private SecureRandom init_random;
/**
* initialise the key generator.
*
* @param size size of the key
* @param typeProcedure type procedure A,B = 1; A',B' - else
* @param random random byte source.
*/
public void Init(
int size,
int typeProcedure,
SecureRandom random)
{
this.size = size;
this.typeproc = typeProcedure;
this.init_random = random;
}
//Procedure A
private int procedure_A(int x0, int c, BigInteger[] pq, int size)
{
//Verify and perform condition: 0<x<2^16; 0<c<2^16; c - odd.
while(x0<0 || x0>65536)
{
x0 = init_random.NextInt()/32768;
}
while((c<0 || c>65536) || (c/2==0))
{
c = init_random.NextInt()/32768 + 1;
}
BigInteger C = BigInteger.ValueOf(c);
BigInteger constA16 = BigInteger.ValueOf(19381);
//step1
BigInteger[] y = new BigInteger[1]; // begin length = 1
y[0] = BigInteger.ValueOf(x0);
//step 2
int[] t = new int[1]; // t - orders; begin length = 1
t[0] = size;
int s = 0;
for (int i=0; t[i]>=17; i++)
{
// extension array t
int[] tmp_t = new int[t.Length + 1]; ///////////////
Array.Copy(t,0,tmp_t,0,t.Length); // extension
t = new int[tmp_t.Length]; // array t
Array.Copy(tmp_t, 0, t, 0, tmp_t.Length); ///////////////
t[i+1] = t[i]/2;
s = i+1;
}
//step3
BigInteger[] p = new BigInteger[s+1];
p[s] = new BigInteger("8003",16); //set min prime number length 16 bit
int m = s-1; //step4
for (int i=0; i<s; i++)
{
int rm = t[m]/16; //step5
step6: for(;;)
{
//step 6
BigInteger[] tmp_y = new BigInteger[y.Length]; ////////////////
Array.Copy(y,0,tmp_y,0,y.Length); // extension
y = new BigInteger[rm+1]; // array y
Array.Copy(tmp_y,0,y,0,tmp_y.Length); ////////////////
for (int j=0; j<rm; j++)
{
y[j+1] = (y[j].Multiply(constA16).Add(C)).Mod(BigInteger.Two.Pow(16));
}
//step 7
BigInteger Ym = BigInteger.Zero;
for (int j=0; j<rm; j++)
{
Ym = Ym.Add(y[j].ShiftLeft(16*j));
}
y[0] = y[rm]; //step 8
//step 9
BigInteger N = BigInteger.One.ShiftLeft(t[m]-1).Divide(p[m+1]).Add(
Ym.ShiftLeft(t[m]-1).Divide(p[m+1].ShiftLeft(16*rm)));
if (N.TestBit(0))
{
N = N.Add(BigInteger.One);
}
//step 10
for(;;)
{
//step 11
BigInteger NByLastP = N.Multiply(p[m+1]);
if (NByLastP.BitLength > t[m])
{
goto step6; //step 12
}
p[m] = NByLastP.Add(BigInteger.One);
//step13
if (BigInteger.Two.ModPow(NByLastP, p[m]).CompareTo(BigInteger.One) == 0
&& BigInteger.Two.ModPow(N, p[m]).CompareTo(BigInteger.One) != 0)
{
break;
}
N = N.Add(BigInteger.Two);
}
if (--m < 0)
{
pq[0] = p[0];
pq[1] = p[1];
return y[0].IntValue; //return for procedure B step 2
}
break; //step 14
}
}
return y[0].IntValue;
}
//Procedure A'
private long procedure_Aa(long x0, long c, BigInteger[] pq, int size)
{
//Verify and perform condition: 0<x<2^32; 0<c<2^32; c - odd.
while(x0<0 || x0>4294967296L)
{
x0 = init_random.NextInt()*2;
}
while((c<0 || c>4294967296L) || (c/2==0))
{
c = init_random.NextInt()*2+1;
}
BigInteger C = BigInteger.ValueOf(c);
BigInteger constA32 = BigInteger.ValueOf(97781173);
//step1
BigInteger[] y = new BigInteger[1]; // begin length = 1
y[0] = BigInteger.ValueOf(x0);
//step 2
int[] t = new int[1]; // t - orders; begin length = 1
t[0] = size;
int s = 0;
for (int i=0; t[i]>=33; i++)
{
// extension array t
int[] tmp_t = new int[t.Length + 1]; ///////////////
Array.Copy(t,0,tmp_t,0,t.Length); // extension
t = new int[tmp_t.Length]; // array t
Array.Copy(tmp_t, 0, t, 0, tmp_t.Length); ///////////////
t[i+1] = t[i]/2;
s = i+1;
}
//step3
BigInteger[] p = new BigInteger[s+1];
p[s] = new BigInteger("8000000B",16); //set min prime number length 32 bit
int m = s-1; //step4
for (int i=0; i<s; i++)
{
int rm = t[m]/32; //step5
step6: for(;;)
{
//step 6
BigInteger[] tmp_y = new BigInteger[y.Length]; ////////////////
Array.Copy(y,0,tmp_y,0,y.Length); // extension
y = new BigInteger[rm+1]; // array y
Array.Copy(tmp_y,0,y,0,tmp_y.Length); ////////////////
for (int j=0; j<rm; j++)
{
y[j+1] = (y[j].Multiply(constA32).Add(C)).Mod(BigInteger.Two.Pow(32));
}
//step 7
BigInteger Ym = BigInteger.Zero;
for (int j=0; j<rm; j++)
{
Ym = Ym.Add(y[j].ShiftLeft(32*j));
}
y[0] = y[rm]; //step 8
//step 9
BigInteger N = BigInteger.One.ShiftLeft(t[m]-1).Divide(p[m+1]).Add(
Ym.ShiftLeft(t[m]-1).Divide(p[m+1].ShiftLeft(32*rm)));
if (N.TestBit(0))
{
N = N.Add(BigInteger.One);
}
//step 10
for(;;)
{
//step 11
BigInteger NByLastP = N.Multiply(p[m+1]);
if (NByLastP.BitLength > t[m])
{
goto step6; //step 12
}
p[m] = NByLastP.Add(BigInteger.One);
//step13
if (BigInteger.Two.ModPow(NByLastP, p[m]).CompareTo(BigInteger.One) == 0
&& BigInteger.Two.ModPow(N, p[m]).CompareTo(BigInteger.One) != 0)
{
break;
}
N = N.Add(BigInteger.Two);
}
if (--m < 0)
{
pq[0] = p[0];
pq[1] = p[1];
return y[0].LongValue; //return for procedure B' step 2
}
break; //step 14
}
}
return y[0].LongValue;
}
//Procedure B
private void procedure_B(int x0, int c, BigInteger[] pq)
{
//Verify and perform condition: 0<x<2^16; 0<c<2^16; c - odd.
while(x0<0 || x0>65536)
{
x0 = init_random.NextInt()/32768;
}
while((c<0 || c>65536) || (c/2==0))
{
c = init_random.NextInt()/32768 + 1;
}
BigInteger [] qp = new BigInteger[2];
BigInteger q = null, Q = null, p = null;
BigInteger C = BigInteger.ValueOf(c);
BigInteger constA16 = BigInteger.ValueOf(19381);
//step1
x0 = procedure_A(x0, c, qp, 256);
q = qp[0];
//step2
x0 = procedure_A(x0, c, qp, 512);
Q = qp[0];
BigInteger[] y = new BigInteger[65];
y[0] = BigInteger.ValueOf(x0);
const int tp = 1024;
BigInteger qQ = q.Multiply(Q);
step3:
for(;;)
{
//step 3
for (int j=0; j<64; j++)
{
y[j+1] = (y[j].Multiply(constA16).Add(C)).Mod(BigInteger.Two.Pow(16));
}
//step 4
BigInteger Y = BigInteger.Zero;
for (int j=0; j<64; j++)
{
Y = Y.Add(y[j].ShiftLeft(16*j));
}
y[0] = y[64]; //step 5
//step 6
BigInteger N = BigInteger.One.ShiftLeft(tp-1).Divide(qQ).Add(
Y.ShiftLeft(tp-1).Divide(qQ.ShiftLeft(1024)));
if (N.TestBit(0))
{
N = N.Add(BigInteger.One);
}
//step 7
for(;;)
{
//step 11
BigInteger qQN = qQ.Multiply(N);
if (qQN.BitLength > tp)
{
goto step3; //step 9
}
p = qQN.Add(BigInteger.One);
//step10
if (BigInteger.Two.ModPow(qQN, p).CompareTo(BigInteger.One) == 0
&& BigInteger.Two.ModPow(q.Multiply(N), p).CompareTo(BigInteger.One) != 0)
{
pq[0] = p;
pq[1] = q;
return;
}
N = N.Add(BigInteger.Two);
}
}
}
//Procedure B'
private void procedure_Bb(long x0, long c, BigInteger[] pq)
{
//Verify and perform condition: 0<x<2^32; 0<c<2^32; c - odd.
while(x0<0 || x0>4294967296L)
{
x0 = init_random.NextInt()*2;
}
while((c<0 || c>4294967296L) || (c/2==0))
{
c = init_random.NextInt()*2+1;
}
BigInteger [] qp = new BigInteger[2];
BigInteger q = null, Q = null, p = null;
BigInteger C = BigInteger.ValueOf(c);
BigInteger constA32 = BigInteger.ValueOf(97781173);
//step1
x0 = procedure_Aa(x0, c, qp, 256);
q = qp[0];
//step2
x0 = procedure_Aa(x0, c, qp, 512);
Q = qp[0];
BigInteger[] y = new BigInteger[33];
y[0] = BigInteger.ValueOf(x0);
const int tp = 1024;
BigInteger qQ = q.Multiply(Q);
step3:
for(;;)
{
//step 3
for (int j=0; j<32; j++)
{
y[j+1] = (y[j].Multiply(constA32).Add(C)).Mod(BigInteger.Two.Pow(32));
}
//step 4
BigInteger Y = BigInteger.Zero;
for (int j=0; j<32; j++)
{
Y = Y.Add(y[j].ShiftLeft(32*j));
}
y[0] = y[32]; //step 5
//step 6
BigInteger N = BigInteger.One.ShiftLeft(tp-1).Divide(qQ).Add(
Y.ShiftLeft(tp-1).Divide(qQ.ShiftLeft(1024)));
if (N.TestBit(0))
{
N = N.Add(BigInteger.One);
}
//step 7
for(;;)
{
//step 11
BigInteger qQN = qQ.Multiply(N);
if (qQN.BitLength > tp)
{
goto step3; //step 9
}
p = qQN.Add(BigInteger.One);
//step10
if (BigInteger.Two.ModPow(qQN, p).CompareTo(BigInteger.One) == 0
&& BigInteger.Two.ModPow(q.Multiply(N), p).CompareTo(BigInteger.One) != 0)
{
pq[0] = p;
pq[1] = q;
return;
}
N = N.Add(BigInteger.Two);
}
}
}
/**
* Procedure C
* procedure generates the a value from the given p,q,
* returning the a value.
*/
private BigInteger procedure_C(BigInteger p, BigInteger q)
{
BigInteger pSub1 = p.Subtract(BigInteger.One);
BigInteger pSub1Divq = pSub1.Divide(q);
for(;;)
{
BigInteger d = new BigInteger(p.BitLength, init_random);
// 1 < d < p-1
if (d.CompareTo(BigInteger.One) > 0 && d.CompareTo(pSub1) < 0)
{
BigInteger a = d.ModPow(pSub1Divq, p);
if (a.CompareTo(BigInteger.One) != 0)
{
return a;
}
}
}
}
/**
* which generates the p , q and a values from the given parameters,
* returning the Gost3410Parameters object.
*/
public Gost3410Parameters GenerateParameters()
{
BigInteger [] pq = new BigInteger[2];
BigInteger q = null, p = null, a = null;
int x0, c;
long x0L, cL;
if (typeproc==1)
{
x0 = init_random.NextInt();
c = init_random.NextInt();
switch(size)
{
case 512:
procedure_A(x0, c, pq, 512);
break;
case 1024:
procedure_B(x0, c, pq);
break;
default:
throw new ArgumentException("Ooops! key size 512 or 1024 bit.");
}
p = pq[0]; q = pq[1];
a = procedure_C(p, q);
//System.out.println("p:"+p.toString(16)+"\n"+"q:"+q.toString(16)+"\n"+"a:"+a.toString(16));
//System.out.println("p:"+p+"\n"+"q:"+q+"\n"+"a:"+a);
return new Gost3410Parameters(p, q, a, new Gost3410ValidationParameters(x0, c));
}
else
{
x0L = init_random.NextLong();
cL = init_random.NextLong();
switch(size)
{
case 512:
procedure_Aa(x0L, cL, pq, 512);
break;
case 1024:
procedure_Bb(x0L, cL, pq);
break;
default:
throw new InvalidOperationException("Ooops! key size 512 or 1024 bit.");
}
p = pq[0]; q = pq[1];
a = procedure_C(p, q);
//System.out.println("p:"+p.toString(16)+"\n"+"q:"+q.toString(16)+"\n"+"a:"+a.toString(16));
//System.out.println("p:"+p+"\n"+"q:"+q+"\n"+"a:"+a);
return new Gost3410Parameters(p, q, a, new Gost3410ValidationParameters(x0L, cL));
}
}
}
}
| |
namespace FPL.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class ExtractedFullStatsBase : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.HistoryPasts",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlayerInformationId = c.Int(nullable: false),
FantasyPremierLeagueId = c.Int(nullable: false),
SeasonName = c.String(),
ElementCode = c.Int(nullable: false),
StartCost = c.Int(nullable: false),
EndCost = c.Int(nullable: false),
TotalPoints = c.Int(nullable: false),
Minutes = c.Int(nullable: false),
GoalsScored = c.Int(nullable: false),
Assists = c.Int(nullable: false),
CleanSheets = c.Int(nullable: false),
GoalsConceded = c.Int(nullable: false),
OwnGoals = c.Int(nullable: false),
PenaltiesSaved = c.Int(nullable: false),
PenaltiesMissed = c.Int(nullable: false),
YellowCards = c.Int(nullable: false),
RedCards = c.Int(nullable: false),
Saves = c.Int(nullable: false),
Bonus = c.Int(nullable: false),
Bps = c.Int(nullable: false),
Influence = c.String(),
Creativity = c.String(),
Threat = c.String(),
IctIndex = c.String(),
EaIndex = c.Int(nullable: false),
Season = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.PlayerInformations",
c => new
{
Id = c.Int(nullable: false, identity: true),
UrlId = c.Int(nullable: false),
FirstName = c.String(),
LastName = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Explains",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlayerInformationId = c.Int(nullable: false),
ExplainDetails_Id = c.Int(),
ExplainFixture_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.ExplainDetails", t => t.ExplainDetails_Id)
.ForeignKey("dbo.ExplainFixtures", t => t.ExplainFixture_Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId)
.Index(t => t.ExplainDetails_Id)
.Index(t => t.ExplainFixture_Id);
CreateTable(
"dbo.ExplainDetails",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlayerInformationId = c.Int(nullable: false),
Bonus_Id = c.Int(),
CleanSheets_Id = c.Int(),
GoalsScored_Id = c.Int(),
Minutes_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Bonus", t => t.Bonus_Id)
.ForeignKey("dbo.CleanSheets", t => t.CleanSheets_Id)
.ForeignKey("dbo.GoalsScoreds", t => t.GoalsScored_Id)
.ForeignKey("dbo.Minutes", t => t.Minutes_Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId)
.Index(t => t.Bonus_Id)
.Index(t => t.CleanSheets_Id)
.Index(t => t.GoalsScored_Id)
.Index(t => t.Minutes_Id);
CreateTable(
"dbo.Bonus",
c => new
{
Id = c.Int(nullable: false, identity: true),
Points = c.Int(nullable: false),
Name = c.String(),
Value = c.Int(nullable: false),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.CleanSheets",
c => new
{
Id = c.Int(nullable: false, identity: true),
Points = c.Int(nullable: false),
Name = c.String(),
Value = c.Int(nullable: false),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.GoalsScoreds",
c => new
{
Id = c.Int(nullable: false, identity: true),
Points = c.Int(nullable: false),
Name = c.String(),
Value = c.Int(nullable: false),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.Minutes",
c => new
{
Id = c.Int(nullable: false, identity: true),
Points = c.Int(nullable: false),
Name = c.String(),
Value = c.Int(nullable: false),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.ExplainFixtures",
c => new
{
Id = c.Int(nullable: false, identity: true),
FantasyPremierLeagueId = c.Int(nullable: false),
KickoffTimeFormatted = c.String(),
Started = c.Boolean(nullable: false),
EventDay = c.Int(nullable: false),
DeadlineTime = c.DateTime(nullable: false),
DeadlineTimeFormatted = c.String(),
Code = c.Int(nullable: false),
KickoffTime = c.DateTime(nullable: false),
TeamHomeScore = c.Int(nullable: false),
TeamAwayScore = c.Int(nullable: false),
Finished = c.Boolean(nullable: false),
Minutes = c.Int(nullable: false),
ProvisionalStartTime = c.Boolean(nullable: false),
FinishedProvisional = c.Boolean(nullable: false),
Event = c.Int(nullable: false),
TeamAway = c.Int(nullable: false),
TeamHome = c.Int(nullable: false),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.Stats",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlayerInformationId = c.Int(nullable: false),
Assists_Id = c.Int(),
Bonus_Id = c.Int(),
Bps_Id = c.Int(),
GoalsScored_Id = c.Int(),
OwnGoals_Id = c.Int(),
PenaltiesMissed_Id = c.Int(),
PenaltiesSaved_Id = c.Int(),
RedCards_Id = c.Int(),
Saves_Id = c.Int(),
YellowCards_Id = c.Int(),
ExplainFixture_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Assists", t => t.Assists_Id)
.ForeignKey("dbo.Bonus", t => t.Bonus_Id)
.ForeignKey("dbo.Bps", t => t.Bps_Id)
.ForeignKey("dbo.GoalsScoreds", t => t.GoalsScored_Id)
.ForeignKey("dbo.OwnGoals", t => t.OwnGoals_Id)
.ForeignKey("dbo.PenaltiesMisseds", t => t.PenaltiesMissed_Id)
.ForeignKey("dbo.PenaltiesSaveds", t => t.PenaltiesSaved_Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.ForeignKey("dbo.RedCards", t => t.RedCards_Id)
.ForeignKey("dbo.Saves", t => t.Saves_Id)
.ForeignKey("dbo.YellowCards", t => t.YellowCards_Id)
.ForeignKey("dbo.ExplainFixtures", t => t.ExplainFixture_Id)
.Index(t => t.PlayerInformationId)
.Index(t => t.Assists_Id)
.Index(t => t.Bonus_Id)
.Index(t => t.Bps_Id)
.Index(t => t.GoalsScored_Id)
.Index(t => t.OwnGoals_Id)
.Index(t => t.PenaltiesMissed_Id)
.Index(t => t.PenaltiesSaved_Id)
.Index(t => t.RedCards_Id)
.Index(t => t.Saves_Id)
.Index(t => t.YellowCards_Id)
.Index(t => t.ExplainFixture_Id);
CreateTable(
"dbo.Assists",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.Homes",
c => new
{
Id = c.Int(nullable: false, identity: true),
Value = c.Int(nullable: false),
Element = c.Int(nullable: false),
PlayerInformationId = c.Int(nullable: false),
Assists_Id = c.Int(),
Bps_Id = c.Int(),
OwnGoals_Id = c.Int(),
PenaltiesMissed_Id = c.Int(),
PenaltiesSaved_Id = c.Int(),
RedCards_Id = c.Int(),
Saves_Id = c.Int(),
YellowCards_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.ForeignKey("dbo.Assists", t => t.Assists_Id)
.ForeignKey("dbo.Bps", t => t.Bps_Id)
.ForeignKey("dbo.OwnGoals", t => t.OwnGoals_Id)
.ForeignKey("dbo.PenaltiesMisseds", t => t.PenaltiesMissed_Id)
.ForeignKey("dbo.PenaltiesSaveds", t => t.PenaltiesSaved_Id)
.ForeignKey("dbo.RedCards", t => t.RedCards_Id)
.ForeignKey("dbo.Saves", t => t.Saves_Id)
.ForeignKey("dbo.YellowCards", t => t.YellowCards_Id)
.Index(t => t.PlayerInformationId)
.Index(t => t.Assists_Id)
.Index(t => t.Bps_Id)
.Index(t => t.OwnGoals_Id)
.Index(t => t.PenaltiesMissed_Id)
.Index(t => t.PenaltiesSaved_Id)
.Index(t => t.RedCards_Id)
.Index(t => t.Saves_Id)
.Index(t => t.YellowCards_Id);
CreateTable(
"dbo.Bps",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.Aways",
c => new
{
Id = c.Int(nullable: false, identity: true),
Value = c.Int(nullable: false),
Element = c.Int(nullable: false),
PlayerInformationId = c.Int(nullable: false),
Bps_Id = c.Int(),
OwnGoals_Id = c.Int(),
PenaltiesMissed_Id = c.Int(),
PenaltiesSaved_Id = c.Int(),
RedCards_Id = c.Int(),
Saves_Id = c.Int(),
YellowCards_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.ForeignKey("dbo.Bps", t => t.Bps_Id)
.ForeignKey("dbo.OwnGoals", t => t.OwnGoals_Id)
.ForeignKey("dbo.PenaltiesMisseds", t => t.PenaltiesMissed_Id)
.ForeignKey("dbo.PenaltiesSaveds", t => t.PenaltiesSaved_Id)
.ForeignKey("dbo.RedCards", t => t.RedCards_Id)
.ForeignKey("dbo.Saves", t => t.Saves_Id)
.ForeignKey("dbo.YellowCards", t => t.YellowCards_Id)
.Index(t => t.PlayerInformationId)
.Index(t => t.Bps_Id)
.Index(t => t.OwnGoals_Id)
.Index(t => t.PenaltiesMissed_Id)
.Index(t => t.PenaltiesSaved_Id)
.Index(t => t.RedCards_Id)
.Index(t => t.Saves_Id)
.Index(t => t.YellowCards_Id);
CreateTable(
"dbo.OwnGoals",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.PenaltiesMisseds",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.PenaltiesSaveds",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.RedCards",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.Saves",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.YellowCards",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.Fixtures",
c => new
{
Id = c.Int(nullable: false, identity: true),
FantasyPremierLeagueId = c.Int(nullable: false),
KickoffTimeFormatted = c.String(),
EventName = c.String(),
OpponentName = c.String(),
OpponentShortName = c.String(),
IsHome = c.Boolean(nullable: false),
Difficulty = c.Int(nullable: false),
Code = c.Int(nullable: false),
KickoffTime = c.DateTime(nullable: false),
Finished = c.Boolean(nullable: false),
Minutes = c.Int(nullable: false),
ProvisionalStartTime = c.Boolean(nullable: false),
FinishedProvisional = c.Boolean(nullable: false),
Event = c.Int(nullable: false),
TeamAway = c.Int(nullable: false),
TeamHome = c.Int(nullable: false),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.FixturesSummaries",
c => new
{
Id = c.Int(nullable: false, identity: true),
FantasyPremierLeagueId = c.Int(nullable: false),
KickoffTimeFormatted = c.String(),
EventName = c.String(),
OpponentName = c.String(),
OpponentShortName = c.String(),
IsHome = c.Boolean(nullable: false),
Difficulty = c.Int(nullable: false),
Code = c.Int(nullable: false),
KickoffTime = c.DateTime(nullable: false),
Finished = c.Boolean(nullable: false),
Minutes = c.Int(nullable: false),
ProvisionalStartTime = c.Boolean(nullable: false),
FinishedProvisional = c.Boolean(nullable: false),
Event = c.Int(nullable: false),
TeamAway = c.Int(nullable: false),
TeamHome = c.Int(nullable: false),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.Histories",
c => new
{
Id = c.Int(nullable: false, identity: true),
FantasyPremierLeagueId = c.Int(nullable: false),
KickoffTime = c.DateTime(nullable: false),
KickoffTimeFormatted = c.String(),
TeamHomeScore = c.Int(nullable: false),
TeamAwayScore = c.Int(nullable: false),
WasHome = c.Boolean(nullable: false),
Round = c.Int(nullable: false),
TotalPoints = c.Int(nullable: false),
Value = c.Int(nullable: false),
TransfersBalance = c.Int(nullable: false),
Selected = c.Int(nullable: false),
TransfersIn = c.Int(nullable: false),
TransfersOut = c.Int(nullable: false),
LoanedIn = c.Int(nullable: false),
LoanedOut = c.Int(nullable: false),
Minutes = c.Int(nullable: false),
GoalsScored = c.Int(nullable: false),
Assists = c.Int(nullable: false),
CleanSheets = c.Int(nullable: false),
GoalsConceded = c.Int(nullable: false),
OwnGoals = c.Int(nullable: false),
PenaltiesSaved = c.Int(nullable: false),
PenaltiesMissed = c.Int(nullable: false),
YellowCards = c.Int(nullable: false),
RedCards = c.Int(nullable: false),
Saves = c.Int(nullable: false),
Bonus = c.Int(nullable: false),
Bps = c.Int(nullable: false),
Influence = c.String(),
Creativity = c.String(),
Threat = c.String(),
IctIndex = c.String(),
EaIndex = c.Int(nullable: false),
OpenPlayCrosses = c.Int(nullable: false),
BigChancesCreated = c.Int(nullable: false),
ClearancesBlocksInterceptions = c.Int(nullable: false),
Recoveries = c.Int(nullable: false),
KeyPasses = c.Int(nullable: false),
Tackles = c.Int(nullable: false),
WinningGoals = c.Int(nullable: false),
AttemptedPasses = c.Int(nullable: false),
CompletedPasses = c.Int(nullable: false),
PenaltiesConceded = c.Int(nullable: false),
BigChancesMissed = c.Int(nullable: false),
ErrorsLeadingToGoal = c.Int(nullable: false),
ErrorsLeadingToGoalAttempt = c.Int(nullable: false),
Tackled = c.Int(nullable: false),
Offside = c.Int(nullable: false),
TargetMissed = c.Int(nullable: false),
Fouls = c.Int(nullable: false),
Dribbles = c.Int(nullable: false),
Element = c.Int(nullable: false),
Fixture = c.Int(nullable: false),
OpponentTeam = c.Int(nullable: false),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
CreateTable(
"dbo.HistorySummaries",
c => new
{
Id = c.Int(nullable: false, identity: true),
FantasyPremierLeagueId = c.Int(nullable: false),
KickoffTime = c.DateTime(nullable: false),
KickoffTimeFormatted = c.String(),
TeamHomeScore = c.Int(nullable: false),
TeamAwayScore = c.Int(nullable: false),
WasHome = c.Boolean(nullable: false),
Round = c.Int(nullable: false),
TotalPoints = c.Int(nullable: false),
Value = c.Int(nullable: false),
TransfersBalance = c.Int(nullable: false),
Selected = c.Int(nullable: false),
TransfersIn = c.Int(nullable: false),
TransfersOut = c.Int(nullable: false),
LoanedIn = c.Int(nullable: false),
LoanedOut = c.Int(nullable: false),
Minutes = c.Int(nullable: false),
GoalsScored = c.Int(nullable: false),
Assists = c.Int(nullable: false),
CleanSheets = c.Int(nullable: false),
GoalsConceded = c.Int(nullable: false),
OwnGoals = c.Int(nullable: false),
PenaltiesSaved = c.Int(nullable: false),
PenaltiesMissed = c.Int(nullable: false),
YellowCards = c.Int(nullable: false),
RedCards = c.Int(nullable: false),
Saves = c.Int(nullable: false),
Bonus = c.Int(nullable: false),
Bps = c.Int(nullable: false),
Influence = c.String(),
Creativity = c.String(),
Threat = c.String(),
IctIndex = c.String(),
EaIndex = c.Int(nullable: false),
OpenPlayCrosses = c.Int(nullable: false),
BigChancesCreated = c.Int(nullable: false),
ClearancesBlocksInterceptions = c.Int(nullable: false),
Recoveries = c.Int(nullable: false),
KeyPasses = c.Int(nullable: false),
Tackles = c.Int(nullable: false),
WinningGoals = c.Int(nullable: false),
AttemptedPasses = c.Int(nullable: false),
CompletedPasses = c.Int(nullable: false),
PenaltiesConceded = c.Int(nullable: false),
BigChancesMissed = c.Int(nullable: false),
ErrorsLeadingToGoal = c.Int(nullable: false),
ErrorsLeadingToGoalAttempt = c.Int(nullable: false),
Tackled = c.Int(nullable: false),
Offside = c.Int(nullable: false),
TargetMissed = c.Int(nullable: false),
Fouls = c.Int(nullable: false),
Dribbles = c.Int(nullable: false),
Element = c.Int(nullable: false),
HistorySummaryFixture = c.Int(nullable: false),
OpponentTeam = c.Int(nullable: false),
PlayerInformationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PlayerInformations", t => t.PlayerInformationId, cascadeDelete: true)
.Index(t => t.PlayerInformationId);
}
public override void Down()
{
DropForeignKey("dbo.HistorySummaries", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.HistoryPasts", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Histories", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.FixturesSummaries", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Fixtures", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Explains", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Explains", "ExplainFixture_Id", "dbo.ExplainFixtures");
DropForeignKey("dbo.Stats", "ExplainFixture_Id", "dbo.ExplainFixtures");
DropForeignKey("dbo.Stats", "YellowCards_Id", "dbo.YellowCards");
DropForeignKey("dbo.YellowCards", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Homes", "YellowCards_Id", "dbo.YellowCards");
DropForeignKey("dbo.Aways", "YellowCards_Id", "dbo.YellowCards");
DropForeignKey("dbo.Stats", "Saves_Id", "dbo.Saves");
DropForeignKey("dbo.Saves", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Homes", "Saves_Id", "dbo.Saves");
DropForeignKey("dbo.Aways", "Saves_Id", "dbo.Saves");
DropForeignKey("dbo.Stats", "RedCards_Id", "dbo.RedCards");
DropForeignKey("dbo.RedCards", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Homes", "RedCards_Id", "dbo.RedCards");
DropForeignKey("dbo.Aways", "RedCards_Id", "dbo.RedCards");
DropForeignKey("dbo.Stats", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Stats", "PenaltiesSaved_Id", "dbo.PenaltiesSaveds");
DropForeignKey("dbo.PenaltiesSaveds", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Homes", "PenaltiesSaved_Id", "dbo.PenaltiesSaveds");
DropForeignKey("dbo.Aways", "PenaltiesSaved_Id", "dbo.PenaltiesSaveds");
DropForeignKey("dbo.Stats", "PenaltiesMissed_Id", "dbo.PenaltiesMisseds");
DropForeignKey("dbo.PenaltiesMisseds", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Homes", "PenaltiesMissed_Id", "dbo.PenaltiesMisseds");
DropForeignKey("dbo.Aways", "PenaltiesMissed_Id", "dbo.PenaltiesMisseds");
DropForeignKey("dbo.Stats", "OwnGoals_Id", "dbo.OwnGoals");
DropForeignKey("dbo.OwnGoals", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Homes", "OwnGoals_Id", "dbo.OwnGoals");
DropForeignKey("dbo.Aways", "OwnGoals_Id", "dbo.OwnGoals");
DropForeignKey("dbo.Stats", "GoalsScored_Id", "dbo.GoalsScoreds");
DropForeignKey("dbo.Stats", "Bps_Id", "dbo.Bps");
DropForeignKey("dbo.Bps", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Homes", "Bps_Id", "dbo.Bps");
DropForeignKey("dbo.Aways", "Bps_Id", "dbo.Bps");
DropForeignKey("dbo.Aways", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Stats", "Bonus_Id", "dbo.Bonus");
DropForeignKey("dbo.Stats", "Assists_Id", "dbo.Assists");
DropForeignKey("dbo.Assists", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Homes", "Assists_Id", "dbo.Assists");
DropForeignKey("dbo.Homes", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.ExplainFixtures", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.Explains", "ExplainDetails_Id", "dbo.ExplainDetails");
DropForeignKey("dbo.ExplainDetails", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.ExplainDetails", "Minutes_Id", "dbo.Minutes");
DropForeignKey("dbo.Minutes", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.ExplainDetails", "GoalsScored_Id", "dbo.GoalsScoreds");
DropForeignKey("dbo.GoalsScoreds", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.ExplainDetails", "CleanSheets_Id", "dbo.CleanSheets");
DropForeignKey("dbo.CleanSheets", "PlayerInformationId", "dbo.PlayerInformations");
DropForeignKey("dbo.ExplainDetails", "Bonus_Id", "dbo.Bonus");
DropForeignKey("dbo.Bonus", "PlayerInformationId", "dbo.PlayerInformations");
DropIndex("dbo.HistorySummaries", new[] { "PlayerInformationId" });
DropIndex("dbo.Histories", new[] { "PlayerInformationId" });
DropIndex("dbo.FixturesSummaries", new[] { "PlayerInformationId" });
DropIndex("dbo.Fixtures", new[] { "PlayerInformationId" });
DropIndex("dbo.YellowCards", new[] { "PlayerInformationId" });
DropIndex("dbo.Saves", new[] { "PlayerInformationId" });
DropIndex("dbo.RedCards", new[] { "PlayerInformationId" });
DropIndex("dbo.PenaltiesSaveds", new[] { "PlayerInformationId" });
DropIndex("dbo.PenaltiesMisseds", new[] { "PlayerInformationId" });
DropIndex("dbo.OwnGoals", new[] { "PlayerInformationId" });
DropIndex("dbo.Aways", new[] { "YellowCards_Id" });
DropIndex("dbo.Aways", new[] { "Saves_Id" });
DropIndex("dbo.Aways", new[] { "RedCards_Id" });
DropIndex("dbo.Aways", new[] { "PenaltiesSaved_Id" });
DropIndex("dbo.Aways", new[] { "PenaltiesMissed_Id" });
DropIndex("dbo.Aways", new[] { "OwnGoals_Id" });
DropIndex("dbo.Aways", new[] { "Bps_Id" });
DropIndex("dbo.Aways", new[] { "PlayerInformationId" });
DropIndex("dbo.Bps", new[] { "PlayerInformationId" });
DropIndex("dbo.Homes", new[] { "YellowCards_Id" });
DropIndex("dbo.Homes", new[] { "Saves_Id" });
DropIndex("dbo.Homes", new[] { "RedCards_Id" });
DropIndex("dbo.Homes", new[] { "PenaltiesSaved_Id" });
DropIndex("dbo.Homes", new[] { "PenaltiesMissed_Id" });
DropIndex("dbo.Homes", new[] { "OwnGoals_Id" });
DropIndex("dbo.Homes", new[] { "Bps_Id" });
DropIndex("dbo.Homes", new[] { "Assists_Id" });
DropIndex("dbo.Homes", new[] { "PlayerInformationId" });
DropIndex("dbo.Assists", new[] { "PlayerInformationId" });
DropIndex("dbo.Stats", new[] { "ExplainFixture_Id" });
DropIndex("dbo.Stats", new[] { "YellowCards_Id" });
DropIndex("dbo.Stats", new[] { "Saves_Id" });
DropIndex("dbo.Stats", new[] { "RedCards_Id" });
DropIndex("dbo.Stats", new[] { "PenaltiesSaved_Id" });
DropIndex("dbo.Stats", new[] { "PenaltiesMissed_Id" });
DropIndex("dbo.Stats", new[] { "OwnGoals_Id" });
DropIndex("dbo.Stats", new[] { "GoalsScored_Id" });
DropIndex("dbo.Stats", new[] { "Bps_Id" });
DropIndex("dbo.Stats", new[] { "Bonus_Id" });
DropIndex("dbo.Stats", new[] { "Assists_Id" });
DropIndex("dbo.Stats", new[] { "PlayerInformationId" });
DropIndex("dbo.ExplainFixtures", new[] { "PlayerInformationId" });
DropIndex("dbo.Minutes", new[] { "PlayerInformationId" });
DropIndex("dbo.GoalsScoreds", new[] { "PlayerInformationId" });
DropIndex("dbo.CleanSheets", new[] { "PlayerInformationId" });
DropIndex("dbo.Bonus", new[] { "PlayerInformationId" });
DropIndex("dbo.ExplainDetails", new[] { "Minutes_Id" });
DropIndex("dbo.ExplainDetails", new[] { "GoalsScored_Id" });
DropIndex("dbo.ExplainDetails", new[] { "CleanSheets_Id" });
DropIndex("dbo.ExplainDetails", new[] { "Bonus_Id" });
DropIndex("dbo.ExplainDetails", new[] { "PlayerInformationId" });
DropIndex("dbo.Explains", new[] { "ExplainFixture_Id" });
DropIndex("dbo.Explains", new[] { "ExplainDetails_Id" });
DropIndex("dbo.Explains", new[] { "PlayerInformationId" });
DropIndex("dbo.HistoryPasts", new[] { "PlayerInformationId" });
DropTable("dbo.HistorySummaries");
DropTable("dbo.Histories");
DropTable("dbo.FixturesSummaries");
DropTable("dbo.Fixtures");
DropTable("dbo.YellowCards");
DropTable("dbo.Saves");
DropTable("dbo.RedCards");
DropTable("dbo.PenaltiesSaveds");
DropTable("dbo.PenaltiesMisseds");
DropTable("dbo.OwnGoals");
DropTable("dbo.Aways");
DropTable("dbo.Bps");
DropTable("dbo.Homes");
DropTable("dbo.Assists");
DropTable("dbo.Stats");
DropTable("dbo.ExplainFixtures");
DropTable("dbo.Minutes");
DropTable("dbo.GoalsScoreds");
DropTable("dbo.CleanSheets");
DropTable("dbo.Bonus");
DropTable("dbo.ExplainDetails");
DropTable("dbo.Explains");
DropTable("dbo.PlayerInformations");
DropTable("dbo.HistoryPasts");
}
}
}
| |
namespace VitaliiPianykh.FileWall.Client
{
partial class RulesetGrid
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RulesetGrid));
DevExpress.XtraGrid.GridLevelNode gridLevelNode1 = new DevExpress.XtraGrid.GridLevelNode();
DevExpress.XtraGrid.GridLevelNode gridLevelNode2 = new DevExpress.XtraGrid.GridLevelNode();
this.gridViewItems = new DevExpress.XtraGrid.Views.Grid.GridView();
this.colID = new DevExpress.XtraGrid.Columns.GridColumn();
this.colItemImage = new DevExpress.XtraGrid.Columns.GridColumn();
this.editorImage = new DevExpress.XtraEditors.Repository.RepositoryItemPictureEdit();
this.colItemName = new DevExpress.XtraGrid.Columns.GridColumn();
this.grid = new DevExpress.XtraGrid.GridControl();
this._ruleSet = new VitaliiPianykh.FileWall.Shared.Ruleset();
this.gridViewCategories = new DevExpress.XtraGrid.Views.Grid.GridView();
this.colCategoryID = new DevExpress.XtraGrid.Columns.GridColumn();
this.colCategoryImage = new DevExpress.XtraGrid.Columns.GridColumn();
this.colCategoryName = new DevExpress.XtraGrid.Columns.GridColumn();
this.colCategoryDescription = new DevExpress.XtraGrid.Columns.GridColumn();
this.editorActionColumn = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();
this.gridViewRules = new DevExpress.XtraGrid.Views.Grid.GridView();
this.colRuleID = new DevExpress.XtraGrid.Columns.GridColumn();
this.colRuleName = new DevExpress.XtraGrid.Columns.GridColumn();
this.colProtectedPath = new DevExpress.XtraGrid.Columns.GridColumn();
this.colProcessPath = new DevExpress.XtraGrid.Columns.GridColumn();
this.colAction = new DevExpress.XtraGrid.Columns.GridColumn();
((System.ComponentModel.ISupportInitialize)(this.gridViewItems)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.editorImage)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.grid)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this._ruleSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.gridViewCategories)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.editorActionColumn)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.gridViewRules)).BeginInit();
this.SuspendLayout();
//
// gridViewItems
//
this.gridViewItems.Appearance.FocusedCell.BackColor = System.Drawing.Color.LightSteelBlue;
this.gridViewItems.Appearance.FocusedCell.Options.UseBackColor = true;
this.gridViewItems.Appearance.FocusedRow.BackColor = System.Drawing.Color.LightSteelBlue;
this.gridViewItems.Appearance.FocusedRow.Options.UseBackColor = true;
this.gridViewItems.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
this.colID,
this.colItemImage,
this.colItemName});
this.gridViewItems.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
this.gridViewItems.GridControl = this.grid;
this.gridViewItems.Name = "gridViewItems";
this.gridViewItems.OptionsBehavior.AutoPopulateColumns = false;
this.gridViewItems.OptionsDetail.ShowDetailTabs = false;
this.gridViewItems.OptionsSelection.EnableAppearanceFocusedCell = false;
this.gridViewItems.OptionsView.EnableAppearanceEvenRow = true;
this.gridViewItems.OptionsView.EnableAppearanceOddRow = true;
this.gridViewItems.OptionsView.ShowColumnHeaders = false;
this.gridViewItems.OptionsView.ShowGroupPanel = false;
this.gridViewItems.OptionsView.ShowIndicator = false;
this.gridViewItems.OptionsView.ShowVertLines = false;
this.gridViewItems.RowHeight = 32;
this.gridViewItems.CustomUnboundColumnData += new DevExpress.XtraGrid.Views.Base.CustomColumnDataEventHandler(this.gridViewItems_CustomUnboundColumnData);
//
// colID
//
resources.ApplyResources(this.colID, "colID");
this.colID.FieldName = "ID";
this.colID.Name = "colID";
//
// colItemImage
//
resources.ApplyResources(this.colItemImage, "colItemImage");
this.colItemImage.ColumnEdit = this.editorImage;
this.colItemImage.FieldName = "colItemImage";
this.colItemImage.Name = "colItemImage";
this.colItemImage.OptionsColumn.AllowFocus = false;
this.colItemImage.OptionsColumn.FixedWidth = true;
this.colItemImage.UnboundType = DevExpress.Data.UnboundColumnType.Object;
//
// editorImage
//
this.editorImage.Name = "editorImage";
this.editorImage.PictureStoreMode = DevExpress.XtraEditors.Controls.PictureStoreMode.ByteArray;
this.editorImage.ShowMenu = false;
this.editorImage.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom;
//
// colItemName
//
resources.ApplyResources(this.colItemName, "colItemName");
this.colItemName.FieldName = "Name";
this.colItemName.Name = "colItemName";
this.colItemName.OptionsColumn.AllowFocus = false;
//
// grid
//
resources.ApplyResources(this.grid, "grid");
this.grid.DataSource = this._ruleSet;
gridLevelNode1.LevelTemplate = this.gridViewItems;
gridLevelNode2.LevelTemplate = this.gridViewRules;
gridLevelNode2.RelationName = "FK_Items_Rules";
gridLevelNode1.Nodes.AddRange(new DevExpress.XtraGrid.GridLevelNode[] {
gridLevelNode2});
gridLevelNode1.RelationName = "FK_Categories_Items";
this.grid.LevelTree.Nodes.AddRange(new DevExpress.XtraGrid.GridLevelNode[] {
gridLevelNode1});
this.grid.MainView = this.gridViewCategories;
this.grid.Name = "grid";
this.grid.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] {
this.editorImage,
this.editorActionColumn});
this.grid.ShowOnlyPredefinedDetails = true;
this.grid.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] {
this.gridViewCategories,
this.gridViewRules,
this.gridViewItems});
//
// _ruleSet
//
this._ruleSet.DataSetName = "Ruleset";
this._ruleSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// gridViewCategories
//
this.gridViewCategories.Appearance.FocusedCell.BackColor = System.Drawing.Color.LightSteelBlue;
this.gridViewCategories.Appearance.FocusedCell.Options.UseBackColor = true;
this.gridViewCategories.Appearance.FocusedRow.BackColor = System.Drawing.Color.LightSteelBlue;
this.gridViewCategories.Appearance.FocusedRow.Options.UseBackColor = true;
this.gridViewCategories.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
this.colCategoryID,
this.colCategoryImage,
this.colCategoryName,
this.colCategoryDescription});
this.gridViewCategories.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
this.gridViewCategories.GridControl = this.grid;
this.gridViewCategories.Name = "gridViewCategories";
this.gridViewCategories.OptionsBehavior.AutoPopulateColumns = false;
this.gridViewCategories.OptionsDetail.ShowDetailTabs = false;
this.gridViewCategories.OptionsSelection.EnableAppearanceFocusedCell = false;
this.gridViewCategories.OptionsView.EnableAppearanceEvenRow = true;
this.gridViewCategories.OptionsView.EnableAppearanceOddRow = true;
this.gridViewCategories.OptionsView.ShowColumnHeaders = false;
this.gridViewCategories.OptionsView.ShowGroupPanel = false;
this.gridViewCategories.OptionsView.ShowIndicator = false;
this.gridViewCategories.OptionsView.ShowVertLines = false;
this.gridViewCategories.RowHeight = 32;
this.gridViewCategories.CustomUnboundColumnData += new DevExpress.XtraGrid.Views.Base.CustomColumnDataEventHandler(this.gridViewCategories_CustomUnboundColumnData);
//
// colCategoryID
//
resources.ApplyResources(this.colCategoryID, "colCategoryID");
this.colCategoryID.FieldName = "ID";
this.colCategoryID.Name = "colCategoryID";
this.colCategoryID.OptionsColumn.AllowFocus = false;
//
// colCategoryImage
//
resources.ApplyResources(this.colCategoryImage, "colCategoryImage");
this.colCategoryImage.ColumnEdit = this.editorImage;
this.colCategoryImage.FieldName = "colCategoryImage";
this.colCategoryImage.Name = "colCategoryImage";
this.colCategoryImage.OptionsColumn.AllowFocus = false;
this.colCategoryImage.OptionsColumn.FixedWidth = true;
this.colCategoryImage.UnboundType = DevExpress.Data.UnboundColumnType.Object;
//
// colCategoryName
//
resources.ApplyResources(this.colCategoryName, "colCategoryName");
this.colCategoryName.FieldName = "Name";
this.colCategoryName.Name = "colCategoryName";
this.colCategoryName.OptionsColumn.AllowFocus = false;
//
// colCategoryDescription
//
resources.ApplyResources(this.colCategoryDescription, "colCategoryDescription");
this.colCategoryDescription.FieldName = "Description";
this.colCategoryDescription.Name = "colCategoryDescription";
this.colCategoryDescription.OptionsColumn.AllowFocus = false;
//
// editorActionColumn
//
this.editorActionColumn.AllowGrayed = true;
resources.ApplyResources(this.editorActionColumn, "editorActionColumn");
this.editorActionColumn.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.UserDefined;
this.editorActionColumn.Name = "editorActionColumn";
this.editorActionColumn.PictureChecked = global::VitaliiPianykh.FileWall.Client.Properties.Resources.AllowAccess;
this.editorActionColumn.PictureGrayed = global::VitaliiPianykh.FileWall.Client.Properties.Resources.AlwaysAsk;
this.editorActionColumn.PictureUnchecked = global::VitaliiPianykh.FileWall.Client.Properties.Resources.BlockAccess;
this.editorActionColumn.ValueChecked = 1;
this.editorActionColumn.ValueGrayed = -1;
this.editorActionColumn.ValueUnchecked = 0;
this.editorActionColumn.QueryCheckStateByValue += new DevExpress.XtraEditors.Controls.QueryCheckStateByValueEventHandler(this.editorActionColumn_QueryCheckStateByValue);
//
// gridViewRules
//
this.gridViewRules.Appearance.FocusedCell.BackColor = System.Drawing.Color.LightSteelBlue;
this.gridViewRules.Appearance.FocusedCell.Options.UseBackColor = true;
this.gridViewRules.Appearance.FocusedRow.BackColor = System.Drawing.Color.LightSteelBlue;
this.gridViewRules.Appearance.FocusedRow.Options.UseBackColor = true;
this.gridViewRules.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
this.colRuleID,
this.colRuleName,
this.colProtectedPath,
this.colProcessPath,
this.colAction});
this.gridViewRules.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
this.gridViewRules.GridControl = this.grid;
this.gridViewRules.Name = "gridViewRules";
this.gridViewRules.OptionsBehavior.AutoPopulateColumns = false;
this.gridViewRules.OptionsSelection.EnableAppearanceFocusedCell = false;
this.gridViewRules.OptionsView.EnableAppearanceEvenRow = true;
this.gridViewRules.OptionsView.EnableAppearanceOddRow = true;
this.gridViewRules.OptionsView.ShowGroupPanel = false;
this.gridViewRules.OptionsView.ShowIndicator = false;
this.gridViewRules.OptionsView.ShowVertLines = false;
this.gridViewRules.CustomUnboundColumnData += new DevExpress.XtraGrid.Views.Base.CustomColumnDataEventHandler(this.gridViewRules_CustomUnboundColumnData);
this.gridViewRules.DoubleClick += new System.EventHandler(this.gridViewRules_DoubleClick);
this.gridViewRules.MouseDown += new System.Windows.Forms.MouseEventHandler(this.gridViewRules_MouseDown);
//
// colRuleID
//
resources.ApplyResources(this.colRuleID, "colRuleID");
this.colRuleID.FieldName = "ID";
this.colRuleID.Name = "colRuleID";
//
// colRuleName
//
resources.ApplyResources(this.colRuleName, "colRuleName");
this.colRuleName.FieldName = "Name";
this.colRuleName.Name = "colRuleName";
this.colRuleName.OptionsColumn.AllowFocus = false;
//
// colProtectedPath
//
this.colProtectedPath.AppearanceCell.Options.UseTextOptions = true;
this.colProtectedPath.AppearanceCell.TextOptions.Trimming = DevExpress.Utils.Trimming.EllipsisPath;
resources.ApplyResources(this.colProtectedPath, "colProtectedPath");
this.colProtectedPath.FieldName = "ProtectedPath";
this.colProtectedPath.Name = "colProtectedPath";
this.colProtectedPath.OptionsColumn.AllowFocus = false;
this.colProtectedPath.UnboundType = DevExpress.Data.UnboundColumnType.String;
//
// colProcessPath
//
this.colProcessPath.AppearanceCell.Options.UseTextOptions = true;
this.colProcessPath.AppearanceCell.TextOptions.Trimming = DevExpress.Utils.Trimming.EllipsisPath;
resources.ApplyResources(this.colProcessPath, "colProcessPath");
this.colProcessPath.FieldName = "ProcessPath";
this.colProcessPath.Name = "colProcessPath";
this.colProcessPath.OptionsColumn.AllowFocus = false;
this.colProcessPath.UnboundType = DevExpress.Data.UnboundColumnType.String;
//
// colAction
//
resources.ApplyResources(this.colAction, "colAction");
this.colAction.ColumnEdit = this.editorActionColumn;
this.colAction.FieldName = "Action";
this.colAction.Name = "colAction";
this.colAction.OptionsColumn.AllowFocus = false;
//
// RulesetGrid
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.grid);
this.Name = "RulesetGrid";
((System.ComponentModel.ISupportInitialize)(this.gridViewItems)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.editorImage)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.grid)).EndInit();
((System.ComponentModel.ISupportInitialize)(this._ruleSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.gridViewCategories)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.editorActionColumn)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.gridViewRules)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraEditors.Repository.RepositoryItemPictureEdit editorImage;
private DevExpress.XtraGrid.Views.Grid.GridView gridViewRules;
private DevExpress.XtraGrid.Columns.GridColumn colRuleName;
private DevExpress.XtraGrid.Columns.GridColumn colProtectedPath;
private DevExpress.XtraGrid.Columns.GridColumn colProcessPath;
private DevExpress.XtraGrid.Columns.GridColumn colAction;
private DevExpress.XtraGrid.GridControl grid;
private VitaliiPianykh.FileWall.Shared.Ruleset _ruleSet;
private DevExpress.XtraGrid.Views.Grid.GridView gridViewItems;
private DevExpress.XtraGrid.Columns.GridColumn colItemImage;
private DevExpress.XtraGrid.Columns.GridColumn colItemName;
private DevExpress.XtraGrid.Views.Grid.GridView gridViewCategories;
private DevExpress.XtraGrid.Columns.GridColumn colCategoryID;
private DevExpress.XtraGrid.Columns.GridColumn colCategoryName;
private DevExpress.XtraGrid.Columns.GridColumn colCategoryImage;
private DevExpress.XtraGrid.Columns.GridColumn colCategoryDescription;
private DevExpress.XtraGrid.Columns.GridColumn colID;
private DevExpress.XtraGrid.Columns.GridColumn colRuleID;
private DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit editorActionColumn;
}
}
| |
//---------------------------------------------------------------------
// <copyright file="AtomEntry.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Provides a class to represent an ATOM entry as parsed and as it
// goes through the materialization pipeline.
// </summary>
//---------------------------------------------------------------------
namespace System.Data.Services.Client
{
#region Namespaces.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
using System.Text;
#endregion Namespaces.
/// <summary>
/// Use this class to represent an entry in an ATOM payload as it
/// goes through the WCF Data Services materialization pipeline.
/// </summary>
/// <remarks>
/// Different properties are set on instances of this type at different
/// points during its lifetime.
/// </remarks>
[DebuggerDisplay("AtomEntry {ResolvedObject} @ {Identity}")]
internal class AtomEntry
{
#region Private fields.
/// <summary>Entry flags.</summary>
private EntryFlags flags;
/// <summary>
/// Masks used get/set the status of the entry
/// </summary>
[Flags]
private enum EntryFlags
{
/// <summary>Bitmask for ShouldUpdateFromPayload flag.</summary>
ShouldUpdateFromPayload = 0x01,
/// <summary>Bitmask for CreatedByMaterializer flag.</summary>
CreatedByMaterializer = 0x02,
/// <summary>Bitmask for EntityHasBeenResolved flag.</summary>
EntityHasBeenResolved = 0x04,
/// <summary>Bitmask for MediaLinkEntry flag (value).</summary>
MediaLinkEntryValue = 0x08,
/// <summary>Bitmask for MediaLinkEntry flag (assigned/non-null state).</summary>
MediaLinkEntryAssigned = 0x10,
/// <summary>Bitmask for EntityPropertyMappingsApplied flag.</summary>
EntityPropertyMappingsApplied = 0x20,
/// <summary>Bitmask for IsNull flag.</summary>
IsNull = 0x40
}
#endregion Private fields.
#region Public properties.
/// <summary>MediaLinkEntry. Valid after data values applies.</summary>
public bool? MediaLinkEntry
{
get
{
return this.GetFlagValue(EntryFlags.MediaLinkEntryAssigned) ? (bool?)this.GetFlagValue(EntryFlags.MediaLinkEntryValue) : null;
}
set
{
Debug.Assert(value.HasValue, "value.HasValue -- callers shouldn't set the value to unknown");
this.SetFlagValue(EntryFlags.MediaLinkEntryAssigned, true);
this.SetFlagValue(EntryFlags.MediaLinkEntryValue, value.Value);
}
}
/// <summary>URI for media content. null if MediaLinkEntry is false.</summary>
public Uri MediaContentUri
{
get;
set;
}
/// <summary>URI for editing media. null if MediaLinkEntry is false.</summary>
public Uri MediaEditUri
{
get;
set;
}
/// <summary>Type name, as present in server payload.</summary>
public string TypeName
{
get;
set;
}
/// <summary>Actual type of the ResolvedObject.</summary>
public ClientType ActualType
{
get;
set;
}
/// <summary>Edit link for the ATOM entry - basically link used to update the entity.</summary>
public Uri EditLink
{
get;
set;
}
/// <summary>Self link for the ATOM entry - basically link used to query the entity.</summary>
public Uri QueryLink
{
get;
set;
}
/// <summary>
/// Identity link for the ATOM entry.
/// This is set by the parser (guaranteed, fails to parser if not available on entry).
/// </summary>
public string Identity
{
get;
set;
}
/// <summary>
/// Whether the entry is a null.
/// This is set by the parser only on inlined entries, as it's invalid ATOM in
/// top-level cases.
/// </summary>
public bool IsNull
{
get { return this.GetFlagValue(EntryFlags.IsNull); }
set { this.SetFlagValue(EntryFlags.IsNull, value); }
}
/// <summary>Data names and values.</summary>
public List<AtomContentProperty> DataValues
{
get;
set;
}
/// <summary>Resolved object.</summary>
public object ResolvedObject
{
get;
set;
}
/// <summary>Tag for the entry, set by the parser when an entry callback is invoked.</summary>
public object Tag
{
get;
set;
}
/// <summary>Text for Etag, possibly null.</summary>
public string ETagText
{
get;
set;
}
/// <summary>Text for ETag corresponding to media resource for this entry.</summary>
public string StreamETagText
{
get;
set;
}
/// <summary>Whether values should be updated from payload.</summary>
public bool ShouldUpdateFromPayload
{
get { return this.GetFlagValue(EntryFlags.ShouldUpdateFromPayload); }
set { this.SetFlagValue(EntryFlags.ShouldUpdateFromPayload, value); }
}
/// <summary>Whether the materializer has created the ResolvedObject instance.</summary>
public bool CreatedByMaterializer
{
get { return this.GetFlagValue(EntryFlags.CreatedByMaterializer); }
set { this.SetFlagValue(EntryFlags.CreatedByMaterializer, value); }
}
/// <summary>Whether the entity has been resolved / created.</summary>
public bool EntityHasBeenResolved
{
get { return this.GetFlagValue(EntryFlags.EntityHasBeenResolved); }
set { this.SetFlagValue(EntryFlags.EntityHasBeenResolved, value); }
}
/// <summary>Whether entity Property Mappings (a.k.a. friendly feeds) have been applied to this entry if applicable.</summary>
public bool EntityPropertyMappingsApplied
{
get { return this.GetFlagValue(EntryFlags.EntityPropertyMappingsApplied); }
set { this.SetFlagValue(EntryFlags.EntityPropertyMappingsApplied, value); }
}
#endregion Public properties.
#region Private methods.
/// <summary>Gets the value for a masked item.</summary>
/// <param name="mask">Mask value.</param>
/// <returns>true if the flag is set; false otherwise.</returns>
private bool GetFlagValue(EntryFlags mask)
{
return (this.flags & mask) != 0;
}
/// <summary>Sets the value for a masked item.</summary>
/// <param name="mask">Mask value.</param>
/// <param name="value">Value to set</param>
private void SetFlagValue(EntryFlags mask, bool value)
{
if (value)
{
this.flags |= mask;
}
else
{
this.flags &= (~mask);
}
}
#endregion Private methods.
}
}
| |
// 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.Runtime.InteropServices;
using System.Security.Cryptography;
namespace System.Security
{
public sealed partial class SecureString
{
internal SecureString(SecureString str)
{
Debug.Assert(str != null, "Expected non-null SecureString");
Debug.Assert(str._buffer != null, "Expected other SecureString's buffer to be non-null");
Debug.Assert(str._encrypted, "Expected to be used only on encrypted SecureStrings");
AllocateBuffer(str._buffer.Length);
SafeBSTRHandle.Copy(str._buffer, _buffer, str._buffer.Length * sizeof(char));
_decryptedLength = str._decryptedLength;
_encrypted = str._encrypted;
}
private unsafe void InitializeSecureString(char* value, int length)
{
Debug.Assert(length >= 0, $"Expected non-negative length, got {length}");
AllocateBuffer((uint)length);
_decryptedLength = length;
byte* bufferPtr = null;
try
{
_buffer.AcquirePointer(ref bufferPtr);
Buffer.MemoryCopy((byte*)value, bufferPtr, (long)_buffer.ByteLength, length * sizeof(char));
}
finally
{
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
ProtectMemory();
}
private void AppendCharCore(char c)
{
UnprotectMemory();
try
{
EnsureCapacity(_decryptedLength + 1);
_buffer.Write<char>((uint)_decryptedLength * sizeof(char), c);
_decryptedLength++;
}
finally
{
ProtectMemory();
}
}
private void ClearCore()
{
_decryptedLength = 0;
_buffer.ClearBuffer();
}
private void DisposeCore()
{
if (_buffer != null)
{
_buffer.Dispose();
_buffer = null;
}
}
private unsafe void InsertAtCore(int index, char c)
{
byte* bufferPtr = null;
UnprotectMemory();
try
{
EnsureCapacity(_decryptedLength + 1);
_buffer.AcquirePointer(ref bufferPtr);
char* pBuffer = (char*)bufferPtr;
for (int i = _decryptedLength; i > index; i--)
{
pBuffer[i] = pBuffer[i - 1];
}
pBuffer[index] = c;
++_decryptedLength;
}
finally
{
ProtectMemory();
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
}
private unsafe void RemoveAtCore(int index)
{
byte* bufferPtr = null;
UnprotectMemory();
try
{
_buffer.AcquirePointer(ref bufferPtr);
char* pBuffer = (char*)bufferPtr;
for (int i = index; i < _decryptedLength - 1; i++)
{
pBuffer[i] = pBuffer[i + 1];
}
pBuffer[--_decryptedLength] = (char)0;
}
finally
{
ProtectMemory();
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
}
private void SetAtCore(int index, char c)
{
UnprotectMemory();
try
{
_buffer.Write<char>((uint)index * sizeof(char), c);
}
finally
{
ProtectMemory();
}
}
internal unsafe IntPtr MarshalToStringCore(bool globalAlloc, bool unicode)
{
int length = _decryptedLength;
IntPtr ptr = IntPtr.Zero;
IntPtr result = IntPtr.Zero;
byte* bufferPtr = null;
UnprotectMemory();
try
{
_buffer.AcquirePointer(ref bufferPtr);
if (unicode)
{
int resultByteLength = (length + 1) * sizeof(char);
ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength);
Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char));
*(length + (char*)ptr) = '\0';
}
else
{
uint defaultChar = '?';
int resultByteLength = 1 + Interop.mincore.WideCharToMultiByte(
Interop.mincore.CP_ACP, Interop.mincore.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, null, 0, (IntPtr)(&defaultChar), IntPtr.Zero);
ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength);
Interop.mincore.WideCharToMultiByte(
Interop.mincore.CP_ACP, Interop.mincore.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, (byte*)ptr, resultByteLength - 1, (IntPtr)(&defaultChar), IntPtr.Zero);
*(resultByteLength - 1 + (byte*)ptr) = 0;
}
result = ptr;
}
finally
{
ProtectMemory();
// If we failed for any reason, free the new buffer
if (result == IntPtr.Zero && ptr != IntPtr.Zero)
{
Interop.NtDll.ZeroMemory(ptr, (UIntPtr)(length * sizeof(char)));
MarshalFree(ptr, globalAlloc);
}
if (bufferPtr != null)
{
_buffer.ReleasePointer();
}
}
return result;
}
private void EnsureNotDisposed()
{
if (_buffer == null)
{
throw new ObjectDisposedException(GetType().Name);
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private const int BlockSize = (int)Interop.Crypt32.CRYPTPROTECTMEMORY_BLOCK_SIZE / sizeof(char);
private SafeBSTRHandle _buffer;
private bool _encrypted;
private void AllocateBuffer(uint size)
{
_buffer = SafeBSTRHandle.Allocate(GetAlignedSize(size));
}
private static uint GetAlignedSize(uint size) =>
size == 0 || size % BlockSize != 0 ?
BlockSize + ((size / BlockSize) * BlockSize) :
size;
private void EnsureCapacity(int capacity)
{
if (capacity > MaxLength)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity);
}
if (((uint)capacity * sizeof(char)) <= _buffer.ByteLength)
{
return;
}
var oldBuffer = _buffer;
SafeBSTRHandle newBuffer = SafeBSTRHandle.Allocate(GetAlignedSize((uint)capacity));
SafeBSTRHandle.Copy(oldBuffer, newBuffer, (uint)_decryptedLength * sizeof(char));
_buffer = newBuffer;
oldBuffer.Dispose();
}
private void ProtectMemory()
{
Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!");
if (_decryptedLength != 0 &&
!_encrypted &&
!Interop.Crypt32.CryptProtectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS))
{
throw new CryptographicException(Marshal.GetLastWin32Error());
}
_encrypted = true;
}
private void UnprotectMemory()
{
Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!");
if (_decryptedLength != 0 &&
_encrypted &&
!Interop.Crypt32.CryptUnprotectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS))
{
throw new CryptographicException(Marshal.GetLastWin32Error());
}
_encrypted = false;
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET //
// Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See license-pdn.txt for full licensing and attribution details. //
// //
// Ported to Pinta by: Jonathan Pobst <monkey@jpobst.com> //
/////////////////////////////////////////////////////////////////////////////////
using System;
using Cairo;
using Pinta.Core;
using Mono.Unix;
namespace Pinta.Effects
{
public class GaussianBlurEffect
{
public static int[] CreateGaussianBlurRow (int amount)
{
int size = 1 + (amount * 2);
int[] weights = new int[size];
for (int i = 0; i <= amount; ++i) {
// 1 + aa - aa + 2ai - ii
weights[i] = 16 * (i + 1);
weights[weights.Length - i - 1] = weights[i];
}
return weights;
}
unsafe public static void RenderBlurEffect (ImageSurface src, ImageSurface dest, Gdk.Rectangle[] rois, int radius)
{
int r = radius;
int[] w = CreateGaussianBlurRow (r);
int wlen = w.Length;
int localStoreSize = wlen * 6 * sizeof (long);
byte* localStore = stackalloc byte[localStoreSize];
byte* p = localStore;
long* waSums = (long*)p;
p += wlen * sizeof (long);
long* wcSums = (long*)p;
p += wlen * sizeof (long);
long* aSums = (long*)p;
p += wlen * sizeof (long);
long* bSums = (long*)p;
p += wlen * sizeof (long);
long* gSums = (long*)p;
p += wlen * sizeof (long);
long* rSums = (long*)p;
p += wlen * sizeof (long);
// Cache these for a massive performance boost
int src_width = src.Width;
int src_height = src.Height;
ColorBgra* src_data_ptr = (ColorBgra*)src.DataPtr;
foreach (Gdk.Rectangle rect in rois) {
if (rect.Height >= 1 && rect.Width >= 1) {
for (int y = rect.Top; y < rect.Bottom; ++y) {
//Memory.SetToZero (localStore, (ulong)localStoreSize);
long waSum = 0;
long wcSum = 0;
long aSum = 0;
long bSum = 0;
long gSum = 0;
long rSum = 0;
ColorBgra* dstPtr = dest.GetPointAddressUnchecked (rect.Left, y);
for (int wx = 0; wx < wlen; ++wx) {
int srcX = rect.Left + wx - r;
waSums[wx] = 0;
wcSums[wx] = 0;
aSums[wx] = 0;
bSums[wx] = 0;
gSums[wx] = 0;
rSums[wx] = 0;
if (srcX >= 0 && srcX < src_width) {
for (int wy = 0; wy < wlen; ++wy) {
int srcY = y + wy - r;
if (srcY >= 0 && srcY < src_height) {
ColorBgra c = src.GetPointUnchecked (src_data_ptr, src_width, srcX, srcY);
int wp = w[wy];
waSums[wx] += wp;
wp *= c.A + (c.A >> 7);
wcSums[wx] += wp;
wp >>= 8;
aSums[wx] += wp * c.A;
bSums[wx] += wp * c.B;
gSums[wx] += wp * c.G;
rSums[wx] += wp * c.R;
}
}
int wwx = w[wx];
waSum += wwx * waSums[wx];
wcSum += wwx * wcSums[wx];
aSum += wwx * aSums[wx];
bSum += wwx * bSums[wx];
gSum += wwx * gSums[wx];
rSum += wwx * rSums[wx];
}
}
wcSum >>= 8;
if (waSum == 0 || wcSum == 0) {
dstPtr->Bgra = 0;
} else {
int alpha = (int)(aSum / waSum);
int blue = (int)(bSum / wcSum);
int green = (int)(gSum / wcSum);
int red = (int)(rSum / wcSum);
dstPtr->Bgra = ColorBgra.BgraToUInt32 (blue, green, red, alpha);
}
++dstPtr;
for (int x = rect.Left + 1; x < rect.Right; ++x) {
for (int i = 0; i < wlen - 1; ++i) {
waSums[i] = waSums[i + 1];
wcSums[i] = wcSums[i + 1];
aSums[i] = aSums[i + 1];
bSums[i] = bSums[i + 1];
gSums[i] = gSums[i + 1];
rSums[i] = rSums[i + 1];
}
waSum = 0;
wcSum = 0;
aSum = 0;
bSum = 0;
gSum = 0;
rSum = 0;
int wx;
for (wx = 0; wx < wlen - 1; ++wx) {
long wwx = (long)w[wx];
waSum += wwx * waSums[wx];
wcSum += wwx * wcSums[wx];
aSum += wwx * aSums[wx];
bSum += wwx * bSums[wx];
gSum += wwx * gSums[wx];
rSum += wwx * rSums[wx];
}
wx = wlen - 1;
waSums[wx] = 0;
wcSums[wx] = 0;
aSums[wx] = 0;
bSums[wx] = 0;
gSums[wx] = 0;
rSums[wx] = 0;
int srcX = x + wx - r;
if (srcX >= 0 && srcX < src_width) {
for (int wy = 0; wy < wlen; ++wy) {
int srcY = y + wy - r;
if (srcY >= 0 && srcY < src_height) {
ColorBgra c = src.GetPointUnchecked (src_data_ptr, src_width, srcX, srcY);
int wp = w[wy];
waSums[wx] += wp;
wp *= c.A + (c.A >> 7);
wcSums[wx] += wp;
wp >>= 8;
aSums[wx] += wp * (long)c.A;
bSums[wx] += wp * (long)c.B;
gSums[wx] += wp * (long)c.G;
rSums[wx] += wp * (long)c.R;
}
}
int wr = w[wx];
waSum += (long)wr * waSums[wx];
wcSum += (long)wr * wcSums[wx];
aSum += (long)wr * aSums[wx];
bSum += (long)wr * bSums[wx];
gSum += (long)wr * gSums[wx];
rSum += (long)wr * rSums[wx];
}
wcSum >>= 8;
if (waSum == 0 || wcSum == 0) {
dstPtr->Bgra = 0;
} else {
int alpha = (int)(aSum / waSum);
int blue = (int)(bSum / wcSum);
int green = (int)(gSum / wcSum);
int red = (int)(rSum / wcSum);
dstPtr->Bgra = ColorBgra.BgraToUInt32 (blue, green, red, alpha);
}
++dstPtr;
}
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public static class CommandCancelTest
{
// Shrink the packet size - this should make timeouts more likely
private static readonly string s_connStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { PacketSize = 512 }).ConnectionString;
[CheckConnStrSetupFact]
public static void PlainCancelTest()
{
PlainCancel(s_connStr);
}
[CheckConnStrSetupFact]
public static void PlainMARSCancelTest()
{
PlainCancel((new SqlConnectionStringBuilder(s_connStr) { MultipleActiveResultSets = true }).ConnectionString);
}
[CheckConnStrSetupFact]
public static void PlainCancelTestAsync()
{
PlainCancelAsync(s_connStr);
}
[CheckConnStrSetupFact]
public static void PlainMARSCancelTestAsync()
{
PlainCancelAsync((new SqlConnectionStringBuilder(s_connStr) { MultipleActiveResultSets = true }).ConnectionString);
}
private static void PlainCancel(string connString)
{
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("select * from dbo.Orders; waitfor delay '00:00:10'; select * from dbo.Orders", conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
cmd.Cancel();
DataTestUtility.AssertThrowsWrapper<SqlException>(
() =>
{
do
{
while (reader.Read())
{
}
}
while (reader.NextResult());
},
"A severe error occurred on the current command. The results, if any, should be discarded.");
}
}
}
private static void PlainCancelAsync(string connString)
{
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("select * from dbo.Orders; waitfor delay '00:00:10'; select * from dbo.Orders", conn))
{
conn.Open();
Task<SqlDataReader> readerTask = cmd.ExecuteReaderAsync();
DataTestUtility.AssertThrowsWrapper<SqlException>(
() =>
{
readerTask.Wait(2000);
SqlDataReader reader = readerTask.Result;
cmd.Cancel();
do
{
while (reader.Read())
{
}
}
while (reader.NextResult());
},
"A severe error occurred on the current command. The results, if any, should be discarded.");
}
}
[CheckConnStrSetupFact]
public static void MultiThreadedCancel_NonAsync()
{
MultiThreadedCancel(s_connStr, false);
}
[CheckConnStrSetupFact]
public static void MultiThreadedCancel_Async()
{
MultiThreadedCancel(s_connStr, true);
}
[CheckConnStrSetupFact]
public static void TimeoutCancel()
{
TimeoutCancel(s_connStr);
}
[CheckConnStrSetupFact]
public static void CancelAndDisposePreparedCommand()
{
CancelAndDisposePreparedCommand(s_connStr);
}
[CheckConnStrSetupFact]
public static void TimeOutDuringRead()
{
TimeOutDuringRead(s_connStr);
}
private static void MultiThreadedCancel(string constr, bool async)
{
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
var command = con.CreateCommand();
command.CommandText = "select * from orders; waitfor delay '00:00:08'; select * from customers";
Barrier threadsReady = new Barrier(2);
object state = new Tuple<bool, SqlCommand, Barrier>(async, command, threadsReady);
Task[] tasks = new Task[2];
tasks[0] = new Task(ExecuteCommandCancelExpected, state);
tasks[1] = new Task(CancelSharedCommand, state);
tasks[0].Start();
tasks[1].Start();
Task.WaitAll(tasks, 15 * 1000);
CommandCancelTest.VerifyConnection(command);
}
}
private static void TimeoutCancel(string constr)
{
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandTimeout = 1;
cmd.CommandText = "WAITFOR DELAY '00:00:30';select * from Customers";
string errorMessage = SystemDataResourceManager.Instance.SQL_Timeout;
DataTestUtility.ExpectFailure<SqlException>(() => cmd.ExecuteReader(), new string[] { errorMessage });
VerifyConnection(cmd);
}
}
//InvalidOperationException from connection.Dispose if that connection has prepared command cancelled during reading of data
private static void CancelAndDisposePreparedCommand(string constr)
{
int expectedValue = 1;
using (var connection = new SqlConnection(constr))
{
try
{
// Generate a query with a large number of results.
using (var command = new SqlCommand("select @P from sysobjects a cross join sysobjects b cross join sysobjects c cross join sysobjects d cross join sysobjects e cross join sysobjects f", connection))
{
command.Parameters.Add(new SqlParameter("@P", SqlDbType.Int) { Value = expectedValue });
connection.Open();
// Prepare the query.
// Currently this does nothing until command.ExecuteReader is called.
// Ideally this should call sp_prepare up-front.
command.Prepare();
using (var reader = command.ExecuteReader(CommandBehavior.SingleResult))
{
if (reader.Read())
{
int actualValue = reader.GetInt32(0);
Assert.True(actualValue == expectedValue, string.Format("Got incorrect value. Expected: {0}, Actual: {1}", expectedValue, actualValue));
}
// Abandon reading the results.
command.Cancel();
}
}
}
finally
{
connection.Dispose(); // before the fix, InvalidOperationException happened here
}
}
}
private static void VerifyConnection(SqlCommand cmd)
{
Assert.True(cmd.Connection.State == ConnectionState.Open, "FAILURE: - unexpected non-open state after Execute!");
cmd.CommandText = "select 'ABC'"; // Verify Connection
string value = (string)cmd.ExecuteScalar();
Assert.True(value == "ABC", "FAILURE: upon validation execute on connection: '" + value + "'");
}
private static void ExecuteCommandCancelExpected(object state)
{
var stateTuple = (Tuple<bool, SqlCommand, Barrier>)state;
bool async = stateTuple.Item1;
SqlCommand command = stateTuple.Item2;
Barrier threadsReady = stateTuple.Item3;
string errorMessage = SystemDataResourceManager.Instance.SQL_OperationCancelled;
string errorMessageSevereFailure = SystemDataResourceManager.Instance.SQL_SevereError;
DataTestUtility.ExpectFailure<SqlException>(() =>
{
threadsReady.SignalAndWait();
using (SqlDataReader r = command.ExecuteReader())
{
do
{
while (r.Read())
{
}
} while (r.NextResult());
}
}, new string[] { errorMessage, errorMessageSevereFailure });
}
private static void CancelSharedCommand(object state)
{
var stateTuple = (Tuple<bool, SqlCommand, Barrier>)state;
// sleep 1 seconds before cancel to ensure ExecuteReader starts and ensure it does not end before Cancel is called (command is running WAITFOR 8 seconds)
stateTuple.Item3.SignalAndWait();
Thread.Sleep(TimeSpan.FromSeconds(1));
stateTuple.Item2.Cancel();
}
private static void TimeOutDuringRead(string constr)
{
// Create the proxy
ProxyServer proxy = ProxyServer.CreateAndStartProxy(constr, out constr);
proxy.SimulatedPacketDelay = 100;
proxy.SimulatedOutDelay = true;
try
{
using (SqlConnection conn = new SqlConnection(constr))
{
// Start the command
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT @p", conn);
cmd.Parameters.AddWithValue("p", new byte[20000]);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
// Tweak the timeout to 1ms, stop the proxy from proxying and then try GetValue (which should timeout)
reader.SetDefaultTimeout(1);
proxy.PauseCopying();
string errorMessage = SystemDataResourceManager.Instance.SQL_Timeout;
Exception exception = Assert.Throws<SqlException>(() => reader.GetValue(0));
Assert.True(exception.Message.Contains(errorMessage));
// Return everything to normal and close
proxy.ResumeCopying();
reader.SetDefaultTimeout(30000);
reader.Dispose();
}
proxy.Stop();
}
catch
{
// In case of error, stop the proxy and dump its logs (hopefully this will help with debugging
proxy.Stop();
Console.WriteLine(proxy.GetServerEventLog());
Assert.True(false, "Error while reading through proxy");
throw;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 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 ChooseLevelDlg::onWake( %this )
{
CL_levelList.clear();
ChooseLevelWindow->SmallPreviews.clear();
%this->CurrentPreview.visible = false;
%this->levelName.visible = false;
%this->LevelDescriptionLabel.visible = false;
%this->LevelDescription.visible = false;
%count = LevelFilesList.count();
if(%count == 0)
{
//We have no levels found. Prompt the user to open the editor to the default level if the tools are present
if(IsDirectory("tools"))
{
MessageBoxYesNo("Error", "No levels were found in any modules. Do you want to load the editor and start a new level?",
"fastLoadWorldEdit(1);",
"Canvas.popDialog(ChooseLevelDlg); if(isObject(ChooseLevelDlg.returnGui) && ChooseLevelDlg.returnGui.isMethod(\"onReturnTo\")) ChooseLevelDlg.returnGui.onReturnTo();");
}
else
{
MessageBoxOK("Error", "No levels were found in any modules. Please ensure you have modules loaded that contain gameplay code and level files.",
"Canvas.popDialog(ChooseLevelDlg); if(isObject(ChooseLevelDlg.returnGui) && ChooseLevelDlg.returnGui.isMethod(\"onReturnTo\")) ChooseLevelDlg.returnGui.onReturnTo();");
}
return;
}
for ( %i=0; %i < %count; %i++ )
{
%file = LevelFilesList.getKey( %i );
if ( !isFile(%file @ ".mis") && !isFile(%file) )
continue;
// Skip our new level/mission if we arent choosing a level
// to launch in the editor.
if ( !%this.launchInEditor )
{
%fileName = fileName(%file);
if (strstr(%fileName, "newMission.mis") > -1 || strstr(%fileName, "newLevel.mis") > -1)
continue;
}
%this.addMissionFile( %file );
}
// Also add the new level mission as defined in the world editor settings
// if we are choosing a level to launch in the editor.
if ( %this.launchInEditor )
{
%file = EditorSettings.value( "WorldEditor/newLevelFile" );
if ( %file !$= "" )
%this.addMissionFile( %file );
}
// Sort our list
CL_levelList.sort(0);
// Set the first row as the selected row
CL_levelList.setSelectedRow(0);
for (%i = 0; %i < CL_levelList.rowCount(); %i++)
{
%preview = new GuiButtonCtrl() {
profile = "GuiMenuButtonProfile";
internalName = "SmallPreview" @ %i;
Extent = "368 35";
text = getField(CL_levelList.getRowText(%i), 0);
command = "ChooseLevelWindow.previewSelected(ChooseLevelWindow->SmallPreviews->SmallPreview" @ %i @ ");";
buttonType = "RadioButton";
};
ChooseLevelWindow->SmallPreviews.add(%preview);
%rowText = CL_levelList.getRowText(%i);
// Set the level index
%preview.levelIndex = %i;
// Get the name
%name = getField(CL_levelList.getRowText(%i), 0);
%preview.levelName = %name;
%file = getField(CL_levelList.getRowText(%i), 1);
// Find the preview image
%levelPreview = getField(CL_levelList.getRowText(%i), 3);
// Test against all of the different image formats
// This should probably be moved into an engine function
if (isFile(%levelPreview @ ".png") ||
isFile(%levelPreview @ ".jpg") ||
isFile(%levelPreview @ ".bmp") ||
isFile(%levelPreview @ ".gif") ||
isFile(%levelPreview @ ".jng") ||
isFile(%levelPreview @ ".mng") ||
isFile(%levelPreview @ ".tga"))
{
%preview.bitmap = %levelPreview;
}
// Get the description
%desc = getField(CL_levelList.getRowText(%i), 2);
%preview.levelDesc = %desc;
}
ChooseLevelWindow->SmallPreviews.firstVisible = -1;
ChooseLevelWindow->SmallPreviews.lastVisible = -1;
if (ChooseLevelWindow->SmallPreviews.getCount() > 0)
{
ChooseLevelWindow->SmallPreviews.firstVisible = 0;
if (ChooseLevelWindow->SmallPreviews.getCount() < 6)
ChooseLevelWindow->SmallPreviews.lastVisible = ChooseLevelWindow->SmallPreviews.getCount() - 1;
else
ChooseLevelWindow->SmallPreviews.lastVisible = 4;
}
if (ChooseLevelWindow->SmallPreviews.getCount() > 0)
ChooseLevelWindow.previewSelected(ChooseLevelWindow->SmallPreviews.getObject(0));
// If we have 5 or less previews then hide our next/previous buttons
// and resize to fill their positions
if (ChooseLevelWindow->SmallPreviews.getCount() < 6)
{
ChooseLevelWindow->PreviousSmallPreviews.setVisible(false);
ChooseLevelWindow->NextSmallPreviews.setVisible(false);
%previewPos = ChooseLevelWindow->SmallPreviews.getPosition();
%previousPos = ChooseLevelWindow->PreviousSmallPreviews.getPosition();
%previewPosX = getWord(%previousPos, 0);
%previewPosY = getWord(%previewPos, 1);
ChooseLevelWindow->SmallPreviews.setPosition(%previewPosX, %previewPosY);
ChooseLevelWindow->SmallPreviews.colSpacing = 10;//((getWord(NextSmallPreviews.getPosition(), 0)+11)-getWord(PreviousSmallPreviews.getPosition(), 0))/4;
ChooseLevelWindow->SmallPreviews.refresh();
}
/*if (ChooseLevelWindow->SmallPreviews.getCount() <= 1)
{
// Hide the small previews
ChooseLevelWindow->SmallPreviews.setVisible(false);
// Shrink the ChooseLevelWindow so that we don't have a large blank space
%extentX = getWord(ChooseLevelWindow.getExtent(), 0);
%extentY = getWord(ChooseLevelWindow->SmallPreviews.getPosition(), 1);
ChooseLevelWIndow.setExtent(%extentX, %extentY);
}
else
{
// Make sure the small previews are visible
ChooseLevelWindow->SmallPreviews.setVisible(true);
%extentX = getWord(ChooseLevelWindow.getExtent(), 0);
%extentY = getWord(ChooseLevelWindow->SmallPreviews.getPosition(), 1);
%extentY = %extentY + getWord(ChooseLevelWindow->SmallPreviews.getExtent(), 1);
%extentY = %extentY + 9;
//ChooseLevelWIndow.setExtent(%extentX, %extentY);
//}*/
}
function ChooseLevelDlg::addMissionFile( %this, %file )
{
%levelName = fileBase(%file);
%levelDesc = "A Torque level";
%LevelInfoObject = getLevelInfo(%file);
if (%LevelInfoObject != 0)
{
if(%LevelInfoObject.levelName !$= "")
%levelName = %LevelInfoObject.levelName;
else if(%LevelInfoObject.name !$= "")
%levelName = %LevelInfoObject.name;
if (%LevelInfoObject.desc0 !$= "")
%levelDesc = %LevelInfoObject.desc0;
if (%LevelInfoObject.preview !$= "")
%levelPreview = %LevelInfoObject.preview;
%LevelInfoObject.delete();
}
CL_levelList.addRow( CL_levelList.rowCount(), %levelName TAB %file TAB %levelDesc TAB %levelPreview );
}
function ChooseLevelDlg::onSleep( %this )
{
// This is set from the outside, only stays true for a single wake/sleep
// cycle.
%this.launchInEditor = false;
}
function ChooseLevelWindow::previewSelected(%this, %preview)
{
// Set the selected level
if (isObject(%preview) && %preview.levelIndex !$= "")
CL_levelList.setSelectedRow(%preview.levelIndex);
else
CL_levelList.setSelectedRow(-1);
// Set the large preview image
if (isObject(%preview) && %preview.bitmap !$= "")
{
%this->CurrentPreview.visible = true;
%this->CurrentPreview.setBitmap(%preview.bitmap);
}
else
{
%this->CurrentPreview.visible = false;
}
// Set the current level name
if (isObject(%preview) && %preview.levelName !$= "")
{
%this->LevelName.visible = true;
%this->LevelName.setText(%preview.levelName);
}
else
{
%this->LevelName.visible = false;
}
// Set the current level description
if (isObject(%preview) && %preview.levelDesc !$= "")
{
%this->LevelDescription.visible = true;
%this->LevelDescriptionLabel.visible = true;
%this->LevelDescription.setText(%preview.levelDesc);
}
else
{
%this->LevelDescription.visible = false;
%this->LevelDescriptionLabel.visible = false;
}
}
function ChooseLevelWindow::previousPreviews(%this)
{
%prevHiddenIdx = %this->SmallPreviews.firstVisible - 1;
if (%prevHiddenIdx < 0)
return;
%lastVisibleIdx = %this->SmallPreviews.lastVisible;
if (%lastVisibleIdx >= %this->SmallPreviews.getCount())
return;
%prevHiddenObj = %this->SmallPreviews.getObject(%prevHiddenIdx);
%lastVisibleObj = %this->SmallPreviews.getObject(%lastVisibleIdx);
if (isObject(%prevHiddenObj) && isObject(%lastVisibleObj))
{
%this->SmallPreviews.firstVisible--;
%this->SmallPreviews.lastVisible--;
%prevHiddenObj.setVisible(true);
%lastVisibleObj.setVisible(false);
}
}
function ChooseLevelWindow::nextPreviews(%this)
{
%firstVisibleIdx = %this->SmallPreviews.firstVisible;
if (%firstVisibleIdx < 0)
return;
%firstHiddenIdx = %this->SmallPreviews.lastVisible + 1;
if (%firstHiddenIdx >= %this->SmallPreviews.getCount())
return;
%firstVisibleObj = %this->SmallPreviews.getObject(%firstVisibleIdx);
%firstHiddenObj = %this->SmallPreviews.getObject(%firstHiddenIdx);
if (isObject(%firstVisibleObj) && isObject(%firstHiddenObj))
{
%this->SmallPreviews.firstVisible++;
%this->SmallPreviews.lastVisible++;
%firstVisibleObj.setVisible(false);
%firstHiddenObj.setVisible(true);
}
}
// Do this onMouseUp not via Command which occurs onMouseDown so we do
// not have a lingering mouseUp event lingering in the ether.
function ChooseLevelDlgGoBtn::onMouseUp( %this )
{
// So we can't fire the button when loading is in progress.
if ( isObject( ServerGroup ) )
return;
// Launch the chosen level with the editor open?
if ( ChooseLevelDlg.launchInEditor )
{
activatePackage( "BootEditor" );
ChooseLevelDlg.launchInEditor = false;
StartGame("", "SinglePlayer");
}
else
{
StartGame();
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
#if !PocketPC && !SILVERLIGHT && !MONOTOUCH && !__ANDROID__
using System.Web.UI;
#endif
namespace Newtonsoft.Json.Tests.Linq
{
public class JObjectTests : TestFixtureBase
{
[Test]
public void TryGetValue()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
JToken t;
Assert.AreEqual(false, o.TryGetValue("sdf", out t));
Assert.AreEqual(null, t);
Assert.AreEqual(false, o.TryGetValue(null, out t));
Assert.AreEqual(null, t);
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
}
[Test]
public void DictionaryItemShouldSet()
{
JObject o = new JObject();
o["PropertyNameValue"] = new JValue(1);
Assert.AreEqual(1, o.Children().Count());
JToken t;
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
o["PropertyNameValue"] = new JValue(2);
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t));
o["PropertyNameValue"] = null;
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue((object)null), t));
}
[Test]
public void Remove()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(false, o.Remove("sdf"));
Assert.AreEqual(false, o.Remove(null));
Assert.AreEqual(true, o.Remove("PropertyNameValue"));
Assert.AreEqual(0, o.Children().Count());
}
[Test]
public void GenericCollectionRemove()
{
JValue v = new JValue(1);
JObject o = new JObject();
o.Add("PropertyNameValue", v);
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))));
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))));
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))));
Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v)));
Assert.AreEqual(0, o.Children().Count());
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
public void DuplicatePropertyNameShouldThrow()
{
JObject o = new JObject();
o.Add("PropertyNameValue", null);
o.Add("PropertyNameValue", null);
}
[Test]
public void GenericDictionaryAdd()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, (int)o["PropertyNameValue"]);
o.Add("PropertyNameValue1", null);
Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value);
Assert.AreEqual(2, o.Children().Count());
}
[Test]
public void GenericCollectionAdd()
{
JObject o = new JObject();
((ICollection<KeyValuePair<string,JToken>>)o).Add(new KeyValuePair<string,JToken>("PropertyNameValue", new JValue(1)));
Assert.AreEqual(1, (int)o["PropertyNameValue"]);
Assert.AreEqual(1, o.Children().Count());
}
[Test]
public void GenericCollectionClear()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
JProperty p = (JProperty)o.Children().ElementAt(0);
((ICollection<KeyValuePair<string, JToken>>)o).Clear();
Assert.AreEqual(0, o.Children().Count());
Assert.AreEqual(null, p.Parent);
}
[Test]
public void GenericCollectionContains()
{
JValue v = new JValue(1);
JObject o = new JObject();
o.Add("PropertyNameValue", v);
Assert.AreEqual(1, o.Children().Count());
bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v));
Assert.AreEqual(true, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>));
Assert.AreEqual(false, contains);
}
[Test]
public void GenericDictionaryContains()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue");
Assert.AreEqual(true, contains);
}
[Test]
public void GenericCollectionCopyTo()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
o.Add("PropertyNameValue3", new JValue(3));
Assert.AreEqual(3, o.Children().Count());
KeyValuePair<string, JToken>[] a = new KeyValuePair<string,JToken>[5];
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1);
Assert.AreEqual(default(KeyValuePair<string,JToken>), a[0]);
Assert.AreEqual("PropertyNameValue", a[1].Key);
Assert.AreEqual(1, (int)a[1].Value);
Assert.AreEqual("PropertyNameValue2", a[2].Key);
Assert.AreEqual(2, (int)a[2].Value);
Assert.AreEqual("PropertyNameValue3", a[3].Key);
Assert.AreEqual(3, (int)a[3].Value);
Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]);
}
[Test]
[ExpectedException(typeof(ArgumentNullException), ExpectedMessage = @"Value cannot be null.
Parameter name: array")]
public void GenericCollectionCopyToNullArrayShouldThrow()
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0);
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException), ExpectedMessage = @"arrayIndex is less than 0.
Parameter name: arrayIndex")]
public void GenericCollectionCopyToNegativeArrayIndexShouldThrow()
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = @"arrayIndex is equal to or greater than the length of array.")]
public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow()
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.")]
public void GenericCollectionCopyToInsufficientArrayCapacity()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
o.Add("PropertyNameValue3", new JValue(3));
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1);
}
[Test]
public void FromObjectRaw()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
Assert.AreEqual("FirstNameValue", (string)o["first_name"]);
Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type);
Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]);
Assert.AreEqual("LastNameValue", (string)o["last_name"]);
}
[Test]
public void JTokenReader()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
JsonReader reader = new JTokenReader(o);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Raw, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
Assert.IsFalse(reader.Read());
}
[Test]
public void DeserializeFromRaw()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
JsonReader reader = new JTokenReader(o);
JsonSerializer serializer = new JsonSerializer();
raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw));
Assert.AreEqual("FirstNameValue", raw.FirstName);
Assert.AreEqual("LastNameValue", raw.LastName);
Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray")]
public void Parse_ShouldThrowOnUnexpectedToken()
{
string json = @"[""prop""]";
JObject.Parse(json);
}
[Test]
public void ParseJavaScriptDate()
{
string json = @"[new Date(1207285200000)]";
JArray a = (JArray)JsonConvert.DeserializeObject(json);
JValue v = (JValue)a[0];
Assert.AreEqual(JsonConvert.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v);
}
[Test]
public void GenericValueCast()
{
string json = @"{""foo"":true}";
JObject o = (JObject)JsonConvert.DeserializeObject(json);
bool? value = o.Value<bool?>("foo");
Assert.AreEqual(true, value);
json = @"{""foo"":null}";
o = (JObject)JsonConvert.DeserializeObject(json);
value = o.Value<bool?>("foo");
Assert.AreEqual(null, value);
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Invalid property identifier character: ]. Line 3, position 9.")]
public void Blog()
{
JObject person = JObject.Parse(@"{
""name"": ""James"",
]!#$THIS IS: BAD JSON![{}}}}]
}");
// Invalid property identifier character: ]. Line 3, position 9.
}
[Test]
public void RawChildValues()
{
JObject o = new JObject();
o["val1"] = new JRaw("1");
o["val2"] = new JRaw("1");
string json = o.ToString();
Assert.AreEqual(@"{
""val1"": 1,
""val2"": 1
}", json);
}
[Test]
public void Iterate()
{
JObject o = new JObject();
o.Add("PropertyNameValue1", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
JToken t = o;
int i = 1;
foreach (JProperty property in t)
{
Assert.AreEqual("PropertyNameValue" + i, property.Name);
Assert.AreEqual(i, (int)property.Value);
i++;
}
}
[Test]
public void KeyValuePairIterate()
{
JObject o = new JObject();
o.Add("PropertyNameValue1", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
int i = 1;
foreach (KeyValuePair<string, JToken> pair in o)
{
Assert.AreEqual("PropertyNameValue" + i, pair.Key);
Assert.AreEqual(i, (int)pair.Value);
i++;
}
}
[Test]
public void WriteObjectNullStringValue()
{
string s = null;
JValue v = new JValue(s);
Assert.AreEqual(null, v.Value);
Assert.AreEqual(JTokenType.String, v.Type);
JObject o = new JObject();
o["title"] = v;
string output = o.ToString();
Assert.AreEqual(@"{
""title"": null
}", output);
}
[Test]
public void Example()
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Small
Console.WriteLine(name);
Console.WriteLine(smallest);
}
[Test]
public void DeserializeClassManually()
{
string jsonText = @"{
""short"":{
""original"":""http://www.foo.com/"",
""short"":""krehqk"",
""error"":{
""code"":0,
""msg"":""No action taken""}
}";
JObject json = JObject.Parse(jsonText);
Shortie shortie = new Shortie
{
Original = (string)json["short"]["original"],
Short = (string)json["short"]["short"],
Error = new ShortieException
{
Code = (int)json["short"]["error"]["code"],
ErrorMessage = (string)json["short"]["error"]["msg"]
}
};
Console.WriteLine(shortie.Original);
// http://www.foo.com/
Console.WriteLine(shortie.Error.ErrorMessage);
// No action taken
Assert.AreEqual("http://www.foo.com/", shortie.Original);
Assert.AreEqual("krehqk", shortie.Short);
Assert.AreEqual(null, shortie.Shortened);
Assert.AreEqual(0, shortie.Error.Code);
Assert.AreEqual("No action taken", shortie.Error.ErrorMessage);
}
[Test]
public void JObjectContainingHtml()
{
JObject o = new JObject();
o["rc"] = new JValue(200);
o["m"] = new JValue("");
o["o"] = new JValue(@"<div class='s1'>
<div class='avatar'>
<a href='asdf'>asdf</a><br />
<strong>0</strong>
</div>
<div class='sl'>
<p>
444444444
</p>
</div>
<div class='clear'>
</div>
</div>");
Assert.AreEqual(@"{
""rc"": 200,
""m"": """",
""o"": ""<div class='s1'>\r\n <div class='avatar'> \r\n <a href='asdf'>asdf</a><br />\r\n <strong>0</strong>\r\n </div>\r\n <div class='sl'>\r\n <p>\r\n 444444444\r\n </p>\r\n </div>\r\n <div class='clear'>\r\n </div> \r\n</div>""
}", o.ToString());
}
[Test]
public void ImplicitValueConversions()
{
JObject moss = new JObject();
moss["FirstName"] = new JValue("Maurice");
moss["LastName"] = new JValue("Moss");
moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30));
moss["Department"] = new JValue("IT");
moss["JobTitle"] = new JValue("Support");
Console.WriteLine(moss.ToString());
//{
// "FirstName": "Maurice",
// "LastName": "Moss",
// "BirthDate": "\/Date(252241200000+1300)\/",
// "Department": "IT",
// "JobTitle": "Support"
//}
JObject jen = new JObject();
jen["FirstName"] = "Jen";
jen["LastName"] = "Barber";
jen["BirthDate"] = new DateTime(1978, 3, 15);
jen["Department"] = "IT";
jen["JobTitle"] = "Manager";
Console.WriteLine(jen.ToString());
//{
// "FirstName": "Jen",
// "LastName": "Barber",
// "BirthDate": "\/Date(258721200000+1300)\/",
// "Department": "IT",
// "JobTitle": "Manager"
//}
}
[Test]
public void ReplaceJPropertyWithJPropertyWithSameName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
IList l = o;
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p2, l[1]);
JProperty p3 = new JProperty("Test1", "III");
p1.Replace(p3);
Assert.AreEqual(null, p1.Parent);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
Assert.AreEqual(2, l.Count);
Assert.AreEqual(2, o.Properties().Count());
JProperty p4 = new JProperty("Test4", "IV");
p2.Replace(p4);
Assert.AreEqual(null, p2.Parent);
Assert.AreEqual(l, p4.Parent);
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p4, l[1]);
}
#if !PocketPC && !SILVERLIGHT && !NET20 && !MONOTOUCH && !__ANDROID__
[Test]
public void PropertyChanging()
{
object changing = null;
object changed = null;
int changingCount = 0;
int changedCount = 0;
JObject o = new JObject();
o.PropertyChanging += (sender, args) =>
{
JObject s = (JObject) sender;
changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changingCount++;
};
o.PropertyChanged += (sender, args) =>
{
JObject s = (JObject)sender;
changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changedCount++;
};
o["StringValue"] = "value1";
Assert.AreEqual(null, changing);
Assert.AreEqual("value1", changed);
Assert.AreEqual("value1", (string)o["StringValue"]);
Assert.AreEqual(1, changingCount);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value1";
Assert.AreEqual(1, changingCount);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value2";
Assert.AreEqual("value1", changing);
Assert.AreEqual("value2", changed);
Assert.AreEqual("value2", (string)o["StringValue"]);
Assert.AreEqual(2, changingCount);
Assert.AreEqual(2, changedCount);
o["StringValue"] = null;
Assert.AreEqual("value2", changing);
Assert.AreEqual(null, changed);
Assert.AreEqual(null, (string)o["StringValue"]);
Assert.AreEqual(3, changingCount);
Assert.AreEqual(3, changedCount);
o["NullValue"] = null;
Assert.AreEqual(null, changing);
Assert.AreEqual(null, changed);
Assert.AreEqual(new JValue((object)null), o["NullValue"]);
Assert.AreEqual(4, changingCount);
Assert.AreEqual(4, changedCount);
o["NullValue"] = null;
Assert.AreEqual(4, changingCount);
Assert.AreEqual(4, changedCount);
}
#endif
[Test]
public void PropertyChanged()
{
object changed = null;
int changedCount = 0;
JObject o = new JObject();
o.PropertyChanged += (sender, args) =>
{
JObject s = (JObject)sender;
changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changedCount++;
};
o["StringValue"] = "value1";
Assert.AreEqual("value1", changed);
Assert.AreEqual("value1", (string)o["StringValue"]);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value1";
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value2";
Assert.AreEqual("value2", changed);
Assert.AreEqual("value2", (string)o["StringValue"]);
Assert.AreEqual(2, changedCount);
o["StringValue"] = null;
Assert.AreEqual(null, changed);
Assert.AreEqual(null, (string)o["StringValue"]);
Assert.AreEqual(3, changedCount);
o["NullValue"] = null;
Assert.AreEqual(null, changed);
Assert.AreEqual(new JValue((object)null), o["NullValue"]);
Assert.AreEqual(4, changedCount);
o["NullValue"] = null;
Assert.AreEqual(4, changedCount);
}
[Test]
public void IListContains()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.IsTrue(l.Contains(p));
Assert.IsFalse(l.Contains(new JProperty("Test", 1)));
}
[Test]
public void IListIndexOf()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.AreEqual(0, l.IndexOf(p));
Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1)));
}
[Test]
public void IListClear()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.AreEqual(1, l.Count);
l.Clear();
Assert.AreEqual(0, l.Count);
}
[Test]
public void IListCopyTo()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
object[] a = new object[l.Count];
l.CopyTo(a, 0);
Assert.AreEqual(p1, a[0]);
Assert.AreEqual(p2, a[1]);
}
[Test]
public void IListAdd()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Add(p3);
Assert.AreEqual(3, l.Count);
Assert.AreEqual(p3, l[2]);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
public void IListAddBadToken()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l.Add(new JValue("Bad!"));
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Argument is not a JToken.")]
public void IListAddBadValue()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l.Add("Bad!");
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
public void IListAddPropertyWithExistingName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test2", "II");
l.Add(p3);
}
[Test]
public void IListRemove()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
// won't do anything
l.Remove(p3);
Assert.AreEqual(2, l.Count);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
Assert.IsFalse(l.Contains(p1));
Assert.IsTrue(l.Contains(p2));
l.Remove(p2);
Assert.AreEqual(0, l.Count);
Assert.IsFalse(l.Contains(p2));
Assert.AreEqual(null, p2.Parent);
}
[Test]
public void IListRemoveAt()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
// won't do anything
l.RemoveAt(0);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
l.Remove(p2);
Assert.AreEqual(0, l.Count);
}
[Test]
public void IListInsert()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Insert(1, p3);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p3, l[1]);
Assert.AreEqual(p2, l[2]);
}
[Test]
public void IListIsReadOnly()
{
IList l = new JObject();
Assert.IsFalse(l.IsReadOnly);
}
[Test]
public void IListIsFixedSize()
{
IList l = new JObject();
Assert.IsFalse(l.IsFixedSize);
}
[Test]
public void IListSetItem()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
public void IListSetItemAlreadyExists()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
l[1] = p3;
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
public void IListSetItemInvalid()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l[0] = new JValue(true);
}
[Test]
public void IListSyncRoot()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
Assert.IsNotNull(l.SyncRoot);
}
[Test]
public void IListIsSynchronized()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
Assert.IsFalse(l.IsSynchronized);
}
[Test]
public void GenericListJTokenContains()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.IsTrue(l.Contains(p));
Assert.IsFalse(l.Contains(new JProperty("Test", 1)));
}
[Test]
public void GenericListJTokenIndexOf()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.AreEqual(0, l.IndexOf(p));
Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1)));
}
[Test]
public void GenericListJTokenClear()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.AreEqual(1, l.Count);
l.Clear();
Assert.AreEqual(0, l.Count);
}
[Test]
public void GenericListJTokenCopyTo()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JToken[] a = new JToken[l.Count];
l.CopyTo(a, 0);
Assert.AreEqual(p1, a[0]);
Assert.AreEqual(p2, a[1]);
}
[Test]
public void GenericListJTokenAdd()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Add(p3);
Assert.AreEqual(3, l.Count);
Assert.AreEqual(p3, l[2]);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
public void GenericListJTokenAddBadToken()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
l.Add(new JValue("Bad!"));
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
public void GenericListJTokenAddBadValue()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
// string is implicitly converted to JValue
l.Add("Bad!");
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
public void GenericListJTokenAddPropertyWithExistingName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test2", "II");
l.Add(p3);
}
[Test]
public void GenericListJTokenRemove()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
// won't do anything
Assert.IsFalse(l.Remove(p3));
Assert.AreEqual(2, l.Count);
Assert.IsTrue(l.Remove(p1));
Assert.AreEqual(1, l.Count);
Assert.IsFalse(l.Contains(p1));
Assert.IsTrue(l.Contains(p2));
Assert.IsTrue(l.Remove(p2));
Assert.AreEqual(0, l.Count);
Assert.IsFalse(l.Contains(p2));
Assert.AreEqual(null, p2.Parent);
}
[Test]
public void GenericListJTokenRemoveAt()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
// won't do anything
l.RemoveAt(0);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
l.Remove(p2);
Assert.AreEqual(0, l.Count);
}
[Test]
public void GenericListJTokenInsert()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Insert(1, p3);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p3, l[1]);
Assert.AreEqual(p2, l[2]);
}
[Test]
public void GenericListJTokenIsReadOnly()
{
IList<JToken> l = new JObject();
Assert.IsFalse(l.IsReadOnly);
}
[Test]
public void GenericListJTokenSetItem()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
public void GenericListJTokenSetItemAlreadyExists()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
l[1] = p3;
}
#if !(SILVERLIGHT || MONOTOUCH || __ANDROID__)
[Test]
public void IBindingListSortDirection()
{
IBindingList l = new JObject();
Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection);
}
[Test]
public void IBindingListSortProperty()
{
IBindingList l = new JObject();
Assert.AreEqual(null, l.SortProperty);
}
[Test]
public void IBindingListSupportsChangeNotification()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.SupportsChangeNotification);
}
[Test]
public void IBindingListSupportsSearching()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.SupportsSearching);
}
[Test]
public void IBindingListSupportsSorting()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.SupportsSorting);
}
[Test]
public void IBindingListAllowEdit()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowEdit);
}
[Test]
public void IBindingListAllowNew()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowNew);
}
[Test]
public void IBindingListAllowRemove()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowRemove);
}
[Test]
public void IBindingListAddIndex()
{
IBindingList l = new JObject();
// do nothing
l.AddIndex(null);
}
[Test]
[ExpectedException(typeof(NotSupportedException))]
public void IBindingListApplySort()
{
IBindingList l = new JObject();
l.ApplySort(null, ListSortDirection.Ascending);
}
[Test]
[ExpectedException(typeof(NotSupportedException))]
public void IBindingListRemoveSort()
{
IBindingList l = new JObject();
l.RemoveSort();
}
[Test]
public void IBindingListRemoveIndex()
{
IBindingList l = new JObject();
// do nothing
l.RemoveIndex(null);
}
[Test]
[ExpectedException(typeof(NotSupportedException))]
public void IBindingListFind()
{
IBindingList l = new JObject();
l.Find(null, null);
}
[Test]
public void IBindingListIsSorted()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.IsSorted);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.")]
public void IBindingListAddNew()
{
IBindingList l = new JObject();
l.AddNew();
}
[Test]
public void IBindingListAddNewWithEvent()
{
JObject o = new JObject();
o.AddingNew += (s, e) => e.NewObject = new JProperty("Property!");
IBindingList l = o;
object newObject = l.AddNew();
Assert.IsNotNull(newObject);
JProperty p = (JProperty) newObject;
Assert.AreEqual("Property!", p.Name);
Assert.AreEqual(o, p.Parent);
}
[Test]
public void ITypedListGetListName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
ITypedList l = new JObject(p1, p2);
Assert.AreEqual(string.Empty, l.GetListName(null));
}
[Test]
public void ITypedListGetItemProperties()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
ITypedList l = new JObject(p1, p2);
PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null);
Assert.IsNull(propertyDescriptors);
}
[Test]
public void ListChanged()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
ListChangedType? changedType = null;
int? index = null;
o.ListChanged += (s, a) =>
{
changedType = a.ListChangedType;
index = a.NewIndex;
};
JProperty p3 = new JProperty("Test3", "III");
o.Add(p3);
Assert.AreEqual(changedType, ListChangedType.ItemAdded);
Assert.AreEqual(index, 2);
Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]);
JProperty p4 = new JProperty("Test4", "IV");
((IList<JToken>) o)[index.Value] = p4;
Assert.AreEqual(changedType, ListChangedType.ItemChanged);
Assert.AreEqual(index, 2);
Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]);
Assert.IsFalse(((IList<JToken>)o).Contains(p3));
Assert.IsTrue(((IList<JToken>)o).Contains(p4));
o["Test1"] = 2;
Assert.AreEqual(changedType, ListChangedType.ItemChanged);
Assert.AreEqual(index, 0);
Assert.AreEqual(2, (int)o["Test1"]);
}
#endif
#if SILVERLIGHT || !(NET20 || NET35)
[Test]
public void CollectionChanged()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
NotifyCollectionChangedAction? changedType = null;
int? index = null;
o.CollectionChanged += (s, a) =>
{
changedType = a.Action;
index = a.NewStartingIndex;
};
JProperty p3 = new JProperty("Test3", "III");
o.Add(p3);
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add);
Assert.AreEqual(index, 2);
Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]);
JProperty p4 = new JProperty("Test4", "IV");
((IList<JToken>)o)[index.Value] = p4;
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace);
Assert.AreEqual(index, 2);
Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]);
Assert.IsFalse(((IList<JToken>)o).Contains(p3));
Assert.IsTrue(((IList<JToken>)o).Contains(p4));
o["Test1"] = 2;
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace);
Assert.AreEqual(index, 0);
Assert.AreEqual(2, (int)o["Test1"]);
}
#endif
[Test]
public void GetGeocodeAddress()
{
string json = @"{
""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"",
""Status"": {
""code"": 200,
""request"": ""geocode""
},
""Placemark"": [ {
""id"": ""p1"",
""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"",
""AddressDetails"": {
""Accuracy"" : 8,
""Country"" : {
""AdministrativeArea"" : {
""AdministrativeAreaName"" : ""IL"",
""SubAdministrativeArea"" : {
""Locality"" : {
""LocalityName"" : ""Rockford"",
""PostalCode"" : {
""PostalCodeNumber"" : ""61107""
},
""Thoroughfare"" : {
""ThoroughfareName"" : ""435 N Mulford Rd""
}
},
""SubAdministrativeAreaName"" : ""Winnebago""
}
},
""CountryName"" : ""USA"",
""CountryNameCode"" : ""US""
}
},
""ExtendedData"": {
""LatLonBox"": {
""north"": 42.2753076,
""south"": 42.2690124,
""east"": -88.9964645,
""west"": -89.0027597
}
},
""Point"": {
""coordinates"": [ -88.9995886, 42.2721596, 0 ]
}
} ]
}";
JObject o = JObject.Parse(json);
string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"];
Assert.AreEqual("435 N Mulford Rd", searchAddress);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Set JObject values with invalid key value: 0. Object property name expected.")]
public void SetValueWithInvalidPropertyName()
{
JObject o = new JObject();
o[0] = new JValue(3);
}
[Test]
public void SetValue()
{
object key = "TestKey";
JObject o = new JObject();
o[key] = new JValue(3);
Assert.AreEqual(3, (int)o[key]);
}
[Test]
public void ParseMultipleProperties()
{
string json = @"{
""Name"": ""Name1"",
""Name"": ""Name2""
}";
JObject o = JObject.Parse(json);
string value = (string)o["Name"];
Assert.AreEqual("Name2", value);
}
[Test]
public void WriteObjectNullDBNullValue()
{
DBNull dbNull = DBNull.Value;
JValue v = new JValue(dbNull);
Assert.AreEqual(DBNull.Value, v.Value);
Assert.AreEqual(JTokenType.Null, v.Type);
JObject o = new JObject();
o["title"] = v;
string output = o.ToString();
Assert.AreEqual(@"{
""title"": null
}", output);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not convert Object to String.")]
public void InvalidValueCastExceptionMessage()
{
string json = @"{
""responseData"": {},
""responseDetails"": null,
""responseStatus"": 200
}";
JObject o = JObject.Parse(json);
string name = (string)o["responseData"];
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not convert Object to String.")]
public void InvalidPropertyValueCastExceptionMessage()
{
string json = @"{
""responseData"": {},
""responseDetails"": null,
""responseStatus"": 200
}";
JObject o = JObject.Parse(json);
string name = (string)o.Property("responseData");
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "JSON integer 307953220000517141511 is too large or small for an Int64.")]
public void NumberTooBigForInt64()
{
string json = @"{""code"": 307953220000517141511}";
JObject.Parse(json);
}
#if !SILVERLIGHT
[Test]
public void GetProperties()
{
JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}");
ICustomTypeDescriptor descriptor = o;
PropertyDescriptorCollection properties = descriptor.GetProperties();
Assert.AreEqual(4, properties.Count);
PropertyDescriptor prop1 = properties[0];
Assert.AreEqual("prop1", prop1.Name);
Assert.AreEqual(typeof(long), prop1.PropertyType);
Assert.AreEqual(typeof(JObject), prop1.ComponentType);
Assert.AreEqual(false, prop1.CanResetValue(o));
Assert.AreEqual(false, prop1.ShouldSerializeValue(o));
PropertyDescriptor prop2 = properties[1];
Assert.AreEqual("prop2", prop2.Name);
Assert.AreEqual(typeof(string), prop2.PropertyType);
Assert.AreEqual(typeof(JObject), prop2.ComponentType);
Assert.AreEqual(false, prop2.CanResetValue(o));
Assert.AreEqual(false, prop2.ShouldSerializeValue(o));
PropertyDescriptor prop3 = properties[2];
Assert.AreEqual("prop3", prop3.Name);
Assert.AreEqual(typeof(object), prop3.PropertyType);
Assert.AreEqual(typeof(JObject), prop3.ComponentType);
Assert.AreEqual(false, prop3.CanResetValue(o));
Assert.AreEqual(false, prop3.ShouldSerializeValue(o));
PropertyDescriptor prop4 = properties[3];
Assert.AreEqual("prop4", prop4.Name);
Assert.AreEqual(typeof(JArray), prop4.PropertyType);
Assert.AreEqual(typeof(JObject), prop4.ComponentType);
Assert.AreEqual(false, prop4.CanResetValue(o));
Assert.AreEqual(false, prop4.ShouldSerializeValue(o));
}
#endif
}
}
| |
using System;
using Valle.GtkUtilidades;
namespace Valle.TpvFinal
{
public class EventoSalirElegirMonedas : EventArgs
{
public decimal Importe = 0m;
public decimal Cambio = 0m;
public decimal entrega = 0m;
public bool cancelado = true;
public EventoSalirElegirMonedas(decimal Cambio){
cancelado = false;
this.Cambio = Cambio;
}
public EventoSalirElegirMonedas(){
}
public EventoSalirElegirMonedas(decimal Cambio, decimal Importe, decimal entrega){
cancelado = false;
this.Cambio = Cambio;
this.Importe = Importe;
this.entrega = entrega;
}
}
public partial class ElegirMoneda : FormularioBase
{
protected virtual void OnBtnManualClicked (object sender, System.EventArgs e)
{
this.modoBilletes = false;
this.pneMonedas.Visible =true;
this.btnSalir.Visible =false;
this.btnBackSp.Visible = true;
this.btnJusto.Sensitive = false;
this.SetSizeRequest(700,500);
}
public event EventHandler<EventoSalirElegirMonedas> SalirElegirMonedas;
public Valle.ToolsTpv.Ticket ticket;
decimal cambio = 0m;
public decimal Cambio {
get{ return cambio;}
}
public bool SepararArticulos = false;
object listaAritulos;
public object Articulos{
get{
SepararArticulos = false;
return listaAritulos;
}
set {
listaAritulos = value;
SepararArticulos = true;
}
}
decimal importe =0m;
public decimal Importe{
set{
importe = value;
acomulado = 0m;
pilaAcomulados.Clear();
this.lblImporte.LabelProp = String.Format("<span size=\"xx-large\">Importe {0:c}</span>",importe);
this.modoBilletes = true;
this.pneMonedas.Visible =false;
this.btnSalir.Visible =true;
this.btnBackSp.Visible = false;
this.SetSizeRequest(500,500);
}
get{
return importe;
}
}
decimal acomulado = 0m;
bool modoBilletes = true;
System.Collections.Generic.Stack<decimal> pilaAcomulados;
public ElegirMoneda ()
{
this.Init ();
this.LblTituloBase = this.lblTitulo;
pilaAcomulados = new System.Collections.Generic.Stack<decimal>();
Titulo = "Introducir metalico";
this.pneMonedas.Visible = false;
this.btnBackSp.Visible = false;
this.WindowPosition = Gtk.WindowPosition.CenterAlways;
this.KeepAbove = true;
}
void SumarMoneda(decimal mon){
pilaAcomulados.Push (mon);
acomulado += mon;
cambio = acomulado >= importe ? acomulado - importe : -1;
this.MostrarResultado();
}
void MostrarResultado(){
this.lblImporte.LabelProp = String.Format("<small>Importe {0:c} </small>\n"+
"<span size=\"xx-large\">Metalico {1:c} </span>\n"+
"<big>Cambio {2:c} </big>",importe,acomulado,cambio > 0 ? cambio : 0);
}
protected virtual void OnBtnJusto1Clicked (object sender, System.EventArgs e)
{
if(SalirElegirMonedas!=null) SalirElegirMonedas(this,new EventoSalirElegirMonedas(0m,importe,0m));
this.CerrarFormulario();
}
protected virtual void OnBtnSalirClicked (object sender, System.EventArgs e)
{
if(SalirElegirMonedas!=null) SalirElegirMonedas(this,new EventoSalirElegirMonedas());
this.CerrarFormulario();
}
protected virtual void OnBtnCancelarClicked (object sender, System.EventArgs e)
{
this.modoBilletes = true;
this.pneMonedas.Visible =false;
this.btnSalir.Visible =true;
this.btnBackSp.Visible = false;
this.btnJusto.Sensitive = true;
this.SetSizeRequest(500,500);
}
protected virtual void OnBtnAceptarClicked (object sender, System.EventArgs e)
{
if(cambio>-1m){
if(SalirElegirMonedas!=null) SalirElegirMonedas(this,new EventoSalirElegirMonedas(cambio,importe,acomulado));
OnBtnCancelarClicked(null,null);
this.CerrarFormulario();
}
}
protected virtual void OnBtn500Clicked (object sender, System.EventArgs e)
{
if(modoBilletes && (500m >= importe))
{
cambio = 500m - importe;
if(SalirElegirMonedas!=null) SalirElegirMonedas(this,new EventoSalirElegirMonedas(cambio,importe,500m));
this.CerrarFormulario();
} else if(!modoBilletes)
this.SumarMoneda(500m);
}
protected virtual void OnBtn200Clicked (object sender, System.EventArgs e)
{
if(modoBilletes && (200m >= importe))
{
cambio = 200m - importe;
if(SalirElegirMonedas!=null) SalirElegirMonedas(this,new EventoSalirElegirMonedas(cambio,importe,200m));
this.CerrarFormulario();
} else if(!modoBilletes)
this.SumarMoneda(200m);
}
protected virtual void OnBtn100Clicked (object sender, System.EventArgs e)
{
if(modoBilletes && (100m >= importe))
{
cambio = 100m - importe;
if(SalirElegirMonedas!=null) SalirElegirMonedas(this,new EventoSalirElegirMonedas(cambio,importe,100m));
this.CerrarFormulario();
} else if(!modoBilletes)
this.SumarMoneda(100m);
}
protected virtual void OnBtn50Clicked (object sender, System.EventArgs e)
{
if(modoBilletes && (50m >= importe))
{
cambio = 50m - importe;
if(SalirElegirMonedas!=null) SalirElegirMonedas(this,new EventoSalirElegirMonedas(cambio,importe,50m));
this.CerrarFormulario();
} else{
this.SumarMoneda(50m);
}
}
protected virtual void OnBtn20Clicked (object sender, System.EventArgs e)
{
if(modoBilletes && (20m >= importe))
{
cambio = 20m - importe;
if(SalirElegirMonedas!=null) SalirElegirMonedas(this,new EventoSalirElegirMonedas(cambio,importe,20m));
this.CerrarFormulario();
} else if(!modoBilletes){
this.SumarMoneda(20m);
}
}
protected virtual void OnBtn5Clicked (object sender, System.EventArgs e)
{
if(modoBilletes && (5m >= importe))
{
cambio = 5m - importe;
if(SalirElegirMonedas!=null) SalirElegirMonedas(this,new EventoSalirElegirMonedas(cambio,importe,5m));
this.CerrarFormulario();
} else if (!modoBilletes)
this.SumarMoneda(5m);
}
protected virtual void OnBtn10Clicked (object sender, System.EventArgs e)
{
if(modoBilletes && (10m >= importe))
{
cambio = 10m - importe;
if(SalirElegirMonedas!=null) SalirElegirMonedas(this,new EventoSalirElegirMonedas(cambio,importe,10m));
this.CerrarFormulario();
} else if(!modoBilletes)
this.SumarMoneda(10m);
}
protected virtual void OnBtn2Clicked (object sender, System.EventArgs e)
{
this.SumarMoneda(2m);
}
protected virtual void OnBtn1Clicked (object sender, System.EventArgs e)
{
this.SumarMoneda(1m);
}
protected virtual void OnBtn51Clicked (object sender, System.EventArgs e)
{
this.SumarMoneda(0.5m);
}
protected virtual void OnBtn21Clicked (object sender, System.EventArgs e)
{
this.SumarMoneda(0.20m);
}
protected virtual void OnBtn11Clicked (object sender, System.EventArgs e)
{
this.SumarMoneda(0.10m);
}
protected virtual void OnBtn6Clicked (object sender, System.EventArgs e)
{
this.SumarMoneda(0.05m);
}
protected virtual void OnBtnBackSpClicked (object sender, System.EventArgs e)
{
if(pilaAcomulados.Count>0){
decimal mon = pilaAcomulados.Pop();
acomulado -= mon;
cambio = acomulado >= importe ? acomulado - importe : -1;
this.MostrarResultado();
}
}
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.Reflection;
using dnlib.Threading;
namespace dnlib.DotNet {
/// <summary>
/// <see cref="Importer"/> options
/// </summary>
[Flags]
public enum ImporterOptions {
/// <summary>
/// Use <see cref="TypeDef"/>s whenever possible if the <see cref="TypeDef"/> is located
/// in this module.
/// </summary>
TryToUseTypeDefs = 1,
/// <summary>
/// Use <see cref="MethodDef"/>s whenever possible if the <see cref="MethodDef"/> is located
/// in this module.
/// </summary>
TryToUseMethodDefs = 2,
/// <summary>
/// Use <see cref="FieldDef"/>s whenever possible if the <see cref="FieldDef"/> is located
/// in this module.
/// </summary>
TryToUseFieldDefs = 4,
/// <summary>
/// Use <see cref="TypeDef"/>s, <see cref="MethodDef"/>s and <see cref="FieldDef"/>s
/// whenever possible if the definition is located in this module.
/// </summary>
/// <seealso cref="TryToUseTypeDefs"/>
/// <seealso cref="TryToUseMethodDefs"/>
/// <seealso cref="TryToUseFieldDefs"/>
TryToUseDefs = TryToUseTypeDefs | TryToUseMethodDefs | TryToUseFieldDefs,
/// <summary>
/// Don't set this flag. For internal use only.
/// </summary>
FixSignature = int.MinValue,
}
/// <summary>
/// Imports <see cref="Type"/>s, <see cref="ConstructorInfo"/>s, <see cref="MethodInfo"/>s
/// and <see cref="FieldInfo"/>s as references
/// </summary>
public struct Importer {
readonly ModuleDef module;
readonly GenericParamContext gpContext;
RecursionCounter recursionCounter;
ImporterOptions options;
bool TryToUseTypeDefs {
get { return (options & ImporterOptions.TryToUseTypeDefs) != 0; }
}
bool TryToUseMethodDefs {
get { return (options & ImporterOptions.TryToUseMethodDefs) != 0; }
}
bool TryToUseFieldDefs {
get { return (options & ImporterOptions.TryToUseFieldDefs) != 0; }
}
bool FixSignature {
get { return (options & ImporterOptions.FixSignature) != 0; }
set {
if (value)
options |= ImporterOptions.FixSignature;
else
options &= ~ImporterOptions.FixSignature;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">The module that will own all references</param>
public Importer(ModuleDef module)
: this(module, 0, new GenericParamContext()) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">The module that will own all references</param>
/// <param name="gpContext">Generic parameter context</param>
public Importer(ModuleDef module, GenericParamContext gpContext)
: this(module, 0, gpContext) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">The module that will own all references</param>
/// <param name="options">Importer options</param>
public Importer(ModuleDef module, ImporterOptions options)
: this(module, options, new GenericParamContext()) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">The module that will own all references</param>
/// <param name="options">Importer options</param>
/// <param name="gpContext">Generic parameter context</param>
public Importer(ModuleDef module, ImporterOptions options, GenericParamContext gpContext) {
this.module = module;
this.recursionCounter = new RecursionCounter();
this.options = options;
this.gpContext = gpContext;
}
/// <summary>
/// Imports a <see cref="Type"/> as a <see cref="ITypeDefOrRef"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c> if <paramref name="type"/> is invalid</returns>
public ITypeDefOrRef Import(Type type) {
return module.UpdateRowId(ImportAsTypeSig(type).ToTypeDefOrRef());
}
/// <summary>
/// Imports a <see cref="Type"/> as a <see cref="ITypeDefOrRef"/>
/// </summary>
/// <param name="type">The type</param>
/// <param name="requiredModifiers">A list of all required modifiers or <c>null</c></param>
/// <param name="optionalModifiers">A list of all optional modifiers or <c>null</c></param>
/// <returns>The imported type or <c>null</c> if <paramref name="type"/> is invalid</returns>
public ITypeDefOrRef Import(Type type, IList<Type> requiredModifiers, IList<Type> optionalModifiers) {
return module.UpdateRowId(ImportAsTypeSig(type, requiredModifiers, optionalModifiers).ToTypeDefOrRef());
}
/// <summary>
/// Imports a <see cref="Type"/> as a <see cref="TypeSig"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c> if <paramref name="type"/> is invalid</returns>
public TypeSig ImportAsTypeSig(Type type) {
return ImportAsTypeSig(type, false);
}
TypeSig ImportAsTypeSig(Type type, bool treatAsGenericInst) {
if (type == null)
return null;
switch (treatAsGenericInst ? ElementType.GenericInst : type.GetElementType2()) {
case ElementType.Void: return module.CorLibTypes.Void;
case ElementType.Boolean: return module.CorLibTypes.Boolean;
case ElementType.Char: return module.CorLibTypes.Char;
case ElementType.I1: return module.CorLibTypes.SByte;
case ElementType.U1: return module.CorLibTypes.Byte;
case ElementType.I2: return module.CorLibTypes.Int16;
case ElementType.U2: return module.CorLibTypes.UInt16;
case ElementType.I4: return module.CorLibTypes.Int32;
case ElementType.U4: return module.CorLibTypes.UInt32;
case ElementType.I8: return module.CorLibTypes.Int64;
case ElementType.U8: return module.CorLibTypes.UInt64;
case ElementType.R4: return module.CorLibTypes.Single;
case ElementType.R8: return module.CorLibTypes.Double;
case ElementType.String: return module.CorLibTypes.String;
case ElementType.TypedByRef:return module.CorLibTypes.TypedReference;
case ElementType.U: return module.CorLibTypes.UIntPtr;
case ElementType.Object: return module.CorLibTypes.Object;
case ElementType.Ptr: return new PtrSig(ImportAsTypeSig(type.GetElementType(), treatAsGenericInst));
case ElementType.ByRef: return new ByRefSig(ImportAsTypeSig(type.GetElementType(), treatAsGenericInst));
case ElementType.SZArray: return new SZArraySig(ImportAsTypeSig(type.GetElementType(), treatAsGenericInst));
case ElementType.ValueType: return new ValueTypeSig(CreateTypeRef(type));
case ElementType.Class: return new ClassSig(CreateTypeRef(type));
case ElementType.Var: return new GenericVar((uint)type.GenericParameterPosition, gpContext.Type);
case ElementType.MVar: return new GenericMVar((uint)type.GenericParameterPosition, gpContext.Method);
case ElementType.I:
FixSignature = true; // FnPtr is mapped to System.IntPtr
return module.CorLibTypes.IntPtr;
case ElementType.Array:
FixSignature = true; // We don't know sizes and lower bounds
return new ArraySig(ImportAsTypeSig(type.GetElementType(), treatAsGenericInst), (uint)type.GetArrayRank());
case ElementType.GenericInst:
var typeGenArgs = type.GetGenericArguments();
var git = new GenericInstSig(ImportAsTypeSig(type.GetGenericTypeDefinition()) as ClassOrValueTypeSig, (uint)typeGenArgs.Length);
foreach (var ga in typeGenArgs)
git.GenericArguments.Add(ImportAsTypeSig(ga));
return git;
case ElementType.Sentinel:
case ElementType.Pinned:
case ElementType.FnPtr: // mapped to System.IntPtr
case ElementType.CModReqd:
case ElementType.CModOpt:
case ElementType.ValueArray:
case ElementType.R:
case ElementType.Internal:
case ElementType.Module:
case ElementType.End:
default:
return null;
}
}
ITypeDefOrRef TryResolve(TypeRef tr) {
if (!TryToUseTypeDefs || tr == null)
return tr;
if (!IsThisModule(tr))
return tr;
var td = tr.Resolve();
if (td == null || td.Module != module)
return tr;
return td;
}
IMethodDefOrRef TryResolveMethod(IMethodDefOrRef mdr) {
if (!TryToUseMethodDefs || mdr == null)
return mdr;
var mr = mdr as MemberRef;
if (mr == null)
return mdr;
if (!mr.IsMethodRef)
return mr;
var declType = GetDeclaringType(mr);
if (declType == null)
return mr;
if (declType.Module != module)
return mr;
return (IMethodDefOrRef)declType.ResolveMethod(mr) ?? mr;
}
IField TryResolveField(MemberRef mr) {
if (!TryToUseFieldDefs || mr == null)
return mr;
if (!mr.IsFieldRef)
return mr;
var declType = GetDeclaringType(mr);
if (declType == null)
return mr;
if (declType.Module != module)
return mr;
return (IField)declType.ResolveField(mr) ?? mr;
}
TypeDef GetDeclaringType(MemberRef mr) {
if (mr == null)
return null;
var td = mr.Class as TypeDef;
if (td != null)
return td;
td = TryResolve(mr.Class as TypeRef) as TypeDef;
if (td != null)
return td;
var modRef = mr.Class as ModuleRef;
if (IsThisModule(modRef))
return module.GlobalType;
return null;
}
bool IsThisModule(TypeRef tr) {
if (tr == null)
return false;
var scopeType = tr.ScopeType.GetNonNestedTypeRefScope() as TypeRef;
if (scopeType == null)
return false;
if (module == scopeType.ResolutionScope)
return true;
var modRef = scopeType.ResolutionScope as ModuleRef;
if (modRef != null)
return IsThisModule(modRef);
var asmRef = scopeType.ResolutionScope as AssemblyRef;
return Equals(module.Assembly, asmRef);
}
bool IsThisModule(ModuleRef modRef) {
return modRef != null &&
module.Name == modRef.Name &&
Equals(module.Assembly, modRef.DefinitionAssembly);
}
static bool Equals(IAssembly a, IAssembly b) {
if (a == b)
return true;
if (a == null || b == null)
return false;
return Utils.Equals(a.Version, b.Version) &&
PublicKeyBase.TokenEquals(a.PublicKeyOrToken, b.PublicKeyOrToken) &&
UTF8String.Equals(a.Name, b.Name) &&
UTF8String.CaseInsensitiveEquals(a.Culture, b.Culture);
}
ITypeDefOrRef CreateTypeRef(Type type) {
return TryResolve(CreateTypeRef2(type));
}
TypeRef CreateTypeRef2(Type type) {
if (!type.IsNested)
return module.UpdateRowId(new TypeRefUser(module, type.Namespace ?? string.Empty, type.Name ?? string.Empty, CreateScopeReference(type)));
return module.UpdateRowId(new TypeRefUser(module, string.Empty, type.Name ?? string.Empty, CreateTypeRef2(type.DeclaringType)));
}
IResolutionScope CreateScopeReference(Type type) {
if (type == null)
return null;
var asmName = type.Assembly.GetName();
var modAsm = module.Assembly;
if (modAsm != null) {
if (UTF8String.ToSystemStringOrEmpty(modAsm.Name).Equals(asmName.Name, StringComparison.OrdinalIgnoreCase)) {
if (UTF8String.ToSystemStringOrEmpty(module.Name).Equals(type.Module.ScopeName, StringComparison.OrdinalIgnoreCase))
return module;
return module.UpdateRowId(new ModuleRefUser(module, type.Module.ScopeName));
}
}
var pkt = asmName.GetPublicKeyToken();
if (pkt == null || pkt.Length == 0)
pkt = null;
return module.UpdateRowId(new AssemblyRefUser(asmName.Name, asmName.Version, PublicKeyBase.CreatePublicKeyToken(pkt), asmName.CultureInfo.Name));
}
/// <summary>
/// Imports a <see cref="Type"/> as a <see cref="ITypeDefOrRef"/>
/// </summary>
/// <param name="type">The type</param>
/// <param name="requiredModifiers">A list of all required modifiers or <c>null</c></param>
/// <param name="optionalModifiers">A list of all optional modifiers or <c>null</c></param>
/// <returns>The imported type or <c>null</c> if <paramref name="type"/> is invalid</returns>
public TypeSig ImportAsTypeSig(Type type, IList<Type> requiredModifiers, IList<Type> optionalModifiers) {
return ImportAsTypeSig(type, requiredModifiers, optionalModifiers, false);
}
TypeSig ImportAsTypeSig(Type type, IList<Type> requiredModifiers, IList<Type> optionalModifiers, bool treatAsGenericInst) {
if (type == null)
return null;
if (IsEmpty(requiredModifiers) && IsEmpty(optionalModifiers))
return ImportAsTypeSig(type, treatAsGenericInst);
FixSignature = true; // Order of modifiers is unknown
var ts = ImportAsTypeSig(type, treatAsGenericInst);
// We don't know the original order of the modifiers.
// Assume all required modifiers are closer to the real type.
// Assume all modifiers should be applied in the same order as in the lists.
if (requiredModifiers != null) {
foreach (var modifier in requiredModifiers.GetSafeEnumerable())
ts = new CModReqdSig(Import(modifier), ts);
}
if (optionalModifiers != null) {
foreach (var modifier in optionalModifiers.GetSafeEnumerable())
ts = new CModOptSig(Import(modifier), ts);
}
return ts;
}
static bool IsEmpty<T>(IList<T> list) {
return list == null || list.Count == 0;
}
/// <summary>
/// Imports a <see cref="MethodBase"/> as a <see cref="IMethod"/>. This will be either
/// a <see cref="MemberRef"/> or a <see cref="MethodSpec"/>.
/// </summary>
/// <param name="methodBase">The method</param>
/// <returns>The imported method or <c>null</c> if <paramref name="methodBase"/> is invalid
/// or if we failed to import the method</returns>
public IMethod Import(MethodBase methodBase) {
return Import(methodBase, false);
}
/// <summary>
/// Imports a <see cref="MethodBase"/> as a <see cref="IMethod"/>. This will be either
/// a <see cref="MemberRef"/> or a <see cref="MethodSpec"/>.
/// </summary>
/// <param name="methodBase">The method</param>
/// <param name="forceFixSignature">Always verify method signature to make sure the
/// returned reference matches the metadata in the source assembly</param>
/// <returns>The imported method or <c>null</c> if <paramref name="methodBase"/> is invalid
/// or if we failed to import the method</returns>
public IMethod Import(MethodBase methodBase, bool forceFixSignature) {
FixSignature = false;
return ImportInternal(methodBase, forceFixSignature);
}
IMethod ImportInternal(MethodBase methodBase) {
return ImportInternal(methodBase, false);
}
IMethod ImportInternal(MethodBase methodBase, bool forceFixSignature) {
if (methodBase == null)
return null;
if (forceFixSignature) {
//TODO:
}
bool isMethodSpec = methodBase.IsGenericButNotGenericMethodDefinition();
if (isMethodSpec) {
IMethodDefOrRef method;
var origMethod = methodBase.Module.ResolveMethod(methodBase.MetadataToken);
if (methodBase.DeclaringType.GetElementType2() == ElementType.GenericInst)
method = module.UpdateRowId(new MemberRefUser(module, methodBase.Name, CreateMethodSig(origMethod), Import(methodBase.DeclaringType)));
else
method = ImportInternal(origMethod) as IMethodDefOrRef;
method = TryResolveMethod(method);
var gim = CreateGenericInstMethodSig(methodBase);
var methodSpec = module.UpdateRowId(new MethodSpecUser(method, gim));
if (FixSignature && !forceFixSignature) {
//TODO:
}
return methodSpec;
}
else {
IMemberRefParent parent;
if (methodBase.DeclaringType == null) {
// It's the global type. We can reference it with a ModuleRef token.
parent = GetModuleParent(methodBase.Module);
}
else
parent = Import(methodBase.DeclaringType);
if (parent == null)
return null;
MethodBase origMethod;
try {
// Get the original method def in case the declaring type is a generic
// type instance and the method uses at least one generic type parameter.
origMethod = methodBase.Module.ResolveMethod(methodBase.MetadataToken);
}
catch (ArgumentException) {
// Here if eg. the method was created by the runtime (eg. a multi-dimensional
// array getter/setter method). The method token is in that case 0x06000000,
// which is invalid.
origMethod = methodBase;
}
var methodSig = CreateMethodSig(origMethod);
IMethodDefOrRef methodRef = module.UpdateRowId(new MemberRefUser(module, methodBase.Name, methodSig, parent));
methodRef = TryResolveMethod(methodRef);
if (FixSignature && !forceFixSignature) {
//TODO:
}
return methodRef;
}
}
MethodSig CreateMethodSig(MethodBase mb) {
var sig = new MethodSig(GetCallingConvention(mb));
var mi = mb as MethodInfo;
if (mi != null)
sig.RetType = ImportAsTypeSig(mi.ReturnParameter, mb.DeclaringType);
else
sig.RetType = module.CorLibTypes.Void;
foreach (var p in mb.GetParameters())
sig.Params.Add(ImportAsTypeSig(p, mb.DeclaringType));
if (mb.IsGenericMethodDefinition)
sig.GenParamCount = (uint)mb.GetGenericArguments().Length;
return sig;
}
TypeSig ImportAsTypeSig(ParameterInfo p, Type declaringType) {
return ImportAsTypeSig(p.ParameterType, p.GetRequiredCustomModifiers(), p.GetOptionalCustomModifiers(), declaringType.MustTreatTypeAsGenericInstType(p.ParameterType));
}
CallingConvention GetCallingConvention(MethodBase mb) {
CallingConvention cc = 0;
var mbcc = mb.CallingConvention;
if (mb.IsGenericMethodDefinition)
cc |= CallingConvention.Generic;
if ((mbcc & CallingConventions.HasThis) != 0)
cc |= CallingConvention.HasThis;
if ((mbcc & CallingConventions.ExplicitThis) != 0)
cc |= CallingConvention.ExplicitThis;
switch (mbcc & CallingConventions.Any) {
case CallingConventions.Standard:
cc |= CallingConvention.Default;
break;
case CallingConventions.VarArgs:
cc |= CallingConvention.VarArg;
break;
case CallingConventions.Any:
default:
FixSignature = true;
cc |= CallingConvention.Default;
break;
}
return cc;
}
GenericInstMethodSig CreateGenericInstMethodSig(MethodBase mb) {
var genMethodArgs = mb.GetGenericArguments();
var gim = new GenericInstMethodSig(CallingConvention.GenericInst, (uint)genMethodArgs.Length);
foreach (var gma in genMethodArgs)
gim.GenericArguments.Add(ImportAsTypeSig(gma));
return gim;
}
IMemberRefParent GetModuleParent(Module module2) {
// If we have no assembly, assume this is a netmodule in the same assembly as module
var modAsm = module.Assembly;
bool isSameAssembly = modAsm == null ||
UTF8String.ToSystemStringOrEmpty(modAsm.Name).Equals(module2.Assembly.GetName().Name, StringComparison.OrdinalIgnoreCase);
if (!isSameAssembly)
return null;
return module.UpdateRowId(new ModuleRefUser(module, module.Name));
}
/// <summary>
/// Imports a <see cref="FieldInfo"/> as a <see cref="MemberRef"/>
/// </summary>
/// <param name="fieldInfo">The field</param>
/// <returns>The imported field or <c>null</c> if <paramref name="fieldInfo"/> is invalid
/// or if we failed to import the field</returns>
public IField Import(FieldInfo fieldInfo) {
return Import(fieldInfo, false);
}
/// <summary>
/// Imports a <see cref="FieldInfo"/> as a <see cref="MemberRef"/>
/// </summary>
/// <param name="fieldInfo">The field</param>
/// <param name="forceFixSignature">Always verify field signature to make sure the
/// returned reference matches the metadata in the source assembly</param>
/// <returns>The imported field or <c>null</c> if <paramref name="fieldInfo"/> is invalid
/// or if we failed to import the field</returns>
public IField Import(FieldInfo fieldInfo, bool forceFixSignature) {
FixSignature = false;
if (fieldInfo == null)
return null;
if (forceFixSignature) {
//TODO:
}
IMemberRefParent parent;
if (fieldInfo.DeclaringType == null) {
// It's the global type. We can reference it with a ModuleRef token.
parent = GetModuleParent(fieldInfo.Module);
}
else
parent = Import(fieldInfo.DeclaringType);
if (parent == null)
return null;
FieldInfo origField;
try {
// Get the original field def in case the declaring type is a generic
// type instance and the field uses a generic type parameter.
origField = fieldInfo.Module.ResolveField(fieldInfo.MetadataToken);
}
catch (ArgumentException) {
origField = fieldInfo;
}
MemberRef fieldRef;
if (origField.FieldType.ContainsGenericParameters) {
var origDeclType = origField.DeclaringType;
var asm = module.Context.AssemblyResolver.Resolve(origDeclType.Module.Assembly.GetName(), module);
if (asm == null || asm.FullName != origDeclType.Assembly.FullName)
throw new Exception("Couldn't resolve the correct assembly");
var mod = asm.FindModule(origDeclType.Module.Name) as ModuleDefMD;
if (mod == null)
throw new Exception("Couldn't resolve the correct module");
var fieldDef = mod.ResolveField((uint)(origField.MetadataToken & 0x00FFFFFF));
if (fieldDef == null)
throw new Exception("Couldn't resolve the correct field");
var fieldSig = new FieldSig(Import(fieldDef.FieldSig.GetFieldType()));
fieldRef = module.UpdateRowId(new MemberRefUser(module, fieldInfo.Name, fieldSig, parent));
}
else {
var fieldSig = new FieldSig(ImportAsTypeSig(fieldInfo.FieldType, fieldInfo.GetRequiredCustomModifiers(), fieldInfo.GetOptionalCustomModifiers()));
fieldRef = module.UpdateRowId(new MemberRefUser(module, fieldInfo.Name, fieldSig, parent));
}
var field = TryResolveField(fieldRef);
if (FixSignature && !forceFixSignature) {
//TODO:
}
return field;
}
/// <summary>
/// Imports a <see cref="IType"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c></returns>
public IType Import(IType type) {
if (type == null)
return null;
if (!recursionCounter.Increment())
return null;
IType result;
TypeDef td;
TypeRef tr;
TypeSpec ts;
TypeSig sig;
if ((td = type as TypeDef) != null)
result = Import(td);
else if ((tr = type as TypeRef) != null)
result = Import(tr);
else if ((ts = type as TypeSpec) != null)
result = Import(ts);
else if ((sig = type as TypeSig) != null)
result = Import(sig);
else
result = null;
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="TypeDef"/> as a <see cref="TypeRef"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c></returns>
public ITypeDefOrRef Import(TypeDef type) {
if (type == null)
return null;
if (TryToUseTypeDefs && type.Module == module)
return type;
return Import2(type);
}
TypeRef Import2(TypeDef type) {
if (type == null)
return null;
if (!recursionCounter.Increment())
return null;
TypeRef result;
var declType = type.DeclaringType;
if (declType != null)
result = module.UpdateRowId(new TypeRefUser(module, type.Namespace, type.Name, Import2(declType)));
else
result = module.UpdateRowId(new TypeRefUser(module, type.Namespace, type.Name, CreateScopeReference(type.DefinitionAssembly, type.Module)));
recursionCounter.Decrement();
return result;
}
IResolutionScope CreateScopeReference(IAssembly defAsm, ModuleDef defMod) {
if (defAsm == null)
return null;
var modAsm = module.Assembly;
if (defMod != null && defAsm != null && modAsm != null) {
if (UTF8String.CaseInsensitiveEquals(modAsm.Name, defAsm.Name)) {
if (UTF8String.CaseInsensitiveEquals(module.Name, defMod.Name))
return module;
return module.UpdateRowId(new ModuleRefUser(module, defMod.Name));
}
}
var pkt = PublicKeyBase.ToPublicKeyToken(defAsm.PublicKeyOrToken);
if (PublicKeyBase.IsNullOrEmpty2(pkt))
pkt = null;
return module.UpdateRowId(new AssemblyRefUser(defAsm.Name, defAsm.Version, pkt, defAsm.Culture) { Attributes = defAsm.Attributes & ~AssemblyAttributes.PublicKey });
}
/// <summary>
/// Imports a <see cref="TypeRef"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c></returns>
public ITypeDefOrRef Import(TypeRef type) {
return TryResolve(Import2(type));
}
TypeRef Import2(TypeRef type) {
if (type == null)
return null;
if (!recursionCounter.Increment())
return null;
TypeRef result;
var declaringType = type.DeclaringType;
if (declaringType != null)
result = module.UpdateRowId(new TypeRefUser(module, type.Namespace, type.Name, Import2(declaringType)));
else
result = module.UpdateRowId(new TypeRefUser(module, type.Namespace, type.Name, CreateScopeReference(type.DefinitionAssembly, type.Module)));
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="TypeSpec"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c></returns>
public TypeSpec Import(TypeSpec type) {
if (type == null)
return null;
return module.UpdateRowId(new TypeSpecUser(Import(type.TypeSig)));
}
/// <summary>
/// Imports a <see cref="TypeSig"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c></returns>
public TypeSig Import(TypeSig type) {
if (type == null)
return null;
if (!recursionCounter.Increment())
return null;
TypeSig result;
switch (type.ElementType) {
case ElementType.Void: result = module.CorLibTypes.Void; break;
case ElementType.Boolean: result = module.CorLibTypes.Boolean; break;
case ElementType.Char: result = module.CorLibTypes.Char; break;
case ElementType.I1: result = module.CorLibTypes.SByte; break;
case ElementType.U1: result = module.CorLibTypes.Byte; break;
case ElementType.I2: result = module.CorLibTypes.Int16; break;
case ElementType.U2: result = module.CorLibTypes.UInt16; break;
case ElementType.I4: result = module.CorLibTypes.Int32; break;
case ElementType.U4: result = module.CorLibTypes.UInt32; break;
case ElementType.I8: result = module.CorLibTypes.Int64; break;
case ElementType.U8: result = module.CorLibTypes.UInt64; break;
case ElementType.R4: result = module.CorLibTypes.Single; break;
case ElementType.R8: result = module.CorLibTypes.Double; break;
case ElementType.String: result = module.CorLibTypes.String; break;
case ElementType.TypedByRef:result = module.CorLibTypes.TypedReference; break;
case ElementType.I: result = module.CorLibTypes.IntPtr; break;
case ElementType.U: result = module.CorLibTypes.UIntPtr; break;
case ElementType.Object: result = module.CorLibTypes.Object; break;
case ElementType.Ptr: result = new PtrSig(Import(type.Next)); break;
case ElementType.ByRef: result = new ByRefSig(Import(type.Next)); break;
case ElementType.ValueType: result = CreateClassOrValueType((type as ClassOrValueTypeSig).TypeDefOrRef, true); break;
case ElementType.Class: result = CreateClassOrValueType((type as ClassOrValueTypeSig).TypeDefOrRef, false); break;
case ElementType.Var: result = new GenericVar((type as GenericVar).Number, gpContext.Type); break;
case ElementType.ValueArray:result = new ValueArraySig(Import(type.Next), (type as ValueArraySig).Size); break;
case ElementType.FnPtr: result = new FnPtrSig(Import((type as FnPtrSig).Signature)); break;
case ElementType.SZArray: result = new SZArraySig(Import(type.Next)); break;
case ElementType.MVar: result = new GenericMVar((type as GenericMVar).Number, gpContext.Method); break;
case ElementType.CModReqd: result = new CModReqdSig(Import((type as ModifierSig).Modifier), Import(type.Next)); break;
case ElementType.CModOpt: result = new CModOptSig(Import((type as ModifierSig).Modifier), Import(type.Next)); break;
case ElementType.Module: result = new ModuleSig((type as ModuleSig).Index, Import(type.Next)); break;
case ElementType.Sentinel: result = new SentinelSig(); break;
case ElementType.Pinned: result = new PinnedSig(Import(type.Next)); break;
case ElementType.Array:
var arraySig = (ArraySig)type;
var sizes = new List<uint>(arraySig.Sizes);
var lbounds = new List<int>(arraySig.LowerBounds);
result = new ArraySig(Import(type.Next), arraySig.Rank, sizes, lbounds);
break;
case ElementType.GenericInst:
var gis = (GenericInstSig)type;
var genArgs = new List<TypeSig>(gis.GenericArguments.Count);
foreach (var ga in gis.GenericArguments.GetSafeEnumerable())
genArgs.Add(Import(ga));
result = new GenericInstSig(Import(gis.GenericType) as ClassOrValueTypeSig, genArgs);
break;
case ElementType.End:
case ElementType.R:
case ElementType.Internal:
default:
result = null;
break;
}
recursionCounter.Decrement();
return result;
}
ITypeDefOrRef Import(ITypeDefOrRef type) {
return (ITypeDefOrRef)Import((IType)type);
}
TypeSig CreateClassOrValueType(ITypeDefOrRef type, bool isValueType) {
var corLibType = module.CorLibTypes.GetCorLibTypeSig(type);
if (corLibType != null)
return corLibType;
if (isValueType)
return new ValueTypeSig(Import(type));
return new ClassSig(Import(type));
}
/// <summary>
/// Imports a <see cref="CallingConventionSig"/>
/// </summary>
/// <param name="sig">The sig</param>
/// <returns>The imported sig or <c>null</c> if input is invalid</returns>
public CallingConventionSig Import(CallingConventionSig sig) {
if (sig == null)
return null;
if (!recursionCounter.Increment())
return null;
CallingConventionSig result;
var sigType = sig.GetType();
if (sigType == typeof(MethodSig))
result = Import((MethodSig)sig);
else if (sigType == typeof(FieldSig))
result = Import((FieldSig)sig);
else if (sigType == typeof(GenericInstMethodSig))
result = Import((GenericInstMethodSig)sig);
else if (sigType == typeof(PropertySig))
result = Import((PropertySig)sig);
else if (sigType == typeof(LocalSig))
result = Import((LocalSig)sig);
else
result = null; // Should never be reached
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="FieldSig"/>
/// </summary>
/// <param name="sig">The sig</param>
/// <returns>The imported sig or <c>null</c> if input is invalid</returns>
public FieldSig Import(FieldSig sig) {
if (sig == null)
return null;
if (!recursionCounter.Increment())
return null;
var result = new FieldSig(sig.GetCallingConvention(), Import(sig.Type));
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="MethodSig"/>
/// </summary>
/// <param name="sig">The sig</param>
/// <returns>The imported sig or <c>null</c> if input is invalid</returns>
public MethodSig Import(MethodSig sig) {
if (sig == null)
return null;
if (!recursionCounter.Increment())
return null;
MethodSig result = Import(new MethodSig(sig.GetCallingConvention()), sig);
recursionCounter.Decrement();
return result;
}
T Import<T>(T sig, T old) where T : MethodBaseSig {
sig.RetType = Import(old.RetType);
foreach (var p in old.Params.GetSafeEnumerable())
sig.Params.Add(Import(p));
sig.GenParamCount = old.GenParamCount;
var paramsAfterSentinel = sig.ParamsAfterSentinel;
if (paramsAfterSentinel != null) {
foreach (var p in old.ParamsAfterSentinel.GetSafeEnumerable())
paramsAfterSentinel.Add(Import(p));
}
return sig;
}
/// <summary>
/// Imports a <see cref="PropertySig"/>
/// </summary>
/// <param name="sig">The sig</param>
/// <returns>The imported sig or <c>null</c> if input is invalid</returns>
public PropertySig Import(PropertySig sig) {
if (sig == null)
return null;
if (!recursionCounter.Increment())
return null;
PropertySig result = Import(new PropertySig(sig.GetCallingConvention()), sig);
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="LocalSig"/>
/// </summary>
/// <param name="sig">The sig</param>
/// <returns>The imported sig or <c>null</c> if input is invalid</returns>
public LocalSig Import(LocalSig sig) {
if (sig == null)
return null;
if (!recursionCounter.Increment())
return null;
LocalSig result = new LocalSig(sig.GetCallingConvention(), (uint)sig.Locals.Count);
foreach (var l in sig.Locals.GetSafeEnumerable())
result.Locals.Add(Import(l));
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="GenericInstMethodSig"/>
/// </summary>
/// <param name="sig">The sig</param>
/// <returns>The imported sig or <c>null</c> if input is invalid</returns>
public GenericInstMethodSig Import(GenericInstMethodSig sig) {
if (sig == null)
return null;
if (!recursionCounter.Increment())
return null;
GenericInstMethodSig result = new GenericInstMethodSig(sig.GetCallingConvention(), (uint)sig.GenericArguments.Count);
foreach (var l in sig.GenericArguments.GetSafeEnumerable())
result.GenericArguments.Add(Import(l));
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="IField"/>
/// </summary>
/// <param name="field">The field</param>
/// <returns>The imported type or <c>null</c> if <paramref name="field"/> is invalid</returns>
public IField Import(IField field) {
if (field == null)
return null;
if (!recursionCounter.Increment())
return null;
IField result;
MemberRef mr;
FieldDef fd;
if ((fd = field as FieldDef) != null)
result = Import(fd);
else if ((mr = field as MemberRef) != null)
result = Import(mr);
else
result = null;
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="IMethod"/>
/// </summary>
/// <param name="method">The method</param>
/// <returns>The imported method or <c>null</c> if <paramref name="method"/> is invalid</returns>
public IMethod Import(IMethod method) {
if (method == null)
return null;
if (!recursionCounter.Increment())
return null;
IMethod result;
MethodDef md;
MethodSpec ms;
MemberRef mr;
if ((md = method as MethodDef) != null)
result = Import(md);
else if ((ms = method as MethodSpec) != null)
result = Import(ms);
else if ((mr = method as MemberRef) != null)
result = Import(mr);
else
result = null;
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="FieldDef"/> as an <see cref="IField"/>
/// </summary>
/// <param name="field">The field</param>
/// <returns>The imported type or <c>null</c> if <paramref name="field"/> is invalid</returns>
public IField Import(FieldDef field) {
if (field == null)
return null;
if (TryToUseFieldDefs && field.Module == module)
return field;
if (!recursionCounter.Increment())
return null;
MemberRef result = module.UpdateRowId(new MemberRefUser(module, field.Name));
result.Signature = Import(field.Signature);
result.Class = ImportParent(field.DeclaringType);
recursionCounter.Decrement();
return result;
}
IMemberRefParent ImportParent(TypeDef type) {
if (type == null)
return null;
if (type.IsGlobalModuleType) {
var om = type.Module;
return module.UpdateRowId(new ModuleRefUser(module, om == null ? null : om.Name));
}
return Import(type);
}
/// <summary>
/// Imports a <see cref="MethodDef"/> as an <see cref="IMethod"/>
/// </summary>
/// <param name="method">The method</param>
/// <returns>The imported method or <c>null</c> if <paramref name="method"/> is invalid</returns>
public IMethod Import(MethodDef method) {
if (method == null)
return null;
if (TryToUseMethodDefs && method.Module == module)
return method;
if (!recursionCounter.Increment())
return null;
MemberRef result = module.UpdateRowId(new MemberRefUser(module, method.Name));
result.Signature = Import(method.Signature);
result.Class = ImportParent(method.DeclaringType);
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="MethodSpec"/>
/// </summary>
/// <param name="method">The method</param>
/// <returns>The imported method or <c>null</c> if <paramref name="method"/> is invalid</returns>
public MethodSpec Import(MethodSpec method) {
if (method == null)
return null;
if (!recursionCounter.Increment())
return null;
MethodSpec result = module.UpdateRowId(new MethodSpecUser((IMethodDefOrRef)Import(method.Method)));
result.Instantiation = Import(method.Instantiation);
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="MemberRef"/>
/// </summary>
/// <param name="memberRef">The member ref</param>
/// <returns>The imported member ref or <c>null</c> if <paramref name="memberRef"/> is invalid</returns>
public MemberRef Import(MemberRef memberRef) {
if (memberRef == null)
return null;
if (!recursionCounter.Increment())
return null;
MemberRef result = module.UpdateRowId(new MemberRefUser(module, memberRef.Name));
result.Signature = Import(memberRef.Signature);
result.Class = Import(memberRef.Class);
if (result.Class == null) // Will be null if memberRef.Class is null or a MethodDef
result = null;
recursionCounter.Decrement();
return result;
}
IMemberRefParent Import(IMemberRefParent parent) {
var tdr = parent as ITypeDefOrRef;
if (tdr != null) {
var td = tdr as TypeDef;
if (td != null && td.IsGlobalModuleType) {
var om = td.Module;
return module.UpdateRowId(new ModuleRefUser(module, om == null ? null : om.Name));
}
return Import(tdr);
}
var modRef = parent as ModuleRef;
if (modRef != null)
return module.UpdateRowId(new ModuleRefUser(module, modRef.Name));
var method = parent as MethodDef;
if (method != null) {
var dt = method.DeclaringType;
return dt == null || dt.Module != module ? null : method;
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using VistaControls.TaskDialog;
using System.Drawing.Drawing2D;
using System.Diagnostics;
namespace VistaControlsApp {
public partial class NewMain : VistaControls.Dwm.Helpers.GlassForm {
Timer _timer;
Form _thumbnailedWindow = null;
public NewMain() {
InitializeComponent();
_thumbnailedWindow = new ThumbnailedWindow();
_thumbnailedWindow.Show(this);
_thumbnailedWindow.Location = new Point(Location.X + Size.Width, Location.Y);
thumbnailViewer1.SetThumbnail(_thumbnailedWindow, true);
tabPage5.VisibleChanged += new EventHandler(NewMain_VisibleChanged);
this.ResizeRedraw = true;
}
void NewMain_VisibleChanged(object sender, EventArgs e) {
foreach (Control c in tabPage5.Controls)
c.Visible = tabPage5.Visible;
}
protected override void OnShown(EventArgs e) {
base.OnShown(e);
//Initialize glass sheet
GlassMargins = new VistaControls.Dwm.Margins(0, 0, 58, 28);
//Init timer for animated footer
_timer = new Timer();
_timer.Interval = 4200;
_timer.Enabled = true;
_timer.Tick += new EventHandler(_timer_Tick);
}
protected override void OnClosing(CancelEventArgs e) {
_thumbnailedWindow.Close();
base.OnClosing(e);
}
int _count = 0;
string[] _vFooterMsg = new string[] {
"This is a status message...",
"...implemented using the Glass Sheet effect...",
"...and painted using the glow effect.",
"It is implemented like a standard WinForms control...",
"...therefore you can place the text label using the designer...",
"...and you may change Text and properties in real-time,",
"...achieving a Windows Media Player-like effect.",
"Enjoy!"
};
void _timer_Tick(object sender, EventArgs e) {
themedLabel2.Text = _vFooterMsg[(_count++ % _vFooterMsg.Length)];
}
private void Search(object sender, EventArgs e) {
string txt = searchTextBox1.Text;
foreach (TabPage p in tabControl1.TabPages) {
if (p.Text.IndexOf(txt, StringComparison.InvariantCultureIgnoreCase) >= 0) {
tabControl1.SelectTab(p);
return;
}
}
searchTextBox1.Focus();
//searchTextBox1.SetFocusWithoutSelection();
}
private void Search_cancelled(object sender, EventArgs e) {
tabControl1.SelectTab(0);
}
private void td_info(object sender, EventArgs e) {
TaskDialog.Show("Information", "Task Dialog", "Content of the task dialog.", TaskDialogButton.OK, TaskDialogIcon.Information);
}
private void ts_warning(object sender, EventArgs e) {
TaskDialog.Show("Warning", "Task Dialog", "Content of the task dialog.", TaskDialogButton.OK, TaskDialogIcon.Warning);
}
private void td_error(object sender, EventArgs e) {
TaskDialog.Show("Error", "Task Dialog", "Content of the task dialog.", TaskDialogButton.OK, TaskDialogIcon.Stop);
}
private void td_shield(object sender, EventArgs e) {
TaskDialog.Show("Shield", "Task Dialog", "Content of the task dialog.", TaskDialogButton.OK, TaskDialogIcon.SecurityShield);
}
private void td_shielderror(object sender, EventArgs e) {
TaskDialog.Show("Security error", "Task Dialog", "Content of the task dialog.", TaskDialogButton.OK, TaskDialogIcon.SecurityError);
}
private void td_shieldsuccess(object sender, EventArgs e) {
TaskDialog.Show("Security success", "Task Dialog", "Content of the task dialog.", TaskDialogButton.OK, TaskDialogIcon.SecuritySuccess);
}
private void td_blueshield(object sender, EventArgs e) {
TaskDialog.Show("Blue shield", "Task Dialog", "Content of the task dialog.", TaskDialogButton.OK, TaskDialogIcon.SecurityShieldBlue);
}
private void td_grayshield(object sender, EventArgs e) {
TaskDialog.Show("Gray shield", "Task Dialog", "Content of the task dialog.", TaskDialogButton.OK, TaskDialogIcon.SecurityShieldGray);
}
private void td_complex(object sender, EventArgs e) {
TaskDialog dlg = new TaskDialog("This is the main instruction", "Complex Task Dialog");
dlg.CommonIcon = TaskDialogIcon.SecurityShieldBlue;
dlg.Content = "You may write long and informative messages, with <a href=\"http://www.google.com\">hyperlinks</a> and linebreaks.\nButtons can also be shaped as Command Link buttons instead of standard buttons. You may also use radio buttons or add a progress bar.";
dlg.UseCommandLinks = true;
dlg.EnableHyperlinks = true;
dlg.CustomButtons = new CustomButton[] {
new CustomButton(9, "Upload\nShows a fake upload task dialog."),
new CustomButton(Result.Cancel, "Close")
};
dlg.RadioButtons = new CustomButton[] {
new CustomButton(1, "First radio button"),
new CustomButton(2, "Second radio button"),
new CustomButton(3, "Third radio button")
};
dlg.ExpandedControlText = "Details";
dlg.ExpandedInformation = "Place some \"expanded information\" here...";
dlg.EnableRadioButton(3, false);
//Evt registration
dlg.ButtonClick += new EventHandler<ClickEventArgs>(dlg_ButtonClick);
Results results = dlg.Show(this.Handle);
}
void dlg_ButtonClick(object sender, ClickEventArgs e) {
if (e.ButtonID == 9) {
e.PreventClosing = true;
VistaControls.TaskDialog.TaskDialog newDlg = new TaskDialog("Uploading...", "Upload");
newDlg.ShowProgressBar = true;
newDlg.EnableCallbackTimer = true;
newDlg.ProgressBarMaxRange = 90;
newDlg.CustomButtons = new CustomButton[] {
new CustomButton(Result.Cancel, "Abort transfer")
};
newDlg.Footer = "Elapsed time: 0s.";
newDlg.FooterCommonIcon = TaskDialogIcon.Information;
VistaControls.TaskDialog.TaskDialog dlg = (VistaControls.TaskDialog.TaskDialog)sender;
dlg.Navigate(newDlg);
tickHandler = new EventHandler<TimerEventArgs>(dlg_Tick);
dlg.Tick += tickHandler;
}
}
EventHandler<TimerEventArgs> tickHandler;
int cTicks = 0;
void dlg_Tick(object sender, TimerEventArgs e) {
VistaControls.TaskDialog.TaskDialog dlg = (VistaControls.TaskDialog.TaskDialog)sender;
cTicks += (int)e.Ticks;
dlg.Footer = "Elapsed time: " + cTicks / 1000 + "s.";
if (dlg.ProgressBarState == VistaControls.ProgressBar.States.Normal) {
dlg.ProgressBarPosition += (int)e.Ticks / 100;
e.ResetCount = true;
}
if (dlg.ProgressBarPosition >= 90) {
VistaControls.TaskDialog.TaskDialog newDlg = new TaskDialog("Upload complete.", "Upload", "Thank you!");
newDlg.CustomButtons = new CustomButton[] {
new CustomButton(Result.Cancel, "Close")
};
dlg.Navigate(newDlg);
dlg.Tick -= tickHandler;
}
}
private void td_progress(object sender, EventArgs e) {
TaskDialog dlg = new TaskDialog("This dialog displays a progress bar", "Marquee Progress Bar", "The progress bar below is in 'marquee' mode, that is it will not show the exact percentage of the work done, but it will show that some work is being done.", TaskDialogButton.Close);
dlg.SetMarqueeProgressBar(true, 30);
dlg.Show(this);
}
private void button12_Click(object sender, EventArgs e) {
thumbnailViewer1.Update();
}
private void commandLink3_Click(object sender, EventArgs e)
{
ControlPanel cp = new ControlPanel();
cp.ShowDialog();
cp.Dispose();
}
private void commandLink1_Click(object sender, EventArgs e)
{
}
private void commandLink4_Click(object sender, EventArgs e)
{
HorizontalPanelExample hp = new HorizontalPanelExample();
hp.ShowDialog();
hp.Dispose();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Security;
namespace System.DirectoryServices.Interop
{
[StructLayout(LayoutKind.Explicit)]
internal struct Variant
{
[FieldOffset(0)]
public ushort varType;
[FieldOffset(2)]
public ushort reserved1;
[FieldOffset(4)]
public ushort reserved2;
[FieldOffset(6)]
public ushort reserved3;
[FieldOffset(8)]
public short boolvalue;
[FieldOffset(8)]
public IntPtr ptr1;
[FieldOffset(12)]
public IntPtr ptr2;
}
internal class UnsafeNativeMethods
{
[DllImport(ExternDll.Activeds, ExactSpelling = true, EntryPoint = "ADsOpenObject", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int IntADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject);
public static int ADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject)
{
try
{
return IntADsOpenObject(path, userName, password, flags, ref iid, out ppObject);
}
catch (EntryPointNotFoundException)
{
throw new InvalidOperationException(SR.DSAdsiNotInstalled);
}
}
[ComImport, Guid("FD8256D0-FD15-11CE-ABC4-02608C9E7553")]
public interface IAds
{
string Name
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Class
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string GUID
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string ADsPath
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Parent
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Schema
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
void GetInfo();
void SetInfo();
object Get([In, MarshalAs(UnmanagedType.BStr)] string bstrName);
void Put([In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In] object vProp);
[PreserveSig]
int GetEx([In, MarshalAs(UnmanagedType.BStr)] string bstrName, [Out] out object value);
void PutEx(
[In, MarshalAs(UnmanagedType.U4)] int lnControlCode,
[In, MarshalAs(UnmanagedType.BStr)] string bstrName,
[In] object vProp);
void GetInfoEx([In] object vProperties, [In, MarshalAs(UnmanagedType.U4)] int lnReserved);
}
[ComImport, Guid("001677D0-FD16-11CE-ABC4-02608C9E7553")]
public interface IAdsContainer
{
int Count
{
[return: MarshalAs(UnmanagedType.U4)]
get;
}
object _NewEnum
{
[return: MarshalAs(UnmanagedType.Interface)]
get;
}
object Filter { get; set; }
object Hints { get; set; }
[return: MarshalAs(UnmanagedType.Interface)]
object GetObject(
[In, MarshalAs(UnmanagedType.BStr)] string className,
[In, MarshalAs(UnmanagedType.BStr)] string relativeName);
[return: MarshalAs(UnmanagedType.Interface)]
object Create(
[In, MarshalAs(UnmanagedType.BStr)] string className,
[In, MarshalAs(UnmanagedType.BStr)] string relativeName);
void Delete(
[In, MarshalAs(UnmanagedType.BStr)] string className,
[In, MarshalAs(UnmanagedType.BStr)] string relativeName);
[return: MarshalAs(UnmanagedType.Interface)]
object CopyHere(
[In, MarshalAs(UnmanagedType.BStr)] string sourceName,
[In, MarshalAs(UnmanagedType.BStr)] string newName);
[return: MarshalAs(UnmanagedType.Interface)]
object MoveHere(
[In, MarshalAs(UnmanagedType.BStr)] string sourceName,
[In, MarshalAs(UnmanagedType.BStr)] string newName);
}
[ComImport, Guid("B2BD0902-8878-11D1-8C21-00C04FD8D503")]
public interface IAdsDeleteOps
{
void DeleteObject(int flags);
}
/// <summary>
/// PropertyValue as a co-class that implements the IAdsPropertyValue interface.
/// </summary>
[ComImport, Guid("7b9e38b0-a97c-11d0-8534-00c04fd8d503")]
public class PropertyValue
{
}
[ComImport, Guid("9068270B-0939-11D1-8BE1-00C04FD8D503")]
public interface IADsLargeInteger
{
int HighPart { get; set; }
int LowPart { get; set; }
}
[ComImport, Guid("79FA9AD0-A97C-11D0-8534-00C04FD8D503")]
public interface IAdsPropertyValue
{
void Clear();
int ADsType
{
get;
set;
}
string DNString
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
}
string CaseExactString
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
}
string CaseIgnoreString
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
}
string PrintableString
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
}
string NumericString
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
}
bool Boolean { get; set; }
int Integer { get; set; }
object OctetString
{
get;
set;
}
object SecurityDescriptor
{
get;
set;
}
object LargeInteger
{
get;
set;
}
object UTCTime
{
get;
set;
}
}
/// <summary>
/// PropertyEntry as a co-class that implements the IAdsPropertyEntry interface.
/// </summary>
[ComImport, Guid("72D3EDC2-A4C4-11D0-8533-00C04FD8D503")]
public class PropertyEntry
{
}
[ComImport, Guid("05792C8E-941F-11D0-8529-00C04FD8D503")]
public interface IAdsPropertyEntry
{
void Clear();
string Name
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
}
int ADsType
{
get;
set;
}
int ControlCode
{
get;
set;
}
object Values { get; set; }
}
[ComImport, Guid("C6F602B6-8F69-11D0-8528-00C04FD8D503")]
public interface IAdsPropertyList
{
int PropertyCount
{
[return: MarshalAs(UnmanagedType.U4)]
get;
}
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int Next([Out] out object nextProp);
void Skip([In] int cElements);
void Reset();
object Item([In] object varIndex);
object GetPropertyItem([In, MarshalAs(UnmanagedType.BStr)] string bstrName, int ADsType);
void PutPropertyItem([In] object varData);
void ResetPropertyItem([In] object varEntry);
void PurgePropertyList();
}
[ComImport, Guid("109BA8EC-92F0-11D0-A790-00C04FD8D5A8"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
public interface IDirectorySearch
{
void SetSearchPreference([In] IntPtr /*ads_searchpref_info * */pSearchPrefs, int dwNumPrefs);
void ExecuteSearch(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszSearchFilter,
[In, MarshalAs(UnmanagedType.LPArray)] string[] pAttributeNames,
[In] int dwNumberAttributes,
[Out] out IntPtr hSearchResult);
void AbandonSearch([In] IntPtr hSearchResult);
[return: MarshalAs(UnmanagedType.U4)]
[PreserveSig]
int GetFirstRow([In] IntPtr hSearchResult);
[return: MarshalAs(UnmanagedType.U4)]
[PreserveSig]
int GetNextRow([In] IntPtr hSearchResult);
[return: MarshalAs(UnmanagedType.U4)]
[PreserveSig]
int GetPreviousRow([In] IntPtr hSearchResult);
[return: MarshalAs(UnmanagedType.U4)]
[PreserveSig]
int GetNextColumnName(
[In] IntPtr hSearchResult,
[Out] IntPtr ppszColumnName);
void GetColumn(
[In] IntPtr hSearchResult,
[In] IntPtr /* char * */ szColumnName,
[In] IntPtr pSearchColumn);
void FreeColumn([In] IntPtr pSearchColumn);
void CloseSearchHandle([In] IntPtr hSearchResult);
}
[ComImport, Guid("46F14FDA-232B-11D1-A808-00C04FD8D5A8")]
public interface IAdsObjectOptions
{
object GetOption(int flag);
void SetOption(int flag, [In] object varValue);
}
/// <summary>
/// For boolean type, the default marshaller does not work, so need to have specific marshaller. For other types, use the
/// default marshaller which is more efficient. There is no such interface on the type library this is the same as IAdsObjectOptions
/// with a different signature.
/// </summary>
[ComImport, Guid("46F14FDA-232B-11D1-A808-00C04FD8D5A8")]
public interface IAdsObjectOptions2
{
[PreserveSig]
int GetOption(int flag, [Out] out object value);
void SetOption(int option, Variant value);
}
// IDirecorySearch return codes
internal const int S_ADS_NOMORE_ROWS = 0x00005012;
internal const int INVALID_FILTER = unchecked((int)0x8007203E);
internal const int SIZE_LIMIT_EXCEEDED = unchecked((int)0x80072023);
}
}
| |
// Copyright(c) 2016 Andrei Streltsov <andrei@astreltsov.com>
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
namespace Discriminated
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes", Justification = "Multiple type parameters are necessary.")]
public class Union<T1,
T2,
T3,
T4,
T5,
T6
>
{
int tag;
T1 case1;
T2 case2;
T3 case3;
T4 case4;
T5 case5;
T6 case6;
public Union(T1 value) { this.case1 = value; tag = 1; }
public Union(T2 value) { this.case2 = value; tag = 2; }
public Union(T3 value) { this.case3 = value; tag = 3; }
public Union(T4 value) { this.case4 = value; tag = 4; }
public Union(T5 value) { this.case5 = value; tag = 5; }
public Union(T6 value) { this.case6 = value; tag = 6; }
public virtual TResult Match<TResult>(
Func<T1, TResult> case1Handler,
Func<T2, TResult> case2Handler,
Func<T3, TResult> case3Handler,
Func<T4, TResult> case4Handler,
Func<T5, TResult> case5Handler,
Func<T6, TResult> case6Handler
)
{
if (case1Handler == null) throw new ArgumentNullException("case1Handler");
if (case2Handler == null) throw new ArgumentNullException("case2Handler");
if (case3Handler == null) throw new ArgumentNullException("case3Handler");
if (case4Handler == null) throw new ArgumentNullException("case4Handler");
if (case5Handler == null) throw new ArgumentNullException("case5Handler");
if (case6Handler == null) throw new ArgumentNullException("case6Handler");
switch (tag)
{
case 1: return case1Handler(case1);
case 2: return case2Handler(case2);
case 3: return case3Handler(case3);
case 4: return case4Handler(case4);
case 5: return case5Handler(case5);
case 6: return case6Handler(case6);
default: throw new InvalidOperationException();
}
}
public virtual void Match(
Action<T1> case1Handler,
Action<T2> case2Handler,
Action<T3> case3Handler,
Action<T4> case4Handler,
Action<T5> case5Handler,
Action<T6> case6Handler
)
{
if (case1Handler == null) throw new ArgumentNullException("case1Handler");
if (case2Handler == null) throw new ArgumentNullException("case2Handler");
if (case3Handler == null) throw new ArgumentNullException("case3Handler");
if (case4Handler == null) throw new ArgumentNullException("case4Handler");
if (case5Handler == null) throw new ArgumentNullException("case5Handler");
if (case6Handler == null) throw new ArgumentNullException("case6Handler");
switch (tag)
{
case 1: case1Handler(case1); break;
case 2: case2Handler(case2); break;
case 3: case3Handler(case3); break;
case 4: case4Handler(case4); break;
case 5: case5Handler(case5); break;
case 6: case6Handler(case6); break;
default: throw new InvalidOperationException();
}
}
public static bool operator ==(
Union<T1,
T2,
T3,
T4,
T5,
T6
> instanceA,
Union<T1,
T2,
T3,
T4,
T5,
T6
> instanceB
)
{
if (ReferenceEquals(instanceA, null)) return ReferenceEquals(instanceB, null);
return instanceA.Equals(instanceB);
}
public static bool operator !=(
Union<T1,
T2,
T3,
T4,
T5,
T6
> instanceA,
Union<T1,
T2,
T3,
T4,
T5,
T6
> instanceB)
{
return !(instanceA == instanceB);
}
public override bool Equals(object obj)
{
if (obj == null) return false;
var other = obj as Union<T1,
T2,
T3,
T4,
T5,
T6
>;
if (other == null) return false;
if (this.tag != other.tag) return false;
return Case(this).Equals(Case(other));
}
private static object Case(Union<T1,
T2,
T3,
T4,
T5,
T6
> u)
{
switch (u.tag)
{
case 1: return u.case1;
case 2: return u.case2;
case 3: return u.case3;
case 4: return u.case4;
case 5: return u.case5;
case 6: return u.case6;
default: throw new InvalidOperationException();
}
}
public override int GetHashCode()
{
return 17 * this.tag + Case(this).GetHashCode();
}
public string CaseToString()
{
switch (tag)
{
case 1: return case1.ToString();
case 2: return case2.ToString();
case 3: return case3.ToString();
case 4: return case4.ToString();
case 5: return case5.ToString();
case 6: return case6.ToString();
default: throw new InvalidOperationException();
}
}
public Type CaseType()
{
switch (tag)
{
case 1: return case1.GetType();
case 2: return case2.GetType();
case 3: return case3.GetType();
case 4: return case4.GetType();
case 5: return case5.GetType();
case 6: return case6.GetType();
default: throw new InvalidOperationException();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.Test.ModuleCore;
using Xunit;
namespace System.Xml.Linq.Tests
{
public class Annotations
{
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddStringAnnotation(XObject xo)
{
const string expected = "test string";
xo.AddAnnotation(expected);
ValidateAnnotations(xo, new string[] { expected });
Assert.Equal(expected, xo.Annotation<string>());
Assert.Equal(expected, (string)xo.Annotation(typeof(string)));
Assert.Equal(expected, xo.Annotation(typeof(object)));
Assert.Equal(expected, xo.Annotation<object>());
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddIntAnnotation(XObject xo)
{
const int expected = 123456;
xo.AddAnnotation(expected);
ValidateAnnotations(xo, new object[] { expected });
Assert.Equal(expected, xo.Annotation<object>());
Assert.Equal(expected, (int)xo.Annotation(typeof(int)));
Assert.Equal(expected, xo.Annotation(typeof(object)));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddIntAndStringAnnotation(XObject xo)
{
const string expectedStr = "<!@@63784sgdh111>";
const int expectedNum = 123456;
xo.AddAnnotation(expectedStr);
xo.AddAnnotation(expectedNum);
ValidateAnnotations(xo, new object[] { expectedStr, expectedNum });
ValidateAnnotations(xo, new string[] { expectedStr });
Assert.Equal(expectedNum, (int)xo.Annotation(typeof(int)));
Assert.Equal(expectedStr, xo.Annotation<string>());
Assert.Equal(expectedStr, (string)xo.Annotation(typeof(string)));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddRemoveGetAnnotation(XObject xo)
{
string str1 = "<!@@63784sgdh111>";
string str2 = "<!@@63784sgdh222>";
int num = 123456;
xo.AddAnnotation(str1);
xo.AddAnnotation(str2);
xo.AddAnnotation(num);
ValidateAnnotations(xo, new object[] { str1, str2, num });
ValidateAnnotations(xo, new string[] { str1, str2 });
xo.RemoveAnnotations<string>();
ValidateAnnotations(xo, new object[] { num });
xo.RemoveAnnotations(typeof(int));
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveAnnotationWithoutAdding(XObject xo)
{
xo.RemoveAnnotations<string>();
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
xo.RemoveAnnotations(typeof(int));
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddIntRemoveStringGetIntAnnotation(XObject xo)
{
const int num = 123456;
xo.AddAnnotation(num);
xo.RemoveAnnotations<string>();
ValidateAnnotations(xo, new object[] { num });
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddMultipleStringAnnotations(XObject xo)
{
const string str1 = "<!@@63784sgdh111>";
const string str2 = "sdjverqjbe4 kjvweh342$$% ";
xo.AddAnnotation(str1);
xo.AddAnnotation(str2);
ValidateAnnotations(xo, new string[] { str1, str2 });
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveAnnotationTwice(XObject xo)
{
xo.RemoveAnnotations<object>();
xo.RemoveAnnotations<object>();
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddGenericAnnotation(XObject xo)
{
Dictionary<string, string> d = new Dictionary<string, string>();
xo.AddAnnotation(d);
ValidateAnnotations(xo, new Dictionary<string, string>[] { d });
Assert.Equal(d, xo.Annotation<Dictionary<string, string>>());
Assert.Equal(d, (Dictionary<string, string>)xo.Annotation(typeof(Dictionary<string, string>)));
Assert.Equal(d, xo.Annotation<object>());
Assert.Equal(d, xo.Annotation(typeof(object)));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveGenericAnnotation(XObject xo)
{
Dictionary<string, string> d = new Dictionary<string, string>();
xo.AddAnnotation(d);
xo.RemoveAnnotations<Dictionary<string, string>>();
Assert.Equal(expected: 0, actual: CountAnnotations<Dictionary<string, string>>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddInheritedAnnotation(XObject xo)
{
A a = new A();
B b = new B();
xo.AddAnnotation(a);
xo.AddAnnotation(b);
ValidateAnnotations(xo, new A[] { a, b });
ValidateAnnotations(xo, new B[] { b });
Assert.Equal(b, xo.Annotation<B>());
Assert.Equal(b, (B)xo.Annotation(typeof(B)));
Assert.Equal(a, xo.Annotation<A>());
Assert.Equal(a, (A)xo.Annotation(typeof(A)));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveInheritedAnnotation(XObject xo)
{
A a = new A();
B b = new B();
xo.AddAnnotation(a);
xo.AddAnnotation(b);
xo.RemoveAnnotations<B>();
ValidateAnnotations(xo, new A[] { a });
Assert.Equal(a, xo.Annotation<A>());
Assert.Equal(a, (A)xo.Annotation(typeof(A)));
Assert.Equal(a, xo.Annotation<object>());
Assert.Equal(a, xo.Annotation(typeof(object)));
Assert.Equal(0, CountAnnotations<B>(xo));
xo.RemoveAnnotations(typeof(A));
Assert.Equal(0, CountAnnotations<A>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddNull(XObject xo)
{
Assert.Throws<ArgumentNullException>("annotation", () => xo.AddAnnotation(null));
Assert.Null(xo.Annotation<object>());
Assert.Throws<ArgumentNullException>("annotation", () => xo.AddAnnotation(null));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveNull(XObject xo)
{
Assert.Throws<ArgumentNullException>("type", () => xo.RemoveAnnotations(null));
Assert.Throws<ArgumentNullException>("type", () => xo.RemoveAnnotations(null));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void GetAllNull(XObject xo)
{
Assert.Throws<ArgumentNullException>("type", () => xo.Annotations(null));
Assert.Throws<ArgumentNullException>("type", () => xo.Annotations(null));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void GetOneNull(XObject xo)
{
Assert.Throws<ArgumentNullException>("type", () => xo.Annotation(null));
Assert.Throws<ArgumentNullException>("type", () => xo.Annotation(null));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddNullString(XObject xo)
{
Assert.Throws<ArgumentNullException>("annotation", () => xo.AddAnnotation((string)null));
Assert.Null(xo.Annotation<object>());
Assert.Throws<ArgumentNullException>("annotation", () => xo.AddAnnotation((string)null));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddAnnotationWithSameClassNameButDifferentNamespace(XObject xo)
{
DifferentNamespace.A a1 = new DifferentNamespace.A();
A a2 = new A();
xo.AddAnnotation(a1);
xo.AddAnnotation(a2);
ValidateAnnotations(xo, new DifferentNamespace.A[] { a1 });
ValidateAnnotations(xo, new A[] { a2 });
Assert.Equal(a1, xo.Annotation<DifferentNamespace.A>());
Assert.Equal(a1, (DifferentNamespace.A)xo.Annotation(typeof(DifferentNamespace.A)));
Assert.Equal(a2, xo.Annotation<A>());
Assert.Equal(a2, (A)xo.Annotation(typeof(A)));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveAnnotationWithSameClassNameButDifferentNamespace(XObject xo)
{
DifferentNamespace.A a1 = new DifferentNamespace.A();
A a2 = new A();
xo.AddAnnotation(a1);
xo.AddAnnotation(a2);
xo.RemoveAnnotations<DifferentNamespace.A>();
Assert.Equal(expected: 0, actual: CountAnnotations<DifferentNamespace.A>(xo));
ValidateAnnotations<A>(xo, new A[] { a2 });
Assert.Equal(a2, xo.Annotation<A>());
Assert.Equal(a2, (A)xo.Annotation(typeof(A)));
xo.RemoveAnnotations(typeof(A));
Assert.Equal(expected: 0, actual: CountAnnotations<A>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveAnnotationsOfDifferentTypesAndDifferentXObjects(XObject xo)
{
AddAnnotation(xo);
foreach (Type type in GetTypes())
{
RemoveAnnotations(xo, type);
}
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveTwiceAnnotationsOfDifferentTypesAndDifferentXObjects(XObject xo)
{
foreach (Type type in GetTypes())
{
RemoveAnnotations(xo, type);
}
foreach (Type type in GetTypes())
{
RemoveAnnotations(xo, type);
}
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddTwiceRemoveOnceAnnotationsOfDifferentTypesAndDifferentXObjects(XObject xo)
{
AddAnnotation(xo);
int count = CountAnnotations<object>(xo) * 2;
AddAnnotation(xo);
Assert.Equal(expected: count, actual: CountAnnotations<object>(xo));
foreach (Type type in GetTypes())
{
RemoveAnnotations(xo, type);
}
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Fact]
public void AddAnnotationAndClone()
{
// Add annotation to XElement, and clone this element to another subtree, get null annotation
const string expected = "element1111";
XElement element1 = new XElement("e", new XAttribute("a", "value"));
element1.AddAnnotation(expected);
XElement element2 = new XElement(element1);
ValidateAnnotations(element1, new string[] { expected });
Assert.Equal(expected, element1.Annotation<string>());
Assert.Equal(expected, element1.Annotation(typeof(string)));
Assert.Equal(0, CountAnnotations<string>(element2));
}
[Fact]
public void AddAnnotationXElementRemoveAndGet()
{
// Add annotation to XElement, and remove this element, get annotation
const string expected = "element1111";
XElement root = new XElement("root");
XElement element = new XElement("elem1");
root.Add(element);
element.AddAnnotation(expected);
element.Remove();
ValidateAnnotations(element, new string[] { expected });
Assert.Equal(expected, element.Annotation<string>());
Assert.Equal(expected, element.Annotation(typeof(string)));
}
[Fact]
public void AddAnnotationToParentAndChildAndValIdate()
{
// Add annotation to parent and child, valIdate annotations for each XObjects
string str1 = "root 1111";
string str2 = "element 1111";
XElement root = new XElement("root");
XElement element = new XElement("elem1");
root.Add(element);
root.AddAnnotation(str1);
element.AddAnnotation(str2);
ValidateAnnotations(root, new string[] { str1 });
Assert.Equal(str1, root.Annotation<string>());
Assert.Equal(str1, root.Annotation(typeof(string)));
ValidateAnnotations(element, new string[] { str2 });
Assert.Equal(str2, element.Annotation<string>());
Assert.Equal(str2, element.Annotation(typeof(string)));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void AddAnnotationsAndRemoveOfTypeObject(XObject xo)
{
AddAnnotation(xo);
RemoveAnnotations(xo, typeof(object));
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void EnumerateAnnotationsWithoutAdding(XObject xo)
{
Assert.Null(xo.Annotation(typeof(object)));
Assert.Null(xo.Annotation<object>());
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
Assert.Equal(expected: 0, actual: CountAnnotations<string>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveAnnotationsUsingTypeObject(XObject xo)
{
AddAnnotation(xo);
RemoveAnnotations<object>(xo);
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
[Theory]
[MemberData(nameof(GetXObjects))]
public void RemoveTwiceAnnotationsWithoutAddingUsingTypeObject(XObject xo)
{
RemoveAnnotations<object>(xo);
RemoveAnnotations<object>(xo);
Assert.Equal(expected: 0, actual: CountAnnotations<object>(xo));
}
//
// helpers
//
public static IEnumerable<object[]> GetXObjects()
{
yield return new object[] { new XDocument() };
yield return new object[] { new XAttribute("attr", "val") };
yield return new object[] { new XElement("elem1") };
yield return new object[] { new XText("text1") };
yield return new object[] { new XComment("comment1") };
yield return new object[] { new XProcessingInstruction("pi1", "pi1pi1pi1pi1pi1") };
yield return new object[] { new XCData("cdata cdata") };
yield return new object[] { new XDocumentType("dtd1", "dtd1dtd1dtd1", "dtd1dtd1", "dtd1dtd1dtd1dtd1") };
}
public static object[] GetObjects()
{
object[] aObject = new object[]
{
new A(), new B(), new DifferentNamespace.A(), new DifferentNamespace.B(), "stringstring", 12345,
new Dictionary<string, string>(), new XDocument(), new XAttribute("attr", "val"), new XElement("elem1"),
new XText("text1 text1"), new XComment("comment1 comment1"),
new XProcessingInstruction("pi1", "pi1pi1pi1pi1pi1"), new XCData("cdata cdata"),
new XDeclaration("234", "UTF-8", "yes"), XNamespace.Xmlns,
//new XStreamingElement("elementSequence"),
new XDocumentType("dtd1", "dtd1dtd1dtd1", "dtd1 dtd1", "dtd1 dtd1 dtd1 ")
};
return aObject;
}
private static void ValidateAnnotations<T>(XObject xo, T[] values) where T : class
{
//
// use inefficent n^2 algorithm, which is OK for our testing purposes
// assumes that all items are unique
//
int count = CountAnnotations<T>(xo);
TestLog.Compare(count, values.Length, "unexpected number of annotations");
foreach (T value in values)
{
//
// use non-generics enum first
//
bool found = false;
foreach (T annotation in xo.Annotations(typeof(T)))
{
if (annotation.Equals(value))
{
found = true;
break;
}
}
TestLog.Compare(found, "didn't find value using non-generic enumeration");
//
// now double check with generics one
//
found = false;
foreach (T annotation in xo.Annotations<T>())
{
if (annotation.Equals(value))
{
found = true;
break;
}
}
TestLog.Compare(found, "didn't find value using generic enumeration");
}
}
private static int CountAnnotations<T>(XObject xo) where T : class
{
int count = xo.Annotations(typeof(T)).Count();
Assert.Equal(count, xo.Annotations<T>().Count());
// Generics and non-generics annotations enumerations returned different number of objects
return count;
}
private static void AddAnnotation(XObject xo)
{
foreach (object o in GetObjects())
{
xo.AddAnnotation(o);
}
}
private static void RemoveAnnotations(XObject xo, Type type)
{
xo.RemoveAnnotations(type);
}
private static void RemoveAnnotations<T>(XObject xo) where T : class
{
xo.RemoveAnnotations<T>();
}
private static Type[] GetTypes()
{
Type[] types = new Type[]
{
typeof(string), typeof(int), typeof(Dictionary<string, string>), typeof(A), typeof(B),
typeof(DifferentNamespace.A), typeof(DifferentNamespace.B), typeof(XAttribute), typeof(XElement),
typeof(Extensions), typeof(XDocument), typeof(XText), typeof(XName), typeof(XComment),
typeof(XProcessingInstruction), typeof(XCData), typeof(XDeclaration), typeof(XNamespace),
//typeof(XStreamingElement),
typeof(XDocumentType)
};
return types;
}
public class A
{
}
public class B : A
{
}
}
namespace DifferentNamespace
{
public class A { }
public class B : A { }
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Swashbuckle.SwaggerGen.Annotations;
using SchoolBusAPI.Models;
using SchoolBusAPI.ViewModels;
using SchoolBusAPI.Services;
namespace SchoolBusAPI.Controllers
{
/// <summary>
///
/// </summary>
public partial class UserApiController : Controller
{
private readonly IUserApiService _service;
/// <summary>
/// Create a controller and set the service
/// </summary>
public UserApiController(IUserApiService service)
{
_service = service;
}
/// <summary>
///
/// </summary>
/// <remarks>Adds a number of user groups</remarks>
/// <param name="items"></param>
/// <response code="200">OK</response>
[HttpPost]
[Route("/api/usergroups/bulk")]
[SwaggerOperation("UsergroupsBulkPost")]
public virtual IActionResult UsergroupsBulkPost([FromBody]GroupMembership[] items)
{
return this._service.UsergroupsBulkPostAsync(items);
}
/// <summary>
///
/// </summary>
/// <remarks>Adds a number of user roles</remarks>
/// <param name="items"></param>
/// <response code="200">OK</response>
[HttpPost]
[Route("/api/userroles/bulk")]
[SwaggerOperation("UserrolesBulkPost")]
public virtual IActionResult UserrolesBulkPost([FromBody]UserRole[] items)
{
return this._service.UserrolesBulkPostAsync(items);
}
/// <summary>
///
/// </summary>
/// <remarks>Adds a number of users</remarks>
/// <param name="items"></param>
/// <response code="200">OK</response>
[HttpPost]
[Route("/api/users/bulk")]
[SwaggerOperation("UsersBulkPost")]
public virtual IActionResult UsersBulkPost([FromBody]User[] items)
{
return this._service.UsersBulkPostAsync(items);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns all users</remarks>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
[HttpGet]
[Route("/api/users")]
[SwaggerOperation("UsersGet")]
[SwaggerResponse(200, type: typeof(List<UserViewModel>))]
public virtual IActionResult UsersGet()
{
return this._service.UsersGetAsync();
}
/// <summary>
///
/// </summary>
/// <remarks>Deletes a user</remarks>
/// <param name="id">id of User to delete</param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
[HttpPost]
[Route("/api/users/{id}/delete")]
[SwaggerOperation("UsersIdDeletePost")]
public virtual IActionResult UsersIdDeletePost([FromRoute]int id)
{
return this._service.UsersIdDeletePostAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns a user's favourites of a given context type</remarks>
/// <param name="id">id of User to fetch favorites for</param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
[HttpGet]
[Route("/api/users/{id}/favourites")]
[SwaggerOperation("UsersIdFavouritesGet")]
[SwaggerResponse(200, type: typeof(List<UserFavouriteViewModel>))]
public virtual IActionResult UsersIdFavouritesGet([FromRoute]int id)
{
return this._service.UsersIdFavouritesGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns data for a particular user</remarks>
/// <param name="id">id of User to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
[HttpGet]
[Route("/api/users/{id}")]
[SwaggerOperation("UsersIdGet")]
[SwaggerResponse(200, type: typeof(UserViewModel))]
public virtual IActionResult UsersIdGet([FromRoute]int id)
{
return this._service.UsersIdGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns all groups that a user is a member of</remarks>
/// <param name="id">id of User to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
[HttpGet]
[Route("/api/users/{id}/groups")]
[SwaggerOperation("UsersIdGroupsGet")]
[SwaggerResponse(200, type: typeof(List<GroupMembershipViewModel>))]
public virtual IActionResult UsersIdGroupsGet([FromRoute]int id)
{
return this._service.UsersIdGroupsGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Add to the active set of groups for a user</remarks>
/// <param name="id">id of User to update</param>
/// <param name="items"></param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
[HttpPost]
[Route("/api/users/{id}/groups")]
[SwaggerOperation("UsersIdGroupsPost")]
[SwaggerResponse(200, type: typeof(List<GroupMembershipViewModel>))]
public virtual IActionResult UsersIdGroupsPost([FromRoute]int id, [FromBody]GroupMembership[] items)
{
return this._service.UsersIdGroupsPostAsync(id, items);
}
/// <summary>
///
/// </summary>
/// <remarks>Updates the active set of groups for a user</remarks>
/// <param name="id">id of User to update</param>
/// <param name="items"></param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
[HttpPut]
[Route("/api/users/{id}/groups")]
[SwaggerOperation("UsersIdGroupsPut")]
[SwaggerResponse(200, type: typeof(List<GroupMembershipViewModel>))]
public virtual IActionResult UsersIdGroupsPut([FromRoute]int id, [FromBody]GroupMembership[] items)
{
return this._service.UsersIdGroupsPutAsync(id, items);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns a user's notifications</remarks>
/// <param name="id">id of User to fetch notifications for</param>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/users/{id}/notifications")]
[SwaggerOperation("UsersIdNotificationsGet")]
[SwaggerResponse(200, type: typeof(List<NotificationViewModel>))]
public virtual IActionResult UsersIdNotificationsGet([FromRoute]int id)
{
return this._service.UsersIdNotificationsGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns the set of permissions for a user</remarks>
/// <param name="id">id of User to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
[HttpGet]
[Route("/api/users/{id}/permissions")]
[SwaggerOperation("UsersIdPermissionsGet")]
[SwaggerResponse(200, type: typeof(List<PermissionViewModel>))]
public virtual IActionResult UsersIdPermissionsGet([FromRoute]int id)
{
return this._service.UsersIdPermissionsGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Updates a user</remarks>
/// <param name="id">id of User to update</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
[HttpPut]
[Route("/api/users/{id}")]
[SwaggerOperation("UsersIdPut")]
[SwaggerResponse(200, type: typeof(UserViewModel))]
public virtual IActionResult UsersIdPut([FromRoute]int id, [FromBody]UserViewModel item)
{
return this._service.UsersIdPutAsync(id, item);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns the roles for a user</remarks>
/// <param name="id">id of User to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
[HttpGet]
[Route("/api/users/{id}/roles")]
[SwaggerOperation("UsersIdRolesGet")]
[SwaggerResponse(200, type: typeof(List<UserRoleViewModel>))]
public virtual IActionResult UsersIdRolesGet([FromRoute]int id)
{
return this._service.UsersIdRolesGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Adds a role to a user</remarks>
/// <param name="id">id of User to update</param>
/// <param name="item"></param>
/// <response code="201">Role created for user</response>
[HttpPost]
[Route("/api/users/{id}/roles")]
[SwaggerOperation("UsersIdRolesPost")]
[SwaggerResponse(200, type: typeof(UserRoleViewModel))]
public virtual IActionResult UsersIdRolesPost([FromRoute]int id, [FromBody]UserRoleViewModel item)
{
return this._service.UsersIdRolesPostAsync(id, item);
}
/// <summary>
///
/// </summary>
/// <remarks>Updates the roles for a user</remarks>
/// <param name="id">id of User to update</param>
/// <param name="items"></param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
[HttpPut]
[Route("/api/users/{id}/roles")]
[SwaggerOperation("UsersIdRolesPut")]
[SwaggerResponse(200, type: typeof(List<UserRoleViewModel>))]
public virtual IActionResult UsersIdRolesPut([FromRoute]int id, [FromBody]UserRoleViewModel[] items)
{
return this._service.UsersIdRolesPutAsync(id, items);
}
/// <summary>
///
/// </summary>
/// <remarks>Create new user</remarks>
/// <param name="item"></param>
/// <response code="201">User created</response>
[HttpPost]
[Route("/api/users")]
[SwaggerOperation("UsersPost")]
[SwaggerResponse(200, type: typeof(User))]
public virtual IActionResult UsersPost([FromBody]User item)
{
return this._service.UsersPostAsync(item);
}
}
}
| |
using System;
using System.Collections.Generic;
namespace AsterNET.Manager.Response
{
/// <summary>
/// Represents a response received from the Asterisk server as the result of a
/// previously sent ManagerAction.<br />
/// The response can be linked with the action that caused it by looking the
/// action id attribute that will match the action id of the corresponding
/// action.
/// </summary>
public class ManagerResponse : IParseSupport
{
private string actionId;
protected Dictionary<string, string> attributes;
private DateTime dateReceived;
private string message;
private string privilege;
private string response;
private string server;
private string uniqueId;
#region Constructor - ManagerEvent()
public ManagerResponse()
{
this.dateReceived = DateTime.Now;
}
public ManagerResponse(Dictionary<string, string> attributes)
: this()
{
Helper.SetAttributes(this, attributes);
}
#endregion
#region Attributes
/// <summary>
/// Store all unknown (without setter) keys from manager event.<br />
/// Use in default Parse method <see cref="Parse" />.
/// </summary>
public Dictionary<string, string> Attributes
{
get { return attributes; }
}
#endregion
#region Server
/// <summary>
/// Specify a server to which to send your commands (x.x.x.x or hostname).<br />
/// This should match the server name specified in your config file's "host" entry.
/// If you do not specify a server, the proxy will pick the first one it finds -- fine in single-server configurations.
/// </summary>
public string Server
{
get { return this.server; }
set { this.server = value; }
}
#endregion
#region DateReceived
/// <summary>
/// Get/Set the point in time this response was received from the asterisk server.
/// </summary>
public DateTime DateReceived
{
get { return dateReceived; }
set { this.dateReceived = value; }
}
#endregion
#region Privilege
/// <summary>
/// Get/Set the AMI authorization class of this event.<br />
/// This is one or more of system, call, log, verbose, command, agent or user.
/// Multiple privileges are separated by comma.<br />
/// Note: This property is not available from Asterisk 1.0 servers.
/// </summary>
public string Privilege
{
get { return privilege; }
set { this.privilege = value; }
}
#endregion
#region ActionId
/// <summary>
/// Get/Set the action id received with this response referencing the action that generated this response.
/// </summary>
public string ActionId
{
get { return actionId; }
set { this.actionId = value; }
}
#endregion
#region Message
/// <summary>
/// Get/Set the message received with this response.<br />
/// The content depends on the action that generated this response.
/// </summary>
public string Message
{
get { return message; }
set { this.message = value; }
}
#endregion
#region Response
/// <summary>
/// Get/Set the value of the "Response:" line.<br />
/// This typically a String like "Success" or "Error" but depends on the action that generated this response.
/// </summary>
public string Response
{
get { return response; }
set { this.response = value; }
}
#endregion
#region UniqueId
/// <summary>
/// Get/Set the unique id received with this response.<br />
/// The unique id is used to keep track of channels created by the action sent, for example an OriginateAction.
/// </summary>
public string UniqueId
{
get { return uniqueId; }
set { this.uniqueId = value; }
}
#endregion
#region IsSuccess()
/// <summary>
/// Return true if Response is success
/// </summary>
/// <returns></returns>
public bool IsSuccess()
{
return response == "Success";
}
#endregion
#region GetAttribute(string key)
/// <summary>
/// Returns the value of the attribute with the given key.<br />
/// This is particulary important when a response contains special
/// attributes that are dependent on the action that has been sent.<br />
/// An example of this is the response to the GetVarAction.
/// It contains the value of the channel variable as an attribute
/// stored under the key of the variable name.<br />
/// Example:
/// <pre>
/// GetVarAction action = new GetVarAction();
/// action.setChannel("SIP/1310-22c3");
/// action.setVariable("ALERT_INFO");
/// ManagerResponse response = connection.SendAction(action);
/// String alertInfo = response.getAttribute("ALERT_INFO");
/// </pre>
/// As all attributes are internally stored in lower case the key is
/// automatically converted to lower case before lookup.
/// </summary>
/// <param name="key">the key to lookup.</param>
/// <returns>
/// the value of the attribute stored under this key or
/// null if there is no such attribute.
/// </returns>
public string GetAttribute(string key)
{
return (string) attributes[key.ToLower(Helper.CultureInfo)];
}
#endregion
#region Parse(string key, string value)
/// <summary>
/// Unknown properties parser
/// </summary>
/// <param name="key">key name</param>
/// <param name="value">key value</param>
/// <returns>true - value parsed, false - can't parse value</returns>
public virtual bool Parse(string key, string value)
{
if (attributes == null)
attributes = new Dictionary<string, string>();
if (attributes.ContainsKey(key))
// Key already presents, add with delimiter
attributes[key] += string.Concat(Common.LINE_SEPARATOR, value);
else
attributes.Add(key, value);
return true;
}
#endregion
#region ParseSpecial(Dictionary<string, string> attributes)
/// <summary>
/// Unknown properties parser
/// </summary>
/// <param name="attributes">dictionary</param>
/// <returns>updated dictionary</returns>
public virtual Dictionary<string, string> ParseSpecial(Dictionary<string, string> attributes)
{
return attributes;
}
#endregion
#region ToString()
public override string ToString()
{
return Helper.ToString(this);
}
#endregion
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DynamoDBv2.Model
{
/// <summary>
/// Represents the data for an attribute. You can set one, and only one, of the elements.
///
///
/// <para>
/// Each attribute in an item is a name-value pair. An attribute can be single-valued
/// or multi-valued set. For example, a book item can have title and authors attributes.
/// Each book has one title but can have many authors. The multi-valued attribute is a
/// set; duplicate values are not allowed.
/// </para>
/// </summary>
public partial class AttributeValue
{
private MemoryStream _b;
private bool? _bool;
private List<MemoryStream> _bs = new List<MemoryStream>();
private List<AttributeValue> _l = new List<AttributeValue>();
private Dictionary<string, AttributeValue> _m = new Dictionary<string, AttributeValue>();
private string _n;
private List<string> _ns = new List<string>();
private bool? _null;
private string _s;
private List<string> _ss = new List<string>();
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public AttributeValue() { }
/// <summary>
/// Instantiates AttributeValue with the parameterized properties
/// </summary>
/// <param name="s">A String data type.</param>
public AttributeValue(string s)
{
_s = s;
}
/// <summary>
/// Instantiates AttributeValue with the parameterized properties
/// </summary>
/// <param name="ss">A String Set data type.</param>
public AttributeValue(List<string> ss)
{
_ss = ss;
}
/// <summary>
/// Gets and sets the property B.
/// <para>
/// A Binary data type.
/// </para>
/// </summary>
public MemoryStream B
{
get { return this._b; }
set { this._b = value; }
}
// Check to see if B property is set
internal bool IsSetB()
{
return this._b != null;
}
/// <summary>
/// Gets and sets the property BOOL.
/// <para>
/// A Boolean data type.
/// </para>
/// </summary>
public bool BOOL
{
get { return this._bool.GetValueOrDefault(); }
set { this._bool = value; }
}
/// <summary>
/// This property is set to true if the property <seealso cref="BOOL"/>
/// is set; false otherwise.
/// This property can be used to determine if the related property
/// was returned by a service response or if the related property
/// should be sent to the service during a service call.
/// </summary>
/// <returns>
/// True if the related property was set or will be sent to a service; false otherwise.
/// </returns>
public bool IsBOOLSet
{
get
{
return Amazon.Util.Internal.InternalSDKUtils.GetIsSet(this._bool);
}
set
{
Amazon.Util.Internal.InternalSDKUtils.SetIsSet(value, ref this._bool);
}
}
// Check to see if BOOL property is set
internal bool IsSetBOOL()
{
return this.IsBOOLSet;
}
/// <summary>
/// Gets and sets the property BS.
/// <para>
/// A Binary Set data type.
/// </para>
/// </summary>
public List<MemoryStream> BS
{
get { return this._bs; }
set { this._bs = value; }
}
// Check to see if BS property is set
internal bool IsSetBS()
{
return this._bs != null && this._bs.Count > 0;
}
/// <summary>
/// Gets and sets the property L.
/// <para>
/// A List of attribute values.
/// </para>
/// </summary>
public List<AttributeValue> L
{
get { return this._l; }
set { this._l = value; }
}
/// <summary>
/// This property is set to true if the property <seealso cref="L"/>
/// is set; false otherwise.
/// This property can be used to determine if the related property
/// was returned by a service response or if the related property
/// should be sent to the service during a service call.
/// </summary>
/// <returns>
/// True if the related property was set or will be sent to a service; false otherwise.
/// </returns>
public bool IsLSet
{
get
{
return Amazon.Util.Internal.InternalSDKUtils.GetIsSet(this._l);
}
set
{
Amazon.Util.Internal.InternalSDKUtils.SetIsSet(value, ref this._l);
}
}
// Check to see if L property is set
internal bool IsSetL()
{
return this.IsLSet;
}
/// <summary>
/// Gets and sets the property M.
/// <para>
/// A Map of attribute values.
/// </para>
/// </summary>
public Dictionary<string, AttributeValue> M
{
get { return this._m; }
set { this._m = value; }
}
/// <summary>
/// This property is set to true if the property <seealso cref="M"/>
/// is set; false otherwise.
/// This property can be used to determine if the related property
/// was returned by a service response or if the related property
/// should be sent to the service during a service call.
/// </summary>
/// <returns>
/// True if the related property was set or will be sent to a service; false otherwise.
/// </returns>
public bool IsMSet
{
get
{
return Amazon.Util.Internal.InternalSDKUtils.GetIsSet(this._m);
}
set
{
Amazon.Util.Internal.InternalSDKUtils.SetIsSet(value, ref this._m);
}
}
// Check to see if M property is set
internal bool IsSetM()
{
return this.IsMSet;
}
/// <summary>
/// Gets and sets the property N.
/// <para>
/// A Number data type.
/// </para>
/// </summary>
public string N
{
get { return this._n; }
set { this._n = value; }
}
// Check to see if N property is set
internal bool IsSetN()
{
return this._n != null;
}
/// <summary>
/// Gets and sets the property NS.
/// <para>
/// A Number Set data type.
/// </para>
/// </summary>
public List<string> NS
{
get { return this._ns; }
set { this._ns = value; }
}
// Check to see if NS property is set
internal bool IsSetNS()
{
return this._ns != null && this._ns.Count > 0;
}
/// <summary>
/// Gets and sets the property NULL.
/// <para>
/// A Null data type.
/// </para>
/// </summary>
public bool NULL
{
get { return this._null.GetValueOrDefault(); }
set { this._null = value; }
}
// Check to see if NULL property is set
internal bool IsSetNULL()
{
return this._null.HasValue;
}
/// <summary>
/// Gets and sets the property S.
/// <para>
/// A String data type.
/// </para>
/// </summary>
public string S
{
get { return this._s; }
set { this._s = value; }
}
// Check to see if S property is set
internal bool IsSetS()
{
return this._s != null;
}
/// <summary>
/// Gets and sets the property SS.
/// <para>
/// A String Set data type.
/// </para>
/// </summary>
public List<string> SS
{
get { return this._ss; }
set { this._ss = value; }
}
// Check to see if SS property is set
internal bool IsSetSS()
{
return this._ss != null && this._ss.Count > 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Fluid;
using Fluid.Ast;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.DisplayManagement.Liquid.Tags;
using OrchardCore.Liquid;
namespace OrchardCore.Contents.Liquid
{
public class ContentAnchorTag : IAnchorTag
{
public int Order => -10;
public bool Match(List<FilterArgument> argumentsList)
{
foreach (var argument in argumentsList)
{
switch (argument.Name)
{
case "admin_for":
case "display_for":
case "edit_for":
case "remove_for":
case "create_for": return true;
}
}
return false;
}
public async ValueTask<Completion> WriteToAsync(List<FilterArgument> argumentsList, IReadOnlyList<Statement> statements, TextWriter writer, TextEncoder encoder, LiquidTemplateContext context)
{
var services = context.Services;
var viewContext = context.ViewContext;
var urlHelperFactory = services.GetRequiredService<IUrlHelperFactory>();
var contentManager = services.GetRequiredService<IContentManager>();
ContentItem adminFor = null;
ContentItem displayFor = null;
ContentItem editFor = null;
ContentItem removeFor = null;
ContentItem createFor = null;
Dictionary<string, string> routeValues = null;
Dictionary<string, string> customAttributes = new Dictionary<string, string>();
foreach (var argument in argumentsList)
{
switch (argument.Name)
{
case "admin_for": adminFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; break;
case "display_for": displayFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; break;
case "edit_for": editFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; break;
case "remove_for": removeFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; break;
case "create_for": createFor = (await argument.Expression.EvaluateAsync(context)).ToObjectValue() as ContentItem; break;
default:
if (argument.Name.StartsWith("route_", StringComparison.OrdinalIgnoreCase))
{
routeValues ??= new Dictionary<string, string>();
routeValues[argument.Name[6..]] = (await argument.Expression.EvaluateAsync(context)).ToStringValue();
}
else
{
customAttributes[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue();
}
break;
}
}
ContentItem contentItem = null;
var urlHelper = urlHelperFactory.GetUrlHelper(viewContext);
if (displayFor != null)
{
contentItem = displayFor;
var previewAspect = await contentManager.PopulateAspectAsync<PreviewAspect>(contentItem);
if (!String.IsNullOrEmpty(previewAspect.PreviewUrl))
{
var previewUrl = previewAspect.PreviewUrl;
if (!previewUrl.StartsWith("~/", StringComparison.OrdinalIgnoreCase))
{
if (previewUrl.StartsWith('/'))
{
previewUrl = '~' + previewUrl;
}
else
{
previewUrl = "~/" + previewUrl;
}
}
customAttributes["href"] = urlHelper.Content(previewUrl);
}
else
{
var metadata = await contentManager.PopulateAspectAsync<ContentItemMetadata>(displayFor);
if (metadata.DisplayRouteValues != null)
{
if (routeValues != null)
{
foreach (var attribute in routeValues)
{
metadata.DisplayRouteValues.Add(attribute.Key, attribute.Value);
}
}
customAttributes["href"] = urlHelper.Action(metadata.DisplayRouteValues["action"].ToString(), metadata.DisplayRouteValues);
}
}
}
else if (editFor != null)
{
contentItem = editFor;
var metadata = await contentManager.PopulateAspectAsync<ContentItemMetadata>(editFor);
if (metadata.EditorRouteValues != null)
{
foreach (var attribute in routeValues)
{
metadata.EditorRouteValues.Add(attribute.Key, attribute.Value);
}
customAttributes["href"] = urlHelper.Action(metadata.EditorRouteValues["action"].ToString(), metadata.EditorRouteValues);
}
}
else if (adminFor != null)
{
contentItem = adminFor;
var metadata = await contentManager.PopulateAspectAsync<ContentItemMetadata>(adminFor);
if (metadata.AdminRouteValues != null)
{
if (routeValues != null)
{
foreach (var attribute in routeValues)
{
metadata.AdminRouteValues.Add(attribute.Key, attribute.Value);
}
}
customAttributes["href"] = urlHelper.Action(metadata.AdminRouteValues["action"].ToString(), metadata.AdminRouteValues);
}
}
else if (removeFor != null)
{
contentItem = removeFor;
var metadata = await contentManager.PopulateAspectAsync<ContentItemMetadata>(removeFor);
if (metadata.RemoveRouteValues != null)
{
if (routeValues != null)
{
foreach (var attribute in routeValues)
{
metadata.RemoveRouteValues.Add(attribute.Key, attribute.Value);
}
}
customAttributes["href"] = urlHelper.Action(metadata.RemoveRouteValues["action"].ToString(), metadata.RemoveRouteValues);
}
}
else if (createFor != null)
{
contentItem = createFor;
var metadata = await contentManager.PopulateAspectAsync<ContentItemMetadata>(createFor);
if (metadata.CreateRouteValues == null)
{
if (routeValues != null)
{
foreach (var attribute in routeValues)
{
metadata.CreateRouteValues.Add(attribute.Key, attribute.Value);
}
}
customAttributes["href"] = urlHelper.Action(metadata.CreateRouteValues["action"].ToString(), metadata.CreateRouteValues);
}
}
if (customAttributes.Count == 0)
{
return Completion.Normal;
}
var tagBuilder = new TagBuilder("a");
foreach (var attribute in customAttributes)
{
tagBuilder.Attributes[attribute.Key] = attribute.Value;
}
tagBuilder.RenderStartTag().WriteTo(writer, (HtmlEncoder)encoder);
if (statements != null && statements.Count > 0)
{
var completion = await statements.RenderStatementsAsync(writer, encoder, context);
if (completion != Completion.Normal)
{
return completion;
}
}
else if (!String.IsNullOrEmpty(contentItem.DisplayText))
{
writer.Write(encoder.Encode(contentItem.DisplayText));
}
else
{
var contentDefinitionManager = services.GetRequiredService<IContentDefinitionManager>();
var typeDefinition = contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
writer.Write(encoder.Encode(typeDefinition.ToString()));
}
tagBuilder.RenderEndTag().WriteTo(writer, (HtmlEncoder)encoder);
return Completion.Normal;
}
}
}
| |
using System;
using log4net;
using System.Collections.Generic;
using it.unifi.dsi.stlab.extension_methods;
using it.unifi.dsi.stlab.math.algebra;
using it.unifi.dsi.stlab.utilities.value_holders;
using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance.listeners;
using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance;
using it.unifi.dsi.stlab.extension_methods.for_math_library;
namespace it.unifi.dsi.stlab.networkreasoner.gas.system.listeners
{
public class NetwonRaphsonSystemEventsListenerForLogging :
NetwonRaphsonSystemEventsListener
{
public ILog Log {
get;
set;
}
Dictionary<NodeForNetwonRaphsonSystem, int> NodesEnumeration {
get;
set;
}
List<EdgeForNetwonRaphsonSystem> Edges {
get;
set;
}
#region NetwonRaphsonSystemEventsListener implementation
public void onMutateStepCompleted (OneStepMutationResults result)
{
}
public void onInitializationCompleted (
System.Collections.Generic.List<NodeForNetwonRaphsonSystem> nodes,
System.Collections.Generic.List<EdgeForNetwonRaphsonSystem> edges,
Dictionary<NodeForNetwonRaphsonSystem, int> nodesEnumeration)
{
this.NodesEnumeration = nodesEnumeration;
this.Edges = edges;
this.Log.Info ("================================================================");
this.Log.Info ("Start of a new mutation step");
this.Log.Info ("The following nodes enumeration is used throughout the system computation:");
foreach (var pair in this.NodesEnumeration) {
this.Log.InfoFormat ("Node: {0} -> Index: {1}",
pair.Key.Identifier, pair.Value);
}
// this.Log.Info ("The following edges enumeration is used throughout the system computation:");
// foreach (var pair in this.DecoredSystemImplementation.EdgesEnumeration.Value) {
// this.Log.InfoFormat ("(StartNode, EndNode): ({0},{1}) -> Index: {2}",
// pair.Key.StartNode.Identifier,
// pair.Key.EndNode.Identifier,
// pair.Value);
// }
}
public void onRepeatMutateUntilStarted ()
{
this.Log.Info ("***********************************************************");
this.Log.Info ("* Start of a new computation driven by until conditions *");
this.Log.Info ("***********************************************************");
}
public void onComputationShouldBeStoppedDueTo (UntilConditionAbstract condition)
{
string stoppingCauseDescription = condition.stoppingCauseDescription ();
this.Log.InfoFormat ("Computation will be stopped due to reason: {0}",
stoppingCauseDescription);
}
public void onUnknownVectorAtPreviousStepComputed (
Vector<NodeForNetwonRaphsonSystem> unknownVectorAtPreviousStep)
{
unknownVectorAtPreviousStep.forComputationAmong (
this.NodesEnumeration, new ValueHolderNoInfoShouldBeRequested<Double> ()).stringRepresentation (
representation => this.Log.InfoFormat (
"Relative Unknowns at previous step: {0}", representation)
);
}
public void onFvectorAtPreviousStepComputed (
Vector<EdgeForNetwonRaphsonSystem> FvectorAtPreviousStep)
{
this.Edges.ForEach (anEdge => anEdge.stringRepresentationUsing (
FvectorAtPreviousStep, (edgeRepresentation, FvalueRepresentation) =>
this.Log.InfoFormat ("F value of {0} at previous step: {1}",
edgeRepresentation, FvalueRepresentation)
)
);
}
public void onMatricesFixedIfSupplyGadgetsPresent (
Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> AmatrixAtCurrentStep,
Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> JacobianMatrixAtCurrentStep)
{
AmatrixAtCurrentStep.forComputationAmong (
this.NodesEnumeration,
this.NodesEnumeration).stringRepresentation (
representation => this.Log.InfoFormat ("A matrix at current step after supply node fix it:\n{0}", representation));
JacobianMatrixAtCurrentStep.forComputationAmong (
this.NodesEnumeration,
this.NodesEnumeration).stringRepresentation (
representation => this.Log.InfoFormat ("Jacobian matrix at current step after supply node fix it:\n{0}", representation));
}
public void onCoefficientsVectorAtCurrentStepComputed (
Vector<NodeForNetwonRaphsonSystem> coefficientsVectorAtCurrentStep)
{
coefficientsVectorAtCurrentStep.forComputationAmong (
this.NodesEnumeration, new ValueHolderNoInfoShouldBeRequested<Double> ()).
stringRepresentation (
representation => this.Log.InfoFormat (
"Coefficients vector at current step: {0}", representation)
);
}
public void onNegativeUnknownsFixed (Vector<NodeForNetwonRaphsonSystem> unknownVectorAtCurrentStep)
{
unknownVectorAtCurrentStep.forComputationAmong (
this.NodesEnumeration, new ValueHolderNoInfoShouldBeRequested<Double> ()).stringRepresentation (
representation => this.Log.InfoFormat (
"Adimensional unknowns vector at current step after fix negative entries: {0}", representation)
);
}
public void onMutateStepStarted (int? iterationNumber)
{
if (iterationNumber.HasValue) {
this.Log.InfoFormat ("-------------------- Iteration {0} ---------------------",
iterationNumber.Value);
}
}
public void onAmatrixComputed (
Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> Amatrix)
{
Amatrix.forComputationAmong (
this.NodesEnumeration,
this.NodesEnumeration).
stringRepresentation (
representation => this.Log.InfoFormat (
"A matrix at current step before supply node fix it:\n{0}", representation)
);
}
public void onJacobianMatrixComputed (
Matrix<NodeForNetwonRaphsonSystem, NodeForNetwonRaphsonSystem> JacobianMatrix)
{
JacobianMatrix.forComputationAmong (
this.NodesEnumeration,
this.NodesEnumeration).
stringRepresentation (
representation => this.Log.InfoFormat (
"Jacobian matrix at current step before supply node fix it:\n{0}", representation)
);
}
public void onKvectorComputed (Vector<EdgeForNetwonRaphsonSystem> Kvector)
{
this.Edges.ForEach (anEdge => anEdge.stringRepresentationUsing (
Kvector, (edgeRepresentation, KvalueRepresentation) =>
this.Log.InfoFormat ("K value of {0} at current step: {1}",
edgeRepresentation, KvalueRepresentation)
)
);
}
public void onUnknownVectorAtCurrentStepComputed (Vector<NodeForNetwonRaphsonSystem> unknownVectorAtCurrentStep)
{
unknownVectorAtCurrentStep.forComputationAmong (this.NodesEnumeration, new ValueHolderNoInfoShouldBeRequested<Double> ()).
stringRepresentation (
representation => this.Log.InfoFormat (
"Adimensional unknowns vector at current step before fix negative entries: {0}", representation)
);
}
public void onQvectorComputed (Vector<EdgeForNetwonRaphsonSystem> Qvector)
{
this.Edges.ForEach (anEdge => anEdge.stringRepresentationUsing (
Qvector, (edgeRepresentation, QvalueRepresentation) =>
this.Log.InfoFormat ("Q value of {0} at current step: {1}",
edgeRepresentation, QvalueRepresentation)
)
);
}
public void onFvectorAtCurrentStepComputed (Vector<EdgeForNetwonRaphsonSystem> Fvector)
{
this.Edges.ForEach (anEdge => anEdge.stringRepresentationUsing (
Fvector, (edgeRepresentation, FvalueRepresentation) =>
this.Log.InfoFormat ("F value of {0} at current step: {1}",
edgeRepresentation, FvalueRepresentation)
)
);
}
public void onUnknownWithDimensionReverted (
Dictionary<NodeForNetwonRaphsonSystem, int> nodesEnumeration,
Vector<NodeForNetwonRaphsonSystem> unknownVector)
{
unknownVector.forComputationAmong (
nodesEnumeration, new ValueHolderNoInfoShouldBeRequested<Double> ()).
stringRepresentation (
representation => this.Log.InfoFormat (
"Relative Unknowns vector at current step: {0}", representation)
);
}
public void onRepeatMutateUntilEnded (OneStepMutationResults result)
{
}
#endregion
}
}
| |
// ByteFX.Data data access components for .Net
// Copyright (C) 2002-2003 ByteFX, 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.Windows.Forms;
using System.Data;
using ByteFX.Data.MySqlClient;
namespace ByteFX.Data.Common
{
/// <summary>
/// Summary description for SqlCommandEditorDlg.
/// </summary>
internal class SqlCommandEditorDlg : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox sqlText;
private System.Windows.Forms.Button CancelBtn;
private System.Windows.Forms.Button OKBtn;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.DataGrid dataGrid;
private System.Windows.Forms.ContextMenu sqlMenu;
private System.Windows.Forms.MenuItem runMenuItem;
private IDbCommand command;
private System.Windows.Forms.DataGridTableStyle dataGridTableStyle1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public SqlCommandEditorDlg(object o)
{
command = (IDbCommand)o;
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
public string SQL
{
get { return sqlText.Text; }
set { sqlText.Text = value; }
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.sqlText = new System.Windows.Forms.TextBox();
this.sqlMenu = new System.Windows.Forms.ContextMenu();
this.runMenuItem = new System.Windows.Forms.MenuItem();
this.CancelBtn = new System.Windows.Forms.Button();
this.OKBtn = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.splitter1 = new System.Windows.Forms.Splitter();
this.dataGrid = new System.Windows.Forms.DataGrid();
this.dataGridTableStyle1 = new System.Windows.Forms.DataGridTableStyle();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGrid)).BeginInit();
this.SuspendLayout();
//
// sqlText
//
this.sqlText.ContextMenu = this.sqlMenu;
this.sqlText.Dock = System.Windows.Forms.DockStyle.Top;
this.sqlText.Location = new System.Drawing.Point(10, 10);
this.sqlText.Multiline = true;
this.sqlText.Name = "sqlText";
this.sqlText.Size = new System.Drawing.Size(462, 144);
this.sqlText.TabIndex = 0;
this.sqlText.Text = "";
//
// sqlMenu
//
this.sqlMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.runMenuItem});
//
// runMenuItem
//
this.runMenuItem.Index = 0;
this.runMenuItem.Text = "Run";
this.runMenuItem.Click += new System.EventHandler(this.runMenuItem_Click);
//
// CancelBtn
//
this.CancelBtn.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
this.CancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CancelBtn.Location = new System.Drawing.Point(400, 350);
this.CancelBtn.Name = "CancelBtn";
this.CancelBtn.TabIndex = 3;
this.CancelBtn.Text = "Cancel";
this.CancelBtn.Click += new System.EventHandler(this.CancelBtn_Click);
//
// OKBtn
//
this.OKBtn.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
this.OKBtn.DialogResult = System.Windows.Forms.DialogResult.OK;
this.OKBtn.Location = new System.Drawing.Point(316, 350);
this.OKBtn.Name = "OKBtn";
this.OKBtn.TabIndex = 4;
this.OKBtn.Text = "OK";
this.OKBtn.Click += new System.EventHandler(this.OKBtn_Click);
//
// panel1
//
this.panel1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.panel1.Controls.AddRange(new System.Windows.Forms.Control[] {
this.splitter1,
this.dataGrid,
this.sqlText});
this.panel1.DockPadding.Bottom = 10;
this.panel1.DockPadding.Left = 10;
this.panel1.DockPadding.Right = 14;
this.panel1.DockPadding.Top = 10;
this.panel1.Location = new System.Drawing.Point(2, 2);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(486, 344);
this.panel1.TabIndex = 5;
//
// splitter1
//
this.splitter1.Dock = System.Windows.Forms.DockStyle.Top;
this.splitter1.Location = new System.Drawing.Point(10, 154);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(462, 3);
this.splitter1.TabIndex = 3;
this.splitter1.TabStop = false;
//
// dataGrid
//
this.dataGrid.CaptionVisible = false;
this.dataGrid.DataMember = "";
this.dataGrid.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid.Location = new System.Drawing.Point(10, 154);
this.dataGrid.Name = "dataGrid";
this.dataGrid.Size = new System.Drawing.Size(462, 180);
this.dataGrid.TabIndex = 2;
this.dataGrid.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
this.dataGridTableStyle1});
//
// dataGridTableStyle1
//
this.dataGridTableStyle1.AllowSorting = false;
this.dataGridTableStyle1.DataGrid = this.dataGrid;
this.dataGridTableStyle1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGridTableStyle1.MappingName = "";
//
// SqlCommandEditorDlg
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(486, 384);
this.ControlBox = false;
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.panel1,
this.OKBtn,
this.CancelBtn});
this.DockPadding.Bottom = 10;
this.DockPadding.Left = 10;
this.DockPadding.Right = 12;
this.DockPadding.Top = 10;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "SqlCommandEditorDlg";
this.Text = "Query Builder";
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGrid)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void CancelBtn_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void OKBtn_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void runMenuItem_Click(object sender, System.EventArgs e)
{
if (command is MySqlCommand)
{
RunMySql();
}
}
private void RunMySql()
{
try
{
MySqlDataAdapter da = new MySqlDataAdapter((MySqlCommand)command);
command.CommandText = sqlText.Text;
command.Connection.Open();
DataTable dt = new DataTable();
da.Fill(dt);
dataGrid.DataSource = dt;
command.Connection.Close();
dataGrid.Expand(-1);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
| |
// 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.Win32.SafeHandles;
using System.Security;
namespace System.IO.MemoryMappedFiles
{
public partial class MemoryMappedFile
{
/// <summary>
/// Used by the 2 Create factory method groups. A null fileHandle specifies that the
/// memory mapped file should not be associated with an existing file on disk (i.e. start
/// out empty).
/// </summary>
private static unsafe SafeMemoryMappedFileHandle CreateCore(
FileStream fileStream, string mapName,
HandleInheritability inheritability, MemoryMappedFileAccess access,
MemoryMappedFileOptions options, long capacity)
{
if (mapName != null)
{
// Named maps are not supported in our Unix implementation. We could support named maps on Linux using
// shared memory segments (shmget/shmat/shmdt/shmctl/etc.), but that doesn't work on OSX by default due
// to very low default limits on OSX for the size of such objects; it also doesn't support behaviors
// like copy-on-write or the ability to control handle inheritability, and reliably cleaning them up
// relies on some non-conforming behaviors around shared memory IDs remaining valid even after they've
// been marked for deletion (IPC_RMID). We could also support named maps using the current implementation
// by not unlinking after creating the backing store, but then the backing stores would remain around
// and accessible even after process exit, with no good way to appropriately clean them up.
// (File-backed maps may still be used for cross-process communication.)
throw CreateNamedMapsNotSupportedException();
}
bool ownsFileStream = false;
if (fileStream != null)
{
// This map is backed by a file. Make sure the file's size is increased to be
// at least as big as the requested capacity of the map.
if (fileStream.Length < capacity)
{
try
{
fileStream.SetLength(capacity);
}
catch (ArgumentException exc)
{
// If the capacity is too large, we'll get an ArgumentException from SetLength,
// but on Windows this same condition is represented by an IOException.
throw new IOException(exc.Message, exc);
}
}
}
else
{
// This map is backed by memory-only. With files, multiple views over the same map
// will end up being able to share data through the same file-based backing store;
// for anonymous maps, we need a similar backing store, or else multiple views would logically
// each be their own map and wouldn't share any data. To achieve this, we create a backing object
// (either memory or on disk, depending on the system) and use its file descriptor as the file handle.
// However, we only do this when the permission is more than read-only. We can't change the size
// of an object that has read-only permissions, but we also don't need to worry about sharing
// views over a read-only, anonymous, memory-backed map, because the data will never change, so all views
// will always see zero and can't change that. In that case, we just use the built-in anonymous support of
// the map by leaving fileStream as null.
Interop.Sys.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false);
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0)
{
ownsFileStream = true;
fileStream = CreateSharedBackingObject(protections, capacity, inheritability);
}
}
return new SafeMemoryMappedFileHandle(fileStream, ownsFileStream, inheritability, access, options, capacity);
}
/// <summary>
/// Used by the CreateOrOpen factory method groups.
/// </summary>
private static SafeMemoryMappedFileHandle CreateOrOpenCore(
string mapName,
HandleInheritability inheritability, MemoryMappedFileAccess access,
MemoryMappedFileOptions options, long capacity)
{
// Since we don't support mapName != null, CreateOrOpenCore can't
// be used to Open an existing map, and thus is identical to CreateCore.
return CreateCore(null, mapName, inheritability, access, options, capacity);
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, bool createOrOpen)
{
throw CreateNamedMapsNotSupportedException();
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileRights rights, bool createOrOpen)
{
throw CreateNamedMapsNotSupportedException();
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Gets an exception indicating that named maps are not supported on this platform.</summary>
private static Exception CreateNamedMapsNotSupportedException()
{
return new PlatformNotSupportedException(SR.PlatformNotSupported_NamedMaps);
}
private static FileAccess TranslateProtectionsToFileAccess(Interop.Sys.MemoryMappedProtections protections)
{
return
(protections & (Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite :
(protections & (Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write :
FileAccess.Read;
}
private static FileStream CreateSharedBackingObject(Interop.Sys.MemoryMappedProtections protections, long capacity, HandleInheritability inheritability)
{
return CreateSharedBackingObjectUsingMemory(protections, capacity, inheritability)
?? CreateSharedBackingObjectUsingFile(protections, capacity, inheritability);
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private static FileStream CreateSharedBackingObjectUsingMemory(
Interop.Sys.MemoryMappedProtections protections, long capacity, HandleInheritability inheritability)
{
// The POSIX shared memory object name must begin with '/'. After that we just want something short and unique.
string mapName = "/corefx_map_" + Guid.NewGuid().ToString("N");
// Determine the flags to use when creating the shared memory object
Interop.Sys.OpenFlags flags = (protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 ?
Interop.Sys.OpenFlags.O_RDWR :
Interop.Sys.OpenFlags.O_RDONLY;
flags |= Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL; // CreateNew
// Determine the permissions with which to create the file
Interop.Sys.Permissions perms = default(Interop.Sys.Permissions);
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_READ) != 0)
perms |= Interop.Sys.Permissions.S_IRUSR;
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0)
perms |= Interop.Sys.Permissions.S_IWUSR;
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_EXEC) != 0)
perms |= Interop.Sys.Permissions.S_IXUSR;
// Create the shared memory object.
SafeFileHandle fd = Interop.Sys.ShmOpen(mapName, flags, (int)perms);
if (fd.IsInvalid)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.ENOTSUP)
{
// If ShmOpen is not supported, fall back to file backing object.
// Note that the System.Native shim will force this failure on platforms where
// the result of native shm_open does not work well with our subsequent call
// to mmap.
return null;
}
throw Interop.GetExceptionForIoErrno(errorInfo);
}
try
{
// Unlink the shared memory object immediately so that it'll go away once all handles
// to it are closed (as with opened then unlinked files, it'll remain usable via
// the open handles even though it's unlinked and can't be opened anew via its name).
Interop.CheckIo(Interop.Sys.ShmUnlink(mapName));
// Give it the right capacity. We do this directly with ftruncate rather
// than via FileStream.SetLength after the FileStream is created because, on some systems,
// lseek fails on shared memory objects, causing the FileStream to think it's unseekable,
// causing it to preemptively throw from SetLength.
Interop.CheckIo(Interop.Sys.FTruncate(fd, capacity));
// shm_open sets CLOEXEC implicitly. If the inheritability requested is Inheritable, remove CLOEXEC.
if (inheritability == HandleInheritability.Inheritable &&
Interop.Sys.Fcntl.SetFD(fd, 0) == -1)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo());
}
// Wrap the file descriptor in a stream and return it.
return new FileStream(fd, TranslateProtectionsToFileAccess(protections));
}
catch
{
fd.Dispose();
throw;
}
}
private static FileStream CreateSharedBackingObjectUsingFile(Interop.Sys.MemoryMappedProtections protections, long capacity, HandleInheritability inheritability)
{
// We create a temporary backing file in TMPDIR. We don't bother putting it into subdirectories as the file exists
// extremely briefly: it's opened/created and then immediately unlinked.
string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
FileShare share = inheritability == HandleInheritability.None ?
FileShare.ReadWrite :
FileShare.ReadWrite | FileShare.Inheritable;
// Create the backing file, then immediately unlink it so that it'll be cleaned up when no longer in use.
// Then enlarge it to the requested capacity.
const int DefaultBufferSize = 0x1000;
var fs = new FileStream(path, FileMode.CreateNew, TranslateProtectionsToFileAccess(protections), share, DefaultBufferSize);
try
{
Interop.CheckIo(Interop.Sys.Unlink(path));
fs.SetLength(capacity);
}
catch
{
fs.Dispose();
throw;
}
return fs;
}
}
}
| |
#region License
// Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
#endregion
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using SourceCode.Clay;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
namespace SourceCode.Chasm.IO.AzureBlob
{
partial class AzureBlobChasmRepo // .CommitRef
{
#region Fields
private const string CommitExtension = ".commit";
#endregion
#region List
public override async ValueTask<IReadOnlyList<CommitRef>> GetBranchesAsync(string name, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
var refsContainer = _refsContainer.Value;
var results = new List<CommitRef>();
name = DeriveCommitRefBlobName(name, null);
BlobContinuationToken token = null;
do
{
var resultSegment = await refsContainer.ListBlobsSegmentedAsync(name, false, BlobListingDetails.None, null, token, null, null).ConfigureAwait(false);
foreach (var blobItem in resultSegment.Results)
{
if (!(blobItem is CloudBlob blob))
continue;
if (!blob.Name.EndsWith(CommitExtension, StringComparison.OrdinalIgnoreCase))
continue;
var branch = blob.Name.Substring(name.Length, blob.Name.Length - CommitExtension.Length - name.Length);
branch = Uri.UnescapeDataString(branch);
using (var output = new MemoryStream())
{
await blob.DownloadToStreamAsync(output, default, default, default, cancellationToken).ConfigureAwait(false);
if (output.Length < Sha1.ByteLen)
throw new SerializationException($"{nameof(CommitRef)} '{name}/{branch}' expected to have byte length {Sha1.ByteLen} but has length {output.Length}");
var commitId = Serializer.DeserializeCommitId(output.ToArray());
results.Add(new CommitRef(branch, commitId));
}
}
token = resultSegment.ContinuationToken;
} while (token != null);
return results;
}
public override async ValueTask<IReadOnlyList<string>> GetNamesAsync(CancellationToken cancellationToken)
{
var refsContainer = _refsContainer.Value;
var results = new List<string>();
BlobContinuationToken token = null;
do
{
var resultSegment = await refsContainer.ListBlobsSegmentedAsync("", false, BlobListingDetails.None, null, token, null, null).ConfigureAwait(false);
foreach (var blobItem in resultSegment.Results)
{
if (!(blobItem is CloudBlobDirectory dir))
continue;
var name = dir.Prefix.Substring(0, dir.Prefix.Length - 1); // Ends with / always.
name = Uri.UnescapeDataString(name);
results.Add(name);
}
token = resultSegment.ContinuationToken;
} while (token != null);
return results;
}
#endregion
#region Read
public override async ValueTask<CommitRef?> ReadCommitRefAsync(string name, string branch, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name));
if (string.IsNullOrWhiteSpace(branch)) throw new ArgumentNullException(nameof(branch));
var (found, commitId, _, _) = await ReadCommitRefImplAsync(name, branch, cancellationToken).ConfigureAwait(false);
// NotFound
if (!found) return null;
// Found
var commitRef = new CommitRef(branch, commitId);
return commitRef;
}
#endregion
#region Write
public override async Task WriteCommitRefAsync(CommitId? previousCommitId, string name, CommitRef commitRef, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name));
if (commitRef == CommitRef.Empty) throw new ArgumentNullException(nameof(commitRef));
// Load existing commit ref in order to use its etag
var (found, existingCommitId, ifMatchCondition, blobRef) = await ReadCommitRefImplAsync(name, commitRef.Branch, cancellationToken).ConfigureAwait(false);
// Optimistic concurrency check
if (found)
{
// We found a previous commit but the caller didn't say to expect one
if (!previousCommitId.HasValue)
throw BuildConcurrencyException(name, commitRef.Branch, null); // TODO: May need a different error
// Semantics follow Interlocked.Exchange (compare then exchange)
if (existingCommitId != previousCommitId.Value)
{
throw BuildConcurrencyException(name, commitRef.Branch, null);
}
// Idempotent
if (existingCommitId == commitRef.CommitId) // We already know that the name matches
return;
}
// The caller expected a previous commit, but we didn't find one
else if (previousCommitId.HasValue)
{
throw BuildConcurrencyException(name, commitRef.Branch, null); // TODO: May need a different error
}
try
{
// Required to create blob before appending to it
await blobRef.CreateOrReplaceAsync(ifMatchCondition, default, default, cancellationToken).ConfigureAwait(false); // Note etag access condition
// CommitIds are not compressed
using (var session = Serializer.Serialize(commitRef.CommitId))
using (var output = new MemoryStream())
{
var seg = session.Result;
output.Write(seg.Array, seg.Offset, seg.Count);
output.Position = 0;
// Append blob. Following seems to be the only safe multi-writer method available
// http://stackoverflow.com/questions/32530126/azure-cloudappendblob-errors-with-concurrent-access
await blobRef.AppendBlockAsync(output).ConfigureAwait(false);
}
}
catch (StorageException se) when (se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict)
{
throw BuildConcurrencyException(name, commitRef.Branch, se);
}
}
#endregion
#region Helpers
private static string DeriveCommitRefBlobName(string name, string branch)
{
if (string.IsNullOrEmpty(branch))
return Uri.EscapeDataString(name) + "/";
name = Uri.EscapeDataString(name);
branch = Uri.EscapeDataString(branch);
var refName = $"{name}/{branch}.commit";
return refName;
}
private async ValueTask<(bool found, CommitId, AccessCondition, CloudAppendBlob)> ReadCommitRefImplAsync(string name, string branch, CancellationToken cancellationToken)
{
// Callers have already validated parameters
var refsContainer = _refsContainer.Value;
var blobName = DeriveCommitRefBlobName(name, branch);
var blobRef = refsContainer.GetAppendBlobReference(blobName);
try
{
using (var output = new MemoryStream())
{
// TODO: Perf: Use a stream instead of a preceding call to fetch the buffer length
// Or use blobRef.DownloadToByteArrayAsync() since we already know expected length of data (Sha1.ByteLen)
// Keep in mind Azure and/or specific IChasmSerializer may add some overhead: it looks like emperical byte length is 40-52 bytes
await blobRef.DownloadToStreamAsync(output, default, default, default, cancellationToken).ConfigureAwait(false);
// Grab the etag - we need it for optimistic concurrency control
var ifMatchCondition = AccessCondition.GenerateIfMatchCondition(blobRef.Properties.ETag);
if (output.Length < Sha1.ByteLen)
throw new SerializationException($"{nameof(CommitRef)} '{name}/{branch}' expected to have byte length {Sha1.ByteLen} but has length {output.Length}");
// CommitIds are not compressed
var commitId = Serializer.DeserializeCommitId(output.ToArray()); // TODO: Perf
// Found
return (true, commitId, ifMatchCondition, blobRef);
}
}
catch (StorageException se) when (se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
{
// Try-catch is cheaper than a separate (latent) exists check
se.Suppress();
}
// NotFound
return (false, default, default, blobRef);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Cuyahoga.Core.Util;
using Cuyahoga.Core.Domain;
using Cuyahoga.Web.UI;
using Cuyahoga.Web.Util;
using Cuyahoga.Modules.Forum;
using Cuyahoga.Modules.Forum.Domain;
using Cuyahoga.Modules.Forum.Utils;
using Cuyahoga.Modules.Forum.Web.UI;
namespace Cuyahoga.Modules.Forum
{
/// <summary>
/// Summary description.
/// </summary>
public class ForumNewPost : BaseForumControl
{
protected System.Web.UI.WebControls.Panel pnlTop;
protected System.Web.UI.HtmlControls.HtmlGenericControl Welcome;
protected System.Web.UI.WebControls.Button btnPreview;
protected System.Web.UI.WebControls.Button btnPost;
protected System.Web.UI.WebControls.Button btnCancel;
protected System.Web.UI.WebControls.TextBox txtMessage;
protected System.Web.UI.WebControls.TextBox txtSubject;
protected System.Web.UI.WebControls.RequiredFieldValidator rfvSubject;
protected System.Web.UI.WebControls.RequiredFieldValidator rfvMessage;
protected System.Web.UI.WebControls.PlaceHolder phForumTop;
protected System.Web.UI.WebControls.PlaceHolder phForumFooter;
protected System.Web.UI.WebControls.Literal ltPreviewPost;
protected System.Web.UI.WebControls.Panel pnlPreview;
protected System.Web.UI.WebControls.Label lblPreview;
protected System.Web.UI.WebControls.Literal ltJsInject;
protected System.Web.UI.WebControls.Panel pnlSmily;
protected System.Web.UI.WebControls.Repeater rptSmily;
protected System.Web.UI.HtmlControls.HtmlInputFile txtAttachment;
protected System.Web.UI.WebControls.Panel pnlUploadError;
protected System.Web.UI.WebControls.Literal ltlUploadError;
private ForumForum _forumForum;
private void Page_Load(object sender, System.EventArgs e)
{
this._forumForum = base.ForumModule.GetForumById(base.ForumModule.CurrentForumId);
base.ForumModule.CurrentForumCategoryId = this._forumForum.CategoryId;
this.BindTopFooter();
base.LocalizeControls();
this.BindJS();
this.BindEmoticon();
}
private void BindTopFooter()
{
ForumTop tForumTop;
ForumFooter tForumFooter;
tForumTop = (ForumTop)this.LoadControl("~/Modules/Forum/ForumTop.ascx");
tForumTop.Module = base.ForumModule;
this.phForumTop.Controls.Add(tForumTop);
tForumFooter = (ForumFooter)this.LoadControl("~/Modules/Forum/ForumFooter.ascx");
tForumFooter.Module = base.ForumModule;
this.phForumFooter.Controls.Add(tForumFooter);
}
private void BindJS()
{
Page.RegisterClientScriptBlock("forumscripts", String.Format("<script language=\"JavaScript\" src=\"{0}/Modules/Forum/forum.js\"></script>\n",UrlHelper.GetSiteUrl()));
}
private void BindEmoticon()
{
this.rptSmily.DataSource = base.ForumModule.GetAllEmoticons();
this.rptSmily.DataBind();
}
private void Translate()
{
string uname = "";
if(this.Page.User.Identity.IsAuthenticated)
{
Cuyahoga.Core.Domain.User currentUser = Context.User.Identity as Cuyahoga.Core.Domain.User;
uname = currentUser.FullName;
}
else
{
uname = "Guest";
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnPreview.Click += new System.EventHandler(this.btnPreview_Click);
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
this.btnPost.Click += new System.EventHandler(this.btnPost_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btnPreview_Click(object sender, System.EventArgs e)
{
this.pnlPreview.Visible = true;
this.ltPreviewPost.Visible = true;
this.lblPreview.Visible = true;
this.ltPreviewPost.Text = TextParser.ForumCodeToHtml(this.txtMessage.Text,base.ForumModule);
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
Response.Redirect(String.Format("{0}/ForumView/{1}", UrlHelper.GetUrlFromSection(base.ForumModule.Section), base.ForumModule.CurrentForumId));
}
private void btnPost_Click(object sender, System.EventArgs e)
{
if(this.Page.IsValid)
{
Cuyahoga.Core.Domain.User tUser = this.Page.User.Identity as User;
HttpPostedFile postedFile = this.txtAttachment.PostedFile;
ForumFile fFile;
ForumPost tForumPost = new ForumPost();
tForumPost.ForumId = base.ForumModule.CurrentForumId;
tForumPost.DateCreated = DateTime.Now;
tForumPost.Message = TextParser.ForumCodeToHtml(this.txtMessage.Text,base.ForumModule);
tForumPost.Topic = this.txtSubject.Text;
if(tUser != null)
{
tForumPost.UserId = tUser.Id;
tForumPost.UserName = tUser.UserName;
}
else
{
tForumPost.UserId = 0;
tForumPost.UserName = base.GetText("GUEST");
}
base.ForumModule.SaveForumPost(tForumPost);
// Save attachement
if(postedFile.ContentLength > 0)
{
try
{
this.CheckValidFile(this.txtAttachment);
fFile = this.SaveAttachment(tForumPost,this.txtAttachment);
tForumPost.AttachmentId = fFile.Id;
base.ForumModule.SaveForumPost(tForumPost);
}
catch(Exception ex)
{
this.pnlUploadError.Visible = true;
this.ltlUploadError.Text = ex.Message;
base.ForumModule.DeleteForumPost(tForumPost);
return;
}
}
// Update number of topics and number of posts
ForumForum tForumForum = base.ForumModule.GetForumById(base.ForumModule.CurrentForumId);
tForumForum.NumTopics++;
tForumForum.NumPosts++;
tForumForum.LastPosted = DateTime.Now;
tForumForum.LastPostUserName = tForumPost.UserName;
tForumForum.LastPostId = tForumPost.Id;
base.ForumModule.SaveForum(tForumForum);
Response.Redirect(String.Format("{0}/ForumView/{1}",UrlHelper.GetUrlFromSection(base.ForumModule.Section), base.ForumModule.CurrentForumId));
}
}
private void CheckValidFile(HtmlInputFile file)
{
if(file.PostedFile==null || file.PostedFile.FileName.Trim().Length==0 || file.PostedFile.ContentLength==0)
return;
string filename = file.PostedFile.FileName;
int pos = filename.LastIndexOfAny(new char[]{'/','\\'});
if(pos>=0)
filename = filename.Substring(pos+1);
pos = filename.LastIndexOf('.');
if(pos>=0)
{
switch(filename.Substring(pos+1).ToLower())
{
default:
break;
case "asp":
case "aspx":
case "ascx":
case "config":
case "php":
case "php3":
case "js":
case "vb":
case "vbs":
throw new Exception(String.Format(GetText("fileerror"),filename));
}
}
}
private ForumFile SaveAttachment(ForumPost post, HtmlInputFile file)
{
ForumFile fFile = new ForumFile();
if(file.PostedFile==null || file.PostedFile.FileName.Trim().Length==0 || file.PostedFile.ContentLength==0)
return null;
string sUpDir = Server.MapPath(UrlHelper.GetApplicationPath() + "/Modules/Forum/Attach/");
string filename = file.PostedFile.FileName;
if(!System.IO.Directory.Exists(sUpDir))
{
System.IO.Directory.CreateDirectory(sUpDir);
}
int pos = filename.LastIndexOfAny(new char[]{'/','\\'});
if (pos >= 0)
filename = filename.Substring(pos+1);
string newfilename = String.Format("{0}{1}.{2}",sUpDir,post.Id,filename);
file.PostedFile.SaveAs(newfilename);
fFile.OrigFileName = filename;
fFile.ForumFileName = newfilename;
fFile.FileSize = file.PostedFile.ContentLength;
fFile.ContentType = file.PostedFile.ContentType;
try
{
base.ForumModule.SaveForumFile(fFile);
}
catch(Exception ex)
{
throw new Exception("Unable to save file",ex);
}
return fFile;
}
public string GetEmoticonIcon(object o)
{
ForumEmoticon ei = (ForumEmoticon)o;
string imagepath = String.Format("{0}/Images/Standard/", this.TemplateSourceDirectory);
// HARD CODEDE - CHANGEME!!
string sResult = String.Format("<a href=\"javascript:InsertEmoticon('{0}','{1}');\"><img src=\"{2}{3}\" border=0 alt=\"\"></a>", this.txtMessage.ClientID, ei.TextVersion, imagepath, ei.ImageName);
return sResult;
}
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Grpc.Core;
using Microsoft.VisualStudio.Threading;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace DebuggerGrpcClient.Tests
{
[TestFixture]
[Timeout(15000)]
class GrpcConnectionTests
{
readonly Status rpcStatus = new Status(StatusCode.Aborted, "test error");
GrpcConnection connection;
JoinableTaskContext taskContext;
[SetUp]
public void SetUp()
{
var callInvokerFactory = new PipeCallInvokerFactory();
taskContext = new JoinableTaskContext();
connection = new GrpcConnection(taskContext.Factory, callInvokerFactory.Create());
}
[TearDown]
public void TearDown()
{
connection.Shutdown();
taskContext.Dispose();
}
[Test]
public void InvokeRpcSuccess()
{
connection.RpcException +=
e => Assert.Fail("Unexpected error: " + e.ToString());
bool taskRan = false;
bool result = connection.InvokeRpc(() => { taskRan = true; });
Assert.That(result, Is.True);
Assert.That(taskRan, Is.True);
}
[Test]
public async Task InvokeRpcAsyncSuccessAsync()
{
connection.RpcException +=
e => Assert.Fail("Unexpected error: " + e);
var taskRan = false;
var result = await connection.InvokeRpcAsync(() =>
{
taskRan = true;
return Task.CompletedTask;
}).WithTimeout(TimeSpan.FromSeconds(5));
Assert.That(result, Is.True);
Assert.That(taskRan, Is.True);
}
[Test]
public async Task EventHandlerIsInvokedOnAsyncRpcCompletionAsync()
{
bool handlerInvoked = false;
connection.AsyncRpcCompleted += () => handlerInvoked = true;
await connection.InvokeRpcAsync(() => Task.CompletedTask);
Assert.That(handlerInvoked, Is.True);
}
[Test]
public void InvokeRpcAsyncThrowsExceptions()
{
connection.RpcException +=
e => Assert.Fail("Unexpected error: " + e);
Assert.ThrowsAsync<BadException>(async () =>
{
await connection.InvokeRpcAsync(() => throw new BadException())
.WithTimeout(TimeSpan.FromSeconds(5));
});
}
[Test]
public async Task InvokeRpcSucceedWhenAsyncThrowsAsync()
{
await taskContext.Factory.SwitchToMainThreadAsync();
connection.RpcException +=
e => Assert.Fail("Unexpected error: " + e);
var completeFirstTask = new AsyncManualResetEvent(false);
var taskRanList = new List<int>();
Task<bool> task = connection.InvokeRpcAsync(async () =>
{
await completeFirstTask.WaitAsync();
taskRanList.Add(2);
throw new BadException();
});
completeFirstTask.Set();
taskRanList.Add(1);
var result = connection.InvokeRpc(() => { taskRanList.Add(3); });
try
{
await task;
}
catch (BadException)
{
}
Assert.That(task.Exception?.InnerExceptions[0] is BadException);
Assert.That(result, Is.True);
Assert.AreEqual(new List<int> { 1, 2, 3 }, taskRanList);
}
[Test]
public async Task InvokeRpcAsyncTwiceAsync()
{
connection.RpcException +=
e => Assert.Fail("Unexpected error: " + e);
var completeFirstTask = new AsyncManualResetEvent(false);
var taskRanList = new List<int>();
Task<bool> task1 = connection.InvokeRpcAsync(async () =>
{
await completeFirstTask.WaitAsync().WithTimeout(TimeSpan.FromSeconds(10));
taskRanList.Add(1);
throw new BadException();
});
Task<bool> task2 = connection.InvokeRpcAsync(async () =>
{
taskRanList.Add(2);
await Task.CompletedTask;
});
completeFirstTask.Set();
Assert.ThrowsAsync<BadException>(async () =>
{
await task1.WithTimeout(TimeSpan.FromSeconds(10));
});
Assert.That(task1.Exception?.InnerExceptions[0] is BadException);
Assert.That(await task2, Is.True);
Assert.AreEqual(new List<int> { 1, 2 }, taskRanList);
}
[Test]
public void InvokeRpcFailure()
{
Exception reportedError = null;
connection.RpcException += e => reportedError = e;
bool result = connection.InvokeRpc(() => throw new RpcException(rpcStatus));
Assert.That(result, Is.False);
Assert.That(reportedError, Is.AssignableTo<RpcException>());
RpcException rpcError = (RpcException)reportedError;
Assert.That(rpcError.Status, Is.EqualTo(rpcStatus));
}
[Test]
public void InvokeRpcIgnoredAfterShutdown()
{
connection.Shutdown();
bool taskRan = false;
bool result = connection.InvokeRpc(() => { taskRan = true; });
Assert.That(result, Is.False);
Assert.That(taskRan, Is.False);
}
[Test]
public void InvokeRpcErrorIgnoredInShutdownRace()
{
connection.RpcException +=
e => Assert.Fail("Unexpected error: " + e);
bool result = connection.InvokeRpc(() =>
{
connection.Shutdown();
throw new RpcException(rpcStatus);
});
Assert.That(result, Is.False);
}
[Test]
public void InvokeRpcErrorIgnoredWithoutHandler()
{
bool result = connection.InvokeRpc(() => throw new RpcException(rpcStatus));
Assert.That(result, Is.False);
}
class BadException : Exception
{
}
}
}
| |
using System;
using System.Collections;
using BLToolkit.Data;
using BLToolkit.Reflection.Extension;
namespace BLToolkit.DataAccess
{
public class SqlQuery : SqlQueryBase
{
#region Constructors
public SqlQuery()
{
}
public SqlQuery(DbManager dbManager)
: base(dbManager)
{
}
public SqlQuery(DbManager dbManager, bool dispose)
: base(dbManager, dispose)
{
}
public SqlQuery(ExtensionList extensions)
{
Extensions = extensions;
}
#endregion
#region Overrides
public SqlQueryInfo GetSqlQueryInfo<T>(DbManager db, string actionName)
{
return base.GetSqlQueryInfo(db, typeof(T), actionName);
}
#endregion
#region SelectByKey
public virtual object SelectByKey(DbManager db, Type type, params object[] keys)
{
SqlQueryInfo query = GetSqlQueryInfo(db, type, "SelectByKey");
return db
.SetCommand(query.QueryText, query.GetParameters(db, keys))
.ExecuteObject(type);
}
public virtual object SelectByKey(Type type, params object[] keys)
{
DbManager db = GetDbManager();
try
{
return SelectByKey(db, type, keys);
}
finally
{
if (DisposeDbManager)
db.Dispose();
}
}
public virtual T SelectByKey<T>(DbManager db, params object[] keys)
{
SqlQueryInfo query = GetSqlQueryInfo(db, typeof(T), "SelectByKey");
return db
.SetCommand(query.QueryText, query.GetParameters(db, keys))
.ExecuteObject<T>();
}
public virtual T SelectByKey<T>(params object[] keys)
{
DbManager db = GetDbManager();
try
{
return SelectByKey<T>(db, keys);
}
finally
{
if (DisposeDbManager)
db.Dispose();
}
}
#endregion
#region SelectAll
public virtual ArrayList SelectAll(DbManager db, Type type)
{
SqlQueryInfo query = GetSqlQueryInfo(db, type, "SelectAll");
return db
.SetCommand(query.QueryText)
.ExecuteList(type);
}
public virtual IList SelectAll(DbManager db, IList list, Type type)
{
SqlQueryInfo query = GetSqlQueryInfo(db, type, "SelectAll");
return db
.SetCommand(query.QueryText)
.ExecuteList(list, type);
}
public virtual ArrayList SelectAll(Type type)
{
DbManager db = GetDbManager();
try
{
return SelectAll(db, type);
}
finally
{
Dispose(db);
}
}
public virtual IList SelectAll(IList list, Type type)
{
DbManager db = GetDbManager();
try
{
return SelectAll(db, list, type);
}
finally
{
Dispose(db);
}
}
public virtual System.Collections.Generic.List<T> SelectAll<T>(DbManager db)
{
SqlQueryInfo query = GetSqlQueryInfo(db, typeof(T), "SelectAll");
return db
.SetCommand(query.QueryText)
.ExecuteList<T>();
}
public virtual L SelectAll<L,T>(DbManager db, L list)
where L : System.Collections.Generic.IList<T>
{
SqlQueryInfo query = GetSqlQueryInfo(db, typeof(T), "SelectAll");
return db
.SetCommand(query.QueryText)
.ExecuteList<L,T>(list);
}
public virtual L SelectAll<L,T>(DbManager db)
where L : System.Collections.Generic.IList<T>, new()
{
return SelectAll<L,T>(db, new L());
}
public virtual System.Collections.Generic.List<T> SelectAll<T>()
{
DbManager db = GetDbManager();
try
{
return SelectAll<T>(db);
}
finally
{
Dispose(db);
}
}
public virtual L SelectAll<L,T>(L list)
where L : System.Collections.Generic.IList<T>
{
DbManager db = GetDbManager();
try
{
return SelectAll<L,T>(db, list);
}
finally
{
Dispose(db);
}
}
public virtual L SelectAll<L,T>()
where L : System.Collections.Generic.IList<T>, new()
{
return SelectAll<L,T>(new L());
}
#endregion
#region Insert
public virtual int Insert(DbManager db, object obj)
{
SqlQueryInfo query = GetSqlQueryInfo(db, obj.GetType(), "Insert");
return db
.SetCommand(query.QueryText, query.GetParameters(db, obj))
.ExecuteNonQuery();
}
public virtual int Insert(object obj)
{
DbManager db = GetDbManager();
try
{
return Insert(db, obj);
}
finally
{
Dispose(db);
}
}
#endregion
#region Update
public virtual int Update(DbManager db, object obj)
{
SqlQueryInfo query = GetSqlQueryInfo(db, obj.GetType(), "Update");
return db
.SetCommand(query.QueryText, query.GetParameters(db, obj))
.ExecuteNonQuery();
}
public virtual int Update(object obj)
{
DbManager db = GetDbManager();
try
{
return Update(db, obj);
}
finally
{
Dispose(db);
}
}
#endregion
#region DeleteByKey
public virtual int DeleteByKey(DbManager db, Type type, params object[] key)
{
SqlQueryInfo query = GetSqlQueryInfo(db, type, "Delete");
return db
.SetCommand(query.QueryText, query.GetParameters(db, key))
.ExecuteNonQuery();
}
public virtual int DeleteByKey(Type type, params object[] key)
{
DbManager db = GetDbManager();
try
{
return DeleteByKey(db, type, key);
}
finally
{
Dispose(db);
}
}
public virtual int DeleteByKey<T>(DbManager db, params object[] key)
{
SqlQueryInfo query = GetSqlQueryInfo(db, typeof(T), "Delete");
return db
.SetCommand(query.QueryText, query.GetParameters(db, key))
.ExecuteNonQuery();
}
public virtual int DeleteByKey<T>(params object[] key)
{
DbManager db = GetDbManager();
try
{
return DeleteByKey<T>(db, key);
}
finally
{
Dispose(db);
}
}
#endregion
#region Delete
public virtual int Delete(DbManager db, object obj)
{
SqlQueryInfo query = GetSqlQueryInfo(db, obj.GetType(), "Delete");
return db
.SetCommand(query.QueryText, query.GetParameters(db, obj))
.ExecuteNonQuery();
}
public virtual int Delete(object obj)
{
DbManager db = GetDbManager();
try
{
return Delete(db, obj);
}
finally
{
Dispose(db);
}
}
#endregion
}
}
| |
namespace OdessaGUIProject.DRM_Helpers
{
sealed partial class TFReactivation
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
OdessaGUIProject.TransLabel transLabel1;
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TFReactivation));
this.lblCode = new OdessaGUIProject.TransLabel();
this.label1 = new OdessaGUIProject.TransLabel();
this.label4 = new OdessaGUIProject.TransLabel();
this.label3 = new OdessaGUIProject.TransLabel();
this.tbConfPass = new System.Windows.Forms.TextBox();
this.tbNewPass = new System.Windows.Forms.TextBox();
this.tbCurrentPass = new System.Windows.Forms.TextBox();
this.sendPasswordLinkLabel = new System.Windows.Forms.LinkLabel();
this.cancelButton = new OdessaGUIProject.UI_Controls.PictureButtonControl();
this.activateButton = new OdessaGUIProject.UI_Controls.PictureButtonControl();
transLabel1 = new OdessaGUIProject.TransLabel();
this.SuspendLayout();
//
// transLabel1
//
transLabel1.AutoSize = true;
transLabel1.BackColor = System.Drawing.Color.Transparent;
transLabel1.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
transLabel1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204)))));
transLabel1.Location = new System.Drawing.Point(23, 219);
transLabel1.Name = "transLabel1";
transLabel1.Size = new System.Drawing.Size(331, 18);
transLabel1.TabIndex = 4;
transLabel1.Text = "As a security precaution, please enter a new password.";
//
// lblCode
//
this.lblCode.AutoSize = true;
this.lblCode.BackColor = System.Drawing.Color.Transparent;
this.lblCode.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblCode.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204)))));
this.lblCode.Location = new System.Drawing.Point(24, 44);
this.lblCode.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblCode.Name = "lblCode";
this.lblCode.Size = new System.Drawing.Size(39, 18);
this.lblCode.TabIndex = 0;
this.lblCode.Text = "code";
//
// label1
//
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204)))));
this.label1.Location = new System.Drawing.Point(23, 74);
this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(410, 78);
this.label1.TabIndex = 1;
this.label1.Text = "This code has already been activated and must be re-activated on this machine. Pl" +
"ease enter your current password to re-activate.";
//
// label4
//
this.label4.AutoSize = true;
this.label4.BackColor = System.Drawing.Color.Transparent;
this.label4.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204)))));
this.label4.Location = new System.Drawing.Point(23, 297);
this.label4.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(146, 18);
this.label4.TabIndex = 7;
this.label4.Text = "Confirm new Password";
//
// label3
//
this.label3.AutoSize = true;
this.label3.BackColor = System.Drawing.Color.Transparent;
this.label3.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204)))));
this.label3.Location = new System.Drawing.Point(23, 265);
this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(174, 18);
this.label3.TabIndex = 5;
this.label3.Text = "New (never-used) Password";
//
// tbConfPass
//
this.tbConfPass.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbConfPass.Location = new System.Drawing.Point(230, 294);
this.tbConfPass.Margin = new System.Windows.Forms.Padding(2, 3, 2, 3);
this.tbConfPass.MaxLength = 16;
this.tbConfPass.Name = "tbConfPass";
this.tbConfPass.PasswordChar = '*';
this.tbConfPass.Size = new System.Drawing.Size(199, 25);
this.tbConfPass.TabIndex = 8;
this.tbConfPass.UseSystemPasswordChar = true;
//
// tbNewPass
//
this.tbNewPass.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbNewPass.Location = new System.Drawing.Point(230, 261);
this.tbNewPass.Margin = new System.Windows.Forms.Padding(2, 3, 2, 3);
this.tbNewPass.MaxLength = 16;
this.tbNewPass.Name = "tbNewPass";
this.tbNewPass.PasswordChar = '*';
this.tbNewPass.Size = new System.Drawing.Size(199, 25);
this.tbNewPass.TabIndex = 6;
this.tbNewPass.UseSystemPasswordChar = true;
//
// tbCurrentPass
//
this.tbCurrentPass.AllowDrop = true;
this.tbCurrentPass.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tbCurrentPass.Location = new System.Drawing.Point(26, 139);
this.tbCurrentPass.Margin = new System.Windows.Forms.Padding(2, 3, 2, 3);
this.tbCurrentPass.MaxLength = 16;
this.tbCurrentPass.Name = "tbCurrentPass";
this.tbCurrentPass.PasswordChar = '*';
this.tbCurrentPass.Size = new System.Drawing.Size(199, 25);
this.tbCurrentPass.TabIndex = 2;
this.tbCurrentPass.UseSystemPasswordChar = true;
//
// sendPasswordLinkLabel
//
this.sendPasswordLinkLabel.ActiveLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(153)))), ((int)(((byte)(204)))));
this.sendPasswordLinkLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.sendPasswordLinkLabel.AutoSize = true;
this.sendPasswordLinkLabel.BackColor = System.Drawing.Color.Transparent;
this.sendPasswordLinkLabel.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.sendPasswordLinkLabel.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.sendPasswordLinkLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(153)))), ((int)(((byte)(204)))));
this.sendPasswordLinkLabel.LinkBehavior = System.Windows.Forms.LinkBehavior.NeverUnderline;
this.sendPasswordLinkLabel.LinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(153)))), ((int)(((byte)(204)))));
this.sendPasswordLinkLabel.Location = new System.Drawing.Point(248, 147);
this.sendPasswordLinkLabel.Name = "sendPasswordLinkLabel";
this.sendPasswordLinkLabel.Size = new System.Drawing.Size(106, 17);
this.sendPasswordLinkLabel.TabIndex = 37;
this.sendPasswordLinkLabel.TabStop = true;
this.sendPasswordLinkLabel.Text = "Send Password...";
this.sendPasswordLinkLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.sendPasswordLinkLabel.VisitedLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(153)))), ((int)(((byte)(204)))));
this.sendPasswordLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.sendPasswordLinkLabel_LinkClicked);
//
// cancelButton
//
this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cancelButton.AutoSize = true;
this.cancelButton.DefaultImage = global::OdessaGUIProject.Properties.Resources.button_gray_cancel_normal;
this.cancelButton.HoverImage = global::OdessaGUIProject.Properties.Resources.button_gray_cancel_hover;
this.cancelButton.Location = new System.Drawing.Point(297, 354);
this.cancelButton.MouseDownImage = global::OdessaGUIProject.Properties.Resources.button_gray_cancel_click;
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(192, 43);
this.cancelButton.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.cancelButton.TabIndex = 43;
this.cancelButton.Tooltip = null;
this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
//
// activateButton
//
this.activateButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.activateButton.AutoSize = true;
this.activateButton.DefaultImage = global::OdessaGUIProject.Properties.Resources.button_green_activate_normal;
this.activateButton.HoverImage = global::OdessaGUIProject.Properties.Resources.button_green_activate_hover;
this.activateButton.Location = new System.Drawing.Point(99, 354);
this.activateButton.MouseDownImage = global::OdessaGUIProject.Properties.Resources.button_green_activate_click;
this.activateButton.Name = "activateButton";
this.activateButton.Size = new System.Drawing.Size(192, 43);
this.activateButton.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.activateButton.TabIndex = 42;
this.activateButton.Tooltip = null;
this.activateButton.Click += new System.EventHandler(this.btnReactivate_Click);
//
// TFReactivation
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 18F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(50)))));
this.BackgroundImage = global::OdessaGUIProject.Properties.Resources.background_pattern_102x102_tile;
this.ClientSize = new System.Drawing.Size(501, 409);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.activateButton);
this.Controls.Add(this.sendPasswordLinkLabel);
this.Controls.Add(transLabel1);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.tbConfPass);
this.Controls.Add(this.tbNewPass);
this.Controls.Add(this.tbCurrentPass);
this.Controls.Add(this.lblCode);
this.Controls.Add(this.label1);
this.DoubleBuffered = true;
this.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204)))));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(2, 3, 2, 3);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "TFReactivation";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Activation";
this.Load += new System.EventHandler(this.TFReactivation_Load);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.TFReactivation_Paint);
this.Resize += new System.EventHandler(this.TFReactivation_Resize);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
internal TransLabel lblCode;
private TransLabel label1;
private TransLabel label4;
private TransLabel label3;
internal System.Windows.Forms.TextBox tbConfPass;
internal System.Windows.Forms.TextBox tbNewPass;
internal System.Windows.Forms.TextBox tbCurrentPass;
private System.Windows.Forms.LinkLabel sendPasswordLinkLabel;
private UI_Controls.PictureButtonControl cancelButton;
private UI_Controls.PictureButtonControl activateButton;
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using NFluent;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.Types;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.RequestMatchers
{
public class RequestMessageBodyMatcherTests
{
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsString = "b",
DetectedBodyType = BodyType.String
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.5d);
// Verify
stringMatcherMock.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock.Verify(m => m.IsMatch("b"), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_IStringMatchers()
{
// Assign
var body = new BodyData
{
BodyAsString = "b",
DetectedBodyType = BodyType.String
};
var stringMatcherMock1 = new Mock<IStringMatcher>();
stringMatcherMock1.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.2d);
var stringMatcherMock2 = new Mock<IStringMatcher>();
stringMatcherMock2.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.8d);
var matchers = new[] { stringMatcherMock1.Object, stringMatcherMock2.Object };
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(matchers.Cast<IMatcher>().ToArray());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.8d);
// Verify
stringMatcherMock1.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock1.Verify(m => m.IsMatch("b"), Times.Once);
stringMatcherMock2.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock2.Verify(m => m.IsMatch("b"), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsBytes = new byte[] { 1 },
DetectedBodyType = BodyType.Bytes
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.0d);
// Verify
stringMatcherMock.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Never);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = new { value = 42 },
DetectedBodyType = BodyType.Json
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.5d);
// Verify
stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_and_BodyAsString_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = new { value = 42 },
BodyAsString = "orig",
DetectedBodyType = BodyType.Json
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.5d);
// Verify
stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_IObjectMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = 42,
DetectedBodyType = BodyType.Json
};
var objectMatcherMock = new Mock<IObjectMatcher>();
objectMatcherMock.Setup(m => m.IsMatch(It.IsAny<object>())).Returns(0.5d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(objectMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.5d);
// Verify
objectMatcherMock.Verify(m => m.IsMatch(42), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_CSharpCodeMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = new { value = 42 },
DetectedBodyType = BodyType.Json
};
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(new CSharpCodeMatcher(MatchBehaviour.AcceptOnMatch, "return it.value == 42;"));
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
}
[Theory]
[InlineData(null, 0.0)]
[InlineData(new byte[0], 0.0)]
[InlineData(new byte[] { 48 }, 1.0)]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_NotNullOrEmptyObjectMatcher(byte[] bytes, double expected)
{
// Assign
var body = new BodyData
{
BodyAsBytes = bytes,
DetectedBodyType = BodyType.Bytes
};
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(new NotNullOrEmptyMatcher());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
score.Should().Be(expected);
}
[Theory]
[InlineData(null, 0.0)]
[InlineData("", 0.0)]
[InlineData("x", 1.0)]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_NotNullOrEmptyObjectMatcher(string data, double expected)
{
// Assign
var body = new BodyData
{
BodyAsString = data,
DetectedBodyType = BodyType.String
};
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(new NotNullOrEmptyMatcher());
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
score.Should().Be(expected);
}
[Theory]
[InlineData(new byte[] { 1 })]
[InlineData(new byte[] { 48 })]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_IObjectMatcher(byte[] bytes)
{
// Assign
var body = new BodyData
{
BodyAsBytes = bytes,
DetectedBodyType = BodyType.Bytes
};
var objectMatcherMock = new Mock<IObjectMatcher>();
objectMatcherMock.Setup(m => m.IsMatch(It.IsAny<object>())).Returns(0.5d);
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(objectMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.5d);
// Verify
objectMatcherMock.Verify(m => m.IsMatch(It.IsAny<byte[]>()), Times.Once);
}
[Theory]
[MemberData(nameof(MatchingScoreData))]
public async Task RequestMessageBodyMatcher_GetMatchingScore_Funcs_Matching(object body, RequestMessageBodyMatcher matcher, bool shouldMatch)
{
// assign
BodyData bodyData;
if (body is byte[] b)
{
var bodyParserSettings = new BodyParserSettings
{
Stream = new MemoryStream(b),
ContentType = null,
DeserializeJson = true
};
bodyData = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false);
}
else if (body is string s)
{
var bodyParserSettings = new BodyParserSettings
{
Stream = new MemoryStream(Encoding.UTF8.GetBytes(s)),
ContentType = null,
DeserializeJson = true
};
bodyData = await BodyParser.ParseAsync(bodyParserSettings).ConfigureAwait(false);
}
else
{
throw new Exception();
}
var requestMessage = new RequestMessage(new UrlDetails("http://localhost"), "GET", "127.0.0.1", bodyData);
// act
var result = new RequestMatchResult();
var score = matcher.GetMatchingScore(requestMessage, result);
// assert
Check.That(score).IsEqualTo(shouldMatch ? 1d : 0d);
}
public static TheoryData<object, RequestMessageBodyMatcher, bool> MatchingScoreData
{
get
{
var json = "{'a':'b'}";
var str = "HelloWorld";
var bytes = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00 };
return new TheoryData<object, RequestMessageBodyMatcher, bool>
{
// JSON match +++
{json, new RequestMessageBodyMatcher((object o) => ((dynamic) o).a == "b"), true},
{json, new RequestMessageBodyMatcher((string s) => s == json), true},
{json, new RequestMessageBodyMatcher((byte[] b) => b.SequenceEqual(Encoding.UTF8.GetBytes(json))), true},
// JSON no match ---
{json, new RequestMessageBodyMatcher((object o) => false), false},
{json, new RequestMessageBodyMatcher((string s) => false), false},
{json, new RequestMessageBodyMatcher((byte[] b) => false), false},
{json, new RequestMessageBodyMatcher(), false },
// string match +++
{str, new RequestMessageBodyMatcher((object o) => o == null), true},
{str, new RequestMessageBodyMatcher((string s) => s == str), true},
{str, new RequestMessageBodyMatcher((byte[] b) => b.SequenceEqual(Encoding.UTF8.GetBytes(str))), true},
// string no match ---
{str, new RequestMessageBodyMatcher((object o) => false), false},
{str, new RequestMessageBodyMatcher((string s) => false), false},
{str, new RequestMessageBodyMatcher((byte[] b) => false), false},
{str, new RequestMessageBodyMatcher(), false },
// binary match +++
{bytes, new RequestMessageBodyMatcher((object o) => o == null), true},
{bytes, new RequestMessageBodyMatcher((string s) => s == null), true},
{bytes, new RequestMessageBodyMatcher((byte[] b) => b.SequenceEqual(bytes)), true},
// binary no match ---
{bytes, new RequestMessageBodyMatcher((object o) => false), false},
{bytes, new RequestMessageBodyMatcher((string s) => false), false},
{bytes, new RequestMessageBodyMatcher((byte[] b) => false), false},
{bytes, new RequestMessageBodyMatcher(), false },
};
}
}
}
}
| |
#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: SampleITCH.SampleITCHPublic
File: MainWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleITCH
{
using System;
using System.ComponentModel;
using System.Windows;
using Ecng.Common;
using Ecng.Xaml;
using StockSharp.BusinessEntities;
using StockSharp.ITCH;
using StockSharp.Localization;
using StockSharp.Logging;
using StockSharp.Messages;
using StockSharp.Xaml;
public partial class MainWindow
{
private bool _isConnected;
private bool _initialized;
public ItchTrader Trader;
private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow();
private readonly TradesWindow _tradesWindow = new TradesWindow();
private readonly OrdersLogWindow _orderLogWindow = new OrdersLogWindow();
private readonly LogManager _logManager = new LogManager();
public MainWindow()
{
InitializeComponent();
_orderLogWindow.MakeHideable();
_tradesWindow.MakeHideable();
_securitiesWindow.MakeHideable();
Title = Title.Put("ITCH");
Instance = this;
_logManager.Listeners.Add(new FileLogListener { LogDirectory = "StockSharp_ITCH" });
_logManager.Listeners.Add(new GuiLogListener(Monitor));
// create connector
Trader = new ItchTrader
{
LogLevel = LogLevels.Debug,
CreateDepthFromOrdersLog = true
};
_logManager.Sources.Add(Trader);
Settings.SelectedObject = Trader.MarketDataAdapter;
}
protected override void OnClosing(CancelEventArgs e)
{
_orderLogWindow.DeleteHideable();
_tradesWindow.DeleteHideable();
_securitiesWindow.DeleteHideable();
_securitiesWindow.Close();
_tradesWindow.Close();
_orderLogWindow.Close();
if (Trader != null)
Trader.Dispose();
base.OnClosing(e);
}
public static MainWindow Instance { get; private set; }
private void ConnectClick(object sender, RoutedEventArgs e)
{
if (!_isConnected)
{
if (Trader.Login.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str2974);
return;
}
else if (Trader.Password.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str2975);
return;
}
if (!_initialized)
{
_initialized = true;
// update gui labes
Trader.ReConnectionSettings.WorkingTime = ExchangeBoard.Forts.WorkingTime;
Trader.Restored += () => this.GuiAsync(() =>
{
ChangeConnectStatus(true);
MessageBox.Show(this, LocalizedStrings.Str2958);
});
// subscribe on connection successfully event
Trader.Connected += () =>
{
// set flag (connection is established)
_isConnected = true;
// update gui labes
this.GuiAsync(() => ChangeConnectStatus(true));
};
Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false));
// subscribe on connection error event
Trader.ConnectionError += error => this.GuiAsync(() =>
{
// update gui labes
ChangeConnectStatus(false);
MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
});
// subscribe on error event
Trader.Error += error =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));
// subscribe on error of market data subscription event
Trader.MarketDataSubscriptionFailed += (security, msg, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));
Trader.NewSecurity += _securitiesWindow.SecurityPicker.Securities.Add;
Trader.NewTrade += _tradesWindow.TradeGrid.Trades.Add;
Trader.NewOrderLogItem += _orderLogWindow.OrderLogGrid.LogItems.Add;
var subscribed = false;
//if (AllDepths.IsChecked == true)
{
Trader.LookupSecuritiesResult += (error, securities) =>
{
if (subscribed)
return;
subscribed = true;
Trader.SendInMessage(new MarketDataMessage
{
IsSubscribe = true,
DataType = MarketDataTypes.OrderLog,
TransactionId = Trader.TransactionIdGenerator.GetNextId(),
});
};
}
// set market data provider
_securitiesWindow.SecurityPicker.MarketDataProvider = Trader;
ShowSecurities.IsEnabled = ShowTrades.IsEnabled = ShowOrdersLog.IsEnabled = true;
}
Trader.Connect();
}
else
{
Trader.Disconnect();
}
}
private void ChangeConnectStatus(bool isConnected)
{
_isConnected = isConnected;
ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect;
}
private void ShowSecuritiesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_securitiesWindow);
}
private void ShowTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_tradesWindow);
}
private void ShowOrdersLogClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_orderLogWindow);
}
private static void ShowOrHide(Window window)
{
if (window == null)
throw new ArgumentNullException(nameof(window));
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
using System.Runtime.InteropServices;
// ERROR: Not supported in C#: OptionDeclaration
using VB = Microsoft.VisualBasic;
namespace _4PosBackOffice.NET
{
internal partial class frmLogin : System.Windows.Forms.Form
{
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int BringWindowToTop(int hwnd);
[DllImport("user32", EntryPoint = "FindWindowA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int FindWindow(object lpClassName, object lpWindowName);
public bool LoginSucceeded;
private void loadLanguage()
{
//frmLogin = No Code [4POS Application Suite]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmLogin.Caption = rsLang("LanguageLayoutLnk_Description"): frmLogin.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//NOTE: BACKGROUND IMAGE CONTAINS TEXT- CONVERT TO LABELS!
//lbl_UserId = No Label/NO CODE --> CREATE COMPONENT!
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lbl_userId.Caption = rsLang("LanguageLayoutLnk_Description"): lbl_userId.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//lbl_password = No Label --> CREATE COMPONENT!
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 2490
//If rsLang.RecordCount Then lbl_password.Caption = rsLang("LanguageLayoutLnk_Description"): lbl_password.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1389;
//OK|Checked
if (modRecordSet.rsLang.RecordCount){cmdOK.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdOK.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//Label1 = No Code [NOTE:]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label1.Caption = rsLang("LanguageLayoutLnk_Description"): Label1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label2 = No Code [If this is a new Installation.......]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label2.Caption = rsLang("LanguageLayoutLnk_Description"): Label2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmLogin.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs)
{
//set the global var to false
//to denote a failed login
LoginSucceeded = false;
//End
}
private void cmdOK_Click(System.Object eventSender, System.EventArgs eventArgs)
{
ADODB.Recordset rs = default(ADODB.Recordset);
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
bool createDayend = false;
decimal x = default(decimal);
string revName = null;
// ERROR: Not supported in C#: OnErrorStatement
rs = modRecordSet.getRS(ref "SELECT * FROM Person WHERE (Person_UserID = '" + Strings.Replace(this.txtUserName.Text, "'", "''") + "') AND (Person_Password = '" + Strings.Replace(this.txtPassword.Text, "'", "''") + "')");
ADODB.Recordset rsRpt = new ADODB.Recordset();
if (rs.BOF | rs.EOF) {
Interaction.MsgBox("Invalid User Name or Password, try again!", MsgBoxStyle.Exclamation, "Login");
txtPassword.Focus();
// SendKeys "{Home}+{End}"
} else {
My.MyProject.Forms.frmMenu.Show();
//MsgBox "Login 1"
if (Convert.ToInt32(rs.Fields("Person_SecurityBit").Value + "0")) {
this.Close();
My.MyProject.Forms.frmMenu.lblUser.Text = rs.Fields("Person_FirstName").Value + " " + rs.Fields("Person_LastName").Value;
My.MyProject.Forms.frmMenu.lblUser.Tag = rs.Fields("PersonID").Value;
My.MyProject.Forms.frmMenu.gBit = rs.Fields("Person_SecurityBit").Value;
if (Strings.Len(rs.Fields("Person_QuickAccess").Value) > 0) {
for (x = Strings.Len(rs.Fields("Person_QuickAccess").Value); x >= 1; x += -1) {
revName = revName + Strings.Mid(rs.Fields("Person_QuickAccess").Value, x, 1);
}
if (Strings.LCase(Strings.Left(rs.Fields("Person_Position").Value, 8)) == "4posboss" & Strings.LCase(Strings.Right(rs.Fields("Person_Position").Value, Strings.Len(rs.Fields("Person_QuickAccess").Value))) == revName) {
My.MyProject.Forms.frmMenu.lblUser.ForeColor = System.Drawing.Color.Yellow;
My.MyProject.Forms.frmMenu.gSuper = true;
}
}
rsRpt = modRecordSet.getRS(ref "SELECT Company_LoadTRpt From Company");
if (Information.IsDBNull(rsRpt.Fields("Company_LoadTRpt").Value)) {
} else if (rsRpt.Fields("Company_LoadTRpt").Value == 0) {
} else {
if (fso.FileExists(modRecordSet.serverPath + "templateReport1.mdb")) {
if (fso.FileExists(modRecordSet.serverPath + "report" + My.MyProject.Forms.frmMenu.lblUser.Tag + ".mdb"))
fso.DeleteFile(modRecordSet.serverPath + "report" + My.MyProject.Forms.frmMenu.lblUser.Tag + ".mdb", true);
if (fso.FileExists(modRecordSet.serverPath + "templateReport.mdb"))
fso.DeleteFile(modRecordSet.serverPath + "templateReport.mdb", true);
fso.CopyFile(modRecordSet.serverPath + "templateReport1.mdb", modRecordSet.serverPath + "templateReport.mdb", true);
}
}
//MsgBox "Login 2"
My.MyProject.Forms.frmMenu.loadMenu("stock");
//MsgBox "Login 3"
//frmUpdateReportData.loadReportData
if (fso.FileExists(modRecordSet.serverPath + "report" + My.MyProject.Forms.frmMenu.lblUser.Tag + ".mdb")) {
} else {
fso.CopyFile(modRecordSet.serverPath + "templateReport.mdb", modRecordSet.serverPath + "report" + My.MyProject.Forms.frmMenu.lblUser.Tag + ".mdb");
createDayend = true;
}
//MsgBox "Login 4"
if (modReport.openConnectionReport()) {
} else {
Interaction.MsgBox("Unable to locate the Report Database!" + Constants.vbCrLf + Constants.vbCrLf + "The Update Controller wil terminate.", MsgBoxStyle.Critical, "SERVER ERROR");
System.Environment.Exit(0);
}
//MsgBox "Login 5"
if (createDayend) {
// cnnDBreport.Execute "DELETE * FROM Report"
// cnnDBreport.Execute "INSERT INTO Report ( ReportID, Report_DayEndStartID, Report_DayEndEndID, Report_Heading ) SELECT 1 AS reportKey, Max(aDayEnd.DayEndID) AS MaxOfDayEndID, Max(aDayEnd.DayEndID) AS MaxOfDayEndID1, 'From ' & Format(Max([aDayEnd].[DayEnd_Date]),'ddd dd mmm yyyy') & ' to ' & Format(Max([aDayEnd].[DayEnd_Date]),'ddd dd mmm yyyy') & ' covering a dayend range of 1 days' AS theHeading FROM aDayEnd;"
// frmUpdateDayEnd.show 1
My.MyProject.Forms.frmMenu.cmdToday_Click(null, new System.EventArgs());
My.MyProject.Forms.frmMenu.cmdLoad_Click(null, new System.EventArgs());
}
//MsgBox "Login 6"
rs = modReport.getRSreport(ref "SELECT DayEnd.DayEnd_Date AS fromDate, DayEnd_1.DayEnd_Date AS toDate FROM (Report INNER JOIN DayEnd ON Report.Report_DayEndStartID = DayEnd.DayEndID) INNER JOIN DayEnd AS DayEnd_1 ON Report.Report_DayEndEndID = DayEnd_1.DayEndID;");
if (rs.RecordCount) {
My.MyProject.Forms.frmMenu._DTPicker1_0.Format = DateTimePickerFormat.Custom;
My.MyProject.Forms.frmMenu._DTPicker1_0.CustomFormat = string.Format("{0} {1} {2}", Strings.Format(rs.Fields("fromDate").Value, "yyyy"), Strings.Format(rs.Fields("fromDate").Value, "m"), Strings.Format(rs.Fields("fromDate").Value, "d"));
My.MyProject.Forms.frmMenu._DTPicker1_1.Format = DateTimePickerFormat.Custom;
My.MyProject.Forms.frmMenu._DTPicker1_1.CustomFormat = string.Format("{0} {1} {2}", Strings.Format(rs.Fields("toDate").Value, "yyyy"), Strings.Format(rs.Fields("toDate").Value, "m"), Strings.Format(rs.Fields("toDate").Value, "d"));
}
//MsgBox "Login 7"
My.MyProject.Forms.frmMenu.setDayEndRange();
My.MyProject.Forms.frmMenu.lblDayEndCurrent.Text = My.MyProject.Forms.frmMenu.lblDayEnd.Text;
} else {
Interaction.MsgBox("You do not have the correct permissions to access the 4POS Office Application, try again!", MsgBoxStyle.Exclamation, "Login");
this.txtUserName.Focus();
System.Windows.Forms.SendKeys.Send("{Home}+{End}");
}
//MsgBox "Login 8"
//frmMenu.Show()
}
}
private void frmLogin_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 27) {
KeyAscii = 0;
cmdCancel_Click(cmdCancel, new System.EventArgs());
}
if (KeyAscii == 13) {
KeyAscii = 0;
if (string.IsNullOrEmpty(this.txtUserName.Text)) {
txtUserName.Focus();
} else if (string.IsNullOrEmpty(this.txtPassword.Text)) {
txtPassword.Focus();
} else {
cmdOK.Focus();
System.Windows.Forms.Application.DoEvents();
cmdOK_Click(cmdOK, new System.EventArgs());
}
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmLogin_Load(System.Object eventSender, System.EventArgs eventArgs)
{
loadLanguage();
this.Show();
//frmRegister.checkSecurity()
//Me.Show()
}
private void txtPassword_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
txtPassword.SelectionStart = 0;
txtPassword.SelectionLength = 999;
}
private void txtUserName_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
txtUserName.SelectionStart = 0;
txtUserName.SelectionLength = 999;
}
}
}
| |
// 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.Globalization;
/// <summary>
/// String.System.IConvertible.ToInt32(IFormatProvider provider)
/// This method supports the .NET Framework infrastructure and is
/// not intended to be used directly from your code.
/// Converts the value of the current String object to a 32-bit signed integer.
/// </summary>
class IConvertibleToInt32
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
public static int Main()
{
IConvertibleToInt32 iege = new IConvertibleToInt32();
TestLibrary.TestFramework.BeginTestCase("for method: String.System.IConvertible.ToInt32(IFormatProvider)");
if (iege.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive test scenarioes
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Random numeric string";
const string c_TEST_ID = "P001";
string strSrc;
IFormatProvider provider;
Int32 i;
bool expectedValue = true;
bool actualValue = false;
i = TestLibrary.Generator.GetInt32(-55);
strSrc = i.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (i == ((IConvertible)strSrc).ToInt32(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Positive sign";
const string c_TEST_ID = "P002";
string strSrc;
IFormatProvider provider;
NumberFormatInfo ni = new NumberFormatInfo();
Int32 i;
bool expectedValue = true;
bool actualValue = false;
i = TestLibrary.Generator.GetInt32(-55);
// positive signs cannot have emdedded nulls
ni.PositiveSign = TestLibrary.Generator.GetString(-55, false, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN).Replace((char)0, 'a');
strSrc = ni.PositiveSign + i.ToString();
provider = (IFormatProvider)ni;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (i == ((IConvertible)strSrc).ToInt32(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: string is Int32.MaxValue";
const string c_TEST_ID = "P003";
string strSrc;
IFormatProvider provider;
bool expectedValue = true;
bool actualValue = false;
strSrc = Int32.MaxValue.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (Int32.MaxValue == ((IConvertible)strSrc).ToInt32(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4: string is Int32.MinValue";
const string c_TEST_ID = "P004";
string strSrc;
IFormatProvider provider;
bool expectedValue = true;
bool actualValue = false;
strSrc = Int32.MinValue.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (Int32.MinValue == ((IConvertible)strSrc).ToInt32(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest5() // new update 8-14-2006 Noter(v-yaduoj)
{
bool retVal = true;
const string c_TEST_DESC = "PosTest5: Negative sign";
const string c_TEST_ID = "P005";
string strSrc;
IFormatProvider provider;
NumberFormatInfo ni = new NumberFormatInfo();
Int32 i;
bool expectedValue = true;
bool actualValue = false;
i = TestLibrary.Generator.GetInt32(-55);
ni.NegativeSign = TestLibrary.Generator.GetString(-55, false, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strSrc = ni.NegativeSign + i.ToString();
provider = (IFormatProvider)ni;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = ((-1*i) == ((IConvertible)strSrc).ToInt32(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
#endregion // end for positive test scenarioes
#region Negative test scenarios
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: The value of String object cannot be parsed";
const string c_TEST_ID = "N001";
string strSrc;
IFormatProvider provider;
strSrc = "p" + TestLibrary.Generator.GetString(-55, false, 9, c_MAX_STRING_LEN);
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IConvertible)strSrc).ToInt32(provider);
TestLibrary.TestFramework.LogError("009" + "TestId-" + c_TEST_ID, "FormatException is not thrown as expected" + GetDataString(strSrc, provider));
retVal = false;
}
catch (FormatException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: The value of String object is a number greater than MaxValue";
const string c_TEST_ID = "N002";
string strSrc;
IFormatProvider provider;
Int64 i;
// new update 8-14-2006 Noter(v-yaduoj)
i = TestLibrary.Generator.GetInt64(-55) % Int32.MaxValue + Int32.MaxValue + 1;
strSrc = i.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
// new update 8-14-2006 Noter(v-yaduoj)
((IConvertible)strSrc).ToInt32(provider);
TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider));
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: The value of String object is a number less than MinValue";
const string c_TEST_ID = "N003";
string strSrc;
IFormatProvider provider;
Int64 i;
// new update 8-14-2006 Noter(v-yaduoj)
i = -1 * (TestLibrary.Generator.GetInt64(-55) % Int32.MaxValue) - Int32.MaxValue - 1;
strSrc = i.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IConvertible)strSrc).ToInt32(provider);
TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider));
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
#endregion
private string GetDataString(string strSrc, IFormatProvider provider)
{
string str1, str2, str;
int len1;
if (null == strSrc)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = strSrc;
len1 = strSrc.Length;
}
str2 = (null == provider) ? "null" : provider.ToString();
str = string.Format("\n[Source string value]\n \"{0}\"", str1);
str += string.Format("\n[Length of source string]\n {0}", len1);
str += string.Format("\n[Format provider string]\n {0}", str2);
return str;
}
}
| |
// 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;
using Microsoft.CodeAnalysis.Text;
using Xunit;
#if false
namespace Roslyn.Services.Editor.UnitTests.CodeGeneration
{
public class ExpressionGenerationTests : AbstractCodeGenerationTests
{
[Fact]
public void TestFalseExpression()
{
TestExpression(
f => f.CreateFalseExpression(),
cs: "false",
vb: "False");
}
[Fact]
public void TestTrueExpression()
{
TestExpression(
f => f.CreateTrueExpression(),
cs: "true",
vb: "True");
}
[Fact]
public void TestNullExpression()
{
TestExpression(
f => f.CreateNullExpression(),
cs: "null",
vb: "Nothing");
}
[Fact]
public void TestThisExpression()
{
TestExpression(
f => f.CreateThisExpression(),
cs: "this",
vb: "Me");
}
[Fact]
public void TestBaseExpression()
{
TestExpression(
f => f.CreateBaseExpression(),
cs: "base",
vb: "MyBase");
}
[Fact]
public void TestInt32ConstantExpression0()
{
TestExpression(
f => f.CreateConstantExpression(0),
cs: "0",
vb: "0");
}
[Fact]
public void TestInt32ConstantExpression1()
{
TestExpression(
f => f.CreateConstantExpression(1),
cs: "1",
vb: "1");
}
[Fact]
public void TestInt64ConstantExpression0()
{
TestExpression(
f => f.CreateConstantExpression(0L),
cs: "0L",
vb: "0&");
}
[Fact]
public void TestInt64ConstantExpression1()
{
TestExpression(
f => f.CreateConstantExpression(1L),
cs: "1L",
vb: "1&");
}
[Fact]
public void TestSingleConstantExpression0()
{
TestExpression(
f => f.CreateConstantExpression(0.0f),
cs: "0F",
vb: "0!");
}
[Fact]
public void TestSingleConstantExpression1()
{
TestExpression(
f => f.CreateConstantExpression(0.5F),
cs: "0.5F",
vb: "0.5!");
}
[Fact]
public void TestDoubleConstantExpression0()
{
TestExpression(
f => f.CreateConstantExpression(0.0d),
cs: "0",
vb: "0");
}
[Fact]
public void TestDoubleConstantExpression1()
{
TestExpression(
f => f.CreateConstantExpression(0.5D),
cs: "0.5",
vb: "0.5");
}
[Fact]
public void TestAddExpression1()
{
TestExpression(
f => f.CreateAddExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
cs: "1 + 2",
vb: "1 + 2");
}
[Fact]
public void TestAddExpression2()
{
TestExpression(
f => f.CreateAddExpression(
f.CreateConstantExpression(1),
f.CreateAddExpression(
f.CreateConstantExpression(2),
f.CreateConstantExpression(3))),
cs: "1 + 2 + 3",
vb: "1 + 2 + 3");
}
[Fact]
public void TestAddExpression3()
{
TestExpression(
f => f.CreateAddExpression(
f.CreateAddExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
f.CreateConstantExpression(3)),
cs: "1 + 2 + 3",
vb: "1 + 2 + 3");
}
[Fact]
public void TestMultiplyExpression1()
{
TestExpression(
f => f.CreateMultiplyExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
cs: "1 * 2",
vb: "1 * 2");
}
[Fact]
public void TestMultiplyExpression2()
{
TestExpression(
f => f.CreateMultiplyExpression(
f.CreateConstantExpression(1),
f.CreateMultiplyExpression(
f.CreateConstantExpression(2),
f.CreateConstantExpression(3))),
cs: "1 * 2 * 3",
vb: "1 * 2 * 3");
}
[Fact]
public void TestMultiplyExpression3()
{
TestExpression(
f => f.CreateMultiplyExpression(
f.CreateMultiplyExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
f.CreateConstantExpression(3)),
cs: "1 * 2 * 3",
vb: "1 * 2 * 3");
}
[Fact]
public void TestBinaryAndExpression1()
{
TestExpression(
f => f.CreateBinaryAndExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
cs: "1 & 2",
vb: "1 And 2");
}
[Fact]
public void TestBinaryOrExpression1()
{
TestExpression(
f => f.CreateBinaryOrExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
cs: "1 | 2",
vb: "1 Or 2");
}
[Fact]
public void TestLogicalAndExpression1()
{
TestExpression(
f => f.CreateLogicalAndExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
cs: "1 && 2",
vb: "1 AndAlso 2");
}
[Fact]
public void TestLogicalOrExpression1()
{
TestExpression(
f => f.CreateLogicalOrExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
cs: "1 || 2",
vb: "1 OrElse 2");
}
[Fact]
public void TestMemberAccess1()
{
TestExpression(
f => f.CreateMemberAccessExpression(
f.CreateIdentifierName("E"),
f.CreateIdentifierName("M")),
cs: "E.M",
vb: "E.M");
}
[Fact]
public void TestConditionalExpression1()
{
TestExpression(
f => f.CreateConditionalExpression(
f.CreateIdentifierName("E"),
f.CreateIdentifierName("T"),
f.CreateIdentifierName("F")),
cs: "E ? T : F",
vb: "If(E, T, F)");
}
[Fact]
public void TestInvocation1()
{
TestExpression(
f => f.CreateInvocationExpression(
f.CreateIdentifierName("E")),
cs: "E()",
vb: "E()");
}
[Fact]
public void TestInvocation2()
{
TestExpression(
f => f.CreateInvocationExpression(
f.CreateIdentifierName("E"),
f.CreateArgument(f.CreateIdentifierName("a"))),
cs: "E(a)",
vb: "E(a)");
}
[Fact]
public void TestInvocation3()
{
TestExpression(
f => f.CreateInvocationExpression(
f.CreateIdentifierName("E"),
f.CreateArgument("n", RefKind.None, f.CreateIdentifierName("a"))),
cs: "E(n: a)",
vb: "E(n:=a)");
}
[Fact]
public void TestInvocation4()
{
TestExpression(
f => f.CreateInvocationExpression(
f.CreateIdentifierName("E"),
f.CreateArgument(null, RefKind.Out, f.CreateIdentifierName("a")),
f.CreateArgument(null, RefKind.Ref, f.CreateIdentifierName("b"))),
cs: "E(out a, ref b)",
vb: "E(a, b)");
}
[Fact]
public void TestInvocation5()
{
TestExpression(
f => f.CreateInvocationExpression(
f.CreateIdentifierName("E"),
f.CreateArgument("n1", RefKind.Out, f.CreateIdentifierName("a")),
f.CreateArgument("n2", RefKind.Ref, f.CreateIdentifierName("b"))),
cs: "E(n1: out a, n2: ref b)",
vb: "E(n1:=a, n2:=b)");
}
[Fact]
public void TestElementAccess1()
{
TestExpression(
f => f.CreateElementAccessExpression(
f.CreateIdentifierName("E")),
cs: "E[]",
vb: "E()");
}
[Fact]
public void TestElementAccess2()
{
TestExpression(
f => f.CreateElementAccessExpression(
f.CreateIdentifierName("E"),
f.CreateArgument(f.CreateIdentifierName("a"))),
cs: "E[a]",
vb: "E(a)");
}
[Fact]
public void TestElementAccess3()
{
TestExpression(
f => f.CreateElementAccessExpression(
f.CreateIdentifierName("E"),
f.CreateArgument("n", RefKind.None, f.CreateIdentifierName("a"))),
cs: "E[n: a]",
vb: "E(n:=a)");
}
[Fact]
public void TestElementAccess4()
{
TestExpression(
f => f.CreateElementAccessExpression(
f.CreateIdentifierName("E"),
f.CreateArgument(null, RefKind.Out, f.CreateIdentifierName("a")),
f.CreateArgument(null, RefKind.Ref, f.CreateIdentifierName("b"))),
cs: "E[out a, ref b]",
vb: "E(a, b)");
}
[Fact]
public void TestElementAccess5()
{
TestExpression(
f => f.CreateElementAccessExpression(
f.CreateIdentifierName("E"),
f.CreateArgument("n1", RefKind.Out, f.CreateIdentifierName("a")),
f.CreateArgument("n2", RefKind.Ref, f.CreateIdentifierName("b"))),
cs: "E[n1: out a, n2: ref b]",
vb: "E(n1:=a, n2:=b)");
}
[Fact]
public void TestIsExpression()
{
TestExpression(
f => f.CreateIsExpression(
f.CreateIdentifierName("a"),
CreateClass("SomeType")),
cs: "a is SomeType",
vb: "TypeOf a Is SomeType");
}
[Fact]
public void TestAsExpression()
{
TestExpression(
f => f.CreateAsExpression(
f.CreateIdentifierName("a"),
CreateClass("SomeType")),
cs: "a as SomeType",
vb: "TryCast(a, SomeType)");
}
[Fact]
public void TestNotExpression()
{
TestExpression(
f => f.CreateLogicalNotExpression(
f.CreateIdentifierName("a")),
cs: "!a",
vb: "Not a");
}
[Fact]
public void TestCastExpression()
{
TestExpression(
f => f.CreateCastExpression(
CreateClass("SomeType"),
f.CreateIdentifierName("a")),
cs: "(SomeType)a",
vb: "DirectCast(a, SomeType)");
}
[Fact]
public void TestNegateExpression()
{
TestExpression(
f => f.CreateNegateExpression(
f.CreateIdentifierName("a")),
cs: "-a",
vb: "-a");
}
}
}
#endif
| |
// 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.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Logic
{
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>
/// WorkflowTriggerHistoriesOperations operations.
/// </summary>
internal partial class WorkflowTriggerHistoriesOperations : IServiceOperations<LogicManagementClient>, IWorkflowTriggerHistoriesOperations
{
/// <summary>
/// Initializes a new instance of the WorkflowTriggerHistoriesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal WorkflowTriggerHistoriesOperations(LogicManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the LogicManagementClient
/// </summary>
public LogicManagementClient Client { get; private set; }
/// <summary>
/// Gets a list of workflow trigger histories.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='workflowName'>
/// The workflow name.
/// </param>
/// <param name='triggerName'>
/// The workflow trigger name.
/// </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>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<WorkflowTriggerHistory>>> ListWithHttpMessagesAsync(string resourceGroupName, string workflowName, string triggerName, ODataQuery<WorkflowTriggerHistoryFilter> odataQuery = default(ODataQuery<WorkflowTriggerHistoryFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (workflowName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "workflowName");
}
if (triggerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "triggerName");
}
string apiVersion = "2016-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workflowName", workflowName);
tracingParameters.Add("triggerName", triggerName);
tracingParameters.Add("apiVersion", apiVersion);
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.Logic/workflows/{workflowName}/triggers/{triggerName}/histories").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{workflowName}", Uri.EscapeDataString(workflowName));
_url = _url.Replace("{triggerName}", Uri.EscapeDataString(triggerName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(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<WorkflowTriggerHistory>>();
_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<WorkflowTriggerHistory>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a workflow trigger history.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='workflowName'>
/// The workflow name.
/// </param>
/// <param name='triggerName'>
/// The workflow trigger name.
/// </param>
/// <param name='historyName'>
/// The workflow trigger history name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<WorkflowTriggerHistory>> GetWithHttpMessagesAsync(string resourceGroupName, string workflowName, string triggerName, string historyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (workflowName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "workflowName");
}
if (triggerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "triggerName");
}
if (historyName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "historyName");
}
string apiVersion = "2016-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workflowName", workflowName);
tracingParameters.Add("triggerName", triggerName);
tracingParameters.Add("historyName", historyName);
tracingParameters.Add("apiVersion", apiVersion);
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.Logic/workflows/{workflowName}/triggers/{triggerName}/histories/{historyName}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{workflowName}", Uri.EscapeDataString(workflowName));
_url = _url.Replace("{triggerName}", Uri.EscapeDataString(triggerName));
_url = _url.Replace("{historyName}", Uri.EscapeDataString(historyName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(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<WorkflowTriggerHistory>();
_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<WorkflowTriggerHistory>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of workflow trigger histories.
/// </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>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<WorkflowTriggerHistory>>> 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<WorkflowTriggerHistory>>();
_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<WorkflowTriggerHistory>>(_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;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection.Internal;
using System.Text;
using TestUtilities;
using Xunit;
namespace System.Reflection.Metadata.Tests
{
public class BlobReaderTests
{
[Fact]
public unsafe void PublicBlobReaderCtorValidatesArgs()
{
byte* bufferPtrForLambda;
byte[] buffer = new byte[4] { 0, 1, 0, 2 };
fixed (byte* bufferPtr = buffer)
{
bufferPtrForLambda = bufferPtr;
Assert.Throws<ArgumentOutOfRangeException>(() => new BlobReader(bufferPtrForLambda, -1));
}
Assert.Throws<ArgumentNullException>(() => new BlobReader(null, 1));
Assert.Equal(0, new BlobReader(null, 0).Length); // this is valid
Assert.Throws<BadImageFormatException>(() => new BlobReader(null, 0).ReadByte()); // but can't read anything non-empty from it...
Assert.Same(String.Empty, new BlobReader(null, 0).ReadUtf8NullTerminated()); // can read empty string.
}
[Fact]
public unsafe void ReadFromMemoryReader()
{
byte[] buffer = new byte[4] { 0, 1, 0, 2 };
fixed (byte* bufferPtr = buffer)
{
var reader = new BlobReader(new MemoryBlock(bufferPtr, buffer.Length));
Assert.False(reader.SeekOffset(-1));
Assert.False(reader.SeekOffset(Int32.MaxValue));
Assert.False(reader.SeekOffset(Int32.MinValue));
Assert.False(reader.SeekOffset(buffer.Length));
Assert.True(reader.SeekOffset(buffer.Length - 1));
Assert.True(reader.SeekOffset(0));
Assert.Equal(0, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadUInt64());
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(1));
Assert.Equal(1, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadDouble());
Assert.Equal(1, reader.Offset);
Assert.True(reader.SeekOffset(2));
Assert.Equal(2, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadUInt32());
Assert.Equal((ushort)0x0200, reader.ReadUInt16());
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(2));
Assert.Equal(2, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadSingle());
Assert.Equal(2, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Equal(9.404242E-38F, reader.ReadSingle());
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(3));
Assert.Equal(3, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadUInt16());
Assert.Equal((byte)0x02, reader.ReadByte());
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Equal("\u0000\u0001\u0000\u0002", reader.ReadUTF8(4));
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadUTF8(5));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadUTF8(-1));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Equal("\u0100\u0200", reader.ReadUTF16(4));
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(5));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(-1));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(6));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Equal(buffer, reader.ReadBytes(4));
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Same(String.Empty, reader.ReadUtf8NullTerminated());
Assert.Equal(1, reader.Offset);
Assert.True(reader.SeekOffset(1));
Assert.Equal("\u0001", reader.ReadUtf8NullTerminated());
Assert.Equal(3, reader.Offset);
Assert.True(reader.SeekOffset(3));
Assert.Equal("\u0002", reader.ReadUtf8NullTerminated());
Assert.Equal(4, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Same(String.Empty, reader.ReadUtf8NullTerminated());
Assert.Equal(1, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadBytes(5));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.ReadBytes(Int32.MinValue));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.GetMemoryBlockAt(-1, 1));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Throws<BadImageFormatException>(() => reader.GetMemoryBlockAt(1, -1));
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(0));
Assert.Equal(3, reader.GetMemoryBlockAt(1, 3).Length);
Assert.Equal(0, reader.Offset);
Assert.True(reader.SeekOffset(3));
reader.ReadByte();
Assert.Equal(4, reader.Offset);
Assert.Equal(4, reader.Offset);
Assert.Equal(0, reader.ReadBytes(0).Length);
Assert.Equal(4, reader.Offset);
int value;
Assert.False(reader.TryReadCompressedInteger(out value));
Assert.Equal(BlobReader.InvalidCompressedInteger, value);
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadCompressedInteger());
Assert.Equal(4, reader.Offset);
Assert.Equal(SerializationTypeCode.Invalid, reader.ReadSerializationTypeCode());
Assert.Equal(4, reader.Offset);
Assert.Equal(SignatureTypeCode.Invalid, reader.ReadSignatureTypeCode());
Assert.Equal(4, reader.Offset);
Assert.Equal(default(EntityHandle), reader.ReadTypeHandle());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadBoolean());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadByte());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadSByte());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadUInt32());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadInt32());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadUInt64());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadInt64());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadSingle());
Assert.Equal(4, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadDouble());
Assert.Equal(4, reader.Offset);
}
byte[] buffer2 = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 };
fixed (byte* bufferPtr2 = buffer2)
{
var reader = new BlobReader(new MemoryBlock(bufferPtr2, buffer2.Length));
Assert.Equal(reader.Offset, 0);
Assert.Equal(0x0807060504030201UL, reader.ReadUInt64());
Assert.Equal(reader.Offset, 8);
reader.Reset();
Assert.Equal(reader.Offset, 0);
Assert.Equal(0x0807060504030201L, reader.ReadInt64());
reader.Reset();
Assert.Equal(reader.Offset, 0);
Assert.Equal(BitConverter.ToDouble(buffer2, 0), reader.ReadDouble());
}
}
[Fact]
public unsafe void ValidatePeekReferenceSize()
{
byte[] buffer = new byte[8] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
fixed (byte* bufferPtr = buffer)
{
var block = new MemoryBlock(bufferPtr, buffer.Length);
// small ref size always fits in 16 bits
Assert.Equal(0xFFFF, block.PeekReference(0, smallRefSize: true));
Assert.Equal(0xFFFF, block.PeekReference(4, smallRefSize: true));
Assert.Equal(0xFFFFU, block.PeekTaggedReference(0, smallRefSize: true));
Assert.Equal(0xFFFFU, block.PeekTaggedReference(4, smallRefSize: true));
Assert.Equal(0x01FFU, block.PeekTaggedReference(6, smallRefSize: true));
// large ref size throws on > RIDMask when tagged variant is not used.
Assert.Throws<BadImageFormatException>(() => block.PeekReference(0, smallRefSize: false));
Assert.Throws<BadImageFormatException>(() => block.PeekReference(4, smallRefSize: false));
// large ref size does not throw when Tagged variant is used.
Assert.Equal(0xFFFFFFFFU, block.PeekTaggedReference(0, smallRefSize: false));
Assert.Equal(0x01FFFFFFU, block.PeekTaggedReference(4, smallRefSize: false));
// bounds check applies in all cases
Assert.Throws<BadImageFormatException>(() => block.PeekReference(7, smallRefSize: true));
Assert.Throws<BadImageFormatException>(() => block.PeekReference(5, smallRefSize: false));
}
}
[Fact]
public unsafe void ReadFromMemoryBlock()
{
byte[] buffer = new byte[4] { 0, 1, 0, 2 };
fixed (byte* bufferPtr = buffer)
{
var block = new MemoryBlock(bufferPtr, buffer.Length);
Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(Int32.MaxValue));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(-1));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(Int32.MinValue));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(4));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(1));
Assert.Equal(0x02000100U, block.PeekUInt32(0));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(Int32.MaxValue));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(-1));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(Int32.MinValue));
Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(4));
Assert.Equal(0x0200, block.PeekUInt16(2));
int bytesRead;
MetadataStringDecoder stringDecoder = MetadataStringDecoder.DefaultUTF8;
Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(Int32.MaxValue, null, stringDecoder, out bytesRead));
Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(-1, null, stringDecoder, out bytesRead));
Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(Int32.MinValue, null, stringDecoder, out bytesRead));
Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(5, null, stringDecoder, out bytesRead));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, 1));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(1, -1));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(0, -1));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, 0));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-Int32.MaxValue, Int32.MaxValue));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(Int32.MaxValue, -Int32.MaxValue));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(Int32.MaxValue, Int32.MaxValue));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(block.Length, -1));
Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, block.Length));
Assert.Equal("\u0001", block.PeekUtf8NullTerminated(1, null, stringDecoder, out bytesRead));
Assert.Equal(bytesRead, 2);
Assert.Equal("\u0002", block.PeekUtf8NullTerminated(3, null, stringDecoder, out bytesRead));
Assert.Equal(bytesRead, 1);
Assert.Equal("", block.PeekUtf8NullTerminated(4, null, stringDecoder, out bytesRead));
Assert.Equal(bytesRead, 0);
byte[] helloPrefix = Encoding.UTF8.GetBytes("Hello");
Assert.Equal("Hello\u0001", block.PeekUtf8NullTerminated(1, helloPrefix, stringDecoder, out bytesRead));
Assert.Equal(bytesRead, 2);
Assert.Equal("Hello\u0002", block.PeekUtf8NullTerminated(3, helloPrefix, stringDecoder, out bytesRead));
Assert.Equal(bytesRead, 1);
Assert.Equal("Hello", block.PeekUtf8NullTerminated(4, helloPrefix, stringDecoder, out bytesRead));
Assert.Equal(bytesRead, 0);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using ServiceStack.OrmLite;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using ServiceStack.ServiceInterface.ServiceModel;
using ServiceStack.WebHost.Endpoints.Tests.Support.Host;
namespace ServiceStack.WebHost.Endpoints.Tests.Support.Services
{
public class FunqRequestScope
{
public static int Count = 0;
public FunqRequestScope() { Count++; }
}
public class FunqSingletonScope
{
public static int Count = 0;
public FunqSingletonScope() { Count++; }
}
public class FunqNoneScope
{
public static int Count = 0;
public FunqNoneScope() { Count++; }
}
public class FunqRequestScopeDisposable : IDisposable
{
public static int Count = 0;
public static int DisposeCount = 0;
public FunqRequestScopeDisposable() { Count++; }
public void Dispose()
{
DisposeCount++;
}
}
public class FunqSingletonScopeDisposable : IDisposable
{
public static int Count = 0;
public static int DisposeCount = 0;
public FunqSingletonScopeDisposable() { Count++; }
public void Dispose()
{
DisposeCount++;
}
}
public class FunqNoneScopeDisposable : IDisposable
{
public static int Count = 0;
public static int DisposeCount = 0;
public FunqNoneScopeDisposable() { Count++; }
public void Dispose()
{
DisposeCount++;
}
}
public class FunqRequestScopeDepDisposableProperty : IDisposable
{
public static int Count = 0;
public static int DisposeCount = 0;
public FunqRequestScopeDepDisposableProperty() { Count++; }
public void Dispose() { DisposeCount++; }
}
public class AltRequestScopeDepDisposableProperty : IDisposable
{
public static int Count = 0;
public static int DisposeCount = 0;
public AltRequestScopeDepDisposableProperty() { Count++; }
public void Dispose() { DisposeCount++; }
}
public class FunqDepCtor { }
public class AltDepCtor { }
public class FunqDepProperty { }
public class AltDepProperty { }
public class FunqDepDisposableProperty : IDisposable
{
public static int DisposeCount = 0;
public void Dispose() { DisposeCount++; }
}
public class AltDepDisposableProperty : IDisposable
{
public static int DisposeCount = 0;
public void Dispose() { DisposeCount++; }
}
public class Ioc { }
public class IocResponse : IHasResponseStatus
{
public IocResponse()
{
this.ResponseStatus = new ResponseStatus();
this.Results = new List<string>();
}
public List<string> Results { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
[Route("/action-attr")]
public class ActionAttr : IReturn<IocResponse> {}
public class ActionLevelAttribute : RequestFilterAttribute
{
public IRequestContext RequestContext { get; set; }
public FunqDepProperty FunqDepProperty { get; set; }
public FunqDepDisposableProperty FunqDepDisposableProperty { get; set; }
public AltDepProperty AltDepProperty { get; set; }
public AltDepDisposableProperty AltDepDisposableProperty { get; set; }
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
{
var response = new IocResponse();
var deps = new object[] {
FunqDepProperty, FunqDepDisposableProperty,
AltDepProperty, AltDepDisposableProperty
};
foreach (var dep in deps)
{
if (dep != null)
response.Results.Add(dep.GetType().Name);
}
req.Items["action-attr"] = response;
}
}
public class IocService : IService, IDisposable, IRequiresRequestContext
{
private readonly FunqDepCtor funqDepCtor;
private readonly AltDepCtor altDepCtor;
public IocService(FunqDepCtor funqDepCtor, AltDepCtor altDepCtor)
{
this.funqDepCtor = funqDepCtor;
this.altDepCtor = altDepCtor;
}
public IRequestContext RequestContext { get; set; }
public FunqDepProperty FunqDepProperty { get; set; }
public FunqDepDisposableProperty FunqDepDisposableProperty { get; set; }
public AltDepProperty AltDepProperty { get; set; }
public AltDepDisposableProperty AltDepDisposableProperty { get; set; }
public object Any(Ioc request)
{
var response = new IocResponse();
var deps = new object[] {
funqDepCtor, altDepCtor,
FunqDepProperty, FunqDepDisposableProperty,
AltDepProperty, AltDepDisposableProperty
};
foreach (var dep in deps)
{
if (dep != null)
response.Results.Add(dep.GetType().Name);
}
if (ThrowErrors) throw new ArgumentException("This service has intentionally failed");
return response;
}
[ActionLevel]
public IocResponse Any(ActionAttr request)
{
return RequestContext.Get<IHttpRequest>().Items["action-attr"] as IocResponse;
}
public static int DisposedCount = 0;
public static bool ThrowErrors = false;
public void Dispose()
{
DisposedCount++;
}
}
public class IocScope
{
public bool Throw { get; set; }
}
public class IocScopeResponse : IHasResponseStatus
{
public IocScopeResponse()
{
this.ResponseStatus = new ResponseStatus();
this.Results = new Dictionary<string, int>();
}
public Dictionary<string, int> Results { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
[IocRequestFilter]
public class IocScopeService : IService, IDisposable
{
public FunqRequestScope FunqRequestScope { get; set; }
public FunqSingletonScope FunqSingletonScope { get; set; }
public FunqNoneScope FunqNoneScope { get; set; }
public FunqRequestScopeDepDisposableProperty FunqRequestScopeDepDisposableProperty { get; set; }
public AltRequestScopeDepDisposableProperty AltRequestScopeDepDisposableProperty { get; set; }
public object Any(IocScope request)
{
if (request.Throw)
throw new Exception("Exception requested by user");
var response = new IocScopeResponse {
Results = {
{ typeof(FunqSingletonScope).Name, FunqSingletonScope.Count },
{ typeof(FunqRequestScope).Name, FunqRequestScope.Count },
{ typeof(FunqNoneScope).Name, FunqNoneScope.Count },
},
};
return response;
}
public static int DisposedCount = 0;
public static bool ThrowErrors = false;
public void Dispose()
{
DisposedCount++;
}
}
public class IocDispose : IReturn<IocDisposeResponse>
{
public bool Throw { get; set; }
}
public class IocDisposeResponse : IHasResponseStatus
{
public IocDisposeResponse()
{
this.ResponseStatus = new ResponseStatus();
this.Results = new Dictionary<string, int>();
}
public Dictionary<string, int> Results { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class IocDisposableService : IService, IDisposable
{
public FunqRequestScopeDisposable FunqRequestScopeDisposable { get; set; }
public FunqSingletonScopeDisposable FunqSingletonScopeDisposable { get; set; }
public FunqNoneScopeDisposable FunqNoneScopeDisposable { get; set; }
public FunqRequestScopeDepDisposableProperty FunqRequestScopeDepDisposableProperty { get; set; }
public AltRequestScopeDepDisposableProperty AltRequestScopeDepDisposableProperty { get; set; }
public object Any(IocDispose request)
{
if (request.Throw)
throw new Exception("Exception requested by user");
var response = new IocDisposeResponse
{
Results = {
{ typeof(FunqSingletonScopeDisposable).Name, FunqSingletonScopeDisposable.DisposeCount },
{ typeof(FunqRequestScopeDisposable).Name, FunqRequestScopeDisposable.DisposeCount },
{ typeof(FunqNoneScopeDisposable).Name, FunqNoneScopeDisposable.DisposeCount },
{ typeof(FunqRequestScopeDepDisposableProperty).Name, FunqRequestScopeDepDisposableProperty.DisposeCount },
{ typeof(AltRequestScopeDepDisposableProperty).Name, AltRequestScopeDepDisposableProperty.DisposeCount },
},
};
return response;
}
public static int DisposeCount = 0;
public void Dispose()
{
DisposeCount++;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
namespace ETLStackBrowse
{
public partial class ETLTrace
{
// const int fldCSwitchTimeStamp = 1;
// const int fldCSwitchNewProcessName = 2;
private const int fldCSwitchNewTID = 3;
// const int fldCSwitchNPri = 4;
// const int fldCSwitchNQnt = 5;
// const int fldCSwitchTmSinceLast = 6;
// const int fldCSwitchWaitTime = 7;
// const int fldCSwitchOldProcessName = 8;
private const int fldCSwitchOldTID = 9;
// const int fldCSwitchOPri = 10;
// const int fldCSwitchOQnt = 11;
// const int fldCSwitchOldState = 12;
private const int fldCSwitchWaitReason = 13;
// const int fldCSwitchSwappable = 14;
// const int fldCSwitchInSwitchTime = 15;
private const int fldCSwitchCPU = 16;
// const int fldCSwitchIdealProc = 17;
private const int maxReasons = 32;
public class ThreadStat
{
public ThreadStat(int ithread)
{
this.ithread = ithread;
}
public long time;
public int switches;
public int[] swapReasons;
public UInt32 runmask;
public int ithread;
}
public class ContextSwitchResult
{
public ThreadStat[] stats;
public int countCPU;
public long timeTotal;
public long switchesTotal;
public bool fSimulateHyperthreading;
public bool fSortBySwitches;
public bool reasonsComputed;
public bool[] threadFilters;
public int nTop;
}
private int maxCPU = 64;
private long tStart;
private long tEnd;
public string ComputeContextSwitches()
{
ContextSwitchResult result = ComputeContextSwitchesRaw();
return FormatContextSwitchResult(result);
}
private ByteAtomTable atomsReasons = new ByteAtomTable();
public ContextSwitchResult ComputeContextSwitchesRaw()
{
IContextSwitchParameters icswitchparms = itparms.ContextSwitchParameters;
bool fSimulateHyperthreading = icswitchparms.SimulateHyperthreading;
bool fSortBySwitches = icswitchparms.SortBySwitches;
bool fComputeReasons = icswitchparms.ComputeReasons;
int nTop = icswitchparms.TopThreadCount;
ByteWindow bT = new ByteWindow();
long timeTotal = 0;
int switchesTotal = 0;
tStart = itparms.T0;
tEnd = itparms.T1;
ThreadStat[] stats = NewThreadStats();
CPUState[] state = new CPUState[maxCPU];
int idCSwitch = atomsRecords.Lookup("CSwitch");
bool[] threadFilters = itparms.GetThreadFilters();
InitializeStartingCPUStates(state, idCSwitch);
// rewind
ETWLineReader l = StandardLineReader();
foreach (ByteWindow b in l.Lines())
{
if (l.idType != idCSwitch)
{
continue;
}
int oldTid = b.GetInt(fldCSwitchOldTID);
int cpu = b.GetInt(fldCSwitchCPU);
timeTotal += AddCSwitchTime(fSimulateHyperthreading, l.t, stats, state);
int newTid = b.GetInt(fldCSwitchNewTID);
int idx = FindThreadInfoIndex(l.t, oldTid);
stats[idx].switches++;
switchesTotal++;
if (fComputeReasons)
{
bT.Assign(b, fldCSwitchWaitReason).Trim();
int id = atomsReasons.EnsureContains(bT);
if (stats[idx].swapReasons == null)
{
stats[idx].swapReasons = new int[maxReasons];
}
stats[idx].swapReasons[id]++;
}
state[cpu].active = true;
state[cpu].tid = newTid;
state[cpu].time = l.t;
}
timeTotal += AddCSwitchTime(fSimulateHyperthreading, l.t1, stats, state);
if (fSortBySwitches)
{
Array.Sort(stats,
delegate (ThreadStat c1, ThreadStat c2)
{
if (c1.switches > c2.switches)
{
return -1;
}
if (c1.switches < c2.switches)
{
return 1;
}
return 0;
}
);
}
else
{
Array.Sort(stats,
delegate (ThreadStat c1, ThreadStat c2)
{
if (c1.time > c2.time)
{
return -1;
}
if (c1.time < c2.time)
{
return 1;
}
return 0;
}
);
}
var result = new ContextSwitchResult();
result.stats = stats;
result.switchesTotal = switchesTotal;
result.timeTotal = timeTotal;
result.fSortBySwitches = fSortBySwitches;
result.reasonsComputed = fComputeReasons;
result.threadFilters = threadFilters;
result.countCPU = maxCPU;
result.nTop = nTop;
return result;
}
private void InitializeStartingCPUStates(CPUState[] state, int idCSwitch)
{
int countCPU = 0;
// find the first thread on each proc
ETWLineReader l = StandardLineReader();
l.t1 = Int64.MaxValue - 10000; // keep reading until we find all cpus regardless of how far in the future we have to look
foreach (ByteWindow b in l.Lines())
{
if (l.idType != idCSwitch)
{
continue;
}
int cpu = b.GetInt(fldCSwitchCPU);
if (state[cpu].active)
{
continue;
}
state[cpu].active = true;
state[cpu].tid = b.GetInt(fldCSwitchOldTID);
state[cpu].time = l.t0;
countCPU++;
if (countCPU >= maxCPU)
{
break;
}
}
}
public string FormatContextSwitchResult(ContextSwitchResult results)
{
int nTop = results.nTop;
string[] reasonNames = new string[atomsReasons.Count];
for (int i = 0; i < reasonNames.Length; i++)
{
reasonNames[i] = atomsReasons.MakeString(i);
}
ThreadStat[] stats = results.stats;
int ithreadIdle = IdleThreadIndex;
int iStatsIdle = 0;
// find where the idle thread landed after sorting
for (int i = 0; i < stats.Length; i++)
{
if (stats[i].ithread == ithreadIdle)
{
iStatsIdle = i;
break;
}
}
StringWriter sw = new StringWriter();
sw.WriteLine("Start time: {0:n0} End time: {1:n0} Interval Length: {2:n0}", tStart, tEnd, tEnd - tStart);
sw.WriteLine();
sw.WriteLine("CPUs: {0:n0}, Total CPU Time: {1:n0} usec. Total Switches: {2:n0} Idle: {3,5:f1}% Busy: {4,5:f1}%",
results.countCPU,
results.timeTotal,
results.switchesTotal,
stats[iStatsIdle].time * 100.0 / results.timeTotal,
(results.timeTotal - stats[iStatsIdle].time) * 100.0 / results.timeTotal);
sw.WriteLine();
sw.WriteLine("{0,20} {1,17} {2,35} {3,5} {4,32} {5}", " Time (usec)", " Switches", "Process ( PID)", " TID", "Run Mask", "ThreadProc");
sw.WriteLine("{0,20} {1,17} {2,35} {3,5} {4,32} {5}", "-------------------", "---------------", "--------------", "----", "--------", "----------");
char[] maskChars = new char[32];
for (int i = 0; i < Math.Min(threads.Count, nTop); i++)
{
int ithread = stats[i].ithread;
if (stats[i].time == 0)
{
continue;
}
if (!results.threadFilters[ithread])
{
continue;
}
for (int bit = 0; bit < 32; bit++)
{
maskChars[bit] = ((stats[i].runmask & (1 << bit)) != 0 ? 'X' : '_');
}
sw.WriteLine("{0,11:n0} ({1,5:f1}%) {2,8:n0} ({3,5:f1}%) {4,35} {5,5} {6} {7}",
stats[i].time,
stats[i].time * 100.0 / results.timeTotal,
stats[i].switches,
stats[i].switches * 100.0 / results.switchesTotal,
ByteWindow.MakeString(threads[ithread].processPid),
threads[ithread].threadid,
new String(maskChars),
ByteWindow.MakeString(threads[ithread].threadproc)
);
if (results.reasonsComputed)
{
int[] swapReasons = stats[i].swapReasons;
if (swapReasons != null)
{
for (int k = 0; k < swapReasons.Length; k++)
{
if (swapReasons[k] > 0)
{
sw.WriteLine(" {0,17} {1}", reasonNames[k], swapReasons[k]);
}
}
}
sw.WriteLine();
}
}
if (results.fSimulateHyperthreading)
{
sw.WriteLine();
sw.WriteLine("Hyperthreading Simulation was used to attribute idle cost more accurately");
}
return sw.ToString();
}
public ThreadStat[] NewThreadStats()
{
ThreadStat[] stats = new ThreadStat[threads.Count];
for (int ithread = 0; ithread < threads.Count; ithread++)
{
stats[ithread] = new ThreadStat(ithread);
}
return stats;
}
private int AddCSwitchTime(bool fSimulateHyperthreading, long t, ThreadStat[] stats, CPUState[] state)
{
int timeTotal = 0;
for (int cpu = 0; cpu < maxCPU; cpu++)
{
if (!state[cpu].active)
{
continue;
}
int time = (int)(t - state[cpu].time);
if (fSimulateHyperthreading)
{
int tfull = time;
int th0 = time / 2;
int th1 = time - th0;
if ((cpu & 1) == 0)
{
time = th0;
}
else
{
time = th1;
}
if (state[cpu].tid != 0 && state[cpu ^ 1].tid == 0)
{
time = tfull;
}
else if (state[cpu].tid == 0 && state[cpu ^ 1].tid != 0)
{
time = 0;
}
}
int idx = FindThreadInfoIndex(state[cpu].time, state[cpu].tid);
stats[idx].time += time;
state[cpu].time = t;
int bitStart = (int)((t - time - tStart) * 32 / (tEnd - tStart));
int bitEnd = (int)((t - tStart) * 32 / (tEnd - tStart));
if (bitEnd >= 32)
{
bitEnd = 31;
}
for (int bit = bitStart; bit <= bitEnd; bit++)
{
stats[idx].runmask |= ((uint)1 << bit);
}
timeTotal += time;
}
return timeTotal;
}
private byte[] GetFilterText()
{
return ByteWindow.MakeBytes(itparms.FilterText);
}
public ETWLineReader StandardLineReader()
{
return new ETWLineReader(this);
}
private List<TimeMark> listDelays = null;
public string ComputeDelays(int delaySize)
{
ThreadStat[] stats = NewThreadStats();
bool[] threadFilters = itparms.GetThreadFilters();
int idCSwitch = atomsRecords.Lookup("CSwitch");
StringWriter sw = new StringWriter();
sw.WriteLine("{0,15} {1,15} {2,15} {3,30} {4,5} {5,-60}", "Delay Start", "Delay End", "Delay Duration", "Process Name ( ID )", "TID", "Threadproc");
sw.WriteLine("{0,15} {1,15} {2,15} {3,30} {4,5} {5,-60}", "-----------", "---------", "--------------", "-------------------", "---", "----------");
listDelays = new List<TimeMark>();
int totalDelays = 0;
long totalDelay = 0;
long T0 = itparms.T0;
for (int i = 0; i < stats.Length; i++)
{
stats[i].time = Math.Max(T0, threads[i].timestamp);
}
ETWLineReader l = StandardLineReader();
foreach (ByteWindow b in l.Lines())
{
if (l.idType != idCSwitch)
{
continue;
}
int oldTid = b.GetInt(fldCSwitchOldTID);
int idxOld = FindThreadInfoIndex(l.t, oldTid);
stats[idxOld].time = l.t;
int newTid = b.GetInt(fldCSwitchNewTID);
int idxNew = FindThreadInfoIndex(l.t, newTid);
int waitTime = (int)(l.t - stats[idxNew].time);
if (waitTime <= 0)
{
continue;
}
if (!threadFilters[idxNew])
{
continue;
}
totalDelays++;
totalDelay += waitTime;
if (waitTime > delaySize)
{
TimeMark tm = new TimeMark();
tm.t0 = l.t - waitTime;
tm.t1 = l.t;
string process = ByteWindow.MakeString(threads[idxNew].processPid);
string threadproc = ByteWindow.MakeString(threads[idxNew].threadproc);
tm.desc = String.Format("{0,15:n0} {1,15:n0} {2,15:n0} {3,30} {4,5} {5,-60}", tm.t0, tm.t1, waitTime, process, newTid, threadproc);
sw.WriteLine(tm.desc);
listDelays.Add(tm);
}
}
sw.WriteLine();
sw.WriteLine("Total Delays: {0:n0} Total Delay Time {1:n0}", totalDelays, totalDelay);
return sw.ToString();
}
public void ZoomToDelays()
{
if (listDelays == null)
{
return;
}
if (listDelays.Count < 1)
{
return;
}
ClearZoomedTimes();
foreach (TimeMark tm in listDelays)
{
AddZoomedTimeRow(tm.t0, tm.t1, tm.desc);
}
}
internal void Close()
{
stm.Close();
stm = null;
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2011, Cypress Semiconductor Corporation. All rights reserved.
* You may use this file only in accordance with the license, terms, conditions,
* disclaimers, and limitations in the end user license agreement accompanying
* the software package with which this file was provided.
********************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Diagnostics;
using System.Data;
using System.Text;
using System.Windows.Forms;
using CyDesigner.Extensions.Common;
using CyDesigner.Extensions.Gde;
namespace SPI_HFC_Master_v0_1
{
public partial class CySPIMControl : UserControl, ICyParamEditingControl
{
private const string POINT = ".";
private CySPIMParameters m_params;
#region Constants
// Image constants
public const int PB_SPIMTEXT_WIDTH = 40;
public const int PB_EXTENTS_BORDER = 5;
public const int PB_POLYGON_WIDTH = 4;
public const int NUM_WAVEFORMS = 5;
// Unit constants
public const int POW6 = 1000000;
public const int POW3 = 1000;
#endregion
#region Constructor(s)
public CySPIMControl(CySPIMParameters inst)
{
InitializeComponent();
inst.m_basicTab = this;
this.Dock = DockStyle.Fill;
m_params = inst;
// Set the SPIM Mode Combo Box from Enums
cbMode.DataSource = m_params.m_modeList;
/*
// Set Bidirect Mode ComboBox
cbDataLines.Items.Add(CyBidirectMode.MISO_MOSI);
cbDataLines.Items.Add(CyBidirectMode.BI_DIRECTIONAL);
*/
// Set ShiftDir Combo Box from Enums
cbShiftDir.DataSource = m_params.m_shiftDirectionList;
// Event Handlers declaration
numDataBits.TextChanged += new EventHandler(numDataBits_TextChanged);
numBitRateHertz.TextChanged += new EventHandler(numBitRateHertz_TextChanged);
// Set bitrate units
cbBitRateHertz.SelectedIndex = (m_params.DesiredBitRate > POW6) ? 1 : 0;
}
#endregion
#region ICyParamEditingControl Members
public Control DisplayControl
{
get { return this; }
}
public IEnumerable<CyCustErr> GetErrors()
{
foreach (string paramName in m_params.m_inst.GetParamNames())
{
CyCompDevParam param = m_params.m_inst.GetCommittedParam(paramName);
if (param.TabName.Equals(CyCustomizer.BASIC_TABNAME))
{
if (param.ErrorCount > 0)
{
foreach (string errMsg in param.Errors)
{
yield return new CyCustErr(errMsg);
}
}
}
}
}
#endregion
#region Assigning parameters values to controls
public void UpdateUI()
{
// Mode
switch (m_params.Mode)
{
case E_SPI_MODES.Mode_00:
cbMode.SelectedIndex = 0;
break;
case E_SPI_MODES.Mode_01:
cbMode.SelectedIndex = 1;
break;
case E_SPI_MODES.Mode_10:
cbMode.SelectedIndex = 2;
break;
case E_SPI_MODES.Mode_11:
cbMode.SelectedIndex = 3;
break;
default:
break;
}
/*
// BidirectMode
cbDataLines.SelectedItem = m_params.BidirectMode ? CyBidirectMode.BI_DIRECTIONAL
: CyBidirectMode.MISO_MOSI;
*/
// NumberOfDataBits
numDataBits.Text = m_params.NumberOfDataBits.Value.ToString();
// ShiftDir
cbShiftDir.SelectedItem = CyEnumConverter.GetEnumDesc(m_params.ShiftDir);
// DesiredBitRate
SetBitRateAvailability();
double freq = m_params.DesiredBitRate.Value / ((cbBitRateHertz.SelectedIndex == 0) ? POW3 : POW6);
numBitRateHertz.Text = freq.ToString();
}
#endregion
#region Assigning controls values to parameters
private void SetDesiredBitRate()
{
if (m_params.m_basicTab.Visible && m_params.m_bGlobalEditMode)
{
decimal val = 0;
decimal freq = 0;
if (decimal.TryParse(numBitRateHertz.Text, out val))
{
try
{
freq = val * ((cbBitRateHertz.SelectedIndex == 0) ? POW3 : POW6);
m_params.DesiredBitRate = (double)freq;
}
catch
{
m_params.DesiredBitRate = null;
}
}
else
{
m_params.DesiredBitRate = null;
}
}
}
#endregion
#region Errors handling
public void ShowError(string paramName, CyCustErr err)
{
Control control = null;
string errMsg = (err.IsOk) ? string.Empty : err.Message;
bool isParamOwner = true;
switch (paramName)
{
/*
case CyParamNames.BIDIRECT_MODE:
control = cbDataLines;
break;
*/
case CyParamNames.DESIRED_BIT_RATE:
control = numBitRateHertz;
break;
case CyParamNames.MODE:
control = cbMode;
break;
case CyParamNames.NUMBER_OF_DATA_BITS:
control = numDataBits;
break;
case CyParamNames.SHIFT_DIR:
control = cbShiftDir;
break;
default:
m_params.m_advTab.ShowError(paramName, err);
isParamOwner = false;
break;
}
if (isParamOwner)
{
ep_Errors.SetError(control, errMsg);
}
}
#endregion
#region Bitrate Settings
public void SetBitRateAvailability()
{
if (m_params.ClockInternal)
{
cbBitRateHertz.Enabled = true;
cbBitRateHertz.Visible = true;
numBitRateHertz.Enabled = true;
numBitRateHertz.Visible = true;
lblCalculatedBitRate.Visible = false;
SetBitrateValue();
}
else
{
cbBitRateHertz.Enabled = false;
cbBitRateHertz.Visible = false;
numBitRateHertz.Enabled = false;
numBitRateHertz.Visible = false;
lblCalculatedBitRate.Visible = true;
SetBitrateValue();
lblCalculatedBitRate.Text = "1/2 Input Clock Frequency";
}
}
public void SetBitrateValue()
{
double bitrate = m_params.DesiredBitRate.Value;
if (bitrate > POW6)
{
SetBitRateDecimalPlaces(bitrate, POW6);
try
{
numBitRateHertz.Value = Convert.ToDecimal(bitrate / POW6);
}
catch (Exception) { }
cbBitRateHertz.SelectedIndex = 1;
}
else
{
SetBitRateDecimalPlaces(bitrate, POW3);
try
{
numBitRateHertz.Value = Convert.ToDecimal(bitrate / POW3);
}
catch (Exception) { }
cbBitRateHertz.SelectedIndex = 0;
}
}
private void SetBitRateDecimalPlaces(double bitrate, double denominator)
{
double bitrateDevided = bitrate / denominator;
string textBitrate = bitrateDevided.ToString();
if (textBitrate.Contains(POINT))
{
int start = textBitrate.LastIndexOf(POINT);
numBitRateHertz.DecimalPlaces = textBitrate.Substring(start + 1).Length;
}
}
#endregion
#region Event Handlers
private void CySPIMControl_Load(object sender, EventArgs e)
{
UpdateDrawing();
}
private void numDataBits_TextChanged(object sender, EventArgs e)
{
try
{
m_params.NumberOfDataBits = byte.Parse(numDataBits.Text);
}
catch (Exception)
{
m_params.NumberOfDataBits = null;
}
if (NumUpDownValidated(sender))
{
UpdateDrawing();
}
}
private void cbMode_SelectedIndexChanged(object sender, EventArgs e)
{
switch (cbMode.SelectedIndex)
{
case 0:
m_params.Mode = E_SPI_MODES.Mode_00;
break;
case 1:
m_params.Mode = E_SPI_MODES.Mode_01;
break;
case 2:
m_params.Mode = E_SPI_MODES.Mode_10;
break;
case 3:
m_params.Mode = E_SPI_MODES.Mode_11;
break;
default:
break;
}
UpdateDrawing();
ep_Errors.SetError((Control)sender, string.Empty);
}
/*
private void cbDataLines_SelectedIndexChanged(object sender, EventArgs e)
{
switch (cbDataLines.Text)
{
case CyBidirectMode.BI_DIRECTIONAL:
m_params.BidirectMode = true;
break;
case CyBidirectMode.MISO_MOSI:
m_params.BidirectMode = false;
break;
default:
break;
}
ep_Errors.SetError((Control)sender, string.Empty);
}
*/
private void cbShiftDir_SelectedIndexChanged(object sender, EventArgs e)
{
m_params.ShiftDir = (E_B_SPI_MASTER_SHIFT_DIRECTION)CyEnumConverter.GetEnumValue(
cbShiftDir.Text, typeof(E_B_SPI_MASTER_SHIFT_DIRECTION));
UpdateDrawing();
ep_Errors.SetError((Control)sender, string.Empty);
}
private void numBitRateHertz_TextChanged(object sender, EventArgs e)
{
NumUpDownValidated(sender);
SetDesiredBitRate();
}
private void cbBitRateHertz_SelectedIndexChanged(object sender, EventArgs e)
{
NumUpDownValidated(sender);
SetDesiredBitRate();
}
private void numBitRateHertz_Leave(object sender, EventArgs e)
{
// Trim all trailing points and zeros in floating point value
// This also trims trailing points and zeros if user input some unreasonable value (e.g. 12.0.000.0.0)
string zeroChar = "0";
while (numBitRateHertz.Text.Contains(POINT) &&
(numBitRateHertz.Text.LastIndexOf(zeroChar) == numBitRateHertz.Text.Length - 1 ||
numBitRateHertz.Text.LastIndexOf(POINT) == numBitRateHertz.Text.Length - 1))
{
numBitRateHertz.Text = numBitRateHertz.Text.TrimEnd(zeroChar[0]);
numBitRateHertz.Text = numBitRateHertz.Text.TrimEnd(POINT[0]);
}
}
private bool NumUpDownValidated(object sender)
{
decimal value = 0;
decimal multiplier = 0;
decimal min = 0;
decimal max = 0;
string message = string.Empty;
bool result = false;
string numericText = string.Empty;
if (sender == cbBitRateHertz) sender = numBitRateHertz;
numericText = ((CyNumericUpDown)sender).Text;
if (sender == numBitRateHertz)
{
min = CyParamRange.FREQUENCY_MIN;
max = CyParamRange.FREQUENCY_MAX;
message = Properties.Resources.FrequencyEPMsg;
multiplier = ((cbBitRateHertz.SelectedIndex == 0) ? POW3 : POW6);
}
else if (sender == numDataBits)
{
min = CyParamRange.NUM_BITS_MIN;
max = CyParamRange.NUM_BITS_MAX;
message = string.Format(Properties.Resources.NumOfDataBitsEPMsg, min, max);
multiplier = 1;
if (numericText.EndsWith(POINT) || numericText.EndsWith(","))
{
ep_Errors.SetError((CyNumericUpDown)sender, string.Format(message));
return result;
}
}
if (decimal.TryParse(numericText, out value))
{
try
{
value *= multiplier;
}
catch { }
if (value < min || value > max)
{
ep_Errors.SetError((CyNumericUpDown)sender, string.Format(message));
}
else
{
ep_Errors.SetError((CyNumericUpDown)sender, string.Empty);
result = true;
}
}
else
{ ep_Errors.SetError((CyNumericUpDown)sender, string.Format(message)); }
return result;
}
#endregion
#region Form Drawing
public void UpdateDrawing()
{
if ((pbDrawing.Width == 0) || (pbDrawing.Height == 0))
return;
Image waveform = new Bitmap(pbDrawing.Width, pbDrawing.Height);
Graphics wfg;
wfg = Graphics.FromImage(waveform);
wfg.Clear(Color.White);
SolidBrush blkbrush = new SolidBrush(Color.Black);
float extentsleft = PB_EXTENTS_BORDER + PB_SPIMTEXT_WIDTH;
float extentsright = pbDrawing.Width - PB_EXTENTS_BORDER;
float padding = (extentsright - extentsleft) / 70;
float startleft = extentsleft + padding;
float endright = extentsright - padding;
float startright = startleft + (endright - startleft) / 2;
// Setup the right, left and center indicators
Pen extentspen = new Pen(blkbrush);
extentspen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
// Draw the Left Extents Line
wfg.DrawLine(extentspen, extentsleft, PB_EXTENTS_BORDER,
extentsleft, pbDrawing.Height - PB_EXTENTS_BORDER);
// Draw the Right Extents Line
wfg.DrawLine(extentspen, extentsright, PB_EXTENTS_BORDER,
extentsright, pbDrawing.Height - PB_EXTENTS_BORDER);
extentspen.Dispose();
// Setup and draw all of the waveforms
int numwaveforms = NUM_WAVEFORMS;
string[] wfnames = new string[NUM_WAVEFORMS];
wfnames[0] = "SS";
wfnames[1] = "SCLK";
wfnames[2] = "MOSI";
wfnames[3] = "MISO";
wfnames[4] = "Sample";
Font perfont = new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel);
// Each waveform's height is dependent upon the drawing size minus a top and bottom border
// and the top period waveform which is the size of two polygon widths, and an bottom
// ticker tape of 2 polygon widths
float wfheight = (pbDrawing.Height - (2 * PB_EXTENTS_BORDER) - (4 * PB_POLYGON_WIDTH)) / numwaveforms;
// Fill in All Waveform Names
for (int i = 0; i < numwaveforms; i++)
{
PointF pt = new PointF(extentsleft - wfg.MeasureString(wfnames[i], perfont).Width - PB_EXTENTS_BORDER,
PB_EXTENTS_BORDER + (2 * PB_POLYGON_WIDTH) + (wfheight * i) + (wfheight / 2) -
(wfg.MeasureString(wfnames[i], perfont).Height / 2));
wfg.DrawString(wfnames[i], perfont, blkbrush, pt);
}
// Draw Waveforms
int numsegments = 2 + (Convert.ToInt16(m_params.NumberOfDataBits) * 2) + 3;
for (int i = 0; i < numwaveforms; i++)
{
float HighY = PB_EXTENTS_BORDER + (2 * PB_POLYGON_WIDTH) + (wfheight * i) + (wfheight / 8);
float LowY = PB_EXTENTS_BORDER + (2 * PB_POLYGON_WIDTH) + (wfheight * (i + 1));
float segwidth = (extentsright - extentsleft) / numsegments;
List<float> segsx = new List<float>();
for (int x = 0; x < numsegments; x++)
{
segsx.Add(extentsleft + (x * segwidth));
}
SolidBrush wfbrush = new SolidBrush(Color.Blue);
Pen wfPen = new Pen(wfbrush);
int NumDataBits = Convert.ToInt16(m_params.NumberOfDataBits);
string val = null;
bool ShiftDir = (Convert.ToInt16(m_params.ShiftDir) == 0) ? false : true;
int j = 0;
bool mode = ((Convert.ToInt16(m_params.Mode) == 1) ||
(Convert.ToInt16(m_params.Mode) == 2)) ? true : false;
bool starthigh = ((Convert.ToInt16(m_params.Mode) == 1) ||
(Convert.ToInt16(m_params.Mode) == 3)) ? false : true;
switch (wfnames[i])
{
case "SS":
wfg.DrawLine(wfPen, segsx[0], HighY, segsx[2], HighY);
wfg.DrawLine(wfPen, segsx[2], HighY, segsx[2], LowY);
wfg.DrawLine(wfPen, segsx[2], LowY, segsx[numsegments - 2], LowY);
wfg.DrawLine(wfPen, segsx[numsegments - 2], LowY, segsx[numsegments - 2], HighY);
wfg.DrawLine(wfPen, segsx[numsegments - 2], HighY, segsx[numsegments - 1], HighY);
break;
case "MOSI":
case "MISO":
if (mode)
{
// Draw Bus to First Transition Point
wfg.DrawLine(wfPen, segsx[0], HighY, segsx[2] - 2, HighY);
wfg.DrawLine(wfPen, segsx[0], LowY, segsx[2] - 2, LowY);
// Draw Transition
wfg.DrawLine(wfPen, segsx[2] - 2, HighY, segsx[2] + 2, LowY);
wfg.DrawLine(wfPen, segsx[2] - 2, LowY, segsx[2] + 2, HighY);
for (j = 0; j < (NumDataBits * 2); )
{
// Draw Bus to Transition Point
wfg.DrawLine(wfPen, segsx[2 + j] + 2, HighY, segsx[2 + (j + 2)] - 2, HighY);
wfg.DrawLine(wfPen, segsx[2 + j] + 2, LowY, segsx[2 + (j + 2)] - 2, LowY);
// Draw Transition
wfg.DrawLine(wfPen, segsx[2 + (j + 2)] - 2, HighY, segsx[2 + (j + 2)] + 2, LowY);
wfg.DrawLine(wfPen, segsx[2 + (j + 2)] - 2, LowY, segsx[2 + (j + 2)] + 2, HighY);
if (ShiftDir)
val = String.Format("D{0}", j / 2);
else
val = String.Format("D{0}", NumDataBits - (j / 2) - 1);
SizeF strsize = wfg.MeasureString(val, perfont);
float centerx = segsx[2 + j] + segwidth;
wfg.DrawString(val, perfont, new SolidBrush(Color.Black),
new RectangleF(centerx - (strsize.Width / 2f), HighY + ((wfheight) / 2f)
- (strsize.Height / 2f), strsize.Width, strsize.Height));
j += 2;
}
// Draw Bus to Transition Point
wfg.DrawLine(wfPen, segsx[2 + j] + 2, LowY, segsx[2 + (j + 2)], LowY);
wfg.DrawLine(wfPen, segsx[2 + j] + 2, HighY, segsx[2 + (j + 2)], HighY);
}
else
{
// Draw Bus to First Transition Point
wfg.DrawLine(wfPen, segsx[0], HighY, segsx[3] - 2, HighY);
wfg.DrawLine(wfPen, segsx[0], LowY, segsx[3] - 2, LowY);
// Draw Transition
wfg.DrawLine(wfPen, segsx[3] - 2, HighY, segsx[3] + 2, LowY);
wfg.DrawLine(wfPen, segsx[3] - 2, LowY, segsx[3] + 2, HighY);
for (j = 0; j < (NumDataBits * 2); )
{
// Draw Bus to Transition Point
wfg.DrawLine(wfPen, segsx[3 + j] + 2, HighY, segsx[3 + (j + 2)] - 2, HighY);
wfg.DrawLine(wfPen, segsx[3 + j] + 2, LowY, segsx[3 + (j + 2)] - 2, LowY);
// Draw Transition
wfg.DrawLine(wfPen, segsx[3 + (j + 2)] - 2, HighY, segsx[3 + (j + 2)] + 2, LowY);
wfg.DrawLine(wfPen, segsx[3 + (j + 2)] - 2, LowY, segsx[3 + (j + 2)] + 2, HighY);
if (ShiftDir)
val = String.Format("D{0}", j / 2);
else
val = String.Format("D{0}", NumDataBits - (j / 2) - 1);
SizeF strsize = wfg.MeasureString(val, perfont);
float centerx = segsx[3 + j] + segwidth;
wfg.DrawString(val, perfont, new SolidBrush(Color.Black),
new RectangleF(centerx - (strsize.Width / 2f), HighY + ((wfheight) / 2f)
- (strsize.Height / 2f), strsize.Width, strsize.Height));
j += 2;
}
// Draw Bus to Transition Point
wfg.DrawLine(wfPen, segsx[3 + j] + 2, LowY, segsx[3 + (j + 1)], LowY);
wfg.DrawLine(wfPen, segsx[3 + j] + 2, HighY, segsx[3 + (j + 1)], HighY);
}
break;
case "SCLK":
wfg.DrawLine(wfPen, segsx[0], starthigh ? HighY : LowY, segsx[3], starthigh ? HighY : LowY);
wfg.DrawLine(wfPen, segsx[3], starthigh ? HighY : LowY, segsx[3], starthigh ? HighY : LowY);
for (j = 0; j < (NumDataBits * 2); )
{
wfg.DrawLine(wfPen, segsx[3 + j], starthigh ? HighY : LowY,
segsx[3 + j], starthigh ? LowY : HighY);
wfg.DrawLine(wfPen, segsx[3 + j++], starthigh ? LowY : HighY,
segsx[3 + j], starthigh ? LowY : HighY);
wfg.DrawLine(wfPen, segsx[3 + j], starthigh ? LowY : HighY,
segsx[3 + j], starthigh ? HighY : LowY);
wfg.DrawLine(wfPen, segsx[3 + j++], starthigh ? HighY : LowY,
segsx[3 + j], starthigh ? HighY : LowY);
}
wfg.DrawLine(wfPen, segsx[3 + j++], starthigh ? HighY : LowY,
segsx[3 + j], starthigh ? HighY : LowY);
break;
case "Sample":
if (mode)
{
wfg.DrawLine(wfPen, segsx[0], LowY, segsx[3] - 2, LowY); // Go to first edge
for (j = 0; j < (NumDataBits * 2); )
{
wfg.DrawLine(wfPen, segsx[3 + j] - 2, LowY, segsx[3 + j] - 2, HighY);
wfg.DrawLine(wfPen, segsx[3 + j] - 2, HighY, segsx[3 + j] + 2, HighY);
wfg.DrawLine(wfPen, segsx[3 + j] + 2, HighY, segsx[3 + j] + 2, LowY);
wfg.DrawLine(wfPen, segsx[3 + j] + 2, LowY, segsx[3 + (j + 2)] - 2, LowY);
j += 2;
}
wfg.DrawLine(wfPen, segsx[3 + j] - 2, LowY, segsx[3 + (j + 1)], LowY);
}
else
{
wfg.DrawLine(wfPen, segsx[0], LowY, segsx[4] - 2, LowY); // Go to first edge
for (j = 0; j < (NumDataBits * 2); )
{
wfg.DrawLine(wfPen, segsx[4 + j] - 2, LowY, segsx[4 + j] - 2, HighY);
wfg.DrawLine(wfPen, segsx[4 + j] - 2, HighY, segsx[4 + j] + 2, HighY);
wfg.DrawLine(wfPen, segsx[4 + j] + 2, HighY, segsx[4 + j] + 2, LowY);
wfg.DrawLine(wfPen, segsx[4 + j] + 2, LowY, segsx[4 + (j + 2)] - 2, LowY);
j += 2;
}
wfg.DrawLine(wfPen, segsx[4 + j] - 2, LowY, segsx[4 + j], LowY);
}
break;
case "Interrupt":
break;
}
}
wfg.Dispose();
pbDrawing.Image = waveform;
}
#endregion
}
#region Override NumericUpDown Class
public class CyNumericUpDown : NumericUpDown
{
private bool m_allowNegative;
public CyNumericUpDown()
{
this.AllowNegative = false;
}
public bool AllowNegative
{
get { return m_allowNegative; }
set { m_allowNegative = value; }
}
public override void UpButton()
{
decimal x;
if (decimal.TryParse(this.Text, out x))
{
x = x + this.Increment;
this.Text = x.ToString();
}
}
public override void DownButton()
{
decimal x;
if (decimal.TryParse(this.Text, out x))
{
if (m_allowNegative)
{
x = x - this.Increment;
this.Text = x.ToString();
}
else
{
if ((x - this.Increment) >= 0)
{
x = x - this.Increment;
this.Text = x.ToString();
}
}
}
}
protected override void UpdateEditText()
{
// NOTHING TO DO HERE
}
}
#endregion
/*
public class CyBidirectMode
{
public const string MISO_MOSI = "MOSI + MISO";
public const string BI_DIRECTIONAL = "Bidirectional";
}
*/
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace Jasily.Extensions.System.Threading.Tasks
{
public static class TaskFactoryHelper
{
#region Task<T>
public static async Task<T> FromAsync<T>([NotNull] Func<AsyncCallback, object, IAsyncResult> beginMethod,
[NotNull] Func<IAsyncResult, T> endMethod)
{
if (beginMethod == null) throw new ArgumentNullException(nameof(beginMethod));
if (endMethod == null) throw new ArgumentNullException(nameof(endMethod));
var task = new TaskCompletionSource<T>();
beginMethod(ac =>
{
try
{
task.SetResult(endMethod(ac));
}
catch (Exception e)
{
task.SetException(e);
}
}, null);
return await task.Task;
}
public static async Task<T> FromAsync<T>([NotNull] Func<AsyncCallback, object, IAsyncResult> beginMethod,
[NotNull] Func<IAsyncResult, T> endMethod,
CancellationToken cancellationToken)
{
if (beginMethod == null) throw new ArgumentNullException(nameof(beginMethod));
if (endMethod == null) throw new ArgumentNullException(nameof(endMethod));
var task = new TaskCompletionSource<T>();
using (cancellationToken.Register(() => task.TrySetCanceled(), false))
{
beginMethod(ac =>
{
try
{
task.TrySetResult(endMethod(ac));
}
catch (Exception e)
{
task.TrySetException(e);
}
}, null);
return await task.Task;
}
}
public static async Task<T> FromAsync<T>([NotNull] Func<AsyncCallback, object, IAsyncResult> beginMethod,
[NotNull] Func<IAsyncResult, T> endMethod,
CancellationToken cancellationToken, [NotNull] Action cancelingCallback)
{
if (beginMethod == null) throw new ArgumentNullException(nameof(beginMethod));
if (endMethod == null) throw new ArgumentNullException(nameof(endMethod));
if (cancelingCallback == null) throw new ArgumentNullException(nameof(cancelingCallback));
var task = new TaskCompletionSource<T>();
using (cancellationToken.Register(() =>
{
cancelingCallback();
task.TrySetCanceled();
}, false))
{
beginMethod(ac =>
{
try
{
task.TrySetResult(endMethod(ac));
}
catch (Exception e)
{
task.TrySetException(e);
}
}, null);
return await task.Task;
}
}
public static async Task<T> FromAsync<T>([NotNull] Func<AsyncCallback, object, IAsyncResult> beginMethod,
[NotNull] Func<IAsyncResult, CancellationToken, T> endMethod,
CancellationToken cancellationToken)
{
if (beginMethod == null) throw new ArgumentNullException(nameof(beginMethod));
if (endMethod == null) throw new ArgumentNullException(nameof(endMethod));
var task = new TaskCompletionSource<T>();
using (cancellationToken.Register(() => task.TrySetCanceled(), false))
{
beginMethod(ac =>
{
try
{
task.TrySetResult(endMethod(ac, cancellationToken));
}
catch (Exception e)
{
task.TrySetException(e);
}
}, null);
return await task.Task;
}
}
public static async Task<T> FromAsync<T>([NotNull] Func<AsyncCallback, object, IAsyncResult> beginMethod,
[NotNull] Func<IAsyncResult, CancellationToken, T> endMethod,
CancellationToken cancellationToken, [NotNull] Action cancelingCallback)
{
if (beginMethod == null) throw new ArgumentNullException(nameof(beginMethod));
if (endMethod == null) throw new ArgumentNullException(nameof(endMethod));
if (cancelingCallback == null) throw new ArgumentNullException(nameof(cancelingCallback));
var task = new TaskCompletionSource<T>();
using (cancellationToken.Register(() =>
{
cancelingCallback();
task.TrySetCanceled();
}, false))
{
beginMethod(ac =>
{
try
{
task.TrySetResult(endMethod(ac, cancellationToken));
}
catch (Exception e)
{
task.TrySetException(e);
}
}, null);
return await task.Task;
}
}
#endregion
#region Task
public static async Task FromAsync([NotNull] Func<AsyncCallback, object, IAsyncResult> beginMethod,
[NotNull] Action<IAsyncResult> endMethod)
{
if (beginMethod == null) throw new ArgumentNullException(nameof(beginMethod));
if (endMethod == null) throw new ArgumentNullException(nameof(endMethod));
var task = new TaskCompletionSource<bool>();
beginMethod(ac =>
{
try
{
endMethod(ac);
task.SetResult(true);
}
catch (Exception e)
{
task.SetException(e);
}
}, null);
await task.Task;
}
public static async Task FromAsync([NotNull] Func<AsyncCallback, object, IAsyncResult> beginMethod,
[NotNull] Action<IAsyncResult> endMethod, CancellationToken cancellationToken)
{
if (beginMethod == null) throw new ArgumentNullException(nameof(beginMethod));
if (endMethod == null) throw new ArgumentNullException(nameof(endMethod));
var task = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => task.TrySetCanceled(), false))
{
beginMethod(ac =>
{
try
{
endMethod(ac);
task.TrySetResult(true);
}
catch (Exception e)
{
task.TrySetException(e);
}
}, null);
await task.Task;
}
}
public static async Task FromAsync([NotNull] Func<AsyncCallback, object, IAsyncResult> beginMethod,
[NotNull] Action<IAsyncResult> endMethod, CancellationToken cancellationToken,
[NotNull] Action cancelingCallback)
{
if (beginMethod == null) throw new ArgumentNullException(nameof(beginMethod));
if (endMethod == null) throw new ArgumentNullException(nameof(endMethod));
if (cancelingCallback == null) throw new ArgumentNullException(nameof(cancelingCallback));
var task = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() =>
{
cancelingCallback();
task.TrySetCanceled();
}, false))
{
beginMethod(ac =>
{
try
{
endMethod(ac);
task.TrySetResult(true);
}
catch (Exception e)
{
task.TrySetException(e);
}
}, null);
await task.Task;
}
}
public static async Task FromAsync([NotNull] Func<AsyncCallback, object, IAsyncResult> beginMethod,
[NotNull] Action<IAsyncResult, CancellationToken> endMethod, CancellationToken cancellationToken)
{
if (beginMethod == null) throw new ArgumentNullException(nameof(beginMethod));
if (endMethod == null) throw new ArgumentNullException(nameof(endMethod));
var task = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => task.TrySetCanceled(), false))
{
beginMethod(ac =>
{
try
{
endMethod(ac, cancellationToken);
task.TrySetResult(true);
}
catch (Exception e)
{
task.TrySetException(e);
}
}, null);
await task.Task;
}
}
public static async Task FromAsync([NotNull] Func<AsyncCallback, object, IAsyncResult> beginMethod,
[NotNull] Action<IAsyncResult, CancellationToken> endMethod, CancellationToken cancellationToken,
[NotNull] Action cancelingCallback)
{
if (beginMethod == null) throw new ArgumentNullException(nameof(beginMethod));
if (endMethod == null) throw new ArgumentNullException(nameof(endMethod));
if (cancelingCallback == null) throw new ArgumentNullException(nameof(cancelingCallback));
var task = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() =>
{
cancelingCallback();
task.TrySetCanceled();
}, false))
{
beginMethod(ac =>
{
try
{
endMethod(ac, cancellationToken);
task.TrySetResult(true);
}
catch (Exception e)
{
task.TrySetException(e);
}
}, null);
await task.Task;
}
}
#endregion
}
}
| |
//
// PropertyDefinition.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// 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.Text;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public sealed class PropertyDefinition : PropertyReference, IMemberDefinition, IConstantProvider {
bool? has_this;
ushort attributes;
Collection<CustomAttribute> custom_attributes;
internal MethodDefinition get_method;
internal MethodDefinition set_method;
internal Collection<MethodDefinition> other_methods;
object constant = Mixin.NotResolved;
public PropertyAttributes Attributes {
get { return (PropertyAttributes) attributes; }
set { attributes = (ushort) value; }
}
public bool HasThis {
get {
if (has_this.HasValue)
return has_this.Value;
if (GetMethod != null)
return get_method.HasThis;
if (SetMethod != null)
return set_method.HasThis;
return false;
}
set { has_this = value; }
}
public bool HasCustomAttributes {
get {
if (custom_attributes != null)
return custom_attributes.Count > 0;
return Mixin.GetHasCustomAttributes(this, Module);
}
}
public Collection<CustomAttribute> CustomAttributes {
get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }
}
public MethodDefinition GetMethod {
get {
if (get_method != null)
return get_method;
InitializeMethods ();
return get_method;
}
set { get_method = value; }
}
public MethodDefinition SetMethod {
get {
if (set_method != null)
return set_method;
InitializeMethods ();
return set_method;
}
set { set_method = value; }
}
public bool HasOtherMethods {
get {
if (other_methods != null)
return other_methods.Count > 0;
InitializeMethods ();
return !Mixin.IsNullOrEmpty (other_methods);
}
}
public Collection<MethodDefinition> OtherMethods {
get {
if (other_methods != null)
return other_methods;
InitializeMethods ();
if (other_methods != null)
return other_methods;
return other_methods = new Collection<MethodDefinition> ();
}
}
public bool HasParameters {
get {
InitializeMethods ();
if (get_method != null)
return get_method.HasParameters;
if (set_method != null)
return set_method.HasParameters && set_method.Parameters.Count > 1;
return false;
}
}
public override Collection<ParameterDefinition> Parameters {
get {
InitializeMethods ();
if (get_method != null)
return MirrorParameters (get_method, 0);
if (set_method != null)
return MirrorParameters (set_method, 1);
return new Collection<ParameterDefinition> ();
}
}
static Collection<ParameterDefinition> MirrorParameters (MethodDefinition method, int bound)
{
var parameters = new Collection<ParameterDefinition> ();
if (!method.HasParameters)
return parameters;
var original_parameters = method.Parameters;
var end = original_parameters.Count - bound;
for (int i = 0; i < end; i++)
parameters.Add (original_parameters [i]);
return parameters;
}
public bool HasConstant {
get {
Mixin.ResolveConstant(this, ref constant, Module);
return constant != Mixin.NoValue;
}
set { if (!value) constant = Mixin.NoValue; }
}
public object Constant {
get { return HasConstant ? constant : null; }
set { constant = value; }
}
#region PropertyAttributes
public bool IsSpecialName {
get { return Mixin.GetAttributes(attributes,(ushort) PropertyAttributes.SpecialName); }
set { attributes =Mixin.SetAttributes(attributes,(ushort) PropertyAttributes.SpecialName, value); }
}
public bool IsRuntimeSpecialName {
get { return Mixin.GetAttributes(attributes,(ushort) PropertyAttributes.RTSpecialName); }
set { attributes =Mixin.SetAttributes(attributes,(ushort) PropertyAttributes.RTSpecialName, value); }
}
public bool HasDefault {
get { return Mixin.GetAttributes(attributes,(ushort) PropertyAttributes.HasDefault); }
set { attributes =Mixin.SetAttributes(attributes,(ushort) PropertyAttributes.HasDefault, value); }
}
#endregion
public new TypeDefinition DeclaringType {
get { return (TypeDefinition) base.DeclaringType; }
set { base.DeclaringType = value; }
}
public override bool IsDefinition {
get { return true; }
}
public override string FullName {
get {
var builder = new StringBuilder ();
builder.Append (PropertyType.ToString ());
builder.Append (' ');
builder.Append (MemberFullName ());
builder.Append ('(');
if (HasParameters) {
var parameters = Parameters;
for (int i = 0; i < parameters.Count; i++) {
if (i > 0)
builder.Append (',');
builder.Append (parameters [i].ParameterType.FullName);
}
}
builder.Append (')');
return builder.ToString ();
}
}
public PropertyDefinition (string name, PropertyAttributes attributes, TypeReference propertyType)
: base (name, propertyType)
{
this.attributes = (ushort) attributes;
this.token = new MetadataToken (TokenType.Property);
}
void InitializeMethods ()
{
var module = this.Module;
lock (module.SyncRoot) {
if (get_method != null || set_method != null)
return;
if (!Mixin.HasImage(module))
return;
module.Read (this, (property, reader) => reader.ReadMethods (property));
}
}
public override PropertyDefinition Resolve ()
{
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace EscapistasClub.Core.Helpers
{
public class Base32Encoder
{
private const string DEF_ENCODING_TABLE = "abcdefghijklmnopqrstuvwxyz234567";
private const char DEF_PADDING = '=';
private readonly string eTable; //Encoding table
private readonly char padding;
private readonly byte[] dTable; //Decoding table
public Base32Encoder()
: this(DEF_ENCODING_TABLE, DEF_PADDING)
{
}
public Base32Encoder(char padding)
: this(DEF_ENCODING_TABLE, padding)
{
}
public Base32Encoder(string encodingTable)
: this(encodingTable, DEF_PADDING)
{
}
public Base32Encoder(string encodingTable, char padding)
{
this.eTable = encodingTable;
this.padding = padding;
this.dTable = new byte[0x80];
InitialiseDecodingTable();
}
public virtual string Encode(byte[] input)
{
var output = new StringBuilder();
int specialLength = input.Length % 5;
int normalLength = input.Length - specialLength;
for (int i = 0; i < normalLength; i += 5)
{
int b1 = input[i] & 0xff;
int b2 = input[i + 1] & 0xff;
int b3 = input[i + 2] & 0xff;
int b4 = input[i + 3] & 0xff;
int b5 = input[i + 4] & 0xff;
output.Append(this.eTable[(b1 >> 3) & 0x1f]);
output.Append(this.eTable[((b1 << 2) | (b2 >> 6)) & 0x1f]);
output.Append(this.eTable[(b2 >> 1) & 0x1f]);
output.Append(this.eTable[((b2 << 4) | (b3 >> 4)) & 0x1f]);
output.Append(this.eTable[((b3 << 1) | (b4 >> 7)) & 0x1f]);
output.Append(this.eTable[(b4 >> 2) & 0x1f]);
output.Append(this.eTable[((b4 << 3) | (b5 >> 5)) & 0x1f]);
output.Append(this.eTable[b5 & 0x1f]);
}
switch (specialLength)
{
case 1:
{
int b1 = input[normalLength] & 0xff;
output.Append(this.eTable[(b1 >> 3) & 0x1f]);
output.Append(this.eTable[(b1 << 2) & 0x1f]);
output.Append(this.padding).Append(this.padding).Append(this.padding).Append(this.padding).Append(this.padding).Append(this.padding);
break;
}
case 2:
{
int b1 = input[normalLength] & 0xff;
int b2 = input[normalLength + 1] & 0xff;
output.Append(this.eTable[(b1 >> 3) & 0x1f]);
output.Append(this.eTable[((b1 << 2) | (b2 >> 6)) & 0x1f]);
output.Append(this.eTable[(b2 >> 1) & 0x1f]);
output.Append(this.eTable[(b2 << 4) & 0x1f]);
output.Append(this.padding).Append(this.padding).Append(this.padding).Append(this.padding);
break;
}
case 3:
{
int b1 = input[normalLength] & 0xff;
int b2 = input[normalLength + 1] & 0xff;
int b3 = input[normalLength + 2] & 0xff;
output.Append(this.eTable[(b1 >> 3) & 0x1f]);
output.Append(this.eTable[((b1 << 2) | (b2 >> 6)) & 0x1f]);
output.Append(this.eTable[(b2 >> 1) & 0x1f]);
output.Append(this.eTable[((b2 << 4) | (b3 >> 4)) & 0x1f]);
output.Append(this.eTable[(b3 << 1) & 0x1f]);
output.Append(this.padding).Append(this.padding).Append(this.padding);
break;
}
case 4:
{
int b1 = input[normalLength] & 0xff;
int b2 = input[normalLength + 1] & 0xff;
int b3 = input[normalLength + 2] & 0xff;
int b4 = input[normalLength + 3] & 0xff;
output.Append(this.eTable[(b1 >> 3) & 0x1f]);
output.Append(this.eTable[((b1 << 2) | (b2 >> 6)) & 0x1f]);
output.Append(this.eTable[(b2 >> 1) & 0x1f]);
output.Append(this.eTable[((b2 << 4) | (b3 >> 4)) & 0x1f]);
output.Append(this.eTable[((b3 << 1) | (b4 >> 7)) & 0x1f]);
output.Append(this.eTable[(b4 >> 2) & 0x1f]);
output.Append(this.eTable[(b4 << 3) & 0x1f]);
output.Append(this.padding);
break;
}
}
return output.ToString();
}
public virtual byte[] Decode(string data)
{
var outStream = new List<Byte>();
int length = data.Length;
while (length > 0)
{
if (!Ignore(data[length - 1]))
{
break;
}
length--;
}
int i = 0;
int finish = length - 8;
for (i = NextI(data, i, finish); i < finish; i = NextI(data, i, finish))
{
byte b1 = this.dTable[data[i++]];
i = NextI(data, i, finish);
byte b2 = this.dTable[data[i++]];
i = NextI(data, i, finish);
byte b3 = this.dTable[data[i++]];
i = NextI(data, i, finish);
byte b4 = this.dTable[data[i++]];
i = NextI(data, i, finish);
byte b5 = this.dTable[data[i++]];
i = NextI(data, i, finish);
byte b6 = this.dTable[data[i++]];
i = NextI(data, i, finish);
byte b7 = this.dTable[data[i++]];
i = NextI(data, i, finish);
byte b8 = this.dTable[data[i++]];
outStream.Add((byte)((b1 << 3) | (b2 >> 2)));
outStream.Add((byte)((b2 << 6) | (b3 << 1) | (b4 >> 4)));
outStream.Add((byte)((b4 << 4) | (b5 >> 1)));
outStream.Add((byte)((b5 << 7) | (b6 << 2) | (b7 >> 3)));
outStream.Add((byte)((b7 << 5) | b8));
}
DecodeLastBlock(outStream,
data[length - 8], data[length - 7], data[length - 6], data[length - 5],
data[length - 4], data[length - 3], data[length - 2], data[length - 1]);
return outStream.ToArray();
}
protected virtual int DecodeLastBlock(ICollection<byte> outStream, char c1, char c2, char c3, char c4, char c5, char c6, char c7, char c8)
{
if (c3 == this.padding)
{
byte b1 = this.dTable[c1];
byte b2 = this.dTable[c2];
outStream.Add((byte)((b1 << 3) | (b2 >> 2)));
return 1;
}
if (c5 == this.padding)
{
byte b1 = this.dTable[c1];
byte b2 = this.dTable[c2];
byte b3 = this.dTable[c3];
byte b4 = this.dTable[c4];
outStream.Add((byte)((b1 << 3) | (b2 >> 2)));
outStream.Add((byte)((b2 << 6) | (b3 << 1) | (b4 >> 4)));
return 2;
}
if (c6 == this.padding)
{
byte b1 = this.dTable[c1];
byte b2 = this.dTable[c2];
byte b3 = this.dTable[c3];
byte b4 = this.dTable[c4];
byte b5 = this.dTable[c5];
outStream.Add((byte)((b1 << 3) | (b2 >> 2)));
outStream.Add((byte)((b2 << 6) | (b3 << 1) | (b4 >> 4)));
outStream.Add((byte)((b4 << 4) | (b5 >> 1)));
return 3;
}
if (c8 == this.padding)
{
byte b1 = this.dTable[c1];
byte b2 = this.dTable[c2];
byte b3 = this.dTable[c3];
byte b4 = this.dTable[c4];
byte b5 = this.dTable[c5];
byte b6 = this.dTable[c6];
byte b7 = this.dTable[c7];
outStream.Add((byte)((b1 << 3) | (b2 >> 2)));
outStream.Add((byte)((b2 << 6) | (b3 << 1) | (b4 >> 4)));
outStream.Add((byte)((b4 << 4) | (b5 >> 1)));
outStream.Add((byte)((b5 << 7) | (b6 << 2) | (b7 >> 3)));
return 4;
}
else
{
byte b1 = this.dTable[c1];
byte b2 = this.dTable[c2];
byte b3 = this.dTable[c3];
byte b4 = this.dTable[c4];
byte b5 = this.dTable[c5];
byte b6 = this.dTable[c6];
byte b7 = this.dTable[c7];
byte b8 = this.dTable[c8];
outStream.Add((byte)((b1 << 3) | (b2 >> 2)));
outStream.Add((byte)((b2 << 6) | (b3 << 1) | (b4 >> 4)));
outStream.Add((byte)((b4 << 4) | (b5 >> 1)));
outStream.Add((byte)((b5 << 7) | (b6 << 2) | (b7 >> 3)));
outStream.Add((byte)((b7 << 5) | b8));
return 5;
}
}
protected int NextI(string data, int i, int finish)
{
while ((i < finish) && Ignore(data[i]))
{
i++;
}
return i;
}
protected bool Ignore(char c)
{
return (c == '\n') || (c == '\r') || (c == '\t') || (c == ' ') || (c == '-');
}
protected void InitialiseDecodingTable()
{
for (int i = 0; i < this.eTable.Length; i++)
{
this.dTable[this.eTable[i]] = (byte)i;
}
}
}
}
| |
using System.IO;
using System.Text.RegularExpressions;
using Signum.Engine.Maps;
namespace Signum.Engine.CodeGeneration;
public class ReactCodeGenerator
{
public string SolutionName = null!;
public string SolutionFolder = null!;
public Schema CurrentSchema = null!;
public virtual void GenerateReactFromEntities()
{
CurrentSchema = Schema.Current;
GetSolutionInfo(out SolutionFolder, out SolutionName);
string projectFolder = GetProjectFolder();
if (!Directory.Exists(projectFolder))
throw new InvalidOperationException("{0} not found. Override GetProjectFolder".FormatWith(projectFolder));
bool? overwriteFiles = null;
foreach (var mod in GetModules())
{
if (Directory.Exists(BaseFileName(mod)))
{
var clientFile = GetClientFile(mod);
if(File.Exists(clientFile))
{
var lines = File.ReadAllLines(clientFile).ToList();
{
var index = lines.FindLastIndex(s => s.Contains("Navigator.addSettings(new EntitySettings")).NotFoundToNull() ??
lines.FindLastIndex(s => s.Contains("export function start")).NotFoundToNull() ?? 0;
lines.Insert(index + 1, WritetEntitySettings(mod).Trim().Indent(2));
}
{
var regex = new Regex(@"\s*}\s*from (""(?<path>[^""]+)""|'(?<path>[^']+)')");
var importIndex = lines.FindIndex(a => regex.Match(a) is { } m && m.Success && m.Groups["path"].Value?.TryAfterLast("/") == mod.Types.First().Namespace);
if (importIndex >= 0)
lines[importIndex] = regex.Replace(lines[importIndex], m => ", " + mod.Types.Select(a => a.Name).ToString(", ") + m.ToString());
else
{
var startIndex = lines.FindLastIndex(s => s.Contains("export function start")).NotFoundToNull() ?? 0;
lines.Insert(startIndex, "import { " + mod.Types.Select(a => a.Name).ToString(", ") + " } from './" + mod.Types[0].Namespace! + "';");
}
}
File.WriteAllLines(clientFile, lines);
}
else
{
WriteFile(() => WriteClientFile(mod), () => GetClientFile(mod), ref overwriteFiles);
}
foreach (var t in mod.Types)
{
WriteFile(() => WriteEntityComponentFile(t), () => GetViewFileName(mod, t), ref overwriteFiles);
}
}
else
{
WriteFile(() => WriteClientFile(mod), () => GetClientFile(mod), ref overwriteFiles);
WriteFile(() => WriteTypingsFile(mod), () => GetTypingsFile(mod), ref overwriteFiles);
foreach (var t in mod.Types)
{
WriteFile(() => WriteEntityComponentFile(t), () => GetViewFileName(mod, t), ref overwriteFiles);
}
WriteFile(() => WriteServerFile(mod), () => ServerFileName(mod), ref overwriteFiles);
WriteFile(() => WriteControllerFile(mod), () => ControllerFileName(mod), ref overwriteFiles);
}
}
}
protected virtual void WriteFile(Func<string?> getContent, Func<string> getFileName, ref bool? overwriteFiles)
{
var content = getContent();
if (content == null)
return;
var fileName = getFileName();
FileTools.CreateParentDirectory(fileName);
if (!File.Exists(fileName) || SafeConsole.Ask(ref overwriteFiles, "Overwrite {0}?".FormatWith(fileName)))
File.WriteAllText(fileName, content, Encoding.UTF8);
}
protected virtual string GetProjectFolder()
{
return Path.Combine(SolutionFolder, SolutionName + ".React");
}
protected virtual void GetSolutionInfo(out string solutionFolder, out string solutionName)
{
CodeGenerator.GetSolutionInfo(out solutionFolder, out solutionName);
}
protected virtual string ServerFileName(Module m)
{
return BaseFileName(m) + m.ModuleName + "Server.cs";
}
protected virtual string GetViewFileName(Module m, Type t)
{
return BaseFileName(m) + "Templates\\" + GetComponentName(t) + ".tsx";
}
protected virtual string ControllerFileName(Module m)
{
return BaseFileName(m) + m.ModuleName + "Controller.cs";
}
protected virtual string GetClientFile(Module m)
{
return BaseFileName(m) + m.ModuleName + "Client.tsx";
}
protected virtual string GetTypingsFile(Module m)
{
return BaseFileName(m) + m.Types.First().Namespace + ".t4s";
}
protected virtual string BaseFileName(Module m)
{
return Path.Combine(GetProjectFolder(), "App\\" + m.ModuleName + "\\");
}
protected virtual IEnumerable<Module> GetModules()
{
var files = Directory.GetFiles(Path.Combine(GetProjectFolder(), "App"), "*.tsx", new EnumerationOptions { RecurseSubdirectories = true}).GroupToDictionary(a => Path.GetFileNameWithoutExtension(a));
Dictionary<Type, bool> types = CandidateTypes().ToDictionary(a => a, a => files.ContainsKey(a.Name) || files.ContainsKey(Reflector.CleanTypeName(a)));
return ReactGetModules(types, this.SolutionName);
}
public IEnumerable<Module> ReactGetModules(Dictionary<Type, bool> types, string solutionName)
{
while (true)
{
var typesToShow = types.Keys.OrderBy(a => a.FullName).ToList();
var selectedTypes = new ConsoleSwitch<int, Type>("Chose types for a new React module:")
.Load(typesToShow)
.Do(cs => cs.PrintOption = (key, vwd) =>
{
var used = types.GetOrThrow(vwd.Value);
SafeConsole.WriteColor(used ? ConsoleColor.DarkGray : ConsoleColor.White, " " + key);
SafeConsole.WriteLineColor(used ? ConsoleColor.DarkGray: ConsoleColor.Gray, " - " + vwd.Description);
})
.ChooseMultiple();
if (selectedTypes.IsNullOrEmpty())
yield break;
var modules = selectedTypes.GroupBy(a => a.Namespace!.After(this.SolutionName + ".Entities").DefaultText(this.SolutionName))
.Select(gr => new Module(gr.Key.TryAfterLast(".") ?? gr.Key, gr.ToList())).ToList();
foreach (var m in modules)
{
yield return m;
}
types.SetRange(selectedTypes, a => a, a => true);
}
}
protected virtual List<Type> CandidateTypes()
{
var assembly = Assembly.Load(Assembly.GetEntryAssembly()!.GetReferencedAssemblies().Single(a => a.Name == this.SolutionName + ".Entities"));
return assembly.GetTypes().Where(t => t.IsModifiableEntity() && !t.IsAbstract && !typeof(MixinEntity).IsAssignableFrom(t)).ToList();
}
protected virtual string? WriteServerFile(Module mod)
{
if (!ShouldWriteServerFile(mod))
return null;
StringBuilder sb = new StringBuilder();
foreach (var item in GetServerUsingNamespaces(mod))
sb.AppendLine("using {0};".FormatWith(item));
sb.AppendLine();
sb.AppendLine("namespace " + GetServerNamespace(mod) + ";");
sb.AppendLine();
sb.Append(WriteServerClass(mod));
return sb.ToString();
}
protected virtual bool ShouldWriteServerFile(Module mod)
{
return SafeConsole.Ask($"Write Server File for {mod.ModuleName}?");
}
protected virtual string GetServerNamespace(Module mod)
{
return SolutionName + ".React." + mod.ModuleName;
}
protected virtual string WriteServerClass(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("public static class " + mod.ModuleName + "Server");
sb.AppendLine("{");
sb.AppendLine();
sb.Append(WriteServerStartMethod(mod).Indent(2));
sb.AppendLine("}");
return sb.ToString();
}
protected virtual string WriteServerStartMethod(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("public static void Start()");
sb.AppendLine("{");
sb.AppendLine("}");
return sb.ToString();
}
protected virtual string? WriteControllerFile(Module mod)
{
if (!ShouldWriteControllerFile(mod))
return null;
StringBuilder sb = new StringBuilder();
foreach (var item in GetServerUsingNamespaces(mod))
sb.AppendLine("using {0};".FormatWith(item));
sb.AppendLine();
sb.AppendLine("namespace " + GetServerNamespace(mod) + ";");
sb.AppendLine();
sb.Append(WriteControllerClass(mod));
return sb.ToString();
}
protected virtual bool ShouldWriteControllerFile(Module mod)
{
return SafeConsole.Ask($"Write Controller File for {mod.ModuleName}?");
}
protected virtual string WriteControllerClass(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("public class " + mod.ModuleName + "Controller : ControllerBase");
sb.AppendLine("{");
sb.AppendLine();
sb.Append(WriteControllerExampleMethod(mod).Indent(2));
sb.AppendLine("}");
return sb.ToString();
}
protected virtual string WriteControllerExampleMethod(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine($"//[Route(\"api/{mod.ModuleName.ToLower()}/login\"), HttpPost]");
sb.AppendLine(@"//public MyResponse Login([Required, FromBody]MyRequest data)");
sb.AppendLine(@"//{");
sb.AppendLine(@"//}");
return sb.ToString();
}
protected virtual List<string> GetServerUsingNamespaces(Module mod)
{
var result = new List<string>()
{
};
result.AddRange(mod.Types.Select(t => t.Namespace!).Distinct());
return result;
}
protected virtual string WriteClientFile(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("import * as React from 'react'");
sb.AppendLine("import { Route } from 'react-router'");
sb.AppendLine("import { ajaxPost, ajaxGet } from '@framework/Services';");
sb.AppendLine("import { EntitySettings, ViewPromise } from '@framework/Navigator'");
sb.AppendLine("import * as Navigator from '@framework/Navigator'");
sb.AppendLine("import { EntityOperationSettings } from '@framework/Operations'");
sb.AppendLine("import * as Operations from '@framework/Operations'");
foreach (var gr in mod.Types.GroupBy(a => a.Namespace))
{
sb.AppendLine("import { "
+ gr.Select(t => t.Name).Chunk(5).ToString(a => a.ToString(", "), ",\r\n")
+ " } from './" + gr.Key + "'");
}
sb.AppendLine();
sb.AppendLine(WriteClientStartMethod(mod));
return sb.ToString();
}
protected virtual string WriteTypingsFile(Module mod)
{
return "";
}
protected virtual string WriteClientStartMethod(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("export function start(options: { routes: JSX.Element[] }) {");
sb.AppendLine("");
string entitySettings = WritetEntitySettings(mod);
if (entitySettings != null)
sb.Append(entitySettings.Indent(2));
sb.AppendLine();
string operationSettings = WriteOperationSettings(mod);
if (operationSettings != null)
sb.Append(operationSettings.Indent(2));
sb.AppendLine("}");
return sb.ToString();
}
protected virtual string WritetEntitySettings(Module mod)
{
StringBuilder sb = new StringBuilder();
foreach (var t in mod.Types)
{
string es = GetEntitySetting(t);
if (es != null)
sb.AppendLine(es);
}
return sb.ToString();
}
protected virtual string GetEntitySetting(Type type)
{
var v = GetVarName(type);
return "Navigator.addSettings(new EntitySettings({0}, {1} => import('./Templates/{2}')));".FormatWith(
type.Name, v, GetComponentName(type));
}
protected virtual string GetVarName(Type type)
{
return type.Name.Substring(0, 1).ToLower();
}
protected virtual string WriteOperationSettings(Module mod)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("//Operations.addSettings(new EntityOperationSettings(MyEntityOperations.Save, {}));");
return sb.ToString();
}
protected virtual string GetComponentName(Type type)
{
return Reflector.CleanTypeName(type);
}
protected virtual string WriteEntityComponentFile(Type type)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("import * as React from 'react'");
sb.AppendLine("import { " + type.Name + " } from '../" + type.Namespace + "'");
sb.AppendLine("import { TypeContext, ValueLine, EntityLine, EntityCombo, EntityList, EntityDetail, EntityStrip, EntityRepeater, EntityTable, FormGroup } from '@framework/Lines'");
sb.AppendLine("import { SearchControl, ValueSearchControl, FilterOperation, OrderType, PaginationMode } from '@framework/Search'");
var v = GetVarName(type);
if (this.GenerateFunctionalComponent(type))
{
sb.AppendLine();
sb.AppendLine("export default function {0}(p: {{ ctx: TypeContext<{1}> }}) {{".FormatWith(GetComponentName(type), type.Name));
sb.AppendLine("");
sb.AppendLine(" var ctx = p.ctx;");
sb.AppendLine(" return (");
sb.AppendLine(" <div>");
foreach (var pi in GetProperties(type))
{
string? prop = WriteProperty(pi, v);
if (prop != null)
sb.AppendLine(prop.Indent(6));
}
sb.AppendLine(" </div>");
sb.AppendLine(" );");
sb.AppendLine("}");
}
else
{
sb.AppendLine();
sb.AppendLine("export default class {0} extends React.Component<{{ ctx: TypeContext<{1}> }}> {{".FormatWith(GetComponentName(type), type.Name));
sb.AppendLine("");
sb.AppendLine(" render() {");
sb.AppendLine(" var ctx = this.props.ctx;");
sb.AppendLine(" return (");
sb.AppendLine(" <div>");
foreach (var pi in GetProperties(type))
{
string? prop = WriteProperty(pi, v);
if (prop != null)
sb.AppendLine(prop.Indent(8));
}
sb.AppendLine(" </div>");
sb.AppendLine(" );");
sb.AppendLine(" }");
sb.AppendLine("}");
}
return sb.ToString();
}
protected virtual bool GenerateFunctionalComponent(Type type)
{
return true;
}
protected virtual string? WriteProperty(PropertyInfo pi, string v)
{
if (pi.PropertyType.IsLite() || pi.PropertyType.IsIEntity())
return WriteEntityProperty(pi, v);
if (pi.PropertyType.IsEmbeddedEntity())
return WriteEmbeddedProperty(pi, v);
if (pi.PropertyType.IsMList())
return WriteMListProperty(pi, v);
if (IsValue(pi.PropertyType))
return WriteValueLine(pi, v);
return null;
}
protected virtual string WriteMListProperty(PropertyInfo pi, string v)
{
var elementType = pi.PropertyType.ElementType()!.CleanType();
if (!(elementType.IsLite() || elementType.IsModifiableEntity()))
return $"{{ /* {pi.PropertyType.TypeName()} not supported */ }}";
var eka = elementType.GetCustomAttribute<EntityKindAttribute>();
if (elementType.IsEmbeddedEntity() || !pi.PropertyType.ElementType()!.IsLite() && (eka!.EntityKind == EntityKind.Part || eka!.EntityKind == EntityKind.SharedPart))
if (pi.GetCustomAttribute<ImplementedByAttribute>()?.ImplementedTypes.Length > 1)
return "<EntityRepeater ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
else
return "<EntityTable ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
return "<EntityStrip ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
}
protected virtual string WriteEmbeddedProperty(PropertyInfo pi, string v)
{
return "<EntityDetail ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
}
protected virtual string WriteEntityProperty(PropertyInfo pi, string v)
{
Type type = pi.PropertyType.CleanType();
var eka = type.GetCustomAttribute<EntityKindAttribute>();
if (eka == null)
return "<EntityLine ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
if (!pi.PropertyType.IsLite() && (eka.EntityKind == EntityKind.Part || eka.EntityKind == EntityKind.SharedPart))
return "<EntityDetail ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
if (eka.IsLowPopulation)
return "<EntityCombo ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
return "<EntityLine ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
}
protected virtual bool IsValue(Type type)
{
type = type.UnNullify();
if (type.IsEnum)
return true;
if (type == typeof(TimeSpan) || type == typeof(DateOnly) || type == typeof(TimeOnly) || type == typeof(DateTimeOffset) || type == typeof(Guid))
return true;
TypeCode tc = Type.GetTypeCode(type);
return tc != TypeCode.DBNull &&
tc != TypeCode.Empty &&
tc != TypeCode.Object;
}
protected virtual string WriteValueLine(PropertyInfo pi, string v)
{
return "<ValueLine ctx={{ctx.subCtx({0} => {0}.{1})}} />".FormatWith(v, pi.Name.FirstLower());
}
protected virtual IEnumerable<PropertyInfo> GetProperties(Type type)
{
return Reflector.PublicInstanceDeclaredPropertiesInOrder(type).Where(pi =>
{
var ts = pi.GetCustomAttribute<InTypeScriptAttribute>();
if (ts != null)
{
var inTS = ts.GetInTypeScript();
if (inTS != null)
return inTS.Value;
}
if (pi.HasAttribute<HiddenPropertyAttribute>() || pi.HasAttribute<ExpressionFieldAttribute>())
return false;
return true;
});
}
}
| |
using System;
using System.Collections;
using CodeStage.AdvancedFPSCounter.CountersData;
using CodeStage.AdvancedFPSCounter.Label;
namespace CodeStage.AdvancedFPSCounter
{
using UnityEngine;
/// <summary>
/// Allows to see frames per second counter, memory usage counter and some simple hardware information right in running app on any device.
/// Just use GameObject->Create Other->Code Stage->Advanced FPS Counter (wooh, pretty long, yeah?) menu item and you're ready to go!
/// </summary>
[AddComponentMenu("")] // sorry, but you shouldn't add it via Component menu, read above comment please
public class AFPSCounter: MonoBehaviour
{
private const string CONTAINER_NAME = "Advanced FPS Counter";
#if !UNITY_FLASH
internal static string NEW_LINE = Environment.NewLine;
#else
internal const string NEW_LINE = "\n";
#endif
private static AFPSCounter instance = null;
/// <summary>
/// Frames Per Second counter.
/// </summary>
public FPSCounterData fpsCounter = new FPSCounterData();
/// <summary>
/// Mono or heap memory counter.
/// </summary>
public MemoryCounterData memoryCounter = new MemoryCounterData();
/// <summary>
/// Device hardware info.
/// Shows CPU name, cores (threads) count, GPU name, total VRAM, total RAM, screen DPI and screen size.
/// </summary>
public DeviceInfoCounterData deviceInfoCounter = new DeviceInfoCounterData();
[SerializeField]
private KeyCode hotKey = KeyCode.BackQuote;
/// <summary>
/// Allows to keep Advanced FPS Counter game object on new level (scene) load.
/// </summary>
public bool keepAlive = true;
[SerializeField]
private bool forceFrameRate = false;
[SerializeField]
[Range(-1, 200)]
private int forcedFrameRate = -1;
[SerializeField]
private Vector2 anchorsOffset = new Vector2(5,5);
[SerializeField]
private Font labelsFont;
[SerializeField]
[Range(0, 100)]
private int fontSize = 0;
[SerializeField]
[Range(0f, 10f)]
private float lineSpacing = 1;
internal DrawableLabel[] labels;
private int anchorsCount;
private int cachedVSync = -1;
private int cachedFrameRate = -1;
private Coroutine hotKeyCoroutine = null;
#if UNITY_EDITOR
[HideInInspector]
[SerializeField]
private bool fpsGroupToggle;
[HideInInspector]
[SerializeField]
private bool memoryGroupToggle;
[HideInInspector]
[SerializeField]
private bool deviceGroupToggle;
[HideInInspector]
[SerializeField]
private bool lookAndFeelToggle;
private const string MENU_PATH = "GameObject/Create Other/Code Stage/Advanced FPS Counter %&#F";
[UnityEditor.MenuItem(MENU_PATH, false)]
private static void AddToScene()
{
AFPSCounter counter = (AFPSCounter)FindObjectOfType(typeof(AFPSCounter));
if (counter != null)
{
if (counter.IsPlacedCorrectly())
{
if (UnityEditor.EditorUtility.DisplayDialog("Remove Advanced FPS Counter?", "Advanced FPS Counter already exists in scene and placed correctly. Dou you wish to remove it?", "Yes", "No"))
{
DestroyImmediate(counter.gameObject);
}
}
else
{
if (counter.MayBePlacedHere())
{
int dialogResult = UnityEditor.EditorUtility.DisplayDialogComplex("Fix existing Game Object to work with Adavnced FPS Counter?", "Advanced FPS Counter already exists in scene and placed onto empty Game Object \"" + counter.name + "\".\nDo you wish to let plugin configure and use this Game Object further? Press Delete to remove plugin from scene at all.", "Fix", "Delete", "Cancel");
switch (dialogResult)
{
case 0:
counter.FixCurrentGameObject();
break;
case 1:
DestroyImmediate(counter);
break;
default:
break;
}
}
else
{
int dialogResult = UnityEditor.EditorUtility.DisplayDialogComplex("Move existing Adavnced FPS Counter to own Game Object?", "Looks like Advanced FPS Counter plugin is already exists in scene and placed incorrectly on Game Object \"" + counter.name + "\".\nDo you wish to let plugin move itself onto separate configured Game Object \"" + CONTAINER_NAME + "\"? Press Delete to remove plugin from scene at all.", "Move", "Delete", "Cancel");
switch (dialogResult)
{
case 0:
GameObject go = new GameObject(CONTAINER_NAME);
AFPSCounter newCounter = go.AddComponent<AFPSCounter>();
UnityEditor.EditorUtility.CopySerialized(counter, newCounter);
DestroyImmediate(counter);
break;
case 1:
DestroyImmediate(counter);
break;
default:
break;
}
}
}
}
else
{
GameObject go = new GameObject(CONTAINER_NAME);
go.AddComponent<AFPSCounter>();
}
}
private bool MayBePlacedHere()
{
return (gameObject.GetComponentsInChildren<Component>().Length == 2 &&
transform.childCount == 0 &&
transform.parent == null);
}
private void FixCurrentGameObject()
{
gameObject.name = CONTAINER_NAME;
transform.position = Vector3.zero;
transform.rotation = Quaternion.identity;
transform.localScale = Vector3.one;
tag = "Untagged";
gameObject.layer = 0;
gameObject.isStatic = false;
}
#endif
/// <summary>
/// Allows to control %AFPSCounter from code. %AFPSCounter instance will be spawned if not exists.
/// </summary>
public static AFPSCounter Instance
{
get
{
if (instance == null)
{
AFPSCounter counter = (AFPSCounter)FindObjectOfType(typeof(AFPSCounter));
if (counter != null && counter.IsPlacedCorrectly())
{
//Debug.Log("AFPSCounter instance was found in scene!");
instance = counter;
}
else
{
//Debug.Log("AFPSCounter instance will be created right now!");
GameObject go = new GameObject(CONTAINER_NAME);
go.AddComponent<AFPSCounter>();
}
}
return instance;
}
}
/// <summary>
/// Allows to see how your game performs on specified frame rate.<br/>
/// <strong>\htmlonly<font color="7030A0">IMPORTANT:</font>\endhtmlonly this option disables VSync while enabled!</strong>
/// </summary>
/// Useful to check how physics performs on slow devices for example.
public bool ForceFrameRate
{
get { return forceFrameRate; }
set
{
if (forceFrameRate == value || !Application.isPlaying) return;
forceFrameRate = value;
if (!enabled) return;
RefreshForcedFrameRate();
}
}
/// <summary>
/// Desired frame rate for ForceFrameRate option, does not guarantee selected frame rate.
/// Set to -1 to render as fast as possible in current conditions.
/// </summary>
public int ForcedFrameRate
{
get { return forcedFrameRate; }
set
{
if (forcedFrameRate == value || !Application.isPlaying) return;
forcedFrameRate = value;
if (!enabled) return;
RefreshForcedFrameRate();
}
}
/// <summary>
/// Used to enable / disable plugin at runtime. Set to KeyCode.None to disable.
/// </summary>
public KeyCode HotKey
{
get { return hotKey; }
set
{
if (hotKey == value || !Application.isPlaying) return;
hotKey = value;
if (!enabled) return;
RefreshHotKey();
}
}
/// <summary>
/// Pixel offset for anchored labels. Automatically applied to all 4 corners.
/// </summary>
public Vector2 AnchorsOffset
{
get { return anchorsOffset; }
set
{
if (anchorsOffset == value || !Application.isPlaying) return;
anchorsOffset = value;
if (!enabled || labels == null) return;
for (int i = 0; i < anchorsCount; i++)
{
labels[i].ChangeOffset(anchorsOffset);
}
}
}
/// <summary>
/// Font to render labels with.
/// </summary>
public Font LabelsFont
{
get { return labelsFont; }
set
{
if (labelsFont == value || !Application.isPlaying) return;
labelsFont = value;
if (!enabled || labels == null) return;
for (int i = 0; i < anchorsCount; i++)
{
labels[i].ChangeFont(labelsFont);
}
}
}
/// <summary>
/// The font size to use (for dynamic fonts).
/// </summary>
/// If this is set to a non-zero value, the font size specified in the font importer is overriden with a custom size. This is only supported for fonts set to use dynamic font rendering. Other fonts will always use the default font size.
public int FontSize
{
get { return fontSize; }
set
{
if (fontSize == value || !Application.isPlaying) return;
fontSize = value;
if (!enabled || labels == null) return;
for (int i = 0; i < anchorsCount; i++)
{
labels[i].ChangeFontSize(fontSize);
}
}
}
/// <summary>
/// The font size to use (for dynamic fonts).
/// </summary>
/// If this is set to a non-zero value, the font size specified in the font importer is overriden with a custom size. This is only supported for fonts set to use dynamic font rendering. Other fonts will always use the default font size.
public float LineSpacing
{
get { return lineSpacing; }
set
{
if (lineSpacing == value || !Application.isPlaying) return;
lineSpacing = value;
if (!enabled || labels == null) return;
for (int i = 0; i < anchorsCount; i++)
{
labels[i].ChangeLineSpacing(lineSpacing);
}
}
}
// preventing direct instantiation =P
private AFPSCounter() { }
/// <summary>
/// Use it to completely dispose %AFPSCounter.
/// </summary>
public void Dispose()
{
instance = null;
Destroy(gameObject);
}
private void Awake()
{
if (instance != null)
{
Debug.LogWarning("Only one Advanced FPS Counter instance allowed!");
Destroy(gameObject);
return;
}
if (!IsPlacedCorrectly())
{
Debug.LogWarning("Advanced FPS Counter is placed in scene incorrectly and will be auto-destroyed! Please, use \"GameObject->Create Other->Code Stage->Advanced FPS Counter\" menu to correct this!");
Destroy(this);
return;
}
#if UNITY_EDITOR
Camera[] cameras = Camera.allCameras;
int len = cameras.Length;
float highestCameraDeph = float.MinValue;
float highestSuitableCameraDeph = float.MinValue;
for (int i = 0; i < len; i++)
{
Camera cam = cameras[i];
if (cam.depth > highestCameraDeph)
{
highestCameraDeph = cam.depth;
}
GUILayer guiLayer = cameras[i].GetComponent<GUILayer>();
if (guiLayer != null && guiLayer.enabled)
{
// checking if AFPSCounter's layer in the camera's culling mask
if ((cam.cullingMask & (1 << gameObject.layer)) != 0)
{
if (cam.depth > highestSuitableCameraDeph)
{
highestSuitableCameraDeph = cam.depth;
}
}
}
}
if (len == 0 || highestCameraDeph != highestSuitableCameraDeph)
{
Debug.LogWarning("Please check you have camera and your top-most (highest depth) camera\nhas enabled GUILayer and has layer " + LayerMask.LayerToName(gameObject.layer) + " in the camera's culling mask!");
}
#endif
instance = this;
DontDestroyOnLoad(gameObject);
anchorsCount = Enum.GetNames(typeof(LabelAnchor)).Length;
labels = new DrawableLabel[anchorsCount];
for (int i = 0; i < anchorsCount; i++)
{
labels[i] = new DrawableLabel((LabelAnchor)i, anchorsOffset, labelsFont, fontSize, lineSpacing);
}
RefreshHotKey();
}
private bool IsPlacedCorrectly()
{
return (gameObject.name == CONTAINER_NAME &&
gameObject.GetComponentsInChildren<Component>().Length == 2 &&
transform.childCount == 0 &&
transform.parent == null);
}
/// <summary>
/// For internal usage!
/// </summary>
internal void MakeDrawableLabelDirty(LabelAnchor anchor)
{
labels[(int)anchor].dirty = true;
}
/// <summary>
/// For internal usage!
/// </summary>
internal void UpdateTexts()
{
//Debug.Log("UpdateTexts " + Time.realtimeSinceStartup);
if (!enabled) return;
bool anyContentPresent = false;
//Debug.Log("UpdateTexts1 " + FPSCounter.Enabled);
//Debug.Log("UpdateTexts2 " + FPSCounter.text);
if (fpsCounter.Enabled)
{
DrawableLabel label = labels[(int)fpsCounter.Anchor];
if (label.newText.Length > 0) label.newText.Append(NEW_LINE);
label.newText.Append(fpsCounter.text);
label.dirty |= fpsCounter.dirty;
fpsCounter.dirty = false;
anyContentPresent = true;
}
if (memoryCounter.Enabled)
{
DrawableLabel label = labels[(int)memoryCounter.Anchor];
if (label.newText.Length > 0) label.newText.Append(NEW_LINE);
label.newText.Append(memoryCounter.text);
label.dirty |= memoryCounter.dirty;
memoryCounter.dirty = false;
anyContentPresent = true;
}
if (deviceInfoCounter.Enabled)
{
DrawableLabel label = labels[(int)deviceInfoCounter.Anchor];
if (label.newText.Length > 0) label.newText.Append(NEW_LINE);
label.newText.Append(deviceInfoCounter.text);
label.dirty |= deviceInfoCounter.dirty;
deviceInfoCounter.dirty = false;
anyContentPresent = true;
}
if (anyContentPresent)
{
for (int i = 0; i < anchorsCount; i++)
{
labels[i].CheckAndUpdate();
}
}
else
{
for (int i = 0; i < anchorsCount; i++)
{
labels[i].Clear();
}
}
}
private IEnumerator UpdateFPSCounter()
{
while (true)
{
float previousUpdateTime = Time.time;
int previousUpdateFrames = Time.frameCount;
yield return new WaitForSeconds(fpsCounter.UpdateInterval);
float timeElapsed = Time.time - previousUpdateTime;
int framesChanged = Time.frameCount - previousUpdateFrames;
// flooring FPS
int fps = (int)(framesChanged / (timeElapsed / Time.timeScale));
fpsCounter.UpdateValue(fps);
UpdateTexts();
}
}
private IEnumerator UpdateMemoryCounter()
{
while (true)
{
memoryCounter.UpdateValue();
UpdateTexts();
yield return new WaitForSeconds(memoryCounter.UpdateInterval);
}
}
private IEnumerator WaitForKeyDown()
{
while (true)
{
if (Input.GetKeyDown(hotKey))
{
SwitchCounter();
}
yield return null;
}
}
private void SwitchCounter()
{
enabled = !enabled;
}
private void InitCounters()
{
fpsCounter.Init();
memoryCounter.Init();
deviceInfoCounter.Init();
if (fpsCounter.Enabled || memoryCounter.Enabled || deviceInfoCounter.Enabled)
{
UpdateTexts();
}
}
private void UninitCounters()
{
if (instance == null) return;
fpsCounter.Uninit();
memoryCounter.Uninit();
deviceInfoCounter.Uninit();
}
private void RefreshForcedFrameRate()
{
RefreshForcedFrameRate(false);
}
private void RefreshForcedFrameRate(bool disabling)
{
if (forceFrameRate && !disabling)
{
if (cachedVSync == -1)
{
cachedVSync = QualitySettings.vSyncCount;
cachedFrameRate = Application.targetFrameRate;
QualitySettings.vSyncCount = 0;
}
Application.targetFrameRate = forcedFrameRate;
}
else
{
if (cachedVSync != -1)
{
QualitySettings.vSyncCount = cachedVSync;
Application.targetFrameRate = cachedFrameRate;
cachedVSync = -1;
}
}
}
private void RefreshHotKey()
{
if (hotKey != KeyCode.None)
{
if (hotKeyCoroutine == null)
{
hotKeyCoroutine = StartCoroutine(WaitForKeyDown());
}
else
{
StopCoroutine("WaitForKeyDown");
hotKeyCoroutine = StartCoroutine(WaitForKeyDown());
}
}
else
{
StopCoroutine("WaitForKeyDown");
hotKeyCoroutine = null;
}
}
private void OnLevelWasLoaded(int index)
{
if (!keepAlive)
{
Dispose();
}
else
{
if (fpsCounter.Enabled && fpsCounter.ShowAverage && fpsCounter.resetAverageOnNewScene)
{
fpsCounter.ResetAverage();
}
}
}
private void OnEnable()
{
InitCounters();
Invoke("RefreshForcedFrameRate", 0.5f);
}
private void OnDisable()
{
UninitCounters();
if (IsInvoking("RefreshForcedFrameRate")) CancelInvoke("RefreshForcedFrameRate");
RefreshForcedFrameRate(true);
for (int i = 0; i < anchorsCount; i++)
{
labels[i].Clear();
}
}
private void OnDestroy()
{
if (labels != null)
{
for (int i = 0; i < anchorsCount; i++)
{
labels[i].Dispose();
}
Array.Clear(labels, 0, anchorsCount);
labels = null;
}
}
/// <summary>
/// For internal usage!
/// </summary>
internal static string Color32ToHex(Color32 color)
{
return color.r.ToString("x2") + color.g.ToString("x2") + color.b.ToString("x2") + color.a.ToString("x2");
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ResumeTest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace DMLibTest
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using DMLibTestCodeGen;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.DataMovement;
using MS.Test.Common.MsTestLib;
[MultiDirectionTestClass]
public class ResumeTest : DMLibTestBase
#if DNXCORE50
, IDisposable
#endif
{
#region Initialization and cleanup methods
#if DNXCORE50
public ResumeTest()
{
MyTestInitialize();
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
MyTestCleanup();
}
#endif
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
Test.Info("Class Initialize: ResumeTest");
DMLibTestBase.BaseClassInitialize(testContext);
}
[ClassCleanup()]
public static void MyClassCleanup()
{
DMLibTestBase.BaseClassCleanup();
}
[TestInitialize()]
public void MyTestInitialize()
{
base.BaseTestInitialize();
}
[TestCleanup()]
public void MyTestCleanup()
{
base.BaseTestCleanup();
}
#endregion
[TestCategory(Tag.Function)]
[DMLibTestMethodSet(DMLibTestMethodSet.AllValidDirection)]
public void TestResume()
{
int fileSizeInKB = 100 * 1024;
DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);
DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName, fileSizeInKB);
CancellationTokenSource tokenSource = new CancellationTokenSource();
TransferItem transferItem = null;
var options = new TestExecutionOptions<DMLibDataInfo>();
options.LimitSpeed = true;
bool IsStreamJournal = random.Next(0, 2) == 0;
using (Stream journalStream = new MemoryStream())
{
TransferContext transferContext = IsStreamJournal ? new SingleTransferContext(journalStream) : new SingleTransferContext();
var progressChecker = new ProgressChecker(1, fileSizeInKB * 1024, 0, 1, 0, fileSizeInKB * 1024);
transferContext.ProgressHandler = progressChecker.GetProgressHandler();
options.TransferItemModifier = (fileName, item) =>
{
item.CancellationToken = tokenSource.Token;
item.TransferContext = transferContext;
transferItem = item;
};
TransferCheckpoint firstCheckpoint = null, secondCheckpoint = null;
options.AfterAllItemAdded = () =>
{
if (IsStreamJournal &&
(DMLibTestContext.SourceType == DMLibDataType.Stream
|| DMLibTestContext.DestType == DMLibDataType.Stream))
{
return;
}
// Wait until there are data transferred
progressChecker.DataTransferred.WaitOne();
// Store the first checkpoint
if (!IsStreamJournal)
{
firstCheckpoint = transferContext.LastCheckpoint;
}
Thread.Sleep(1000);
// Cancel the transfer and store the second checkpoint
tokenSource.Cancel();
};
// Cancel and store checkpoint for resume
var result = this.ExecuteTestCase(sourceDataInfo, options);
if (!IsStreamJournal)
{
secondCheckpoint = transferContext.LastCheckpoint;
}
else
{
if (DMLibTestContext.SourceType == DMLibDataType.Stream || DMLibTestContext.DestType == DMLibDataType.Stream)
{
Test.Assert(result.Exceptions.Count == 1, "Verify job is failed");
Exception jobException = result.Exceptions[0];
Test.Info("{0}", jobException);
VerificationHelper.VerifyExceptionErrorMessage(jobException, "Cannot deserialize to TransferLocation when its TransferLocationType is Stream.");
return;
}
}
Test.Assert(result.Exceptions.Count == 1, "Verify job is cancelled");
Exception exception = result.Exceptions[0];
VerificationHelper.VerifyExceptionErrorMessage(exception, "A task was canceled.");
TransferCheckpoint firstResumeCheckpoint = null, secondResumeCheckpoint = null;
ProgressChecker firstProgressChecker = null, secondProgressChecker = null;
if (!IsStreamJournal)
{
// DMLib doesn't support to resume transfer from a checkpoint which is inconsistent with
// the actual transfer progress when the destination is an append blob.
if (Helper.RandomBoolean() && (DMLibTestContext.DestType != DMLibDataType.AppendBlob || DMLibTestContext.IsAsync))
{
Test.Info("Resume with the first checkpoint first.");
firstResumeCheckpoint = firstCheckpoint;
secondResumeCheckpoint = secondCheckpoint;
}
else
{
Test.Info("Resume with the second checkpoint first.");
firstResumeCheckpoint = secondCheckpoint;
secondResumeCheckpoint = firstCheckpoint;
}
}
// first progress checker
if (DMLibTestContext.SourceType == DMLibDataType.Stream && DMLibTestContext.DestType != DMLibDataType.BlockBlob)
{
// The destination is already created, will cause a transfer skip
firstProgressChecker = new ProgressChecker(2, fileSizeInKB * 1024, 0, 1 /* failed */, 1 /* skipped */, fileSizeInKB * 1024);
}
else if (DMLibTestContext.DestType == DMLibDataType.Stream || (DMLibTestContext.SourceType == DMLibDataType.Stream && DMLibTestContext.DestType == DMLibDataType.BlockBlob))
{
firstProgressChecker = new ProgressChecker(2, 2 * fileSizeInKB * 1024, 1 /* transferred */, 1 /* failed */, 0, 2 * fileSizeInKB * 1024);
}
else
{
firstProgressChecker = new ProgressChecker(1, fileSizeInKB * 1024, 1, 0, 0, fileSizeInKB * 1024);
}
// second progress checker
if (DMLibTestContext.SourceType == DMLibDataType.Stream)
{
// The destination is already created, will cause a transfer skip
secondProgressChecker = new ProgressChecker(2, fileSizeInKB * 1024, 0, 1 /* failed */, 1 /* skipped */, fileSizeInKB * 1024);
}
else if (DMLibTestContext.DestType == DMLibDataType.Stream)
{
secondProgressChecker = new ProgressChecker(2, 2 * fileSizeInKB * 1024, 1 /* transferred */, 1 /* failed */, 0, 2 * fileSizeInKB * 1024);
}
else if (DMLibTestContext.DestType == DMLibDataType.AppendBlob && !DMLibTestContext.IsAsync)
{
secondProgressChecker = new ProgressChecker(1, fileSizeInKB * 1024, 0, 1 /* failed */, 0, fileSizeInKB * 1024);
}
else
{
secondProgressChecker = new ProgressChecker(1, fileSizeInKB * 1024, 1 /* transferred */, 0, 0, fileSizeInKB * 1024);
}
// resume with firstResumeCheckpoint
TransferItem resumeItem = transferItem.Clone();
TransferContext resumeContext = null;
if (IsStreamJournal)
{
Exception deserializeEX = null;
try
{
resumeContext = new SingleTransferContext(journalStream)
{
ProgressHandler = firstProgressChecker.GetProgressHandler()
};
}
catch (Exception ex)
{
if ((DMLibTestContext.SourceType != DMLibDataType.Stream)
&& (DMLibTestContext.DestType != DMLibDataType.Stream))
{
Test.Error("Should no exception in deserialization when no target is stream.");
}
deserializeEX = ex;
}
}
else
{
resumeContext = new SingleTransferContext(IsStreamDirection() ? firstResumeCheckpoint : DMLibTestHelper.RandomReloadCheckpoint(firstResumeCheckpoint))
{
ProgressHandler = firstProgressChecker.GetProgressHandler()
};
}
resumeItem.TransferContext = resumeContext;
result = this.RunTransferItems(new List<TransferItem>() { resumeItem }, new TestExecutionOptions<DMLibDataInfo>());
if (DMLibTestContext.SourceType == DMLibDataType.Stream && DMLibTestContext.DestType != DMLibDataType.BlockBlob)
{
Test.Assert(result.Exceptions.Count == 1, "Verify transfer is skipped when source is stream.");
exception = result.Exceptions[0];
VerificationHelper.VerifyTransferException(result.Exceptions[0], TransferErrorCode.NotOverwriteExistingDestination, "Skiped file");
}
else
{
// For sync copy, recalculate md5 of destination by downloading the file to local.
if (IsCloudService(DMLibTestContext.DestType) && !DMLibTestContext.IsAsync)
{
DMLibDataHelper.SetCalculatedFileMD5(result.DataInfo, DestAdaptor);
}
VerificationHelper.VerifySingleObjectResumeResult(result, sourceDataInfo);
}
if (!IsStreamJournal)
{
// resume with secondResumeCheckpoint
resumeItem = transferItem.Clone();
resumeContext = new SingleTransferContext(
IsStreamDirection() ? secondResumeCheckpoint : DMLibTestHelper.RandomReloadCheckpoint(secondResumeCheckpoint))
{
ProgressHandler = secondProgressChecker.GetProgressHandler()
};
resumeItem.TransferContext = resumeContext;
result = this.RunTransferItems(new List<TransferItem>() { resumeItem }, new TestExecutionOptions<DMLibDataInfo>());
if (DMLibTestContext.SourceType == DMLibDataType.Stream)
{
Test.Assert(result.Exceptions.Count == 1, "Verify transfer is skipped when source is stream.");
exception = result.Exceptions[0];
VerificationHelper.VerifyTransferException(result.Exceptions[0], TransferErrorCode.NotOverwriteExistingDestination, "Skiped file");
}
else if (DMLibTestContext.DestType == DMLibDataType.AppendBlob && !DMLibTestContext.IsAsync)
{
Test.Assert(result.Exceptions.Count == 1, "Verify reumse fails when checkpoint is inconsistent with the actual progress when destination is append blob.");
exception = result.Exceptions[0];
Test.Assert(exception is InvalidOperationException, "Verify reumse fails when checkpoint is inconsistent with the actual progress when destination is append blob.");
VerificationHelper.VerifyExceptionErrorMessage(exception, "Destination might be changed by other process or application.");
}
else
{
// For sync copy, recalculate md5 of destination by downloading the file to local.
if (IsCloudService(DMLibTestContext.DestType) && !DMLibTestContext.IsAsync)
{
DMLibDataHelper.SetCalculatedFileMD5(result.DataInfo, DestAdaptor);
}
VerificationHelper.VerifySingleObjectResumeResult(result, sourceDataInfo);
}
}
}
}
[TestCategory(Tag.Function)]
[DMLibTestMethodSet(DMLibTestMethodSet.DirAllValidDirection)]
public void TestDirectoryResume()
{
int bigFileSizeInKB = 5 * 1024; // 5 MB
int smallFileSizeInKB = 1; // 1 KB
int bigFileNum = 5;
int smallFileNum = 50;
long totalSizeInBytes = (bigFileSizeInKB * bigFileNum + smallFileSizeInKB * smallFileNum) * 1024;
int totalFileNum = bigFileNum + smallFileNum;
DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);
DirNode bigFileDirNode = new DirNode("big");
DirNode smallFileDirNode = new DirNode("small");
sourceDataInfo.RootNode.AddDirNode(bigFileDirNode);
sourceDataInfo.RootNode.AddDirNode(smallFileDirNode);
DMLibDataHelper.AddMultipleFiles(bigFileDirNode, FileName, bigFileNum, bigFileSizeInKB);
DMLibDataHelper.AddMultipleFiles(smallFileDirNode, FileName, smallFileNum, smallFileSizeInKB);
CancellationTokenSource tokenSource = new CancellationTokenSource();
TransferItem transferItem = null;
var options = new TestExecutionOptions<DMLibDataInfo>();
options.LimitSpeed = true;
options.IsDirectoryTransfer = true;
using (Stream journalStream = new MemoryStream())
{
bool IsStreamJournal = random.Next(0, 2) == 0;
var transferContext = IsStreamJournal ? new DirectoryTransferContext(journalStream) : new DirectoryTransferContext();
var progressChecker = new ProgressChecker(totalFileNum, totalSizeInBytes, totalFileNum, null, 0, totalSizeInBytes);
transferContext.ProgressHandler = progressChecker.GetProgressHandler();
var eventChecker = new TransferEventChecker();
eventChecker.Apply(transferContext);
transferContext.FileFailed += (sender, e) =>
{
Test.Assert(e.Exception.Message.Contains("cancel"), "Verify task is canceled: {0}", e.Exception.Message);
};
options.TransferItemModifier = (fileName, item) =>
{
dynamic dirOptions = DefaultTransferDirectoryOptions;
dirOptions.Recursive = true;
item.Options = dirOptions;
item.CancellationToken = tokenSource.Token;
item.TransferContext = transferContext;
transferItem = item;
};
TransferCheckpoint firstCheckpoint = null, secondCheckpoint = null;
options.AfterAllItemAdded = () =>
{
// Wait until there are data transferred
progressChecker.DataTransferred.WaitOne();
if (!IsStreamJournal)
{
// Store the first checkpoint
firstCheckpoint = transferContext.LastCheckpoint;
}
Thread.Sleep(1000);
// Cancel the transfer and store the second checkpoint
tokenSource.Cancel();
};
// Cancel and store checkpoint for resume
var result = this.ExecuteTestCase(sourceDataInfo, options);
if (progressChecker.FailedFilesNumber <= 0)
{
Test.Error("Verify file number in progress. Failed: {0}", progressChecker.FailedFilesNumber);
}
TransferCheckpoint firstResumeCheckpoint = null, secondResumeCheckpoint = null;
if (!IsStreamJournal)
{
secondCheckpoint = transferContext.LastCheckpoint;
Test.Info("Resume with the second checkpoint first.");
firstResumeCheckpoint = secondCheckpoint;
secondResumeCheckpoint = firstCheckpoint;
}
// resume with firstResumeCheckpoint
TransferItem resumeItem = transferItem.Clone();
progressChecker.Reset();
TransferContext resumeContext = null;
if (IsStreamJournal)
{
resumeContext = new DirectoryTransferContext(journalStream)
{
ProgressHandler = progressChecker.GetProgressHandler()
};
}
else
{
resumeContext = new DirectoryTransferContext(DMLibTestHelper.RandomReloadCheckpoint(firstResumeCheckpoint))
{
ProgressHandler = progressChecker.GetProgressHandler()
};
}
eventChecker.Reset();
eventChecker.Apply(resumeContext);
resumeItem.TransferContext = resumeContext;
result = this.RunTransferItems(new List<TransferItem>() { resumeItem }, new TestExecutionOptions<DMLibDataInfo>());
VerificationHelper.VerifyFinalProgress(progressChecker, totalFileNum, 0, 0);
VerificationHelper.VerifySingleTransferStatus(result, totalFileNum, 0, 0, totalSizeInBytes);
VerificationHelper.VerifyTransferSucceed(result, sourceDataInfo);
if (!IsStreamJournal)
{
// resume with secondResumeCheckpoint
resumeItem = transferItem.Clone();
progressChecker.Reset();
resumeContext = new DirectoryTransferContext(DMLibTestHelper.RandomReloadCheckpoint(secondResumeCheckpoint))
{
ProgressHandler = progressChecker.GetProgressHandler(),
// Need this overwrite callback since some files is already transferred to destination
ShouldOverwriteCallback = DMLibInputHelper.GetDefaultOverwiteCallbackY(),
};
eventChecker.Reset();
eventChecker.Apply(resumeContext);
resumeItem.TransferContext = resumeContext;
result = this.RunTransferItems(new List<TransferItem>() { resumeItem }, new TestExecutionOptions<DMLibDataInfo>());
VerificationHelper.VerifyFinalProgress(progressChecker, totalFileNum, 0, 0);
VerificationHelper.VerifySingleTransferStatus(result, totalFileNum, 0, 0, totalSizeInBytes);
VerificationHelper.VerifyTransferSucceed(result, sourceDataInfo);
}
}
}
private static bool IsStreamDirection()
{
return DMLibTestContext.DestType == DMLibDataType.Stream || DMLibTestContext.SourceType == DMLibDataType.Stream;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using NServiceKit.Common.Extensions;
using NServiceKit.Text;
namespace NServiceKit.Redis.Tests
{
[TestFixture, Category("Integration")]
public class RedisClientSortedSetTests
: RedisClientTestsBase
{
private const string SetIdSuffix = "testzset";
private List<string> storeMembers;
private string SetId
{
get
{
return PrefixedKey(SetIdSuffix);
}
}
Dictionary<string, double> stringDoubleMap;
public override void OnBeforeEachTest()
{
base.OnBeforeEachTest();
Redis.NamespacePrefix = "RedisClientSortedSetTests";
storeMembers = new List<string> { "one", "two", "three", "four" };
stringDoubleMap = new Dictionary<string, double> {
{"one",1}, {"two",2}, {"three",3}, {"four",4}
};
}
[Test]
public void Can_AddItemToSortedSet_and_GetAllFromSet()
{
var i = 0;
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x, i++));
var members = Redis.GetAllItemsFromSortedSet(SetId);
Assert.That(members.EquivalentTo(storeMembers), Is.True);
}
[Test]
public void Can_AddRangeToSortedSet_and_GetAllFromSet()
{
var success = Redis.AddRangeToSortedSet(SetId, storeMembers, 1);
Assert.That(success, Is.True);
var members = Redis.GetAllItemsFromSortedSet(SetId);
Assert.That(members, Is.EquivalentTo(storeMembers));
}
[Test]
public void Can_AddRangeToSortedSetWithScores_and_GetAllFromSet()
{
var count = Redis.AddRangeToSortedSetWithScores(SetId, storeMembers.Select(x => new KeyValuePair<string, double>(x, 1)).ToList());
Assert.AreEqual(storeMembers.Count, count);
var members = Redis.GetAllItemsFromSortedSet(SetId);
Assert.That(members, Is.EquivalentTo(storeMembers));
}
[Test]
public void Can_AddRangeToSortedSetWithScores_and_GetAllWithScoresFromSortedSet()
{
uint i = 0;
var count = Redis.AddRangeToSortedSetWithScores(SetId, storeMembers.Select(x => new KeyValuePair<string, double>(x, i++)).ToList());
Assert.AreEqual(storeMembers.Count, count);
var members = Redis.GetAllWithScoresFromSortedSet(SetId);
i = 0;
foreach(var member in storeMembers)
{
Assert.IsTrue(members.ContainsKey(member));
Assert.AreEqual(i++, members[member]);
}
}
[Test]
public void AddToSet_without_score_adds_an_implicit_lexical_order_score()
{
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x));
var members = Redis.GetAllItemsFromSortedSet(SetId);
storeMembers.Sort((x, y) => x.CompareTo(y));
Assert.That(members.EquivalentTo(storeMembers), Is.True);
}
[Test]
public void AddToSet_with_same_score_is_still_returned_in_lexical_order_score()
{
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x, 1));
var members = Redis.GetAllItemsFromSortedSet(SetId);
storeMembers.Sort((x, y) => x.CompareTo(y));
Assert.That(members.EquivalentTo(storeMembers));
}
[Test]
public void Can_RemoveFromSet()
{
const string removeMember = "two";
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x));
Redis.RemoveItemFromSortedSet(SetId, removeMember);
storeMembers.Remove(removeMember);
var members = Redis.GetAllItemsFromSortedSet(SetId);
Assert.That(members, Is.EquivalentTo(storeMembers));
}
[Test]
public void Can_PopFromSet()
{
var i = 0;
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x, i++));
var member = Redis.PopItemWithHighestScoreFromSortedSet(SetId);
Assert.That(member, Is.EqualTo("four"));
}
[Test]
public void Can_GetSetCount()
{
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x));
var setCount = Redis.GetSortedSetCount(SetId);
Assert.That(setCount, Is.EqualTo(storeMembers.Count));
}
[Test]
public void Can_GetSetCountByScores()
{
var scores = new List<double>();
storeMembers.ForEach(x =>
{
Redis.AddItemToSortedSet(SetId, x);
scores.Add(RedisClient.GetLexicalScore(x));
});
Assert.That(Redis.GetSortedSetCount(SetId, scores.Min(), scores.Max()), Is.EqualTo(storeMembers.Count()));
Assert.That(Redis.GetSortedSetCount(SetId, scores.Min(), scores.Min()), Is.EqualTo(1));
}
[Test]
public void Does_SortedSetContainsValue()
{
const string existingMember = "two";
const string nonExistingMember = "five";
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x));
Assert.That(Redis.SortedSetContainsItem(SetId, existingMember), Is.True);
Assert.That(Redis.SortedSetContainsItem(SetId, nonExistingMember), Is.False);
}
[Test]
public void Can_GetItemIndexInSortedSet_in_Asc_and_Desc()
{
var i = 10;
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x, i++));
Assert.That(Redis.GetItemIndexInSortedSet(SetId, "one"), Is.EqualTo(0));
Assert.That(Redis.GetItemIndexInSortedSet(SetId, "two"), Is.EqualTo(1));
Assert.That(Redis.GetItemIndexInSortedSet(SetId, "three"), Is.EqualTo(2));
Assert.That(Redis.GetItemIndexInSortedSet(SetId, "four"), Is.EqualTo(3));
Assert.That(Redis.GetItemIndexInSortedSetDesc(SetId, "one"), Is.EqualTo(3));
Assert.That(Redis.GetItemIndexInSortedSetDesc(SetId, "two"), Is.EqualTo(2));
Assert.That(Redis.GetItemIndexInSortedSetDesc(SetId, "three"), Is.EqualTo(1));
Assert.That(Redis.GetItemIndexInSortedSetDesc(SetId, "four"), Is.EqualTo(0));
}
[Test]
public void Can_Store_IntersectBetweenSets()
{
string set1Name = PrefixedKey("testintersectset1");
string set2Name = PrefixedKey("testintersectset2");
string storeSetName = PrefixedKey("testintersectsetstore");
var set1Members = new List<string> { "one", "two", "three", "four", "five" };
var set2Members = new List<string> { "four", "five", "six", "seven" };
set1Members.ForEach(x => Redis.AddItemToSortedSet(set1Name, x));
set2Members.ForEach(x => Redis.AddItemToSortedSet(set2Name, x));
Redis.StoreIntersectFromSortedSets(storeSetName, set1Name, set2Name);
var intersectingMembers = Redis.GetAllItemsFromSortedSet(storeSetName);
Assert.That(intersectingMembers, Is.EquivalentTo(new List<string> { "four", "five" }));
}
[Test]
public void Can_Store_IntersectBetweenSetsWithWeights()
{
string set1Name = PrefixedKey("testintersectset1");
string set2Name = PrefixedKey("testintersectset2");
string storeSetName = PrefixedKey("testintersectsetstore");
Redis.AddItemToSortedSet(set1Name, "three", 3.0);
Redis.AddItemToSortedSet(set1Name, "four", 2.0);
Redis.AddItemToSortedSet(set2Name, "four", 2.0);
Redis.AddItemToSortedSet(set2Name, "three", 1.0);
Redis.StoreIntersectFromSortedSetsWithWeights(storeSetName,
new KeyValuePair<string, double>(set1Name, 1.0),
new KeyValuePair<string, double>(set2Name, 3.0)
);
var intersectingMembers = Redis.GetAllWithScoresFromSortedSet(storeSetName);
Assert.AreEqual(2, intersectingMembers.Count);
Assert.AreEqual(6.0, intersectingMembers["three"]);
Assert.AreEqual(8.0, intersectingMembers["four"]);
}
[Test]
public void Can_Store_UnionBetweenSetsWithWeights()
{
string set1Name = PrefixedKey("testintersectset1");
string set2Name = PrefixedKey("testintersectset2");
string storeSetName = PrefixedKey("testintersectsetstore");
Redis.AddItemToSortedSet(set1Name, "one", 10.0);
Redis.AddItemToSortedSet(set1Name, "three", 3.0);
Redis.AddItemToSortedSet(set1Name, "four", 2.0);
Redis.AddItemToSortedSet(set2Name, "four", 2.0);
Redis.AddItemToSortedSet(set2Name, "three", 1.0);
Redis.StoreUnionFromSortedSetsWithWeights(storeSetName,
new KeyValuePair<string, double>(set1Name, 1.0),
new KeyValuePair<string, double>(set2Name, 3.0)
);
var intersectingMembers = Redis.GetAllWithScoresFromSortedSet(storeSetName);
Assert.AreEqual(3, intersectingMembers.Count);
Assert.AreEqual(6.0, intersectingMembers["three"]);
Assert.AreEqual(8.0, intersectingMembers["four"]);
Assert.AreEqual(10.0, intersectingMembers["one"]);
}
[Test]
public void Can_Store_UnionBetweenSets()
{
string set1Name = PrefixedKey("testunionset1");
string set2Name = PrefixedKey("testunionset2");
string storeSetName = PrefixedKey("testunionsetstore");
var set1Members = new List<string> { "one", "two", "three", "four", "five" };
var set2Members = new List<string> { "four", "five", "six", "seven" };
set1Members.ForEach(x => Redis.AddItemToSortedSet(set1Name, x));
set2Members.ForEach(x => Redis.AddItemToSortedSet(set2Name, x));
Redis.StoreUnionFromSortedSets(storeSetName, set1Name, set2Name);
var unionMembers = Redis.GetAllItemsFromSortedSet(storeSetName);
Assert.That(unionMembers, Is.EquivalentTo(
new List<string> { "one", "two", "three", "four", "five", "six", "seven" }));
}
[Test]
public void Can_pop_items_with_lowest_and_highest_scores_from_sorted_set()
{
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x));
storeMembers.Sort((x, y) => x.CompareTo(y));
var lowestScore = Redis.PopItemWithLowestScoreFromSortedSet(SetId);
Assert.That(lowestScore, Is.EqualTo(storeMembers.First()));
var highestScore = Redis.PopItemWithHighestScoreFromSortedSet(SetId);
Assert.That(highestScore, Is.EqualTo(storeMembers[storeMembers.Count - 1]));
}
[Test]
public void Can_GetRangeFromSortedSetByLowestScore_from_sorted_set()
{
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x));
storeMembers.Sort((x, y) => x.CompareTo(y));
var memberRage = storeMembers.Where(x =>
x.CompareTo("four") >= 0 && x.CompareTo("three") <= 0).ToList();
var range = Redis.GetRangeFromSortedSetByLowestScore(SetId, "four", "three");
Assert.That(range.EquivalentTo(memberRage));
}
[Test]
public void Can_IncrementItemInSortedSet()
{
stringDoubleMap.ForEach(x => Redis.AddItemToSortedSet(SetId, x.Key, x.Value));
var currentScore = Redis.IncrementItemInSortedSet(SetId, "one", 2);
stringDoubleMap["one"] = stringDoubleMap["one"] + 2;
Assert.That(currentScore, Is.EqualTo(stringDoubleMap["one"]));
currentScore = Redis.IncrementItemInSortedSet(SetId, "four", -2);
stringDoubleMap["four"] = stringDoubleMap["four"] - 2;
Assert.That(currentScore, Is.EqualTo(stringDoubleMap["four"]));
var map = Redis.GetAllWithScoresFromSortedSet(SetId);
Assert.That(stringDoubleMap.EquivalentTo(map));
Debug.WriteLine(map.Dump());
}
[Test]
public void Can_WorkInSortedSetUnderDifferentCulture()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("ru-RU");
Redis.AddItemToSortedSet(SetId, "key", 123.22);
var map = Redis.GetAllWithScoresFromSortedSet(SetId);
Assert.AreEqual(123.22, map["key"]);
}
[Ignore("Not implemented yet")]
[Test]
public void Can_GetRangeFromSortedSetByHighestScore_from_sorted_set()
{
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x));
storeMembers.Sort((x, y) => y.CompareTo(x));
var memberRage = storeMembers.Where(x =>
x.CompareTo("four") >= 0 && x.CompareTo("three") <= 0).ToList();
var range = Redis.GetRangeFromSortedSetByHighestScore(SetId, "four", "three");
Assert.That(range.EquivalentTo(memberRage));
}
[Test]
public void Can_get_index_and_score_from_SortedSet()
{
storeMembers = new List<string> { "a", "b", "c", "d" };
const double initialScore = 10d;
var i = initialScore;
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x, i++));
Assert.That(Redis.GetItemIndexInSortedSet(SetId, "a"), Is.EqualTo(0));
Assert.That(Redis.GetItemIndexInSortedSetDesc(SetId, "a"), Is.EqualTo(storeMembers.Count - 1));
Assert.That(Redis.GetItemScoreInSortedSet(SetId, "a"), Is.EqualTo(initialScore));
Assert.That(Redis.GetItemScoreInSortedSet(SetId, "d"), Is.EqualTo(initialScore + storeMembers.Count - 1));
}
[Test]
public void Can_enumerate_small_ICollection_Set()
{
storeMembers.ForEach(x => Redis.AddItemToSortedSet(SetId, x));
var members = new List<string>();
foreach (var item in Redis.SortedSets[SetId])
{
members.Add(item);
}
members.Sort();
Assert.That(members.Count, Is.EqualTo(storeMembers.Count));
Assert.That(members, Is.EquivalentTo(storeMembers));
}
[Test]
public void Can_enumerate_large_ICollection_Set()
{
if (TestConfig.IgnoreLongTests) return;
const int setSize = 2500;
storeMembers = new List<string>();
setSize.Times(x =>
{
Redis.AddItemToSortedSet(SetId, x.ToString());
storeMembers.Add(x.ToString());
});
var members = new List<string>();
foreach (var item in Redis.SortedSets[SetId])
{
members.Add(item);
}
members.Sort((x, y) => int.Parse(x).CompareTo(int.Parse(y)));
Assert.That(members.Count, Is.EqualTo(storeMembers.Count));
Assert.That(members, Is.EquivalentTo(storeMembers));
}
[Test]
public void Can_Add_to_ICollection_Set()
{
var list = Redis.SortedSets[SetId];
storeMembers.ForEach(list.Add);
var members = list.ToList<string>();
Assert.That(members, Is.EquivalentTo(storeMembers));
}
[Test]
public void Can_Clear_ICollection_Set()
{
var list = Redis.SortedSets[SetId];
storeMembers.ForEach(list.Add);
Assert.That(list.Count, Is.EqualTo(storeMembers.Count));
list.Clear();
Assert.That(list.Count, Is.EqualTo(0));
}
[Test]
public void Can_Test_Contains_in_ICollection_Set()
{
var list = Redis.SortedSets[SetId];
storeMembers.ForEach(list.Add);
Assert.That(list.Contains("two"), Is.True);
Assert.That(list.Contains("five"), Is.False);
}
[Test]
public void Can_Remove_value_from_ICollection_Set()
{
var list = Redis.SortedSets[SetId];
storeMembers.ForEach(list.Add);
storeMembers.Remove("two");
list.Remove("two");
var members = list.ToList();
Assert.That(members, Is.EquivalentTo(storeMembers));
}
[Test]
public void Score_from_non_existent_item_returns_NaN()
{
var score = Redis.GetItemScoreInSortedSet("nonexistentset", "value");
Assert.That(score, Is.EqualTo(Double.NaN));
}
[Test]
public void Can_add_large_score_to_sortedset()
{
Redis.AddItemToSortedSet(SetId, "value", 12345678901234567890d);
var score = Redis.GetItemScoreInSortedSet(SetId, "value");
Assert.That(score, Is.EqualTo(12345678901234567890d));
}
}
}
| |
namespace Azure.Storage.Queues
{
public partial class QueueClient
{
protected QueueClient() { }
public QueueClient(string connectionString, string queueName) { }
public QueueClient(string connectionString, string queueName, Azure.Storage.Queues.QueueClientOptions options) { }
public QueueClient(System.Uri queueUri, Azure.AzureSasCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueClient(System.Uri queueUri, Azure.Core.TokenCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueClient(System.Uri queueUri, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueClient(System.Uri queueUri, Azure.Storage.StorageSharedKeyCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public virtual string AccountName { get { throw null; } }
public virtual bool CanGenerateSasUri { get { throw null; } }
public virtual int MaxPeekableMessages { get { throw null; } }
public virtual int MessageMaxBytes { get { throw null; } }
protected virtual System.Uri MessagesUri { get { throw null; } }
public virtual string Name { get { throw null; } }
public virtual System.Uri Uri { get { throw null; } }
public virtual Azure.Response ClearMessages(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> ClearMessagesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response Create(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> CreateAsync(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response CreateIfNotExists(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> CreateIfNotExistsAsync(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response Delete(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<bool> DeleteIfExists(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<bool>> DeleteIfExistsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response DeleteMessage(string messageId, string popReceipt, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteMessageAsync(string messageId, string popReceipt, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<bool> Exists(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Uri GenerateSasUri(Azure.Storage.Sas.QueueSasBuilder builder) { throw null; }
public virtual System.Uri GenerateSasUri(Azure.Storage.Sas.QueueSasPermissions permissions, System.DateTimeOffset expiresOn) { throw null; }
public virtual Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier>> GetAccessPolicy(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier>>> GetAccessPolicyAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
protected internal virtual Azure.Storage.Queues.QueueServiceClient GetParentQueueServiceClientCore() { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueProperties> GetProperties(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueProperties>> GetPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
protected virtual System.Threading.Tasks.Task OnMessageDecodingFailedAsync(Azure.Storage.Queues.Models.QueueMessage receivedMessage, Azure.Storage.Queues.Models.PeekedMessage peekedMessage, bool isRunningSynchronously, System.Threading.CancellationToken cancellationToken) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.PeekedMessage> PeekMessage(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.PeekedMessage>> PeekMessageAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.PeekedMessage[]> PeekMessages(int? maxMessages = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.PeekedMessage[]>> PeekMessagesAsync(int? maxMessages = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage> ReceiveMessage(System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage>> ReceiveMessageAsync(System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages() { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages(int? maxMessages = default(int?), System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync() { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync(int? maxMessages = default(int?), System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(System.BinaryData message, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(System.BinaryData message, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response SetAccessPolicy(System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier> permissions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> SetAccessPolicyAsync(System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier> permissions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response SetMetadata(System.Collections.Generic.IDictionary<string, string> metadata, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> SetMetadataAsync(System.Collections.Generic.IDictionary<string, string> metadata, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt> UpdateMessage(string messageId, string popReceipt, System.BinaryData message, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt> UpdateMessage(string messageId, string popReceipt, string messageText = null, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt>> UpdateMessageAsync(string messageId, string popReceipt, System.BinaryData message, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt>> UpdateMessageAsync(string messageId, string popReceipt, string messageText = null, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
protected internal virtual Azure.Storage.Queues.QueueClient WithClientSideEncryptionOptionsCore(Azure.Storage.ClientSideEncryptionOptions clientSideEncryptionOptions) { throw null; }
}
public partial class QueueClientOptions : Azure.Core.ClientOptions
{
public QueueClientOptions(Azure.Storage.Queues.QueueClientOptions.ServiceVersion version = Azure.Storage.Queues.QueueClientOptions.ServiceVersion.V2021_04_10) { }
public bool EnableTenantDiscovery { get { throw null; } set { } }
public System.Uri GeoRedundantSecondaryUri { get { throw null; } set { } }
public Azure.Storage.Queues.QueueMessageEncoding MessageEncoding { get { throw null; } set { } }
public Azure.Storage.Queues.QueueClientOptions.ServiceVersion Version { get { throw null; } }
public event Azure.Core.SyncAsyncEventHandler<Azure.Storage.Queues.QueueMessageDecodingFailedEventArgs> MessageDecodingFailed { add { } remove { } }
public enum ServiceVersion
{
V2019_02_02 = 1,
V2019_07_07 = 2,
V2019_12_12 = 3,
V2020_02_10 = 4,
V2020_04_08 = 5,
V2020_06_12 = 6,
V2020_08_04 = 7,
V2020_10_02 = 8,
V2020_12_06 = 9,
V2021_02_12 = 10,
V2021_04_10 = 11,
}
}
public partial class QueueMessageDecodingFailedEventArgs : Azure.SyncAsyncEventArgs
{
public QueueMessageDecodingFailedEventArgs(Azure.Storage.Queues.QueueClient queueClient, Azure.Storage.Queues.Models.QueueMessage receivedMessage, Azure.Storage.Queues.Models.PeekedMessage peekedMessage, bool isRunningSynchronously, System.Threading.CancellationToken cancellationToken) : base (default(bool), default(System.Threading.CancellationToken)) { }
public Azure.Storage.Queues.Models.PeekedMessage PeekedMessage { get { throw null; } }
public Azure.Storage.Queues.QueueClient Queue { get { throw null; } }
public Azure.Storage.Queues.Models.QueueMessage ReceivedMessage { get { throw null; } }
}
public enum QueueMessageEncoding
{
None = 0,
Base64 = 1,
}
public partial class QueueServiceClient
{
protected QueueServiceClient() { }
public QueueServiceClient(string connectionString) { }
public QueueServiceClient(string connectionString, Azure.Storage.Queues.QueueClientOptions options) { }
public QueueServiceClient(System.Uri serviceUri, Azure.AzureSasCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueServiceClient(System.Uri serviceUri, Azure.Core.TokenCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueServiceClient(System.Uri serviceUri, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueServiceClient(System.Uri serviceUri, Azure.Storage.StorageSharedKeyCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public virtual string AccountName { get { throw null; } }
public virtual bool CanGenerateAccountSasUri { get { throw null; } }
public virtual System.Uri Uri { get { throw null; } }
public virtual Azure.Response<Azure.Storage.Queues.QueueClient> CreateQueue(string queueName, System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.QueueClient>> CreateQueueAsync(string queueName, System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response DeleteQueue(string queueName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteQueueAsync(string queueName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public System.Uri GenerateAccountSasUri(Azure.Storage.Sas.AccountSasBuilder builder) { throw null; }
public System.Uri GenerateAccountSasUri(Azure.Storage.Sas.AccountSasPermissions permissions, System.DateTimeOffset expiresOn, Azure.Storage.Sas.AccountSasResourceTypes resourceTypes) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueServiceProperties> GetProperties(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueServiceProperties>> GetPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Storage.Queues.QueueClient GetQueueClient(string queueName) { throw null; }
public virtual Azure.Pageable<Azure.Storage.Queues.Models.QueueItem> GetQueues(Azure.Storage.Queues.Models.QueueTraits traits = Azure.Storage.Queues.Models.QueueTraits.None, string prefix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.Storage.Queues.Models.QueueItem> GetQueuesAsync(Azure.Storage.Queues.Models.QueueTraits traits = Azure.Storage.Queues.Models.QueueTraits.None, string prefix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueServiceStatistics> GetStatistics(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueServiceStatistics>> GetStatisticsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response SetProperties(Azure.Storage.Queues.Models.QueueServiceProperties properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> SetPropertiesAsync(Azure.Storage.Queues.Models.QueueServiceProperties properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class QueueUriBuilder
{
public QueueUriBuilder(System.Uri uri) { }
public string AccountName { get { throw null; } set { } }
public string Host { get { throw null; } set { } }
public string MessageId { get { throw null; } set { } }
public bool Messages { get { throw null; } set { } }
public int Port { get { throw null; } set { } }
public string Query { get { throw null; } set { } }
public string QueueName { get { throw null; } set { } }
public Azure.Storage.Sas.SasQueryParameters Sas { get { throw null; } set { } }
public string Scheme { get { throw null; } set { } }
public override string ToString() { throw null; }
public System.Uri ToUri() { throw null; }
}
}
namespace Azure.Storage.Queues.Models
{
public partial class PeekedMessage
{
internal PeekedMessage() { }
public System.BinaryData Body { get { throw null; } }
public long DequeueCount { get { throw null; } }
public System.DateTimeOffset? ExpiresOn { get { throw null; } }
public System.DateTimeOffset? InsertedOn { get { throw null; } }
public string MessageId { get { throw null; } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public string MessageText { get { throw null; } }
}
public partial class QueueAccessPolicy
{
public QueueAccessPolicy() { }
public System.DateTimeOffset? ExpiresOn { get { throw null; } set { } }
public string Permissions { get { throw null; } set { } }
public System.DateTimeOffset? StartsOn { get { throw null; } set { } }
}
public partial class QueueAnalyticsLogging
{
public QueueAnalyticsLogging() { }
public bool Delete { get { throw null; } set { } }
public bool Read { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueRetentionPolicy RetentionPolicy { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
public bool Write { get { throw null; } set { } }
}
public partial class QueueCorsRule
{
public QueueCorsRule() { }
public string AllowedHeaders { get { throw null; } set { } }
public string AllowedMethods { get { throw null; } set { } }
public string AllowedOrigins { get { throw null; } set { } }
public string ExposedHeaders { get { throw null; } set { } }
public int MaxAgeInSeconds { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct QueueErrorCode : System.IEquatable<Azure.Storage.Queues.Models.QueueErrorCode>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public QueueErrorCode(string value) { throw null; }
public static Azure.Storage.Queues.Models.QueueErrorCode AccountAlreadyExists { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AccountBeingCreated { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AccountIsDisabled { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthenticationFailed { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationFailure { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationPermissionMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationProtocolMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationResourceTypeMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationServiceMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationSourceIPMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ConditionHeadersNotSupported { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ConditionNotMet { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode EmptyMetadataKey { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode FeatureVersionMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InsufficientAccountPermissions { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InternalError { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidAuthenticationInfo { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidHeaderValue { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidHttpVerb { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidInput { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMarker { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMd5 { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMetadata { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidQueryParameterValue { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidRange { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidResourceName { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidUri { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidXmlDocument { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidXmlNodeValue { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode Md5Mismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MessageNotFound { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MessageTooLarge { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MetadataTooLarge { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MissingContentLengthHeader { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredHeader { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredQueryParameter { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredXmlNode { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MultipleConditionHeadersNotSupported { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode OperationTimedOut { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode OutOfRangeInput { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode OutOfRangeQueryParameterValue { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode PopReceiptMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueAlreadyExists { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueBeingDeleted { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueDisabled { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueNotEmpty { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueNotFound { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode RequestBodyTooLarge { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode RequestUrlFailedToParse { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ResourceAlreadyExists { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ResourceNotFound { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ResourceTypeMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ServerBusy { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedHeader { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedHttpVerb { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedQueryParameter { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedXmlNode { get { throw null; } }
public bool Equals(Azure.Storage.Queues.Models.QueueErrorCode other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Storage.Queues.Models.QueueErrorCode left, Azure.Storage.Queues.Models.QueueErrorCode right) { throw null; }
public static implicit operator Azure.Storage.Queues.Models.QueueErrorCode (string value) { throw null; }
public static bool operator !=(Azure.Storage.Queues.Models.QueueErrorCode left, Azure.Storage.Queues.Models.QueueErrorCode right) { throw null; }
public override string ToString() { throw null; }
}
public partial class QueueGeoReplication
{
internal QueueGeoReplication() { }
public System.DateTimeOffset? LastSyncedOn { get { throw null; } }
public Azure.Storage.Queues.Models.QueueGeoReplicationStatus Status { get { throw null; } }
}
public enum QueueGeoReplicationStatus
{
Live = 0,
Bootstrap = 1,
Unavailable = 2,
}
public partial class QueueItem
{
internal QueueItem() { }
public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } }
public string Name { get { throw null; } }
}
public partial class QueueMessage
{
internal QueueMessage() { }
public System.BinaryData Body { get { throw null; } }
public long DequeueCount { get { throw null; } }
public System.DateTimeOffset? ExpiresOn { get { throw null; } }
public System.DateTimeOffset? InsertedOn { get { throw null; } }
public string MessageId { get { throw null; } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public string MessageText { get { throw null; } }
public System.DateTimeOffset? NextVisibleOn { get { throw null; } }
public string PopReceipt { get { throw null; } }
public Azure.Storage.Queues.Models.QueueMessage Update(Azure.Storage.Queues.Models.UpdateReceipt updated) { throw null; }
}
public partial class QueueMetrics
{
public QueueMetrics() { }
public bool Enabled { get { throw null; } set { } }
public bool? IncludeApis { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueRetentionPolicy RetentionPolicy { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
}
public partial class QueueProperties
{
public QueueProperties() { }
public int ApproximateMessagesCount { get { throw null; } }
public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } }
}
public partial class QueueRetentionPolicy
{
public QueueRetentionPolicy() { }
public int? Days { get { throw null; } set { } }
public bool Enabled { get { throw null; } set { } }
}
public partial class QueueServiceProperties
{
public QueueServiceProperties() { }
public System.Collections.Generic.IList<Azure.Storage.Queues.Models.QueueCorsRule> Cors { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueMetrics HourMetrics { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueAnalyticsLogging Logging { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueMetrics MinuteMetrics { get { throw null; } set { } }
}
public partial class QueueServiceStatistics
{
internal QueueServiceStatistics() { }
public Azure.Storage.Queues.Models.QueueGeoReplication GeoReplication { get { throw null; } }
}
public partial class QueueSignedIdentifier
{
public QueueSignedIdentifier() { }
public Azure.Storage.Queues.Models.QueueAccessPolicy AccessPolicy { get { throw null; } set { } }
public string Id { get { throw null; } set { } }
}
public static partial class QueuesModelFactory
{
public static Azure.Storage.Queues.Models.PeekedMessage PeekedMessage(string messageId, System.BinaryData message, long dequeueCount, System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static Azure.Storage.Queues.Models.PeekedMessage PeekedMessage(string messageId, string messageText, long dequeueCount, System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; }
public static Azure.Storage.Queues.Models.QueueGeoReplication QueueGeoReplication(Azure.Storage.Queues.Models.QueueGeoReplicationStatus status, System.DateTimeOffset? lastSyncedOn = default(System.DateTimeOffset?)) { throw null; }
public static Azure.Storage.Queues.Models.QueueItem QueueItem(string name, System.Collections.Generic.IDictionary<string, string> metadata = null) { throw null; }
public static Azure.Storage.Queues.Models.QueueMessage QueueMessage(string messageId, string popReceipt, System.BinaryData body, long dequeueCount, System.DateTimeOffset? nextVisibleOn = default(System.DateTimeOffset?), System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static Azure.Storage.Queues.Models.QueueMessage QueueMessage(string messageId, string popReceipt, string messageText, long dequeueCount, System.DateTimeOffset? nextVisibleOn = default(System.DateTimeOffset?), System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; }
public static Azure.Storage.Queues.Models.QueueProperties QueueProperties(System.Collections.Generic.IDictionary<string, string> metadata, int approximateMessagesCount) { throw null; }
public static Azure.Storage.Queues.Models.QueueServiceStatistics QueueServiceStatistics(Azure.Storage.Queues.Models.QueueGeoReplication geoReplication = null) { throw null; }
public static Azure.Storage.Queues.Models.SendReceipt SendReceipt(string messageId, System.DateTimeOffset insertionTime, System.DateTimeOffset expirationTime, string popReceipt, System.DateTimeOffset timeNextVisible) { throw null; }
public static Azure.Storage.Queues.Models.UpdateReceipt UpdateReceipt(string popReceipt, System.DateTimeOffset nextVisibleOn) { throw null; }
}
[System.FlagsAttribute]
public enum QueueTraits
{
None = 0,
Metadata = 1,
}
public partial class SendReceipt
{
internal SendReceipt() { }
public System.DateTimeOffset ExpirationTime { get { throw null; } }
public System.DateTimeOffset InsertionTime { get { throw null; } }
public string MessageId { get { throw null; } }
public string PopReceipt { get { throw null; } }
public System.DateTimeOffset TimeNextVisible { get { throw null; } }
}
public partial class UpdateReceipt
{
internal UpdateReceipt() { }
public System.DateTimeOffset NextVisibleOn { get { throw null; } }
public string PopReceipt { get { throw null; } }
}
}
namespace Azure.Storage.Queues.Specialized
{
public partial class ClientSideDecryptionFailureEventArgs
{
internal ClientSideDecryptionFailureEventArgs() { }
public System.Exception Exception { get { throw null; } }
}
public partial class QueueClientSideEncryptionOptions : Azure.Storage.ClientSideEncryptionOptions
{
public QueueClientSideEncryptionOptions(Azure.Storage.ClientSideEncryptionVersion version) : base (default(Azure.Storage.ClientSideEncryptionVersion)) { }
public event System.EventHandler<Azure.Storage.Queues.Specialized.ClientSideDecryptionFailureEventArgs> DecryptionFailed { add { } remove { } }
}
public partial class SpecializedQueueClientOptions : Azure.Storage.Queues.QueueClientOptions
{
public SpecializedQueueClientOptions(Azure.Storage.Queues.QueueClientOptions.ServiceVersion version = Azure.Storage.Queues.QueueClientOptions.ServiceVersion.V2021_04_10) : base (default(Azure.Storage.Queues.QueueClientOptions.ServiceVersion)) { }
public Azure.Storage.ClientSideEncryptionOptions ClientSideEncryption { get { throw null; } set { } }
}
public static partial class SpecializedQueueExtensions
{
public static Azure.Storage.Queues.QueueServiceClient GetParentQueueServiceClient(this Azure.Storage.Queues.QueueClient client) { throw null; }
public static Azure.Storage.Queues.QueueClient WithClientSideEncryptionOptions(this Azure.Storage.Queues.QueueClient client, Azure.Storage.ClientSideEncryptionOptions clientSideEncryptionOptions) { throw null; }
}
}
namespace Azure.Storage.Sas
{
[System.FlagsAttribute]
public enum QueueAccountSasPermissions
{
All = -1,
Read = 1,
Write = 2,
Delete = 4,
List = 8,
Add = 16,
Update = 32,
Process = 64,
}
public partial class QueueSasBuilder
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public QueueSasBuilder() { }
public QueueSasBuilder(Azure.Storage.Sas.QueueAccountSasPermissions permissions, System.DateTimeOffset expiresOn) { }
public QueueSasBuilder(Azure.Storage.Sas.QueueSasPermissions permissions, System.DateTimeOffset expiresOn) { }
public System.DateTimeOffset ExpiresOn { get { throw null; } set { } }
public string Identifier { get { throw null; } set { } }
public Azure.Storage.Sas.SasIPRange IPRange { get { throw null; } set { } }
public string Permissions { get { throw null; } }
public Azure.Storage.Sas.SasProtocol Protocol { get { throw null; } set { } }
public string QueueName { get { throw null; } set { } }
public System.DateTimeOffset StartsOn { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public string Version { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public void SetPermissions(Azure.Storage.Sas.QueueAccountSasPermissions permissions) { }
public void SetPermissions(Azure.Storage.Sas.QueueSasPermissions permissions) { }
public void SetPermissions(string rawPermissions) { }
public void SetPermissions(string rawPermissions, bool normalize = false) { }
public Azure.Storage.Sas.SasQueryParameters ToSasQueryParameters(Azure.Storage.StorageSharedKeyCredential sharedKeyCredential) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
[System.FlagsAttribute]
public enum QueueSasPermissions
{
All = -1,
Read = 1,
Add = 2,
Update = 4,
Process = 8,
}
}
namespace Microsoft.Extensions.Azure
{
public static partial class QueueClientBuilderExtensions
{
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, System.Uri serviceUri) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, System.Uri serviceUri, Azure.Storage.StorageSharedKeyCredential sharedKeyCredential) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; }
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using JetBrains.Annotations;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Extensions.ImageExtensions;
using osu.Framework.Input;
using osu.Framework.Platform.SDL2;
using osu.Framework.Platform.Windows.Native;
using osu.Framework.Threading;
using osuTK;
using osuTK.Input;
using SDL2;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using Image = SixLabors.ImageSharp.Image;
using Point = System.Drawing.Point;
using Rectangle = System.Drawing.Rectangle;
using Size = System.Drawing.Size;
// ReSharper disable UnusedParameter.Local (Class regularly handles native events where we don't consume all parameters)
namespace osu.Framework.Platform
{
/// <summary>
/// Default implementation of a desktop window, using SDL for windowing and graphics support.
/// </summary>
public class SDL2DesktopWindow : IWindow
{
internal IntPtr SDLWindowHandle { get; private set; } = IntPtr.Zero;
private readonly IGraphicsBackend graphicsBackend;
private bool focused;
/// <summary>
/// Whether the window currently has focus.
/// </summary>
public bool Focused
{
get => focused;
private set
{
if (value == focused)
return;
isActive.Value = focused = value;
}
}
/// <summary>
/// Enables or disables vertical sync.
/// </summary>
public bool VerticalSync
{
get => graphicsBackend.VerticalSync;
set => graphicsBackend.VerticalSync = value;
}
/// <summary>
/// Returns true if window has been created.
/// Returns false if the window has not yet been created, or has been closed.
/// </summary>
public bool Exists { get; private set; }
public WindowMode DefaultWindowMode => Configuration.WindowMode.Windowed;
/// <summary>
/// Returns the window modes that the platform should support by default.
/// </summary>
protected virtual IEnumerable<WindowMode> DefaultSupportedWindowModes => Enum.GetValues(typeof(WindowMode)).OfType<WindowMode>();
private Point position;
/// <summary>
/// Returns or sets the window's position in screen space. Only valid when in <see cref="osu.Framework.Configuration.WindowMode.Windowed"/>
/// </summary>
public Point Position
{
get => position;
set
{
position = value;
ScheduleCommand(() => SDL.SDL_SetWindowPosition(SDLWindowHandle, value.X, value.Y));
}
}
private bool resizable = true;
/// <summary>
/// Returns or sets whether the window is resizable or not. Only valid when in <see cref="osu.Framework.Platform.WindowState.Normal"/>.
/// </summary>
public bool Resizable
{
get => resizable;
set
{
if (resizable == value)
return;
resizable = value;
ScheduleCommand(() => SDL.SDL_SetWindowResizable(SDLWindowHandle, value ? SDL.SDL_bool.SDL_TRUE : SDL.SDL_bool.SDL_FALSE));
}
}
private bool relativeMouseMode;
/// <summary>
/// Set the state of SDL2's RelativeMouseMode (https://wiki.libsdl.org/SDL_SetRelativeMouseMode).
/// On all platforms, this will lock the mouse to the window (although escaping by setting <see cref="ConfineMouseMode"/> is still possible via a local implementation).
/// On windows, this will use raw input if available.
/// </summary>
public bool RelativeMouseMode
{
get => relativeMouseMode;
set
{
if (relativeMouseMode == value)
return;
if (value && !CursorState.HasFlagFast(CursorState.Hidden))
throw new InvalidOperationException($"Cannot set {nameof(RelativeMouseMode)} to true when the cursor is not hidden via {nameof(CursorState)}.");
relativeMouseMode = value;
ScheduleCommand(() => SDL.SDL_SetRelativeMouseMode(value ? SDL.SDL_bool.SDL_TRUE : SDL.SDL_bool.SDL_FALSE));
}
}
private Size size = new Size(default_width, default_height);
/// <summary>
/// Returns or sets the window's internal size, before scaling.
/// </summary>
public Size Size
{
get => size;
private set
{
if (value.Equals(size)) return;
size = value;
ScheduleEvent(() => Resized?.Invoke());
}
}
/// <summary>
/// Provides a bindable that controls the window's <see cref="CursorStateBindable"/>.
/// </summary>
public Bindable<CursorState> CursorStateBindable { get; } = new Bindable<CursorState>();
public CursorState CursorState
{
get => CursorStateBindable.Value;
set => CursorStateBindable.Value = value;
}
public Bindable<Display> CurrentDisplayBindable { get; } = new Bindable<Display>();
public Bindable<WindowMode> WindowMode { get; } = new Bindable<WindowMode>();
private readonly BindableBool isActive = new BindableBool();
public IBindable<bool> IsActive => isActive;
private readonly BindableBool cursorInWindow = new BindableBool();
public IBindable<bool> CursorInWindow => cursorInWindow;
public IBindableList<WindowMode> SupportedWindowModes { get; }
public BindableSafeArea SafeAreaPadding { get; } = new BindableSafeArea();
public virtual Point PointToClient(Point point) => point;
public virtual Point PointToScreen(Point point) => point;
private const int default_width = 1366;
private const int default_height = 768;
private const int default_icon_size = 256;
private readonly Scheduler commandScheduler = new Scheduler();
private readonly Scheduler eventScheduler = new Scheduler();
private readonly Dictionary<int, SDL2ControllerBindings> controllers = new Dictionary<int, SDL2ControllerBindings>();
private string title = string.Empty;
/// <summary>
/// Gets and sets the window title.
/// </summary>
public string Title
{
get => title;
set
{
title = value;
ScheduleCommand(() => SDL.SDL_SetWindowTitle(SDLWindowHandle, title));
}
}
private bool visible;
/// <summary>
/// Enables or disables the window visibility.
/// </summary>
public bool Visible
{
get => visible;
set
{
visible = value;
ScheduleCommand(() =>
{
if (value)
SDL.SDL_ShowWindow(SDLWindowHandle);
else
SDL.SDL_HideWindow(SDLWindowHandle);
});
}
}
private void updateCursorVisibility(bool visible) =>
ScheduleCommand(() => SDL.SDL_ShowCursor(visible ? SDL.SDL_ENABLE : SDL.SDL_DISABLE));
private void updateCursorConfined(bool confined) =>
ScheduleCommand(() => SDL.SDL_SetWindowGrab(SDLWindowHandle, confined ? SDL.SDL_bool.SDL_TRUE : SDL.SDL_bool.SDL_FALSE));
private WindowState windowState = WindowState.Normal;
private WindowState? pendingWindowState;
/// <summary>
/// Returns or sets the window's current <see cref="WindowState"/>.
/// </summary>
public WindowState WindowState
{
get => windowState;
set
{
if (pendingWindowState == null && windowState == value)
return;
pendingWindowState = value;
}
}
/// <summary>
/// Stores whether the window used to be in maximised state or not.
/// Used to properly decide what window state to pick when switching to windowed mode (see <see cref="WindowMode"/> change event)
/// </summary>
private bool windowMaximised;
/// <summary>
/// Returns the drawable area, after scaling.
/// </summary>
public Size ClientSize => new Size(Size.Width, Size.Height);
public float Scale = 1;
/// <summary>
/// Queries the physical displays and their supported resolutions.
/// </summary>
public IEnumerable<Display> Displays => Enumerable.Range(0, SDL.SDL_GetNumVideoDisplays()).Select(displayFromSDL);
/// <summary>
/// Gets the <see cref="Display"/> that has been set as "primary" or "default" in the operating system.
/// </summary>
public virtual Display PrimaryDisplay => Displays.First();
private Display currentDisplay;
private int displayIndex = -1;
/// <summary>
/// Gets or sets the <see cref="Display"/> that this window is currently on.
/// </summary>
public Display CurrentDisplay { get; private set; }
public readonly Bindable<ConfineMouseMode> ConfineMouseMode = new Bindable<ConfineMouseMode>();
private readonly Bindable<DisplayMode> currentDisplayMode = new Bindable<DisplayMode>();
/// <summary>
/// The <see cref="DisplayMode"/> for the display that this window is currently on.
/// </summary>
public IBindable<DisplayMode> CurrentDisplayMode => currentDisplayMode;
/// <summary>
/// Gets the native window handle as provided by the operating system.
/// </summary>
public IntPtr WindowHandle
{
get
{
if (SDLWindowHandle == IntPtr.Zero)
return IntPtr.Zero;
var wmInfo = getWindowWMInfo();
// Window handle is selected per subsystem as defined at:
// https://wiki.libsdl.org/SDL_SysWMinfo
switch (wmInfo.subsystem)
{
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WINDOWS:
return wmInfo.info.win.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_X11:
return wmInfo.info.x11.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_DIRECTFB:
return wmInfo.info.dfb.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_COCOA:
return wmInfo.info.cocoa.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_UIKIT:
return wmInfo.info.uikit.window;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WAYLAND:
return wmInfo.info.wl.shell_surface;
case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_ANDROID:
return wmInfo.info.android.window;
default:
return IntPtr.Zero;
}
}
}
private SDL.SDL_SysWMinfo getWindowWMInfo()
{
if (SDLWindowHandle == IntPtr.Zero)
return default;
var wmInfo = new SDL.SDL_SysWMinfo();
SDL.SDL_GetWindowWMInfo(SDLWindowHandle, ref wmInfo);
return wmInfo;
}
private Rectangle windowDisplayBounds
{
get
{
SDL.SDL_GetDisplayBounds(displayIndex, out var rect);
return new Rectangle(rect.x, rect.y, rect.w, rect.h);
}
}
public bool CapsLockPressed => SDL.SDL_GetModState().HasFlagFast(SDL.SDL_Keymod.KMOD_CAPS);
private bool firstDraw = true;
private readonly BindableSize sizeFullscreen = new BindableSize();
private readonly BindableSize sizeWindowed = new BindableSize();
private readonly BindableDouble windowPositionX = new BindableDouble();
private readonly BindableDouble windowPositionY = new BindableDouble();
private readonly Bindable<DisplayIndex> windowDisplayIndexBindable = new Bindable<DisplayIndex>();
public SDL2DesktopWindow()
{
SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_GAMECONTROLLER);
graphicsBackend = CreateGraphicsBackend();
SupportedWindowModes = new BindableList<WindowMode>(DefaultSupportedWindowModes);
CursorStateBindable.ValueChanged += evt =>
{
updateCursorVisibility(!evt.NewValue.HasFlagFast(CursorState.Hidden));
updateCursorConfined(evt.NewValue.HasFlagFast(CursorState.Confined));
};
populateJoysticks();
}
/// <summary>
/// Creates the window and initialises the graphics backend.
/// </summary>
public virtual void Create()
{
SDL.SDL_WindowFlags flags = SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL |
SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE |
SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI |
SDL.SDL_WindowFlags.SDL_WINDOW_HIDDEN | // shown after first swap to avoid white flash on startup (windows)
WindowState.ToFlags();
SDL.SDL_SetHint(SDL.SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4, "1");
SDL.SDL_SetHint(SDL.SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "1");
SDLWindowHandle = SDL.SDL_CreateWindow(title, Position.X, Position.Y, Size.Width, Size.Height, flags);
Exists = true;
MouseEntered += () => cursorInWindow.Value = true;
MouseLeft += () => cursorInWindow.Value = false;
graphicsBackend.Initialise(this);
updateWindowSpecifics();
updateWindowSize();
WindowMode.TriggerChange();
}
// reference must be kept to avoid GC, see https://stackoverflow.com/a/6193914
[UsedImplicitly]
private SDL.SDL_EventFilter eventFilterDelegate;
/// <summary>
/// Starts the window's run loop.
/// </summary>
public void Run()
{
// polling via SDL_PollEvent blocks on resizes (https://stackoverflow.com/a/50858339)
SDL.SDL_SetEventFilter(eventFilterDelegate = (_, eventPtr) =>
{
// ReSharper disable once PossibleNullReferenceException
var e = (SDL.SDL_Event)Marshal.PtrToStructure(eventPtr, typeof(SDL.SDL_Event));
if (e.type == SDL.SDL_EventType.SDL_WINDOWEVENT && e.window.windowEvent == SDL.SDL_WindowEventID.SDL_WINDOWEVENT_RESIZED)
{
updateWindowSize();
}
return 1;
}, IntPtr.Zero);
while (Exists)
{
commandScheduler.Update();
if (!Exists)
break;
if (pendingWindowState != null)
updateWindowSpecifics();
pollSDLEvents();
if (!cursorInWindow.Value)
pollMouse();
eventScheduler.Update();
Update?.Invoke();
}
Exited?.Invoke();
if (SDLWindowHandle != IntPtr.Zero)
SDL.SDL_DestroyWindow(SDLWindowHandle);
SDL.SDL_Quit();
}
/// <summary>
/// Updates the client size and the scale according to the window.
/// </summary>
/// <returns>Whether the window size has been changed after updating.</returns>
private void updateWindowSize()
{
SDL.SDL_GL_GetDrawableSize(SDLWindowHandle, out var w, out var h);
SDL.SDL_GetWindowSize(SDLWindowHandle, out var actualW, out var _);
Scale = (float)w / actualW;
Size = new Size(w, h);
// This function may be invoked before the SDL internal states are all changed. (as documented here: https://wiki.libsdl.org/SDL_SetEventFilter)
// Scheduling the store to config until after the event poll has run will ensure the window is in the correct state.
eventScheduler.Add(storeWindowSizeToConfig, true);
}
/// <summary>
/// Forcefully closes the window.
/// </summary>
public void Close() => ScheduleCommand(() => Exists = false);
/// <summary>
/// Attempts to close the window.
/// </summary>
public void RequestClose() => ScheduleEvent(() =>
{
if (ExitRequested?.Invoke() != true)
Close();
});
public void SwapBuffers()
{
graphicsBackend.SwapBuffers();
if (firstDraw)
{
Visible = true;
firstDraw = false;
}
}
/// <summary>
/// Requests that the graphics backend become the current context.
/// May not be required for some backends.
/// </summary>
public void MakeCurrent() => graphicsBackend.MakeCurrent();
/// <summary>
/// Requests that the current context be cleared.
/// </summary>
public void ClearCurrent() => graphicsBackend.ClearCurrent();
private void enqueueJoystickAxisInput(JoystickAxisSource axisSource, short axisValue)
{
// SDL reports axis values in the range short.MinValue to short.MaxValue, so we scale and clamp it to the range of -1f to 1f
var clamped = Math.Clamp((float)axisValue / short.MaxValue, -1f, 1f);
ScheduleEvent(() => JoystickAxisChanged?.Invoke(new JoystickAxis(axisSource, clamped)));
}
private void enqueueJoystickButtonInput(JoystickButton button, bool isPressed)
{
if (isPressed)
ScheduleEvent(() => JoystickButtonDown?.Invoke(button));
else
ScheduleEvent(() => JoystickButtonUp?.Invoke(button));
}
/// <summary>
/// Attempts to set the window's icon to the specified image.
/// </summary>
/// <param name="image">An <see cref="Image{Rgba32}"/> to set as the window icon.</param>
private unsafe void setSDLIcon(Image<Rgba32> image)
{
var pixelMemory = image.CreateReadOnlyPixelMemory();
var imageSize = image.Size();
ScheduleCommand(() =>
{
var pixelSpan = pixelMemory.Span;
IntPtr surface;
fixed (Rgba32* ptr = pixelSpan)
surface = SDL.SDL_CreateRGBSurfaceFrom(new IntPtr(ptr), imageSize.Width, imageSize.Height, 32, imageSize.Width * 4, 0xff, 0xff00, 0xff0000, 0xff000000);
SDL.SDL_SetWindowIcon(SDLWindowHandle, surface);
SDL.SDL_FreeSurface(surface);
});
}
private Point previousPolledPoint = Point.Empty;
private void pollMouse()
{
SDL.SDL_GetGlobalMouseState(out var x, out var y);
if (previousPolledPoint.X == x && previousPolledPoint.Y == y)
return;
previousPolledPoint = new Point(x, y);
var pos = WindowMode.Value == Configuration.WindowMode.Windowed ? Position : windowDisplayBounds.Location;
var rx = x - pos.X;
var ry = y - pos.Y;
ScheduleEvent(() => MouseMove?.Invoke(new Vector2(rx * Scale, ry * Scale)));
}
#region SDL Event Handling
/// <summary>
/// Adds an <see cref="Action"/> to the <see cref="Scheduler"/> expected to handle event callbacks.
/// </summary>
/// <param name="action">The <see cref="Action"/> to execute.</param>
protected void ScheduleEvent(Action action) => eventScheduler.Add(action, false);
protected void ScheduleCommand(Action action) => commandScheduler.Add(action, false);
private const int events_per_peep = 64;
private SDL.SDL_Event[] events = new SDL.SDL_Event[events_per_peep];
/// <summary>
/// Poll for all pending events.
/// </summary>
private void pollSDLEvents()
{
SDL.SDL_PumpEvents();
int eventsRead;
do
{
eventsRead = SDL.SDL_PeepEvents(events, events_per_peep, SDL.SDL_eventaction.SDL_GETEVENT, SDL.SDL_EventType.SDL_FIRSTEVENT, SDL.SDL_EventType.SDL_LASTEVENT);
for (int i = 0; i < eventsRead; i++)
handleSDLEvent(events[i]);
} while (eventsRead == events_per_peep);
}
private void handleSDLEvent(SDL.SDL_Event e)
{
switch (e.type)
{
case SDL.SDL_EventType.SDL_QUIT:
case SDL.SDL_EventType.SDL_APP_TERMINATING:
handleQuitEvent(e.quit);
break;
case SDL.SDL_EventType.SDL_WINDOWEVENT:
handleWindowEvent(e.window);
break;
case SDL.SDL_EventType.SDL_KEYDOWN:
case SDL.SDL_EventType.SDL_KEYUP:
handleKeyboardEvent(e.key);
break;
case SDL.SDL_EventType.SDL_TEXTEDITING:
handleTextEditingEvent(e.edit);
break;
case SDL.SDL_EventType.SDL_TEXTINPUT:
handleTextInputEvent(e.text);
break;
case SDL.SDL_EventType.SDL_MOUSEMOTION:
handleMouseMotionEvent(e.motion);
break;
case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN:
case SDL.SDL_EventType.SDL_MOUSEBUTTONUP:
handleMouseButtonEvent(e.button);
break;
case SDL.SDL_EventType.SDL_MOUSEWHEEL:
handleMouseWheelEvent(e.wheel);
break;
case SDL.SDL_EventType.SDL_JOYAXISMOTION:
handleJoyAxisEvent(e.jaxis);
break;
case SDL.SDL_EventType.SDL_JOYBALLMOTION:
handleJoyBallEvent(e.jball);
break;
case SDL.SDL_EventType.SDL_JOYHATMOTION:
handleJoyHatEvent(e.jhat);
break;
case SDL.SDL_EventType.SDL_JOYBUTTONDOWN:
case SDL.SDL_EventType.SDL_JOYBUTTONUP:
handleJoyButtonEvent(e.jbutton);
break;
case SDL.SDL_EventType.SDL_JOYDEVICEADDED:
case SDL.SDL_EventType.SDL_JOYDEVICEREMOVED:
handleJoyDeviceEvent(e.jdevice);
break;
case SDL.SDL_EventType.SDL_CONTROLLERAXISMOTION:
handleControllerAxisEvent(e.caxis);
break;
case SDL.SDL_EventType.SDL_CONTROLLERBUTTONDOWN:
case SDL.SDL_EventType.SDL_CONTROLLERBUTTONUP:
handleControllerButtonEvent(e.cbutton);
break;
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEADDED:
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMOVED:
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMAPPED:
handleControllerDeviceEvent(e.cdevice);
break;
case SDL.SDL_EventType.SDL_FINGERDOWN:
case SDL.SDL_EventType.SDL_FINGERUP:
case SDL.SDL_EventType.SDL_FINGERMOTION:
handleTouchFingerEvent(e.tfinger);
break;
case SDL.SDL_EventType.SDL_DROPFILE:
case SDL.SDL_EventType.SDL_DROPTEXT:
case SDL.SDL_EventType.SDL_DROPBEGIN:
case SDL.SDL_EventType.SDL_DROPCOMPLETE:
handleDropEvent(e.drop);
break;
}
}
private void handleQuitEvent(SDL.SDL_QuitEvent evtQuit) => RequestClose();
private void handleDropEvent(SDL.SDL_DropEvent evtDrop)
{
switch (evtDrop.type)
{
case SDL.SDL_EventType.SDL_DROPFILE:
var str = SDL.UTF8_ToManaged(evtDrop.file, true);
if (str != null)
ScheduleEvent(() => DragDrop?.Invoke(str));
break;
}
}
private void handleTouchFingerEvent(SDL.SDL_TouchFingerEvent evtTfinger)
{
}
private void handleControllerDeviceEvent(SDL.SDL_ControllerDeviceEvent evtCdevice)
{
switch (evtCdevice.type)
{
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEADDED:
addJoystick(evtCdevice.which);
break;
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMOVED:
SDL.SDL_GameControllerClose(controllers[evtCdevice.which].ControllerHandle);
controllers.Remove(evtCdevice.which);
break;
case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMAPPED:
if (controllers.TryGetValue(evtCdevice.which, out var state))
state.PopulateBindings();
break;
}
}
private void handleControllerButtonEvent(SDL.SDL_ControllerButtonEvent evtCbutton)
{
var button = ((SDL.SDL_GameControllerButton)evtCbutton.button).ToJoystickButton();
switch (evtCbutton.type)
{
case SDL.SDL_EventType.SDL_CONTROLLERBUTTONDOWN:
enqueueJoystickButtonInput(button, true);
break;
case SDL.SDL_EventType.SDL_CONTROLLERBUTTONUP:
enqueueJoystickButtonInput(button, false);
break;
}
}
private void handleControllerAxisEvent(SDL.SDL_ControllerAxisEvent evtCaxis) =>
enqueueJoystickAxisInput(((SDL.SDL_GameControllerAxis)evtCaxis.axis).ToJoystickAxisSource(), evtCaxis.axisValue);
private void addJoystick(int which)
{
var instanceID = SDL.SDL_JoystickGetDeviceInstanceID(which);
// if the joystick is already opened, ignore it
if (controllers.ContainsKey(instanceID))
return;
var joystick = SDL.SDL_JoystickOpen(which);
var controller = IntPtr.Zero;
if (SDL.SDL_IsGameController(which) == SDL.SDL_bool.SDL_TRUE)
controller = SDL.SDL_GameControllerOpen(which);
controllers[instanceID] = new SDL2ControllerBindings(joystick, controller);
}
/// <summary>
/// Populates <see cref="controllers"/> with joysticks that are already connected.
/// </summary>
private void populateJoysticks()
{
for (int i = 0; i < SDL.SDL_NumJoysticks(); i++)
{
addJoystick(i);
}
}
private void handleJoyDeviceEvent(SDL.SDL_JoyDeviceEvent evtJdevice)
{
switch (evtJdevice.type)
{
case SDL.SDL_EventType.SDL_JOYDEVICEADDED:
addJoystick(evtJdevice.which);
break;
case SDL.SDL_EventType.SDL_JOYDEVICEREMOVED:
// if the joystick is already closed, ignore it
if (!controllers.ContainsKey(evtJdevice.which))
break;
SDL.SDL_JoystickClose(controllers[evtJdevice.which].JoystickHandle);
controllers.Remove(evtJdevice.which);
break;
}
}
private void handleJoyButtonEvent(SDL.SDL_JoyButtonEvent evtJbutton)
{
// if this button exists in the controller bindings, skip it
if (controllers.TryGetValue(evtJbutton.which, out var state) && state.GetButtonForIndex(evtJbutton.button) != SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID)
return;
var button = JoystickButton.FirstButton + evtJbutton.button;
switch (evtJbutton.type)
{
case SDL.SDL_EventType.SDL_JOYBUTTONDOWN:
enqueueJoystickButtonInput(button, true);
break;
case SDL.SDL_EventType.SDL_JOYBUTTONUP:
enqueueJoystickButtonInput(button, false);
break;
}
}
private void handleJoyHatEvent(SDL.SDL_JoyHatEvent evtJhat)
{
}
private void handleJoyBallEvent(SDL.SDL_JoyBallEvent evtJball)
{
}
private void handleJoyAxisEvent(SDL.SDL_JoyAxisEvent evtJaxis)
{
// if this axis exists in the controller bindings, skip it
if (controllers.TryGetValue(evtJaxis.which, out var state) && state.GetAxisForIndex(evtJaxis.axis) != SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_INVALID)
return;
enqueueJoystickAxisInput(JoystickAxisSource.Axis1 + evtJaxis.axis, evtJaxis.axisValue);
}
private void handleMouseWheelEvent(SDL.SDL_MouseWheelEvent evtWheel) =>
ScheduleEvent(() => TriggerMouseWheel(new Vector2(evtWheel.x, evtWheel.y), false));
private void handleMouseButtonEvent(SDL.SDL_MouseButtonEvent evtButton)
{
MouseButton button = mouseButtonFromEvent(evtButton.button);
switch (evtButton.type)
{
case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN:
ScheduleEvent(() => MouseDown?.Invoke(button));
break;
case SDL.SDL_EventType.SDL_MOUSEBUTTONUP:
ScheduleEvent(() => MouseUp?.Invoke(button));
break;
}
}
private void handleMouseMotionEvent(SDL.SDL_MouseMotionEvent evtMotion)
{
if (SDL.SDL_GetRelativeMouseMode() == SDL.SDL_bool.SDL_FALSE)
ScheduleEvent(() => MouseMove?.Invoke(new Vector2(evtMotion.x * Scale, evtMotion.y * Scale)));
else
ScheduleEvent(() => MouseMoveRelative?.Invoke(new Vector2(evtMotion.xrel * Scale, evtMotion.yrel * Scale)));
}
private unsafe void handleTextInputEvent(SDL.SDL_TextInputEvent evtText)
{
var ptr = new IntPtr(evtText.text);
if (ptr == IntPtr.Zero)
return;
string text = Marshal.PtrToStringUTF8(ptr) ?? "";
foreach (char c in text)
ScheduleEvent(() => KeyTyped?.Invoke(c));
}
private void handleTextEditingEvent(SDL.SDL_TextEditingEvent evtEdit)
{
}
private void handleKeyboardEvent(SDL.SDL_KeyboardEvent evtKey)
{
Key key = evtKey.keysym.ToKey();
if (key == Key.Unknown)
return;
switch (evtKey.type)
{
case SDL.SDL_EventType.SDL_KEYDOWN:
ScheduleEvent(() => KeyDown?.Invoke(key));
break;
case SDL.SDL_EventType.SDL_KEYUP:
ScheduleEvent(() => KeyUp?.Invoke(key));
break;
}
}
private void handleWindowEvent(SDL.SDL_WindowEvent evtWindow)
{
updateWindowSpecifics();
switch (evtWindow.windowEvent)
{
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_MOVED:
// explicitly requery as there are occasions where what SDL has provided us with is not up-to-date.
SDL.SDL_GetWindowPosition(SDLWindowHandle, out int x, out int y);
var newPosition = new Point(x, y);
if (!newPosition.Equals(Position))
{
position = newPosition;
ScheduleEvent(() => Moved?.Invoke(newPosition));
if (WindowMode.Value == Configuration.WindowMode.Windowed)
storeWindowPositionToConfig();
}
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_SIZE_CHANGED:
updateWindowSize();
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_ENTER:
cursorInWindow.Value = true;
ScheduleEvent(() => MouseEntered?.Invoke());
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_LEAVE:
cursorInWindow.Value = false;
ScheduleEvent(() => MouseLeft?.Invoke());
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_RESTORED:
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_GAINED:
ScheduleEvent(() => Focused = true);
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_MINIMIZED:
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_LOST:
ScheduleEvent(() => Focused = false);
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_CLOSE:
break;
}
}
/// <summary>
/// Should be run on a regular basis to check for external window state changes.
/// </summary>
private void updateWindowSpecifics()
{
// don't attempt to run before the window is initialised, as Create() will do so anyway.
if (SDLWindowHandle == IntPtr.Zero)
return;
var stateBefore = windowState;
// check for a pending user state change and give precedence.
if (pendingWindowState != null)
{
windowState = pendingWindowState.Value;
pendingWindowState = null;
updateWindowStateAndSize();
}
else
{
windowState = ((SDL.SDL_WindowFlags)SDL.SDL_GetWindowFlags(SDLWindowHandle)).ToWindowState();
}
if (windowState != stateBefore)
{
ScheduleEvent(() => WindowStateChanged?.Invoke(windowState));
updateMaximisedState();
}
int newDisplayIndex = SDL.SDL_GetWindowDisplayIndex(SDLWindowHandle);
if (displayIndex != newDisplayIndex)
{
displayIndex = newDisplayIndex;
currentDisplay = Displays.ElementAtOrDefault(displayIndex) ?? PrimaryDisplay;
ScheduleEvent(() =>
{
CurrentDisplayBindable.Value = currentDisplay;
});
}
}
/// <summary>
/// Should be run after a local window state change, to propagate the correct SDL actions.
/// </summary>
private void updateWindowStateAndSize()
{
// this reset is required even on changing from one fullscreen resolution to another.
// if it is not included, the GL context will not get the correct size.
// this is mentioned by multiple sources as an SDL issue, which seems to resolve by similar means (see https://discourse.libsdl.org/t/sdl-setwindowsize-does-not-work-in-fullscreen/20711/4).
SDL.SDL_SetWindowBordered(SDLWindowHandle, SDL.SDL_bool.SDL_TRUE);
SDL.SDL_SetWindowFullscreen(SDLWindowHandle, (uint)SDL.SDL_bool.SDL_FALSE);
switch (windowState)
{
case WindowState.Normal:
Size = (sizeWindowed.Value * Scale).ToSize();
SDL.SDL_RestoreWindow(SDLWindowHandle);
SDL.SDL_SetWindowSize(SDLWindowHandle, sizeWindowed.Value.Width, sizeWindowed.Value.Height);
SDL.SDL_SetWindowResizable(SDLWindowHandle, Resizable ? SDL.SDL_bool.SDL_TRUE : SDL.SDL_bool.SDL_FALSE);
readWindowPositionFromConfig();
break;
case WindowState.Fullscreen:
var closestMode = getClosestDisplayMode(sizeFullscreen.Value, currentDisplayMode.Value.RefreshRate, currentDisplay.Index);
Size = new Size(closestMode.w, closestMode.h);
SDL.SDL_SetWindowDisplayMode(SDLWindowHandle, ref closestMode);
SDL.SDL_SetWindowFullscreen(SDLWindowHandle, (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN);
break;
case WindowState.FullscreenBorderless:
Size = SetBorderless();
break;
case WindowState.Maximised:
SDL.SDL_RestoreWindow(SDLWindowHandle);
SDL.SDL_MaximizeWindow(SDLWindowHandle);
SDL.SDL_GL_GetDrawableSize(SDLWindowHandle, out int w, out int h);
Size = new Size(w, h);
break;
case WindowState.Minimised:
SDL.SDL_MinimizeWindow(SDLWindowHandle);
break;
}
updateMaximisedState();
if (SDL.SDL_GetWindowDisplayMode(SDLWindowHandle, out var mode) >= 0)
currentDisplayMode.Value = new DisplayMode(mode.format.ToString(), new Size(mode.w, mode.h), 32, mode.refresh_rate, displayIndex, displayIndex);
}
private void updateMaximisedState()
{
if (windowState == WindowState.Normal || windowState == WindowState.Maximised)
windowMaximised = windowState == WindowState.Maximised;
}
private void readWindowPositionFromConfig()
{
if (WindowState != WindowState.Normal)
return;
var configPosition = new Vector2((float)windowPositionX.Value, (float)windowPositionY.Value);
var displayBounds = CurrentDisplay.Bounds;
var windowSize = sizeWindowed.Value;
var windowX = (int)Math.Round((displayBounds.Width - windowSize.Width) * configPosition.X);
var windowY = (int)Math.Round((displayBounds.Height - windowSize.Height) * configPosition.Y);
Position = new Point(windowX + displayBounds.X, windowY + displayBounds.Y);
}
private void storeWindowPositionToConfig()
{
if (WindowState != WindowState.Normal)
return;
var displayBounds = CurrentDisplay.Bounds;
var windowX = Position.X - displayBounds.X;
var windowY = Position.Y - displayBounds.Y;
var windowSize = sizeWindowed.Value;
windowPositionX.Value = displayBounds.Width > windowSize.Width ? (float)windowX / (displayBounds.Width - windowSize.Width) : 0;
windowPositionY.Value = displayBounds.Height > windowSize.Height ? (float)windowY / (displayBounds.Height - windowSize.Height) : 0;
}
/// <summary>
/// Set to <c>true</c> while the window size is being stored to config to avoid bindable feedback.
/// </summary>
private bool storingSizeToConfig;
private void storeWindowSizeToConfig()
{
if (WindowState != WindowState.Normal)
return;
storingSizeToConfig = true;
sizeWindowed.Value = (Size / Scale).ToSize();
storingSizeToConfig = false;
}
/// <summary>
/// Prepare display of a borderless window.
/// </summary>
/// <returns>
/// The size of the borderless window's draw area.
/// </returns>
protected virtual Size SetBorderless()
{
// this is a generally sane method of handling borderless, and works well on macOS and linux.
SDL.SDL_SetWindowFullscreen(SDLWindowHandle, (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP);
return currentDisplay.Bounds.Size;
}
private MouseButton mouseButtonFromEvent(byte button)
{
switch ((uint)button)
{
default:
case SDL.SDL_BUTTON_LEFT:
return MouseButton.Left;
case SDL.SDL_BUTTON_RIGHT:
return MouseButton.Right;
case SDL.SDL_BUTTON_MIDDLE:
return MouseButton.Middle;
case SDL.SDL_BUTTON_X1:
return MouseButton.Button1;
case SDL.SDL_BUTTON_X2:
return MouseButton.Button2;
}
}
#endregion
protected virtual IGraphicsBackend CreateGraphicsBackend() => new SDL2GraphicsBackend();
public void SetupWindow(FrameworkConfigManager config)
{
CurrentDisplayBindable.ValueChanged += evt =>
{
windowDisplayIndexBindable.Value = (DisplayIndex)evt.NewValue.Index;
};
config.BindWith(FrameworkSetting.LastDisplayDevice, windowDisplayIndexBindable);
windowDisplayIndexBindable.BindValueChanged(evt => CurrentDisplay = Displays.ElementAtOrDefault((int)evt.NewValue) ?? PrimaryDisplay, true);
sizeFullscreen.ValueChanged += evt =>
{
if (storingSizeToConfig) return;
if (windowState != WindowState.Fullscreen) return;
pendingWindowState = windowState;
};
sizeWindowed.ValueChanged += evt =>
{
if (storingSizeToConfig) return;
if (windowState != WindowState.Normal) return;
pendingWindowState = windowState;
};
config.BindWith(FrameworkSetting.SizeFullscreen, sizeFullscreen);
config.BindWith(FrameworkSetting.WindowedSize, sizeWindowed);
config.BindWith(FrameworkSetting.WindowedPositionX, windowPositionX);
config.BindWith(FrameworkSetting.WindowedPositionY, windowPositionY);
config.BindWith(FrameworkSetting.WindowMode, WindowMode);
config.BindWith(FrameworkSetting.ConfineMouseMode, ConfineMouseMode);
WindowMode.BindValueChanged(evt =>
{
switch (evt.NewValue)
{
case Configuration.WindowMode.Fullscreen:
WindowState = WindowState.Fullscreen;
break;
case Configuration.WindowMode.Borderless:
WindowState = WindowState.FullscreenBorderless;
break;
case Configuration.WindowMode.Windowed:
WindowState = windowMaximised ? WindowState.Maximised : WindowState.Normal;
break;
}
updateConfineMode();
});
ConfineMouseMode.BindValueChanged(_ => updateConfineMode());
}
public void CycleMode()
{
var currentValue = WindowMode.Value;
do
{
switch (currentValue)
{
case Configuration.WindowMode.Windowed:
currentValue = Configuration.WindowMode.Borderless;
break;
case Configuration.WindowMode.Borderless:
currentValue = Configuration.WindowMode.Fullscreen;
break;
case Configuration.WindowMode.Fullscreen:
currentValue = Configuration.WindowMode.Windowed;
break;
}
} while (!SupportedWindowModes.Contains(currentValue) && currentValue != WindowMode.Value);
WindowMode.Value = currentValue;
}
/// <summary>
/// Update the host window manager's cursor position based on a location relative to window coordinates.
/// </summary>
/// <param name="position">A position inside the window.</param>
public void UpdateMousePosition(Vector2 position) => ScheduleCommand(() =>
SDL.SDL_WarpMouseInWindow(SDLWindowHandle, (int)(position.X / Scale), (int)(position.Y / Scale)));
public void SetIconFromStream(Stream stream)
{
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
ms.Position = 0;
var imageInfo = Image.Identify(ms);
if (imageInfo != null)
SetIconFromImage(Image.Load<Rgba32>(ms.GetBuffer()));
else if (IconGroup.TryParse(ms.GetBuffer(), out var iconGroup))
SetIconFromGroup(iconGroup);
}
}
internal virtual void SetIconFromGroup(IconGroup iconGroup)
{
// LoadRawIcon returns raw PNG data if available, which avoids any Windows-specific pinvokes
var bytes = iconGroup.LoadRawIcon(default_icon_size, default_icon_size);
if (bytes == null)
return;
SetIconFromImage(Image.Load<Rgba32>(bytes));
}
internal virtual void SetIconFromImage(Image<Rgba32> iconImage) => setSDLIcon(iconImage);
private void updateConfineMode()
{
bool confine = false;
switch (ConfineMouseMode.Value)
{
case Input.ConfineMouseMode.Fullscreen:
confine = WindowMode.Value != Configuration.WindowMode.Windowed;
break;
case Input.ConfineMouseMode.Always:
confine = true;
break;
}
if (confine)
CursorStateBindable.Value |= CursorState.Confined;
else
CursorStateBindable.Value &= ~CursorState.Confined;
}
#region Helper functions
private SDL.SDL_DisplayMode getClosestDisplayMode(Size size, int refreshRate, int displayIndex)
{
var targetMode = new SDL.SDL_DisplayMode { w = size.Width, h = size.Height, refresh_rate = refreshRate };
if (SDL.SDL_GetClosestDisplayMode(displayIndex, ref targetMode, out var mode) != IntPtr.Zero)
return mode;
// fallback to current display's native bounds
targetMode.w = currentDisplay.Bounds.Width;
targetMode.h = currentDisplay.Bounds.Height;
targetMode.refresh_rate = 0;
if (SDL.SDL_GetClosestDisplayMode(displayIndex, ref targetMode, out mode) != IntPtr.Zero)
return mode;
// finally return the current mode if everything else fails.
// not sure this is required.
if (SDL.SDL_GetWindowDisplayMode(SDLWindowHandle, out mode) >= 0)
return mode;
throw new InvalidOperationException("couldn't retrieve valid display mode");
}
private static Display displayFromSDL(int displayIndex)
{
var displayModes = Enumerable.Range(0, SDL.SDL_GetNumDisplayModes(displayIndex))
.Select(modeIndex =>
{
SDL.SDL_GetDisplayMode(displayIndex, modeIndex, out var mode);
return displayModeFromSDL(mode, displayIndex, modeIndex);
})
.ToArray();
SDL.SDL_GetDisplayBounds(displayIndex, out var rect);
return new Display(displayIndex, SDL.SDL_GetDisplayName(displayIndex), new Rectangle(rect.x, rect.y, rect.w, rect.h), displayModes);
}
private static DisplayMode displayModeFromSDL(SDL.SDL_DisplayMode mode, int displayIndex, int modeIndex)
{
SDL.SDL_PixelFormatEnumToMasks(mode.format, out var bpp, out _, out _, out _, out _);
return new DisplayMode(SDL.SDL_GetPixelFormatName(mode.format), new Size(mode.w, mode.h), bpp, mode.refresh_rate, modeIndex, displayIndex);
}
#endregion
#region Events
/// <summary>
/// Invoked once every window event loop.
/// </summary>
public event Action Update;
/// <summary>
/// Invoked after the window has resized.
/// </summary>
public event Action Resized;
/// <summary>
/// Invoked after the window's state has changed.
/// </summary>
public event Action<WindowState> WindowStateChanged;
/// <summary>
/// Invoked when the user attempts to close the window. Return value of true will cancel exit.
/// </summary>
public event Func<bool> ExitRequested;
/// <summary>
/// Invoked when the window is about to close.
/// </summary>
public event Action Exited;
/// <summary>
/// Invoked when the mouse cursor enters the window.
/// </summary>
public event Action MouseEntered;
/// <summary>
/// Invoked when the mouse cursor leaves the window.
/// </summary>
public event Action MouseLeft;
/// <summary>
/// Invoked when the window moves.
/// </summary>
public event Action<Point> Moved;
/// <summary>
/// Invoked when the user scrolls the mouse wheel over the window.
/// </summary>
public event Action<Vector2, bool> MouseWheel;
protected void TriggerMouseWheel(Vector2 delta, bool precise) => MouseWheel?.Invoke(delta, precise);
/// <summary>
/// Invoked when the user moves the mouse cursor within the window.
/// </summary>
public event Action<Vector2> MouseMove;
/// <summary>
/// Invoked when the user moves the mouse cursor within the window (via relative / raw input).
/// </summary>
public event Action<Vector2> MouseMoveRelative;
/// <summary>
/// Invoked when the user presses a mouse button.
/// </summary>
public event Action<MouseButton> MouseDown;
/// <summary>
/// Invoked when the user releases a mouse button.
/// </summary>
public event Action<MouseButton> MouseUp;
/// <summary>
/// Invoked when the user presses a key.
/// </summary>
public event Action<Key> KeyDown;
/// <summary>
/// Invoked when the user releases a key.
/// </summary>
public event Action<Key> KeyUp;
/// <summary>
/// Invoked when the user types a character.
/// </summary>
public event Action<char> KeyTyped;
/// <summary>
/// Invoked when a joystick axis changes.
/// </summary>
public event Action<JoystickAxis> JoystickAxisChanged;
/// <summary>
/// Invoked when the user presses a button on a joystick.
/// </summary>
public event Action<JoystickButton> JoystickButtonDown;
/// <summary>
/// Invoked when the user releases a button on a joystick.
/// </summary>
public event Action<JoystickButton> JoystickButtonUp;
/// <summary>
/// Invoked when the user drops a file into the window.
/// </summary>
public event Action<string> DragDrop;
#endregion
public void Dispose()
{
}
}
}
| |
/* Copyright (c) 2006-2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Change history
* Oct 13 2008 Joe Feser joseph.feser@gmail.com
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
#region Using directives
using System;
using System.Collections;
using System.Text;
using System.Xml;
using Google.GData.Client;
#endregion
namespace Google.GData.GoogleBase {
///////////////////////////////////////////////////////////////////////
/// <summary>Identifiers for standard Google Base attribute types.
/// All non-standard types share the type otherType</summary>
///////////////////////////////////////////////////////////////////////
public enum StandardGBaseAttributeTypeIds
{
/// <summary>Id of the standard type <c>text</c></summary>
textType,
/// <summary>Id of the standard type <c>boolean</c></summary>
booleanType,
/// <summary>Id of the standard type <c>location</c></summary>
locationType,
/// <summary>Id of the standard type <c>url</c></summary>
urlType,
/// <summary>Id of the standard type <c>int</c></summary>
intType,
/// <summary>Id of the standard type <c>float</c></summary>
floatType,
/// <summary>Id of the standard type <c>number</c></summary>
numberType,
/// <summary>Id of the standard type <c>intUnit</c></summary>
intUnitType,
/// <summary>Id of the standard type <c>floatUnit</c></summary>
floatUnitType,
/// <summary>Id of the standard type <c>numberUnit</c></summary>
numberUnitType,
/// <summary>Id of the standard type <c>date</c></summary>
dateType,
/// <summary>Id of the standard type <c>dateTime</c></summary>
dateTimeType,
/// <summary>Id of the standard type <c>dateTimeRange</c></summary>
dateTimeRangeType,
/// <summary>Id of the standard type <c>shipping</c></summary>
shippingType,
/// <summary>An attribute type that could not be recognized by
/// the library. See the attribute name.</summary>
otherType
}
///////////////////////////////////////////////////////////////////////
/// <summary>Object representation of Google Base attribute types.
///
/// To get GBaseAttributeType instance, use one of the predefined
/// constants or call GBaseAttributeType.ForName(string)
/// </summary>
///////////////////////////////////////////////////////////////////////
public class GBaseAttributeType
{
private readonly string name;
private readonly StandardGBaseAttributeTypeIds id;
private readonly GBaseAttributeType supertype;
/// <summary>Text attributes.</summary>
public static readonly GBaseAttributeType Text =
new GBaseAttributeType(StandardGBaseAttributeTypeIds.textType,
"text");
/// <summary>Boolean attributes.</summary>
public static readonly GBaseAttributeType Boolean =
new GBaseAttributeType(StandardGBaseAttributeTypeIds.booleanType,
"boolean");
/// <summary>Location attributes, as a free string.</summary>
public static readonly GBaseAttributeType Location =
new GBaseAttributeType(StandardGBaseAttributeTypeIds.locationType,
"location");
/// <summary>Url attributes.</summary>
public static readonly GBaseAttributeType Url =
new GBaseAttributeType(StandardGBaseAttributeTypeIds.urlType,
"url");
/// <summary>Number attribute: a float or an int.</summary>
public static readonly GBaseAttributeType Number =
new GBaseAttributeType(StandardGBaseAttributeTypeIds.numberType,
"number");
/// <summary>Integer attribute, a subtype of Number.</summary>
public static readonly GBaseAttributeType Int =
new GBaseAttributeType(Number,
StandardGBaseAttributeTypeIds.intType,
"int");
/// <summary>Float attribute, a subtype of Number.</summary>
public static readonly GBaseAttributeType Float =
new GBaseAttributeType(Number,
StandardGBaseAttributeTypeIds.floatType,
"float");
/// <summary>Number attribute with a unit ("12 km"). A supertype
/// of FloatUnit and IntUnit.</summary>
public static readonly GBaseAttributeType NumberUnit =
new GBaseAttributeType(StandardGBaseAttributeTypeIds.numberUnitType,
"numberUnit");
/// <summary>Int attribute with a unit, a subtype of NumberUnit.</summary>
public static readonly GBaseAttributeType IntUnit =
new GBaseAttributeType(NumberUnit,
StandardGBaseAttributeTypeIds.intUnitType,
"intUnit");
/// <summary>Float attribute with a unit, a subtype of NumberUnit.</summary>
public static readonly GBaseAttributeType FloatUnit =
new GBaseAttributeType(NumberUnit,
StandardGBaseAttributeTypeIds.floatUnitType,
"floatUnit");
/// <summary>A time range, with a starting and an end date/time, a
/// supertype of DateTime and Date. For example:
/// "2006-01-01T12:00:00Z 2006-01-02T14:00:00Z"
///
/// Empty time ranges are considered equivalent to DateTime.</summary>
public static readonly GBaseAttributeType DateTimeRange =
new GBaseAttributeType(StandardGBaseAttributeTypeIds.dateTimeRangeType,
"dateTimeRange");
/// <summary>A date, a subtype of DateTime and DateTimeRange.</summary>
public static readonly GBaseAttributeType Date =
new GBaseAttributeType(DateTimeRange,
StandardGBaseAttributeTypeIds.dateType,
"date");
/// <summary>A date and a time, a subtype of DateTimeRange.</summary>
public static readonly GBaseAttributeType DateTime =
new GBaseAttributeType(Date,
StandardGBaseAttributeTypeIds.dateTimeType,
"dateTime");
/// <summary>A Shipping object.</summary>
public static readonly GBaseAttributeType Shipping =
new GBaseAttributeType(StandardGBaseAttributeTypeIds.shippingType,
"shipping");
/// <summary>All standard attribute types.</summary>
public static readonly GBaseAttributeType[] AllStandardTypes = {
Text, Boolean, Location, Url,
Int, Float, Number,
IntUnit, FloatUnit, NumberUnit,
Date, DateTime, DateTimeRange
};
private static readonly IDictionary StandardTypesDict = new Hashtable();
static GBaseAttributeType()
{
foreach(GBaseAttributeType type in AllStandardTypes)
{
StandardTypesDict.Add(type.Name, type);
}
}
private GBaseAttributeType(GBaseAttributeType supertype,
StandardGBaseAttributeTypeIds id,
string name)
{
this.supertype = supertype;
this.name = name;
this.id = id;
}
private GBaseAttributeType(StandardGBaseAttributeTypeIds id, string name)
: this(null, id, name)
{
}
///////////////////////////////////////////////////////////////////////
/// <summary>Get or create an attribute with the given name.
/// If the name corresponds to a standard attribute, the global
/// instance will be returned. Otherwise, a new GBaseAttributeType
/// with Id = otherType will be created.</summary>
///////////////////////////////////////////////////////////////////////
public static GBaseAttributeType ForName(String name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
GBaseAttributeType standard =
StandardTypesDict[name] as GBaseAttributeType;
if (standard != null)
{
return standard;
}
return new GBaseAttributeType(StandardGBaseAttributeTypeIds.otherType,
name);
}
///////////////////////////////////////////////////////////////////////
/// <summary>Returns the attribute name.</summary>
///////////////////////////////////////////////////////////////////////
public override string ToString()
{
return name;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Compares two types by comparing their names.</summary>
///////////////////////////////////////////////////////////////////////
public override bool Equals(object o)
{
if (Object.ReferenceEquals(o, this))
{
return true;
}
if (!(o is GBaseAttributeType))
{
return false;
}
GBaseAttributeType other = o as GBaseAttributeType;
if (other.id == id)
{
if (other.id == StandardGBaseAttributeTypeIds.otherType)
{
return name.Equals(other.name);
}
return true;
}
return false;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Generates a hash code for this element that is
/// consistent with its Equals() method.</summary>
///////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
if (id == StandardGBaseAttributeTypeIds.otherType)
{
return 11 + name.GetHashCode();
}
else
{
return (int)id;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Checks whether this object is a supertype or the
/// same as another type.</summary>
/// <param name="subtype">other attribute type.</param>
///////////////////////////////////////////////////////////////////////
public bool IsSupertypeOf(GBaseAttributeType subtype)
{
if (this == subtype)
{
return true;
}
GBaseAttributeType otherSupertype = subtype.Supertype;
if (otherSupertype == null)
{
return false;
}
return IsSupertypeOf(otherSupertype);
}
///////////////////////////////////////////////////////////////////////
/// <summary>Type name</summary>
///////////////////////////////////////////////////////////////////////
public string Name
{
get
{
return name;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Type identifier, otherType for nonstandard types.</summary>
///////////////////////////////////////////////////////////////////////
public StandardGBaseAttributeTypeIds Id
{
get
{
return id;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>This type's supertype or null.</summary>
///////////////////////////////////////////////////////////////////////
public GBaseAttributeType Supertype
{
get
{
return supertype;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Comparison based on the Equals() method.</summary>
///////////////////////////////////////////////////////////////////////
public static bool operator ==(GBaseAttributeType a, GBaseAttributeType b)
{
if (Object.ReferenceEquals(a, b))
{
return true;
}
if (((object)a == null) || ((object)b == null))
{
return false;
}
return a.Equals(b);
}
///////////////////////////////////////////////////////////////////////
/// <summary>Comparison based on the Equals() method.</summary>
///////////////////////////////////////////////////////////////////////
public static bool operator !=(GBaseAttributeType a, GBaseAttributeType b)
{
return !(a == b);
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Extension element corresponding to a g: tag.
/// This element contains the logic to convert a g: tag to and from
/// XML.
///
/// It is usually not accessed through
/// <see href="GBaseAttributes">GBaseAttributes</see>.
/// </summary>
///////////////////////////////////////////////////////////////////////
public class GBaseAttribute : IExtensionElementFactory
{
private static readonly char[] kXmlWhitespaces = { ' ', '\t', '\n', '\r' };
private string name;
private GBaseAttributeType type;
private bool isPrivate;
/// <summary>Content, null if subElements != null.</summary>
private string content;
private string adjustedValue;
private string adjustedName;
/// <summary>Dictionary of: subElementName x subElementValue.
/// Null if content != null</summary>
private IDictionary subElements;
///////////////////////////////////////////////////////////////////////
/// <summary>Creates an empty GBaseAttribute.</summary>
///////////////////////////////////////////////////////////////////////
public GBaseAttribute()
{
}
///////////////////////////////////////////////////////////////////////
/// <summary>Creates a GBaseAttribute with a name and an undefined
/// type.</summary>
/// <param name="name">attribute name</param>
///////////////////////////////////////////////////////////////////////
public GBaseAttribute(String name)
: this(name, null, null)
{
}
///////////////////////////////////////////////////////////////////////
/// <summary>Creates a GBaseAttribute with a name and a type.</summary>
/// <param name="name">attribute name</param>
/// <param name="type">attribute type or null if unknown</param>
///////////////////////////////////////////////////////////////////////
public GBaseAttribute(String name, GBaseAttributeType type)
: this(name, type, null)
{
}
///////////////////////////////////////////////////////////////////////
/// <summary>Creates a GBaseAttribute</summary>
/// <param name="name">attribute name</param>
/// <param name="type">attribute type or null if unknown</param>
/// <param name="content">value</param>
///////////////////////////////////////////////////////////////////////
public GBaseAttribute(String name, GBaseAttributeType type, String content)
{
this.name = name;
this.type = type;
this.content = content;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Attribute name</summary>
///////////////////////////////////////////////////////////////////////
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Attribute type</summary>
///////////////////////////////////////////////////////////////////////
public GBaseAttributeType Type
{
get
{
return type;
}
set
{
type = value;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Attribute content, as a string.</summary>
///////////////////////////////////////////////////////////////////////
public string Content
{
get
{
return content;
}
set
{
content = value;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Private access (XML attribute access="private")</summary>
///////////////////////////////////////////////////////////////////////
public bool IsPrivate
{
get
{
return isPrivate;
}
set
{
isPrivate = value;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>A better name for this attribute, recommended by
/// Google (when adjustments are turned on)</summary>
///////////////////////////////////////////////////////////////////////
public string AdjustedName
{
get
{
return adjustedName;
}
set
{
adjustedName = value;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>A better value for this string attribute, recommended by
/// Google (when adjustments are turned on)</summary>
///////////////////////////////////////////////////////////////////////
public string AdjustedValue
{
get
{
return adjustedValue;
}
set
{
adjustedValue = value;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>Accesses sub-elements.
///
/// Sub-elements are XML elements put inside the attribute
/// tag. Such as:
/// <g:shipping>
/// <g:country>FR</g:country>
/// <g:price>12 EUR</g:price>
/// </g:shipping>
///
/// An attribute cannot contain both sub-elements and text (content)
/// </summary>
//////////////////////////////////////////////////////////////////////
public string this[string subElementName]
{
get
{
if (subElements == null)
{
return null;
}
return (string)subElements[subElementName];
}
set
{
if (subElements == null)
{
subElements = new Hashtable();
}
if (value == null)
{
subElements.Remove(subElementName);
}
else
{
subElements[subElementName] = value;
}
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>Checks whether the attribute has sub-elements.
/// You can access sub-element names using the property
/// SubElementSames.</summary>
//////////////////////////////////////////////////////////////////////
public bool HasSubElements
{
get
{
return subElements != null && subElements.Count > 0;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>The list of sub-elements name, which might be empty.
///
/// The sub-elements names are returned in no particular order.
///
/// You can get the value of these sub-elements using this[name].
/// </summary>
//////////////////////////////////////////////////////////////////////
public string[] SubElementNames
{
get
{
if (subElements == null)
{
return new string[0];
}
string[] retval = new string[subElements.Count];
subElements.Keys.CopyTo(retval, 0);
return retval;
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>Parses an XML node and create the corresponding
/// GBaseAttribute.</summary>
///////////////////////////////////////////////////////////////////////
public static GBaseAttribute ParseGBaseAttribute(XmlNode node)
{
if (node == null)
{
throw new ArgumentNullException("node");
}
GBaseAttribute attribute = new GBaseAttribute();
attribute.Name = FromXmlTagName(node.LocalName);
String value = Utilities.GetAttributeValue("type", node);
if (value != null)
{
attribute.Type = GBaseAttributeType.ForName(value);
}
value = Utilities.GetAttributeValue("access",node);
attribute.IsPrivate = "private".Equals(value);
foreach (XmlNode child in node.ChildNodes)
{
if (child.NodeType == XmlNodeType.Element)
{
bool parsed = false;
if (child.NamespaceURI == GBaseNameTable.NSGBaseMeta)
{
object localName = child.LocalName;
if (localName.Equals("adjusted_name"))
{
attribute.AdjustedName = child.InnerText;
parsed = true;
}
else if (localName.Equals("adjusted_value"))
{
attribute.AdjustedValue = child.InnerText;
parsed = true;
}
}
// Keep everything else as XML
if (!parsed)
{
attribute[child.LocalName] = child.InnerXml;
}
}
}
// If there are sub-elements, set the Content to null unless
// there is clearly something in there.
string content = ExtractDirectTextChildren(node);
if (!"".Equals(content.Trim(kXmlWhitespaces)))
{
attribute.Content = content;
}
return attribute;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Extracts all text nodes inside an element, ignoring
/// text nodes inside children (contrary to XmlNode.InnerText).
/// </summary>
///////////////////////////////////////////////////////////////////////
private static string ExtractDirectTextChildren(XmlNode parent)
{
StringBuilder retval = new StringBuilder();
for (XmlNode child = parent.FirstChild; child != null; child = child.NextSibling)
{
if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA) {
retval.Append(child.Value);
}
}
return retval.ToString();
}
///////////////////////////////////////////////////////////////////////
/// <summary>Converts the current GBaseAttribute to XML.</summary>
///////////////////////////////////////////////////////////////////////
public void Save(XmlWriter writer)
{
writer.WriteStartElement(XmlPrefix,
ToXmlTagName(name),
XmlNameSpace);
if (type != null)
{
writer.WriteAttributeString("type", type.Name);
}
if (isPrivate)
{
writer.WriteAttributeString("access", "private");
}
if (adjustedValue != null)
{
writer.WriteStartElement(GBaseNameTable.GBaseMetaPrefix,
"adjusted_value",
GBaseNameTable.NSGBaseMeta);
writer.WriteString(adjustedValue);
writer.WriteEndElement();
}
if (adjustedName != null)
{
writer.WriteStartElement(GBaseNameTable.GBaseMetaPrefix,
"adjusted_name",
GBaseNameTable.NSGBaseMeta);
writer.WriteString(adjustedName);
writer.WriteEndElement();
}
if (content != null)
{
writer.WriteString(content);
}
if (subElements != null)
{
foreach (string elementName in subElements.Keys)
{
string elementValue = (string)subElements[elementName];
if (elementValue != null)
{
writer.WriteStartElement(GBaseNameTable.GBasePrefix,
ToXmlTagName(elementName),
GBaseNameTable.NSGBase);
writer.WriteString(elementValue);
writer.WriteEndElement();
}
}
}
writer.WriteEndElement();
}
///////////////////////////////////////////////////////////////////////
/// <summary>A partial text representation, to help
/// debugging.</summary>
///////////////////////////////////////////////////////////////////////
public override string ToString()
{
StringBuilder retval = new StringBuilder();
retval.Append(name);
retval.Append('(');
retval.Append(type);
retval.Append("):");
if (HasSubElements)
{
bool isFirst = true;
foreach (string elementName in subElements.Keys)
{
if (isFirst)
{
isFirst = false;
}
else
{
retval.Append(",");
}
retval.Append(elementName);
retval.Append(":\"");
retval.Append(subElements[elementName]);
retval.Append('"');
}
}
else if (content != null)
{
retval.Append('"');
retval.Append(content);
retval.Append('"');
}
return retval.ToString();
}
///////////////////////////////////////////////////////////////////////
/// <summary>Compares two attribute names, types, content and
/// private flag.</summary>
///////////////////////////////////////////////////////////////////////
public override bool Equals(object o)
{
if (!(o is GBaseAttribute))
{
return false;
}
if (Object.ReferenceEquals(this, o))
{
return true;
}
GBaseAttribute other = o as GBaseAttribute;
return name == other.name && type == other.type &&
content == other.content && isPrivate == other.isPrivate &&
adjustedName == other.adjustedName && adjustedValue == other.adjustedValue &&
HashTablesEquals(subElements, other.subElements);
}
/// <summary>Compares two hash tables.</summary>
private bool HashTablesEquals(IDictionary a, IDictionary b)
{
if (a == null)
{
return b == null;
}
if (b == null)
{
return false;
}
ICollection aKeys = a.Keys;
ICollection bKeys = b.Keys;
if (aKeys.Count != bKeys.Count)
{
return false;
}
foreach (string key in aKeys)
{
object aValue = a[key];
object bValue = b[key];
if (aValue != bValue && (aValue == null || !aValue.Equals(bValue)))
{
return false;
}
}
return true;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Generates a hash code for this element that is
/// consistent with its Equals() method.</summary>
///////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
int retval = 49 * (27 + name.GetHashCode()) + type.GetHashCode();
if (content != null)
{
retval = 49 * retval + content.GetHashCode();
}
return retval;
}
///////////////////////////////////////////////////////////////////////
/// <summary>Given an attribute name, with spaces, generates
/// the corresponding XML tag name.</summary>
/// <param name="name">attribute name</param>
/// <returns>the name with all spaces replaced with underscores
/// </returns>
///////////////////////////////////////////////////////////////////////
static string ToXmlTagName(string name)
{
return name.Replace(' ', '_');
}
///////////////////////////////////////////////////////////////////////
/// <summary>Given an XML tag name, with underscores, generates
/// the corresponding attribute name.</summary>
/// <param name="name">XML tag name, without namespace prefix</param>
/// <returns>the name with all underscores replaced with spaces
/// </returns>
///////////////////////////////////////////////////////////////////////
static string FromXmlTagName(string name)
{
return name.Replace('_', ' ');
}
#region IExtensionElementFactory Members
public string XmlName
{
get
{
return ToXmlTagName(Name);
}
}
public string XmlNameSpace
{
get
{
return GBaseNameTable.NSGBase;
}
}
public string XmlPrefix
{
get
{
return GBaseNameTable.GBasePrefix;
}
}
public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser)
{
return ParseGBaseAttribute(node);
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>Recommendation</c> resource.</summary>
public sealed partial class RecommendationName : gax::IResourceName, sys::IEquatable<RecommendationName>
{
/// <summary>The possible contents of <see cref="RecommendationName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/recommendations/{recommendation_id}</c>.
/// </summary>
CustomerRecommendation = 1,
}
private static gax::PathTemplate s_customerRecommendation = new gax::PathTemplate("customers/{customer_id}/recommendations/{recommendation_id}");
/// <summary>Creates a <see cref="RecommendationName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="RecommendationName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static RecommendationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new RecommendationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="RecommendationName"/> with the pattern
/// <c>customers/{customer_id}/recommendations/{recommendation_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="recommendationId">The <c>Recommendation</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="RecommendationName"/> constructed from the provided ids.</returns>
public static RecommendationName FromCustomerRecommendation(string customerId, string recommendationId) =>
new RecommendationName(ResourceNameType.CustomerRecommendation, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), recommendationId: gax::GaxPreconditions.CheckNotNullOrEmpty(recommendationId, nameof(recommendationId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RecommendationName"/> with pattern
/// <c>customers/{customer_id}/recommendations/{recommendation_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="recommendationId">The <c>Recommendation</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RecommendationName"/> with pattern
/// <c>customers/{customer_id}/recommendations/{recommendation_id}</c>.
/// </returns>
public static string Format(string customerId, string recommendationId) =>
FormatCustomerRecommendation(customerId, recommendationId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RecommendationName"/> with pattern
/// <c>customers/{customer_id}/recommendations/{recommendation_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="recommendationId">The <c>Recommendation</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RecommendationName"/> with pattern
/// <c>customers/{customer_id}/recommendations/{recommendation_id}</c>.
/// </returns>
public static string FormatCustomerRecommendation(string customerId, string recommendationId) =>
s_customerRecommendation.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(recommendationId, nameof(recommendationId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="RecommendationName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/recommendations/{recommendation_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="recommendationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="RecommendationName"/> if successful.</returns>
public static RecommendationName Parse(string recommendationName) => Parse(recommendationName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="RecommendationName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/recommendations/{recommendation_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="recommendationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="RecommendationName"/> if successful.</returns>
public static RecommendationName Parse(string recommendationName, bool allowUnparsed) =>
TryParse(recommendationName, allowUnparsed, out RecommendationName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RecommendationName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/recommendations/{recommendation_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="recommendationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RecommendationName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string recommendationName, out RecommendationName result) =>
TryParse(recommendationName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RecommendationName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/recommendations/{recommendation_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="recommendationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RecommendationName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string recommendationName, bool allowUnparsed, out RecommendationName result)
{
gax::GaxPreconditions.CheckNotNull(recommendationName, nameof(recommendationName));
gax::TemplatedResourceName resourceName;
if (s_customerRecommendation.TryParseName(recommendationName, out resourceName))
{
result = FromCustomerRecommendation(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(recommendationName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private RecommendationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string recommendationId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
RecommendationId = recommendationId;
}
/// <summary>
/// Constructs a new instance of a <see cref="RecommendationName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/recommendations/{recommendation_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="recommendationId">The <c>Recommendation</c> ID. Must not be <c>null</c> or empty.</param>
public RecommendationName(string customerId, string recommendationId) : this(ResourceNameType.CustomerRecommendation, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), recommendationId: gax::GaxPreconditions.CheckNotNullOrEmpty(recommendationId, nameof(recommendationId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>Recommendation</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string RecommendationId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerRecommendation: return s_customerRecommendation.Expand(CustomerId, RecommendationId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as RecommendationName);
/// <inheritdoc/>
public bool Equals(RecommendationName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(RecommendationName a, RecommendationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(RecommendationName a, RecommendationName b) => !(a == b);
}
public partial class Recommendation
{
/// <summary>
/// <see cref="RecommendationName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal RecommendationName ResourceNameAsRecommendationName
{
get => string.IsNullOrEmpty(ResourceName) ? null : RecommendationName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignBudgetName"/>-typed view over the <see cref="CampaignBudget"/> resource name property.
/// </summary>
internal CampaignBudgetName CampaignBudgetAsCampaignBudgetName
{
get => string.IsNullOrEmpty(CampaignBudget) ? null : CampaignBudgetName.Parse(CampaignBudget, allowUnparsed: true);
set => CampaignBudget = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property.
/// </summary>
internal CampaignName CampaignAsCampaignName
{
get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true);
set => Campaign = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property.
/// </summary>
internal AdGroupName AdGroupAsAdGroupName
{
get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true);
set => AdGroup = value?.ToString() ?? "";
}
}
}
| |
/*
*
* (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.Globalization;
using System.Linq;
using System.Net;
using System.Runtime.Remoting.Messaging;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Billing;
using ASC.Core.Tenants;
using ASC.Web.Core;
using ASC.Web.Core.Client;
using ASC.Web.Core.Helpers;
using ASC.Web.Core.Utility;
using ASC.Web.Core.Utility.Settings;
using ASC.Web.Core.WhiteLabel;
using ASC.Web.Studio.Core;
using ASC.Web.Studio.Core.Backup;
using ASC.Web.Studio.Utility;
namespace ASC.Web.Studio
{
public class Global : HttpApplication
{
private static readonly object locker = new object();
private static volatile bool applicationStarted;
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (!applicationStarted)
{
lock (locker)
{
if (!applicationStarted)
{
Startup.Configure();
applicationStarted = true;
}
}
}
SecurityContext.Logout();
var tenant = CoreContext.TenantManager.GetCurrentTenant(false);
BlockNotFoundPortal(tenant);
BlockRemovedOrSuspendedPortal(tenant);
BlockTransferingOrRestoringPortal(tenant);
BlockMigratingPortal(tenant);
BlockPortalEncryption(tenant);
BlockNotPaidPortal(tenant);
TenantWhiteLabelSettings.Apply(tenant.TenantId);
Authenticate();
BlockIPSecurityPortal(tenant);
ResolveUserCulture();
}
protected void Application_EndRequest(object sender, EventArgs e)
{
CallContext.FreeNamedDataSlot(TenantManager.CURRENT_TENANT);
SecurityContext.Logout();
}
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
Authenticate();
ResolveUserCulture();
}
protected void Session_Start(object sender, EventArgs e)
{
if (Request.GetUrlRewriter().Scheme == "https")
Response.Cookies["ASP.NET_SessionId"].Secure = true;
Response.Cookies["ASP.NET_SessionId"].HttpOnly = true;
}
public override string GetVaryByCustomString(HttpContext context, string custom)
{
if (String.IsNullOrEmpty(custom)) return base.GetVaryByCustomString(context, custom);
if (custom == "cacheKey") return ClientSettings.ResetCacheKey;
var result = String.Empty;
foreach (Match match in Regex.Matches(custom.ToLower(), "(?<key>\\w+)(\\[(?<subkey>\\w+)\\])?;?", RegexOptions.Compiled))
{
var key = String.Empty;
var subkey = String.Empty;
if (match.Groups["key"].Success)
key = match.Groups["key"].Value;
if (match.Groups["subkey"].Success)
subkey = match.Groups["subkey"].Value;
var value = String.Empty;
switch (key)
{
case "relativeurl":
var appUrl = VirtualPathUtility.ToAbsolute("~/");
value = Request.GetUrlRewriter().AbsolutePath.Remove(0, appUrl.Length - 1);
break;
case "url":
value = Request.GetUrlRewriter().AbsoluteUri;
break;
case "page":
value = Request.GetUrlRewriter().AbsolutePath.Substring(Request.Url.AbsolutePath.LastIndexOfAny(new[] { '/', '\\' }) + 1);
break;
case "module":
var module = "common";
var matches = Regex.Match(Request.Url.AbsolutePath.ToLower(), "(products|addons)/(\\w+)/?", RegexOptions.Compiled);
if (matches.Success && matches.Groups.Count > 2 && matches.Groups[2].Success)
module = matches.Groups[2].Value;
value = module;
break;
case "culture":
value = Thread.CurrentThread.CurrentUICulture.Name;
break;
case "theme":
value = ColorThemesSettings.GetColorThemesSettings();
break;
case "whitelabel":
var whiteLabelSettings = TenantWhiteLabelSettings.Load();
value = whiteLabelSettings.LogoText ?? string.Empty;
break;
}
if (!(String.Compare((value ?? "").ToLower(), subkey, StringComparison.Ordinal) == 0
|| String.IsNullOrEmpty(subkey))) continue;
result += "|" + value;
}
if (!string.IsNullOrEmpty(result)) return String.Join("|", ClientSettings.ResetCacheKey, result);
return base.GetVaryByCustomString(context, custom);
}
public static bool Authenticate()
{
if (SecurityContext.IsAuthenticated)
{
return true;
}
var authenticated = false;
var tenant = CoreContext.TenantManager.GetCurrentTenant(false);
if (tenant != null)
{
if (HttpContext.Current != null)
{
string cookie;
if (AuthorizationHelper.ProcessBasicAuthorization(HttpContext.Current, out cookie))
{
CookiesManager.SetCookies(CookiesType.AuthKey, cookie);
authenticated = true;
}
}
if (!authenticated)
{
var cookie = CookiesManager.GetCookies(CookiesType.AuthKey);
if (!string.IsNullOrEmpty(cookie))
{
authenticated = SecurityContext.AuthenticateMe(cookie);
if (!authenticated)
{
Auth.ProcessLogout();
return false;
}
}
}
var accessSettings = TenantAccessSettings.Load();
if (authenticated && SecurityContext.CurrentAccount.ID == ASC.Core.Users.Constants.OutsideUser.ID && !accessSettings.Anyone)
{
Auth.ProcessLogout();
authenticated = false;
}
}
return authenticated;
}
private static void ResolveUserCulture()
{
CultureInfo culture = null;
var tenant = CoreContext.TenantManager.GetCurrentTenant(false);
if (tenant != null)
{
culture = tenant.GetCulture();
}
var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
if (!string.IsNullOrEmpty(user.CultureName))
{
culture = CultureInfo.GetCultureInfo(user.CultureName);
}
if (culture != null && !Equals(Thread.CurrentThread.CurrentCulture, culture))
{
Thread.CurrentThread.CurrentCulture = culture;
}
if (culture != null && !Equals(Thread.CurrentThread.CurrentUICulture, culture))
{
Thread.CurrentThread.CurrentUICulture = culture;
}
}
private void BlockNotFoundPortal(Tenant tenant)
{
if (tenant == null)
{
if (string.IsNullOrEmpty(SetupInfo.NoTenantRedirectURL))
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
Response.End();
}
else
{
var redirectUrl = string.Format("{0}?url={1}", SetupInfo.NoTenantRedirectURL, Request.GetUrlRewriter().Host);
ResponseRedirect(redirectUrl, HttpStatusCode.NotFound);
}
}
}
private void BlockRemovedOrSuspendedPortal(Tenant tenant)
{
if (tenant.Status != TenantStatus.RemovePending && tenant.Status != TenantStatus.Suspended)
{
return;
}
var passthroughtRequestEndings = new[] { ".js", ".css", ".less", "confirm.aspx", "capabilities.json" };
if (tenant.Status == TenantStatus.Suspended && passthroughtRequestEndings.Any(path => Request.Url.AbsolutePath.EndsWith(path, StringComparison.InvariantCultureIgnoreCase)))
{
return;
}
if (string.IsNullOrEmpty(SetupInfo.NoTenantRedirectURL))
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
Response.End();
}
else
{
var redirectUrl = string.Format("{0}?url={1}", SetupInfo.NoTenantRedirectURL, Request.GetUrlRewriter().Host);
ResponseRedirect(redirectUrl, HttpStatusCode.NotFound);
}
}
private void BlockTransferingOrRestoringPortal(Tenant tenant)
{
if (tenant.Status != TenantStatus.Restoring && tenant.Status != TenantStatus.Transfering)
{
return;
}
// allow requests to backup handler to get access to the GetRestoreStatus method
var handlerType = typeof(BackupAjaxHandler);
var backupHandler = handlerType.FullName + "," + handlerType.Assembly.GetName().Name + ".ashx";
var passthroughtRequestEndings = new[] { ".js", ".css", ".less", ".ico", ".png", backupHandler, "PreparationPortal.aspx", "TenantLogo.ashx", "portal/getrestoreprogress.json", "capabilities.json" };
if (passthroughtRequestEndings.Any(path => Request.Url.AbsolutePath.EndsWith(path, StringComparison.InvariantCultureIgnoreCase)))
{
return;
}
ResponseRedirect("~/PreparationPortal.aspx?type=" + (tenant.Status == TenantStatus.Transfering ? "0" : "1"), HttpStatusCode.ServiceUnavailable);
}
private void BlockMigratingPortal(Tenant tenant)
{
if (tenant.Status != TenantStatus.Migrating)
{
return;
}
var passthroughtRequestEndings = new[] { ".js", ".css", ".less", ".ico", ".png", "MigrationPortal.aspx", "TenantLogo.ashx", "settings/storage/progress.json", "capabilities.json" };
if (passthroughtRequestEndings.Any(path => Request.Url.AbsolutePath.EndsWith(path, StringComparison.InvariantCultureIgnoreCase)))
{
return;
}
ResponseRedirect("~/MigrationPortal.aspx", HttpStatusCode.ServiceUnavailable);
}
private void BlockPortalEncryption(Tenant tenant)
{
if (tenant.Status != TenantStatus.Encryption)
{
return;
}
var passthroughtRequestEndings = new[] { ".js", ".css", ".less", ".ico", ".png", "PortalEncryption.aspx", "TenantLogo.ashx", "settings/encryption/progress.json", "capabilities.json" };
if (passthroughtRequestEndings.Any(path => Request.Url.AbsolutePath.EndsWith(path, StringComparison.InvariantCultureIgnoreCase)))
{
return;
}
ResponseRedirect("~/PortalEncryption.aspx", HttpStatusCode.ServiceUnavailable);
}
private void BlockNotPaidPortal(Tenant tenant)
{
if (tenant == null) return;
var passthroughtRequestEndings = new[] { ".htm", ".ashx", ".png", ".ico", ".less", ".css", ".js", "capabilities.json" };
if (passthroughtRequestEndings.Any(path => Request.Url.AbsolutePath.EndsWith(path, StringComparison.InvariantCultureIgnoreCase)))
{
return;
}
if (!TenantExtra.EnableTariffSettings && TenantExtra.GetCurrentTariff().State >= TariffState.NotPaid)
{
if (string.IsNullOrEmpty(AdditionalWhiteLabelSettings.Instance.BuyUrl)
|| AdditionalWhiteLabelSettings.Instance.BuyUrl == AdditionalWhiteLabelSettings.DefaultBuyUrl)
{
LogManager.GetLogger("ASC").WarnFormat("Tenant {0} is not paid", tenant.TenantId);
Response.StatusCode = (int)HttpStatusCode.PaymentRequired;
Response.End();
}
else if (!Request.Url.AbsolutePath.EndsWith(CommonLinkUtility.ToAbsolute(PaymentRequired.Location)))
{
ResponseRedirect(PaymentRequired.Location, HttpStatusCode.PaymentRequired);
}
}
}
private void BlockIPSecurityPortal(Tenant tenant)
{
if (tenant == null) return;
var settings = IPRestrictionsSettings.LoadForTenant(tenant.TenantId);
if (settings.Enable && SecurityContext.IsAuthenticated && !IPSecurity.IPSecurity.Verify(tenant))
{
Auth.ProcessLogout();
ResponseRedirect("~/Auth.aspx?error=ipsecurity", HttpStatusCode.Forbidden);
}
}
private void ResponseRedirect(string url, HttpStatusCode httpStatusCode)
{
if (Request.Url.AbsolutePath.StartsWith(SetupInfo.WebApiBaseUrl, StringComparison.InvariantCultureIgnoreCase) ||
Request.Url.AbsolutePath.EndsWith(".svc", StringComparison.InvariantCultureIgnoreCase) ||
Request.Url.AbsolutePath.EndsWith(".ashx", StringComparison.InvariantCultureIgnoreCase))
{
// we shouldn't redirect
Response.StatusCode = (int)httpStatusCode;
Response.End();
}
Response.Redirect(url, true);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using SAP.IW.SSO;
using System.Globalization;
using SAP.IW.GWPAM.Common.Configuration;
using System.Web;
using AdnWebAPI.Controllers;
namespace AdnWebAPI.BusinessEntity
{
/// <summary>
/// This class handles the connectivity to the oData endpoint.
/// It performs the required handling to enable authentication to the SAP NetWeaver Gateway endpoint.
/// It also decorates the call to the SAP NetWeaver Gateway endpoint with requestId and SAP Passport required for Enterprise readiness
/// </summary>
static class BusinessConnectivityHelper
{
/// <summary>
/// This property should be set with the user identity in case the X509 SSO from a server
/// </summary>
public static string UserContext { get; set; }
#region Function import helper
/// <summary>
/// This method will call the function import call for the provided service detail, function name and parameter list
/// </summary>
/// <param name="serviceDetail">serviceDetail object</param>
/// <param name="functionName">name of the fuction import</param>
/// <param name="paramList">url parameter list for the key properties</param>
/// <param name="methodType">type - POST</param>
/// <returns>http web response</returns>
internal static HttpWebResponse CallFunctionImport(ServiceDetails serviceDetail, string functionName, List<UrlParam> paramList, string methodType = "POST")
{
Logger.Log(Severity.Info, Categories.ServiceCall, "Triggering service operation call "+ functionName);
string serviceUrl = GetFunctionImportUrl(serviceDetail.Url, functionName, paramList);
HttpWebRequest request = CreateNewRequest(new Uri(serviceUrl), serviceDetail, methodType);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
SAP.IW.SSO.Supportability.SingleActivityTraceUtil.Instance.UpdateRequestForSAT(GetHttpResponseHeaders(response), (int)response.StatusCode, response.ResponseUri.ToString());
return response;
}
/// <summary>
/// This method returns the header of the HttpWebResponse
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private static Dictionary<string, string> GetHttpResponseHeaders(WebResponse response)
{
Dictionary<string,string> headers = new Dictionary<string,string>();
foreach (string header in response.Headers)
{
headers.Add(header, response.Headers[header]);
}
return headers;
}
/// <summary>
/// This method will get the function import url for the provided function import and url
/// </summary>
/// <param name="baseUrl">absolute url of the service</param>
/// <param name="functionName">name of the function import</param>
/// <param name="paramList">url parameter list for the key properties</param>
/// <returns>http web response</returns>
internal static string GetFunctionImportUrl(string baseUrl, string functionName, List<UrlParam> paramList)
{
Logger.Log(Severity.Verbose, Categories.ServiceCall, "BusinessConnectivityHelper::GetFunctionImportUrl(functionName={0})",functionName);
string serviceUrl = string.Concat(baseUrl.TrimEnd('/'), string.Format(CultureInfo.InvariantCulture,"/{0}?", functionName));
string formattedString = string.Empty;
foreach (var item in paramList)
{
formattedString += item.GetFormmattedParamValue();
}
serviceUrl = string.Concat(serviceUrl, formattedString.TrimEnd('&'));
return serviceUrl;
}
/// <summary>
/// This method will return the Read item url based on the baseurl, collection name and the url params list
/// </summary>
/// <param name="baseUrl">base url of the service</param>
/// <param name="collectionName">collection name</param>
/// <param name="paramList">url parameter list for the key properties</param>
/// <returns>url</returns>
internal static string GetReadItemUrl(string baseUrl,string collectionName, List<UrlParam> paramList)
{
Logger.Log(Severity.Verbose, Categories.ServiceCall, "BusinessConnectivityHelper::GetReadItemUrl(collectionName={0})",collectionName);
string serviceUrl = string.Concat(baseUrl.TrimEnd('/'), string.Format(CultureInfo.InvariantCulture,"/{0}(", collectionName));
string formattedString = string.Empty;
foreach (var item in paramList)
{
formattedString += item.GetFormmattedParamValue();
formattedString = formattedString.Replace("&", ",");
}
serviceUrl = string.Concat(serviceUrl, formattedString.TrimEnd(','));
serviceUrl = string.Concat(serviceUrl, ")");
return serviceUrl;
}
/// <summary>
/// This method will prepare the http web request for the SAP connectivity and will handle SSO, E2E tracing and SAP Passport handling
/// </summary>
/// <param name="serviceDetail">Service Details</param>
/// <param name="webRequest">Web Request</param>
internal static void HandleSAPConnectivity(ServiceDetails serviceDetail,ref HttpWebRequest webRequest)
{
string requestID="";
Logger.Log(Severity.Verbose, Categories.ServiceCall, "BusinessConnectivityHelper::HandleSAPConnectivity()");
AuthenticationType authenticationType = GetAuthenticationType(serviceDetail.SSO);
webRequest.Headers["sap-client"] = serviceDetail.Client;
requestID=webRequest.Headers["RequestID"] = SAP.IW.SSO.Supportability.E2ETraceUtil.GetRequestId();
Logger.Log(Severity.Info, Categories.ServiceCall, "Setting Request Id : " + requestID);
SAP.IW.SSO.Supportability.SingleActivityTraceUtil.Instance.PrepareRequestForSAT(ref webRequest);
Logger.Log(Severity.Info,
Categories.Outlook,
"Selected authentication type " + authenticationType);
//ADN Modif
ISSOProvider ssoProvider = SSOProviderFactory.Instance.GetSSOProvider(
authenticationType,
webRequest.Method,
"",
"",
serviceDetail.RootCASubjectName,
true);
switch(authenticationType)
{
case AuthenticationType.BASIC:
webRequest.Credentials = new System.Net.NetworkCredential(
Credentials.SAP_USERNAME,
Credentials.SAP_PASSWORD);
break;
}
ssoProvider.SAPCredientials(ref webRequest);
}
#endregion
#region Private Helper
/// <summary>
/// This method will create the new http web request with SSO and E2E tracing handled
/// </summary>
/// <param name="uri">end point</param>
/// <param name="serviceDetail">service details object</param>
/// <param name="methodType">http method</param>
/// <returns>http web request</returns>
internal static HttpWebRequest CreateNewRequest(Uri uri, ServiceDetails serviceDetail, string methodType = "POST")
{
HttpWebRequest webRequest = WebRequest.Create(uri) as HttpWebRequest;
webRequest.Method = methodType;
HandleSAPConnectivity(serviceDetail, ref webRequest);
return webRequest;
}
/// <summary>
/// This method will return the current logged on user context from the Http headears. This method should be changed in case the
/// the subject name required for the user certificate is different.
/// </summary>
/// <returns>current logged on user name</returns>
internal static string GetUserContext()
{
return HttpContext.Current.User.Identity.Name;
}
/// <summary>
/// This method will get the authentication type
/// </summary>
/// <param name="authenticationString">authentication type["BASIC","X509","SAML20"]</param>
/// <returns>authentication type - BASIC,SAML20,X509</returns>
private static AuthenticationType GetAuthenticationType(string authenticationString)
{
AuthenticationType authenticationType = AuthenticationType.BASIC;
if (Enum.IsDefined(typeof(AuthenticationType), authenticationString))
authenticationType = (AuthenticationType)Enum.Parse(typeof(AuthenticationType), authenticationString, true);
return authenticationType;
}
#endregion
}
///<summary>
///This class contains the methods for formatting the parmater values to construct an url
///</summary>
internal class UrlParam
{
#region Function Param property
internal string ParamName { get; set; }
internal dynamic ParamValue { get; set; }
internal bool IsBinaryParam { get; set; }
#endregion
#region Helper methods
internal UrlParam() { this.IsBinaryParam = false; }
/// <summary>
/// This method will return the formatted parameter values
/// </summary>
/// <returns>formatted value of the parameter</returns>
internal string GetFormmattedParamValue()
{
string formmatedParamValue = string.Concat(this.ParamName, "=");
if (ParamValue.GetType() == typeof(string))
{
if (this.IsBinaryParam == false)
{
formmatedParamValue += string.Format("'{0}'&", this.ParamValue);
}
else
{
formmatedParamValue += string.Format("binary'{0}'&", this.ParamValue);
}
}
else if (ParamValue.GetType() == typeof(DateTime))
{
formmatedParamValue += string.Format("datetime'{0}'&", this.ParamValue);
}
else if (ParamValue.GetType() == typeof(Guid))
{
formmatedParamValue += string.Format("guid'{0}'&", this.ParamValue);
}
else if (ParamValue.GetType() == typeof(DateTimeOffset))
{
formmatedParamValue += string.Format("{0}&", this.ParamValue);
}
else if (ParamValue.GetType() == typeof(Int32))
{
formmatedParamValue += string.Format("{0}&", this.ParamValue);
}
return formmatedParamValue;
}
#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;
using System.Runtime.InteropServices;
using TestLibrary;
/// <summary>
/// Pass Array Size by out keyword using SizeParamIndex Attributes
/// </summary>
public class ClientMarshalArrayAsSizeParamIndexByOutTest
{
#region ByOut
[DllImport("PInvokePassingByOutNative")]
private static extern bool MarshalCStyleArrayByte_AsByOut_AsSizeParamIndex(
out byte arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] out byte[] arrByte);
[DllImport("PInvokePassingByOutNative")]
private static extern bool MarshalCStyleArraySbyte_AsByOut_AsSizeParamIndex(
out sbyte arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] out sbyte[] arrSbyte);
[DllImport("PInvokePassingByOutNative")]
private static extern bool MarshalCStyleArrayShort_AsByOut_AsSizeParamIndex(
out short arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] out short[] arrShort);
[DllImport("PInvokePassingByOutNative")]
private static extern bool MarshalCStyleArrayShortReturnNegative_AsByOut_AsSizeParamIndex(
out short arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] out short[] arrShort);
[DllImport("PInvokePassingByOutNative")]
private static extern bool MarshalCStyleArrayUshort_AsByOut_AsSizeParamIndex(
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out ushort[] arrUshort, out ushort arrSize);
[DllImport("PInvokePassingByOutNative")]
private static extern bool MarshalCStyleArrayInt_AsByOut_AsSizeParamIndex(
out Int32 arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] out Int32[] arrInt32);
[DllImport("PInvokePassingByOutNative")]
private static extern bool MarshalCStyleArrayUInt_AsByOut_AsSizeParamIndex(
out UInt32 arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] out UInt32[] arrUInt32);
[DllImport("PInvokePassingByOutNative")]
private static extern bool MarshalCStyleArrayLong_AsByOut_AsSizeParamIndex(
out long arrSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] out long[] arrLong);
[DllImport("PInvokePassingByOutNative")]
private static extern bool MarshalCStyleArrayUlong_AsByOut_AsSizeParamIndex(
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out ulong[] arrUlong, out ulong arrSize, ulong unused);
[DllImport("PInvokePassingByOutNative")]
private static extern bool MarshalCStyleArrayString_AsByOut_AsSizeParamIndex(
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1, ArraySubType = UnmanagedType.BStr)] out string[] arrInt32, out int arrSize);
#endregion
static void SizeParamTypeIsByte()
{
string strDescription = "Scenario(byte ==> BYTE): Array_Size(N->M) = 1";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
byte byte_Array_Size;
byte[] arrByte;
Assert.IsTrue(MarshalCStyleArrayByte_AsByOut_AsSizeParamIndex(out byte_Array_Size, out arrByte));
//Construct Expected array
int expected_ByteArray_Size = 1;
byte[] expectedArrByte = Helper.GetExpChangeArray<byte>(expected_ByteArray_Size);
Assert.IsTrue(Helper.EqualArray<byte>(arrByte, (int)byte_Array_Size, expectedArrByte, (int)expectedArrByte.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsSByte()
{
string strDescription = "Scenario(sbyte ==> CHAR):Array_Size(N->M) = sbyte.Max";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
sbyte sbyte_Array_Size;
sbyte[] arrSbyte;
Assert.IsTrue(MarshalCStyleArraySbyte_AsByOut_AsSizeParamIndex(out sbyte_Array_Size, out arrSbyte));
sbyte[] expectedArrSbyte = Helper.GetExpChangeArray<sbyte>(sbyte.MaxValue);
Assert.IsTrue(Helper.EqualArray<sbyte>(arrSbyte, (int)sbyte_Array_Size, expectedArrSbyte, (int)expectedArrSbyte.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsShort1()
{
string strDescription = "Scenario(short ==> SHORT)1,Array_Size(M->N) = -1, Array_Size(N->M)=(ShortMax+1)/2";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
short shortArray_Size = (short)-1;
short[] arrShort = Helper.InitArray<short>(10);
Assert.IsTrue(MarshalCStyleArrayShort_AsByOut_AsSizeParamIndex(out shortArray_Size, out arrShort));
//Construct Expected Array
int expected_ShortArray_Size = 16384;//(SHRT_MAX+1)/2
short[] expectedArrShort = Helper.GetExpChangeArray<short>(expected_ShortArray_Size);
Assert.IsTrue(Helper.EqualArray<short>(arrShort, (int)shortArray_Size, expectedArrShort, (int)expectedArrShort.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsShort2()
{
string strDescription = "Scenario(short ==> SHORT)2, Array_Size = 10, Array_Size(N->M) = -1";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
short short_Array_Size = (short)10;
short[] arrShort = Helper.InitArray<short>(short_Array_Size);
Assert.Throws<OverflowException>(() => MarshalCStyleArrayShortReturnNegative_AsByOut_AsSizeParamIndex(out short_Array_Size, out arrShort));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsUShort()
{
string strDescription = "Scenario(ushort==>USHORT): Array_Size(N->M) = ushort.MaxValue";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
ushort ushort_Array_Size;
ushort[] arrUshort;
Assert.IsTrue(MarshalCStyleArrayUshort_AsByOut_AsSizeParamIndex(out arrUshort, out ushort_Array_Size));
//Expected Array
ushort[] expectedArrUshort = Helper.GetExpChangeArray<ushort>(ushort.MaxValue);
Assert.IsTrue(Helper.EqualArray<ushort>(arrUshort, (int)ushort_Array_Size, expectedArrUshort, (ushort)expectedArrUshort.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsInt32()
{
string strDescription = "Scenario(Int32 ==> LONG): Array_Size(N->M) = 0 ";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
Int32 Int32_Array_Size;
Int32[] arrInt32;
Assert.IsTrue(MarshalCStyleArrayInt_AsByOut_AsSizeParamIndex(out Int32_Array_Size, out arrInt32));
//Expected Array
Int32[] expectedArrInt32 = Helper.GetExpChangeArray<Int32>(0);
Assert.IsTrue(Helper.EqualArray<Int32>(arrInt32, Int32_Array_Size, expectedArrInt32, expectedArrInt32.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsUInt32()
{
string strDescription = "Scenario(UInt32 ==> ULONG): Array_Size(N->M) = 20";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
int expected_UInt32ArraySize = 20;
UInt32 UInt32_Array_Size = (UInt32)10;
UInt32[] arrUInt32 = Helper.InitArray<UInt32>((Int32)UInt32_Array_Size);
Assert.IsTrue(MarshalCStyleArrayUInt_AsByOut_AsSizeParamIndex(out UInt32_Array_Size, out arrUInt32));
//Construct expected
UInt32[] expectedArrUInt32 = Helper.GetExpChangeArray<UInt32>(expected_UInt32ArraySize);
Assert.IsTrue(Helper.EqualArray<UInt32>(arrUInt32, (Int32)UInt32_Array_Size, expectedArrUInt32, (Int32)expectedArrUInt32.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsLong()
{
string strDescription = "Scenario(long ==> LONGLONG): Array_Size(N->M) = 20";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
int expected_LongArraySize = 20;
long long_Array_Size = (long)10;
long[] arrLong = Helper.InitArray<long>((Int32)long_Array_Size);
Assert.IsTrue(MarshalCStyleArrayLong_AsByOut_AsSizeParamIndex(out long_Array_Size, out arrLong));
long[] expectedArrLong = Helper.GetExpChangeArray<long>(expected_LongArraySize);
Assert.IsTrue(Helper.EqualArray<long>(arrLong, (Int32)long_Array_Size, expectedArrLong, (Int32)expectedArrLong.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsULong()
{
string strDescription = "Scenario(ulong ==> ULONGLONG): Array_Size(N->M) = 1000";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
int expected_ULongArraySize = 1000;
ulong ulong_Array_Size = (ulong)10;
ulong[] arrUlong = Helper.InitArray<ulong>((Int32)ulong_Array_Size);
Assert.IsTrue(MarshalCStyleArrayUlong_AsByOut_AsSizeParamIndex(out arrUlong, out ulong_Array_Size, ulong_Array_Size));
ulong[] expectedArrUlong = Helper.GetExpChangeArray<ulong>(expected_ULongArraySize);
Assert.IsTrue(Helper.EqualArray<ulong>(arrUlong, (Int32)ulong_Array_Size, expectedArrUlong, (Int32)expectedArrUlong.Length));
Console.WriteLine(strDescription + " Ends!");
}
static void SizeParamTypeIsString()
{
string strDescription = "Scenario(String ==> BSTR): Array_Size(N->M) = 20";
Console.WriteLine();
Console.WriteLine(strDescription + " Starts!");
int expected_StringArraySize = 20;
int string_Array_Size = 10;
String[] arrString = Helper.InitArray<String>(string_Array_Size);
Assert.IsTrue(MarshalCStyleArrayString_AsByOut_AsSizeParamIndex(out arrString, out string_Array_Size));
String[] expArrString = Helper.GetExpChangeArray<String>(expected_StringArraySize);
Assert.IsTrue(Helper.EqualArray<String>(arrString, string_Array_Size, expArrString, expArrString.Length));
Console.WriteLine(strDescription + " Ends!");
}
static int Main()
{
try{
SizeParamTypeIsByte();
SizeParamTypeIsSByte();
SizeParamTypeIsShort1();
SizeParamTypeIsShort2();
SizeParamTypeIsUShort();
SizeParamTypeIsInt32();
SizeParamTypeIsUInt32();
SizeParamTypeIsLong();
SizeParamTypeIsULong();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
SizeParamTypeIsString();
}
return 100;
}
catch (Exception e)
{
Console.WriteLine($"Test Failure: {e}");
return 101;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="SharedSetServiceClient"/> instances.</summary>
public sealed partial class SharedSetServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="SharedSetServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="SharedSetServiceSettings"/>.</returns>
public static SharedSetServiceSettings GetDefault() => new SharedSetServiceSettings();
/// <summary>Constructs a new <see cref="SharedSetServiceSettings"/> object with default settings.</summary>
public SharedSetServiceSettings()
{
}
private SharedSetServiceSettings(SharedSetServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetSharedSetSettings = existing.GetSharedSetSettings;
MutateSharedSetsSettings = existing.MutateSharedSetsSettings;
OnCopy(existing);
}
partial void OnCopy(SharedSetServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SharedSetServiceClient.GetSharedSet</c> and <c>SharedSetServiceClient.GetSharedSetAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetSharedSetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SharedSetServiceClient.MutateSharedSets</c> and <c>SharedSetServiceClient.MutateSharedSetsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateSharedSetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="SharedSetServiceSettings"/> object.</returns>
public SharedSetServiceSettings Clone() => new SharedSetServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="SharedSetServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
internal sealed partial class SharedSetServiceClientBuilder : gaxgrpc::ClientBuilderBase<SharedSetServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public SharedSetServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public SharedSetServiceClientBuilder()
{
UseJwtAccessWithScopes = SharedSetServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref SharedSetServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<SharedSetServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override SharedSetServiceClient Build()
{
SharedSetServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<SharedSetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<SharedSetServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private SharedSetServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return SharedSetServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<SharedSetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return SharedSetServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => SharedSetServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => SharedSetServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => SharedSetServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>SharedSetService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage shared sets.
/// </remarks>
public abstract partial class SharedSetServiceClient
{
/// <summary>
/// The default endpoint for the SharedSetService service, which is a host of "googleads.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default SharedSetService scopes.</summary>
/// <remarks>
/// The default SharedSetService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="SharedSetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="SharedSetServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="SharedSetServiceClient"/>.</returns>
public static stt::Task<SharedSetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new SharedSetServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="SharedSetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="SharedSetServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="SharedSetServiceClient"/>.</returns>
public static SharedSetServiceClient Create() => new SharedSetServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="SharedSetServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="SharedSetServiceSettings"/>.</param>
/// <returns>The created <see cref="SharedSetServiceClient"/>.</returns>
internal static SharedSetServiceClient Create(grpccore::CallInvoker callInvoker, SharedSetServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
SharedSetService.SharedSetServiceClient grpcClient = new SharedSetService.SharedSetServiceClient(callInvoker);
return new SharedSetServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC SharedSetService client</summary>
public virtual SharedSetService.SharedSetServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested shared set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::SharedSet GetSharedSet(GetSharedSetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested shared set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::SharedSet> GetSharedSetAsync(GetSharedSetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested shared set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::SharedSet> GetSharedSetAsync(GetSharedSetRequest request, st::CancellationToken cancellationToken) =>
GetSharedSetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested shared set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the shared set to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::SharedSet GetSharedSet(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetSharedSet(new GetSharedSetRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested shared set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the shared set to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::SharedSet> GetSharedSetAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetSharedSetAsync(new GetSharedSetRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested shared set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the shared set to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::SharedSet> GetSharedSetAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetSharedSetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested shared set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the shared set to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::SharedSet GetSharedSet(gagvr::SharedSetName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetSharedSet(new GetSharedSetRequest
{
ResourceNameAsSharedSetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested shared set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the shared set to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::SharedSet> GetSharedSetAsync(gagvr::SharedSetName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetSharedSetAsync(new GetSharedSetRequest
{
ResourceNameAsSharedSetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested shared set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the shared set to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::SharedSet> GetSharedSetAsync(gagvr::SharedSetName resourceName, st::CancellationToken cancellationToken) =>
GetSharedSetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes shared sets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SharedSetError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateSharedSetsResponse MutateSharedSets(MutateSharedSetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes shared sets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SharedSetError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateSharedSetsResponse> MutateSharedSetsAsync(MutateSharedSetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes shared sets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SharedSetError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateSharedSetsResponse> MutateSharedSetsAsync(MutateSharedSetsRequest request, st::CancellationToken cancellationToken) =>
MutateSharedSetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes shared sets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SharedSetError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose shared sets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual shared sets.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateSharedSetsResponse MutateSharedSets(string customerId, scg::IEnumerable<SharedSetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateSharedSets(new MutateSharedSetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes shared sets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SharedSetError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose shared sets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual shared sets.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateSharedSetsResponse> MutateSharedSetsAsync(string customerId, scg::IEnumerable<SharedSetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateSharedSetsAsync(new MutateSharedSetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes shared sets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SharedSetError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose shared sets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual shared sets.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateSharedSetsResponse> MutateSharedSetsAsync(string customerId, scg::IEnumerable<SharedSetOperation> operations, st::CancellationToken cancellationToken) =>
MutateSharedSetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>SharedSetService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage shared sets.
/// </remarks>
public sealed partial class SharedSetServiceClientImpl : SharedSetServiceClient
{
private readonly gaxgrpc::ApiCall<GetSharedSetRequest, gagvr::SharedSet> _callGetSharedSet;
private readonly gaxgrpc::ApiCall<MutateSharedSetsRequest, MutateSharedSetsResponse> _callMutateSharedSets;
/// <summary>
/// Constructs a client wrapper for the SharedSetService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="SharedSetServiceSettings"/> used within this client.</param>
public SharedSetServiceClientImpl(SharedSetService.SharedSetServiceClient grpcClient, SharedSetServiceSettings settings)
{
GrpcClient = grpcClient;
SharedSetServiceSettings effectiveSettings = settings ?? SharedSetServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetSharedSet = clientHelper.BuildApiCall<GetSharedSetRequest, gagvr::SharedSet>(grpcClient.GetSharedSetAsync, grpcClient.GetSharedSet, effectiveSettings.GetSharedSetSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetSharedSet);
Modify_GetSharedSetApiCall(ref _callGetSharedSet);
_callMutateSharedSets = clientHelper.BuildApiCall<MutateSharedSetsRequest, MutateSharedSetsResponse>(grpcClient.MutateSharedSetsAsync, grpcClient.MutateSharedSets, effectiveSettings.MutateSharedSetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateSharedSets);
Modify_MutateSharedSetsApiCall(ref _callMutateSharedSets);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetSharedSetApiCall(ref gaxgrpc::ApiCall<GetSharedSetRequest, gagvr::SharedSet> call);
partial void Modify_MutateSharedSetsApiCall(ref gaxgrpc::ApiCall<MutateSharedSetsRequest, MutateSharedSetsResponse> call);
partial void OnConstruction(SharedSetService.SharedSetServiceClient grpcClient, SharedSetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC SharedSetService client</summary>
public override SharedSetService.SharedSetServiceClient GrpcClient { get; }
partial void Modify_GetSharedSetRequest(ref GetSharedSetRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateSharedSetsRequest(ref MutateSharedSetsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested shared set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::SharedSet GetSharedSet(GetSharedSetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetSharedSetRequest(ref request, ref callSettings);
return _callGetSharedSet.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested shared set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::SharedSet> GetSharedSetAsync(GetSharedSetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetSharedSetRequest(ref request, ref callSettings);
return _callGetSharedSet.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes shared sets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SharedSetError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateSharedSetsResponse MutateSharedSets(MutateSharedSetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateSharedSetsRequest(ref request, ref callSettings);
return _callMutateSharedSets.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes shared sets. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SharedSetError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateSharedSetsResponse> MutateSharedSetsAsync(MutateSharedSetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateSharedSetsRequest(ref request, ref callSettings);
return _callMutateSharedSets.Async(request, callSettings);
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Junit.Framework.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 Junit.Framework
{
/// <summary>
/// <para>A <b>Protectable</b> can be run and can throw a Throwable.</para><para><para>TestResult </para></para>
/// </summary>
/// <java-name>
/// junit/framework/Protectable
/// </java-name>
[Dot42.DexImport("junit/framework/Protectable", AccessFlags = 1537)]
public partial interface IProtectable
/* scope: __dot42__ */
{
/// <summary>
/// <para>Run the the following method protected. </para>
/// </summary>
/// <java-name>
/// protect
/// </java-name>
[Dot42.DexImport("protect", "()V", AccessFlags = 1025)]
void Protect() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>A <code>TestFailure</code> collects a failed test together with the caught exception. <para>TestResult </para></para>
/// </summary>
/// <java-name>
/// junit/framework/TestFailure
/// </java-name>
[Dot42.DexImport("junit/framework/TestFailure", AccessFlags = 33)]
public partial class TestFailure
/* scope: __dot42__ */
{
/// <java-name>
/// fFailedTest
/// </java-name>
[Dot42.DexImport("fFailedTest", "Ljunit/framework/Test;", AccessFlags = 4)]
protected internal global::Junit.Framework.ITest FFailedTest;
/// <java-name>
/// fThrownException
/// </java-name>
[Dot42.DexImport("fThrownException", "Ljava/lang/Throwable;", AccessFlags = 4)]
protected internal global::System.Exception FThrownException;
/// <summary>
/// <para>Constructs a TestFailure with the given test and exception. </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public TestFailure(global::Junit.Framework.ITest failedTest, global::System.Exception thrownException) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the failed test. </para>
/// </summary>
/// <java-name>
/// failedTest
/// </java-name>
[Dot42.DexImport("failedTest", "()Ljunit/framework/Test;", AccessFlags = 1)]
public virtual global::Junit.Framework.ITest FailedTest() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.ITest);
}
/// <summary>
/// <para>Gets the thrown exception. </para>
/// </summary>
/// <java-name>
/// thrownException
/// </java-name>
[Dot42.DexImport("thrownException", "()Ljava/lang/Throwable;", AccessFlags = 1)]
public virtual global::System.Exception ThrownException() /* MethodBuilder.Create */
{
return default(global::System.Exception);
}
/// <summary>
/// <para>Returns a short description of the failure. </para>
/// </summary>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// trace
/// </java-name>
[Dot42.DexImport("trace", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string Trace() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// exceptionMessage
/// </java-name>
[Dot42.DexImport("exceptionMessage", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string ExceptionMessage() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// isFailure
/// </java-name>
[Dot42.DexImport("isFailure", "()Z", AccessFlags = 1)]
public virtual bool IsFailure() /* MethodBuilder.Create */
{
return default(bool);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal TestFailure() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>A set of assert methods. Messages are only displayed when an assert fails. </para>
/// </summary>
/// <java-name>
/// junit/framework/Assert
/// </java-name>
[Dot42.DexImport("junit/framework/Assert", AccessFlags = 33)]
public partial class Assert
/* scope: __dot42__ */
{
/// <summary>
/// <para>Protect constructor since it is a static only class </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal Assert() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that a condition is true. If it isn't it throws an AssertionFailedError with the given message. </para>
/// </summary>
/// <java-name>
/// assertTrue
/// </java-name>
[Dot42.DexImport("assertTrue", "(Ljava/lang/String;Z)V", AccessFlags = 9)]
public static void AssertTrue(string message, bool condition) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that a condition is true. If it isn't it throws an AssertionFailedError. </para>
/// </summary>
/// <java-name>
/// assertTrue
/// </java-name>
[Dot42.DexImport("assertTrue", "(Z)V", AccessFlags = 9)]
public static void AssertTrue(bool condition) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that a condition is false. If it isn't it throws an AssertionFailedError with the given message. </para>
/// </summary>
/// <java-name>
/// assertFalse
/// </java-name>
[Dot42.DexImport("assertFalse", "(Ljava/lang/String;Z)V", AccessFlags = 9)]
public static void AssertFalse(string message, bool condition) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that a condition is false. If it isn't it throws an AssertionFailedError. </para>
/// </summary>
/// <java-name>
/// assertFalse
/// </java-name>
[Dot42.DexImport("assertFalse", "(Z)V", AccessFlags = 9)]
public static void AssertFalse(bool condition) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Fails a test with the given message. </para>
/// </summary>
/// <java-name>
/// fail
/// </java-name>
[Dot42.DexImport("fail", "(Ljava/lang/String;)V", AccessFlags = 9)]
public static void Fail(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Fails a test with no message. </para>
/// </summary>
/// <java-name>
/// fail
/// </java-name>
[Dot42.DexImport("fail", "()V", AccessFlags = 9)]
public static void Fail() /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertEquals(string @string, object @object, object object1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertEquals(object expected, object actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 9)]
public static void AssertEquals(string @string, string string1, string string2) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 9)]
public static void AssertEquals(string expected, string actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;DDD)V", AccessFlags = 9)]
public static void AssertEquals(string @string, double @double, double double1, double double2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(DDD)V", AccessFlags = 9)]
public static void AssertEquals(double @double, double double1, double double2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;FFF)V", AccessFlags = 9)]
public static void AssertEquals(string @string, float single, float single1, float single2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(FFF)V", AccessFlags = 9)]
public static void AssertEquals(float single, float single1, float single2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;JJ)V", AccessFlags = 9)]
public static void AssertEquals(string @string, long int64, long int641) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(JJ)V", AccessFlags = 9)]
public static void AssertEquals(long expected, long actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;ZZ)V", AccessFlags = 9)]
public static void AssertEquals(string @string, bool boolean, bool boolean1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(ZZ)V", AccessFlags = 9)]
public static void AssertEquals(bool expected, bool actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;BB)V", AccessFlags = 9)]
public static void AssertEquals(string @string, sbyte sByte, sbyte sByte1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;BB)V", AccessFlags = 9, IgnoreFromJava = true)]
public static void AssertEquals(string @string, byte @byte, byte byte1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(BB)V", AccessFlags = 9)]
public static void AssertEquals(sbyte expected, sbyte actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(BB)V", AccessFlags = 9, IgnoreFromJava = true)]
public static void AssertEquals(byte expected, byte actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;CC)V", AccessFlags = 9)]
public static void AssertEquals(string @string, char @char, char char1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(CC)V", AccessFlags = 9)]
public static void AssertEquals(char expected, char actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;SS)V", AccessFlags = 9)]
public static void AssertEquals(string @string, short int16, short int161) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(SS)V", AccessFlags = 9)]
public static void AssertEquals(short expected, short actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;II)V", AccessFlags = 9)]
public static void AssertEquals(string @string, int int32, int int321) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two ints are equal. </para>
/// </summary>
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(II)V", AccessFlags = 9)]
public static void AssertEquals(int expected, int actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that an object isn't null. </para>
/// </summary>
/// <java-name>
/// assertNotNull
/// </java-name>
[Dot42.DexImport("assertNotNull", "(Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotNull(object @object) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that an object isn't null. If it is an AssertionFailedError is thrown with the given message. </para>
/// </summary>
/// <java-name>
/// assertNotNull
/// </java-name>
[Dot42.DexImport("assertNotNull", "(Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotNull(string message, object @object) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that an object is null. If it isn't an AssertionError is thrown. Message contains: Expected: <null> but was: object</para><para></para>
/// </summary>
/// <java-name>
/// assertNull
/// </java-name>
[Dot42.DexImport("assertNull", "(Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNull(object @object) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that an object is null. If it is not an AssertionFailedError is thrown with the given message. </para>
/// </summary>
/// <java-name>
/// assertNull
/// </java-name>
[Dot42.DexImport("assertNull", "(Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNull(string message, object @object) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two objects refer to the same object. If they are not an AssertionFailedError is thrown with the given message. </para>
/// </summary>
/// <java-name>
/// assertSame
/// </java-name>
[Dot42.DexImport("assertSame", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertSame(string message, object expected, object actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two objects refer to the same object. If they are not the same an AssertionFailedError is thrown. </para>
/// </summary>
/// <java-name>
/// assertSame
/// </java-name>
[Dot42.DexImport("assertSame", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertSame(object expected, object actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two objects do not refer to the same object. If they do refer to the same object an AssertionFailedError is thrown with the given message. </para>
/// </summary>
/// <java-name>
/// assertNotSame
/// </java-name>
[Dot42.DexImport("assertNotSame", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotSame(string message, object expected, object actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that two objects do not refer to the same object. If they do refer to the same object an AssertionFailedError is thrown. </para>
/// </summary>
/// <java-name>
/// assertNotSame
/// </java-name>
[Dot42.DexImport("assertNotSame", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotSame(object expected, object actual) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>A <code>TestResult</code> collects the results of executing a test case. It is an instance of the Collecting Parameter pattern. The test framework distinguishes between <b>failures</b> and <b>errors</b>. A failure is anticipated and checked for with assertions. Errors are unanticipated problems like an ArrayIndexOutOfBoundsException.</para><para><para>Test </para></para>
/// </summary>
/// <java-name>
/// junit/framework/TestResult
/// </java-name>
[Dot42.DexImport("junit/framework/TestResult", AccessFlags = 33)]
public partial class TestResult
/* scope: __dot42__ */
{
/// <java-name>
/// fFailures
/// </java-name>
[Dot42.DexImport("fFailures", "Ljava/util/Vector;", AccessFlags = 4)]
protected internal global::Java.Util.Vector<object> FFailures;
/// <java-name>
/// fErrors
/// </java-name>
[Dot42.DexImport("fErrors", "Ljava/util/Vector;", AccessFlags = 4)]
protected internal global::Java.Util.Vector<object> FErrors;
/// <java-name>
/// fListeners
/// </java-name>
[Dot42.DexImport("fListeners", "Ljava/util/Vector;", AccessFlags = 4)]
protected internal global::Java.Util.Vector<object> FListeners;
/// <java-name>
/// fRunTests
/// </java-name>
[Dot42.DexImport("fRunTests", "I", AccessFlags = 4)]
protected internal int FRunTests;
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public TestResult() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Adds an error to the list of errors. The passed in exception caused the error. </para>
/// </summary>
/// <java-name>
/// addError
/// </java-name>
[Dot42.DexImport("addError", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 33)]
public virtual void AddError(global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Adds a failure to the list of failures. The passed in exception caused the failure. </para>
/// </summary>
/// <java-name>
/// addFailure
/// </java-name>
[Dot42.DexImport("addFailure", "(Ljunit/framework/Test;Ljunit/framework/AssertionFailedError;)V", AccessFlags = 33)]
public virtual void AddFailure(global::Junit.Framework.ITest test, global::Junit.Framework.AssertionFailedError t) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Registers a TestListener </para>
/// </summary>
/// <java-name>
/// addListener
/// </java-name>
[Dot42.DexImport("addListener", "(Ljunit/framework/TestListener;)V", AccessFlags = 33)]
public virtual void AddListener(global::Junit.Framework.ITestListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Unregisters a TestListener </para>
/// </summary>
/// <java-name>
/// removeListener
/// </java-name>
[Dot42.DexImport("removeListener", "(Ljunit/framework/TestListener;)V", AccessFlags = 33)]
public virtual void RemoveListener(global::Junit.Framework.ITestListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Informs the result that a test was completed. </para>
/// </summary>
/// <java-name>
/// endTest
/// </java-name>
[Dot42.DexImport("endTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)]
public virtual void EndTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the number of detected errors. </para>
/// </summary>
/// <java-name>
/// errorCount
/// </java-name>
[Dot42.DexImport("errorCount", "()I", AccessFlags = 33)]
public virtual int ErrorCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns an Enumeration for the errors </para>
/// </summary>
/// <java-name>
/// errors
/// </java-name>
[Dot42.DexImport("errors", "()Ljava/util/Enumeration;", AccessFlags = 33)]
public virtual global::Java.Util.IEnumeration<object> Errors() /* MethodBuilder.Create */
{
return default(global::Java.Util.IEnumeration<object>);
}
/// <summary>
/// <para>Gets the number of detected failures. </para>
/// </summary>
/// <java-name>
/// failureCount
/// </java-name>
[Dot42.DexImport("failureCount", "()I", AccessFlags = 33)]
public virtual int FailureCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns an Enumeration for the failures </para>
/// </summary>
/// <java-name>
/// failures
/// </java-name>
[Dot42.DexImport("failures", "()Ljava/util/Enumeration;", AccessFlags = 33)]
public virtual global::Java.Util.IEnumeration<object> Failures() /* MethodBuilder.Create */
{
return default(global::Java.Util.IEnumeration<object>);
}
/// <summary>
/// <para>Runs a TestCase. </para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "(Ljunit/framework/TestCase;)V", AccessFlags = 4)]
protected internal virtual void Run(global::Junit.Framework.TestCase test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the number of run tests. </para>
/// </summary>
/// <java-name>
/// runCount
/// </java-name>
[Dot42.DexImport("runCount", "()I", AccessFlags = 33)]
public virtual int RunCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Runs a TestCase. </para>
/// </summary>
/// <java-name>
/// runProtected
/// </java-name>
[Dot42.DexImport("runProtected", "(Ljunit/framework/Test;Ljunit/framework/Protectable;)V", AccessFlags = 1)]
public virtual void RunProtected(global::Junit.Framework.ITest test, global::Junit.Framework.IProtectable p) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Checks whether the test run should stop </para>
/// </summary>
/// <java-name>
/// shouldStop
/// </java-name>
[Dot42.DexImport("shouldStop", "()Z", AccessFlags = 33)]
public virtual bool ShouldStop() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Informs the result that a test will be started. </para>
/// </summary>
/// <java-name>
/// startTest
/// </java-name>
[Dot42.DexImport("startTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)]
public virtual void StartTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Marks that the test run should stop. </para>
/// </summary>
/// <java-name>
/// stop
/// </java-name>
[Dot42.DexImport("stop", "()V", AccessFlags = 33)]
public virtual void Stop() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns whether the entire test was successful or not. </para>
/// </summary>
/// <java-name>
/// wasSuccessful
/// </java-name>
[Dot42.DexImport("wasSuccessful", "()Z", AccessFlags = 33)]
public virtual bool WasSuccessful() /* MethodBuilder.Create */
{
return default(bool);
}
}
/// <summary>
/// <para>Thrown when an assertion failed. </para>
/// </summary>
/// <java-name>
/// junit/framework/AssertionFailedError
/// </java-name>
[Dot42.DexImport("junit/framework/AssertionFailedError", AccessFlags = 33)]
public partial class AssertionFailedError : global::Java.Lang.Error
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public AssertionFailedError() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public AssertionFailedError(string message) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>A <code>TestSuite</code> is a <code>Composite</code> of Tests. It runs a collection of test cases. Here is an example using the dynamic test definition. <pre>
/// TestSuite suite= new TestSuite();
/// suite.addTest(new MathTest("testAdd"));
/// suite.addTest(new MathTest("testDivideByZero"));
/// </pre> </para><para>Alternatively, a TestSuite can extract the tests to be run automatically. To do so you pass the class of your TestCase class to the TestSuite constructor. <pre>
/// TestSuite suite= new TestSuite(MathTest.class);
/// </pre> </para><para>This constructor creates a suite with all the methods starting with "test" that take no arguments.</para><para>A final option is to do the same for a large array of test classes. <pre>
/// Class[] testClasses = { MathTest.class, AnotherTest.class }
/// TestSuite suite= new TestSuite(testClasses);
/// </pre> </para><para><para>Test </para></para>
/// </summary>
/// <java-name>
/// junit/framework/TestSuite
/// </java-name>
[Dot42.DexImport("junit/framework/TestSuite", AccessFlags = 33)]
public partial class TestSuite : global::Junit.Framework.ITest
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs an empty TestSuite. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public TestSuite() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/Class;Ljava/lang/String;)V", AccessFlags = 1)]
public TestSuite(global::System.Type type, string @string) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/Class;)V", AccessFlags = 1)]
public TestSuite(global::System.Type type) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public TestSuite(string @string) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Adds a test to the suite. </para>
/// </summary>
/// <java-name>
/// addTest
/// </java-name>
[Dot42.DexImport("addTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)]
public virtual void AddTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Adds the tests from the given class to the suite </para>
/// </summary>
/// <java-name>
/// addTestSuite
/// </java-name>
[Dot42.DexImport("addTestSuite", "(Ljava/lang/Class;)V", AccessFlags = 1)]
public virtual void AddTestSuite(global::System.Type testClass) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>...as the moon sets over the early morning Merlin, Oregon mountains, our intrepid adventurers type... </para>
/// </summary>
/// <java-name>
/// createTest
/// </java-name>
[Dot42.DexImport("createTest", "(Ljava/lang/Class;Ljava/lang/String;)Ljunit/framework/Test;", AccessFlags = 9)]
public static global::Junit.Framework.ITest CreateTest(global::System.Type theClass, string name) /* MethodBuilder.Create */
{
return default(global::Junit.Framework.ITest);
}
/// <summary>
/// <para>Counts the number of test cases that will be run by this test. </para>
/// </summary>
/// <java-name>
/// countTestCases
/// </java-name>
[Dot42.DexImport("countTestCases", "()I", AccessFlags = 1)]
public virtual int CountTestCases() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Gets a constructor which takes a single String as its argument or a no arg constructor. </para>
/// </summary>
/// <java-name>
/// getTestConstructor
/// </java-name>
[Dot42.DexImport("getTestConstructor", "(Ljava/lang/Class;)Ljava/lang/reflect/Constructor;", AccessFlags = 9)]
public static global::System.Reflection.ConstructorInfo GetTestConstructor(global::System.Type theClass) /* MethodBuilder.Create */
{
return default(global::System.Reflection.ConstructorInfo);
}
/// <summary>
/// <para>Runs the tests and collects their result in a TestResult. </para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "(Ljunit/framework/TestResult;)V", AccessFlags = 1)]
public virtual void Run(global::Junit.Framework.TestResult result) /* MethodBuilder.Create */
{
}
/// <java-name>
/// runTest
/// </java-name>
[Dot42.DexImport("runTest", "(Ljunit/framework/Test;Ljunit/framework/TestResult;)V", AccessFlags = 1)]
public virtual void RunTest(global::Junit.Framework.ITest test, global::Junit.Framework.TestResult result) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the test at the given index </para>
/// </summary>
/// <java-name>
/// testAt
/// </java-name>
[Dot42.DexImport("testAt", "(I)Ljunit/framework/Test;", AccessFlags = 1)]
public virtual global::Junit.Framework.ITest TestAt(int index) /* MethodBuilder.Create */
{
return default(global::Junit.Framework.ITest);
}
/// <summary>
/// <para>Returns the number of tests in this suite </para>
/// </summary>
/// <java-name>
/// testCount
/// </java-name>
[Dot42.DexImport("testCount", "()I", AccessFlags = 1)]
public virtual int TestCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns the tests as an enumeration </para>
/// </summary>
/// <java-name>
/// tests
/// </java-name>
[Dot42.DexImport("tests", "()Ljava/util/Enumeration;", AccessFlags = 1)]
public virtual global::Java.Util.IEnumeration<object> Tests() /* MethodBuilder.Create */
{
return default(global::Java.Util.IEnumeration<object>);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Sets the name of the suite. </para>
/// </summary>
/// <java-name>
/// setName
/// </java-name>
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetName(string name) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the name of the suite. Not all test suites have a name and this method can return null. </para>
/// </summary>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the name of the suite. Not all test suites have a name and this method can return null. </para>
/// </summary>
/// <java-name>
/// getName
/// </java-name>
public string Name
{
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetName(); }
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetName(value); }
}
}
/// <summary>
/// <para>A test case defines the fixture to run multiple tests. To define a test case<br></br> <ol><li><para>implement a subclass of <code>TestCase</code> </para></li><li><para>define instance variables that store the state of the fixture </para></li><li><para>initialize the fixture state by overriding setUp() </para></li><li><para>clean-up after a test by overriding tearDown(). </para></li></ol>Each test runs in its own fixture so there can be no side effects among test runs. Here is an example: <pre>
/// public class MathTest extends TestCase {
/// protected double fValue1;
/// protected double fValue2;
///
/// protected void setUp() {
/// fValue1= 2.0;
/// fValue2= 3.0;
/// }
/// }
/// </pre></para><para>For each test implement a method which interacts with the fixture. Verify the expected results with assertions specified by calling junit.framework.Assert#assertTrue(String, boolean) with a boolean. <pre>
/// public void testAdd() {
/// double result= fValue1 + fValue2;
/// assertTrue(result == 5.0);
/// }
/// </pre></para><para>Once the methods are defined you can run them. The framework supports both a static type safe and more dynamic way to run a test. In the static way you override the runTest method and define the method to be invoked. A convenient way to do so is with an anonymous inner class. <pre>
/// TestCase test= new MathTest("add") {
/// public void runTest() {
/// testAdd();
/// }
/// };
/// test.run();
/// </pre></para><para>The dynamic way uses reflection to implement runTest(). It dynamically finds and invokes a method. In this case the name of the test case has to correspond to the test method to be run. <pre>
/// TestCase test= new MathTest("testAdd");
/// test.run();
/// </pre></para><para>The tests to be run can be collected into a TestSuite. JUnit provides different <b>test runners</b> which can run a test suite and collect the results. A test runner either expects a static method <code>suite</code> as the entry point to get a test to run or it will extract the suite automatically. <pre>
/// public static Test suite() {
/// suite.addTest(new MathTest("testAdd"));
/// suite.addTest(new MathTest("testDivideByZero"));
/// return suite;
/// }
/// </pre> <para>TestResult </para><simplesectsep></simplesectsep><para>TestSuite </para></para>
/// </summary>
/// <java-name>
/// junit/framework/TestCase
/// </java-name>
[Dot42.DexImport("junit/framework/TestCase", AccessFlags = 1057)]
public abstract partial class TestCase : global::Junit.Framework.Assert, global::Junit.Framework.ITest
/* scope: __dot42__ */
{
/// <summary>
/// <para>No-arg constructor to enable serialization. This method is not intended to be used by mere mortals without calling setName(). </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public TestCase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Constructs a test case with the given name. </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public TestCase(string name) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Counts the number of test cases executed by run(TestResult result). </para>
/// </summary>
/// <java-name>
/// countTestCases
/// </java-name>
[Dot42.DexImport("countTestCases", "()I", AccessFlags = 1)]
public virtual int CountTestCases() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Creates a default TestResult object</para><para><para>TestResult </para></para>
/// </summary>
/// <java-name>
/// createResult
/// </java-name>
[Dot42.DexImport("createResult", "()Ljunit/framework/TestResult;", AccessFlags = 4)]
protected internal virtual global::Junit.Framework.TestResult CreateResult() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.TestResult);
}
/// <summary>
/// <para>A convenience method to run this test, collecting the results with a default TestResult object.</para><para><para>TestResult </para></para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "()Ljunit/framework/TestResult;", AccessFlags = 1)]
public virtual global::Junit.Framework.TestResult Run() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.TestResult);
}
/// <summary>
/// <para>Runs the test case and collects the results in TestResult. </para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "(Ljunit/framework/TestResult;)V", AccessFlags = 1)]
public virtual void Run(global::Junit.Framework.TestResult result) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Runs the bare test sequence. </para>
/// </summary>
/// <java-name>
/// runBare
/// </java-name>
[Dot42.DexImport("runBare", "()V", AccessFlags = 1)]
public virtual void RunBare() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Override to run the test and assert its state. </para>
/// </summary>
/// <java-name>
/// runTest
/// </java-name>
[Dot42.DexImport("runTest", "()V", AccessFlags = 4)]
protected internal virtual void RunTest() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets up the fixture, for example, open a network connection. This method is called before a test is executed. </para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal virtual void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tears down the fixture, for example, close a network connection. This method is called after a test is executed. </para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal virtual void TearDown() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns a string representation of the test case </para>
/// </summary>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Gets the name of a TestCase </para>
/// </summary>
/// <returns>
/// <para>the name of the TestCase </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Sets the name of a TestCase </para>
/// </summary>
/// <java-name>
/// setName
/// </java-name>
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetName(string name) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the name of a TestCase </para>
/// </summary>
/// <returns>
/// <para>the name of the TestCase </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
public string Name
{
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetName(); }
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetName(value); }
}
}
/// <summary>
/// <para>Thrown when an assert equals for Strings failed.</para><para>Inspired by a patch from Alex Chaffee </para>
/// </summary>
/// <java-name>
/// junit/framework/ComparisonFailure
/// </java-name>
[Dot42.DexImport("junit/framework/ComparisonFailure", AccessFlags = 33)]
public partial class ComparisonFailure : global::Junit.Framework.AssertionFailedError
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a comparison failure. </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public ComparisonFailure(string message, string expected, string actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns "..." in place of common prefix and "..." in place of common suffix between expected and actual.</para><para><para>Throwable::getMessage() </para></para>
/// </summary>
/// <java-name>
/// getMessage
/// </java-name>
[Dot42.DexImport("getMessage", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMessage() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ComparisonFailure() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>A Listener for test progress </para>
/// </summary>
/// <java-name>
/// junit/framework/TestListener
/// </java-name>
[Dot42.DexImport("junit/framework/TestListener", AccessFlags = 1537)]
public partial interface ITestListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>An error occurred. </para>
/// </summary>
/// <java-name>
/// addError
/// </java-name>
[Dot42.DexImport("addError", "(Ljunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 1025)]
void AddError(global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>A failure occurred. </para>
/// </summary>
/// <java-name>
/// addFailure
/// </java-name>
[Dot42.DexImport("addFailure", "(Ljunit/framework/Test;Ljunit/framework/AssertionFailedError;)V", AccessFlags = 1025)]
void AddFailure(global::Junit.Framework.ITest test, global::Junit.Framework.AssertionFailedError t) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>A test ended. </para>
/// </summary>
/// <java-name>
/// endTest
/// </java-name>
[Dot42.DexImport("endTest", "(Ljunit/framework/Test;)V", AccessFlags = 1025)]
void EndTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>A test started. </para>
/// </summary>
/// <java-name>
/// startTest
/// </java-name>
[Dot42.DexImport("startTest", "(Ljunit/framework/Test;)V", AccessFlags = 1025)]
void StartTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>A <b>Test</b> can be run and collect its results.</para><para><para>TestResult </para></para>
/// </summary>
/// <java-name>
/// junit/framework/Test
/// </java-name>
[Dot42.DexImport("junit/framework/Test", AccessFlags = 1537)]
public partial interface ITest
/* scope: __dot42__ */
{
/// <summary>
/// <para>Counts the number of test cases that will be run by this test. </para>
/// </summary>
/// <java-name>
/// countTestCases
/// </java-name>
[Dot42.DexImport("countTestCases", "()I", AccessFlags = 1025)]
int CountTestCases() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Runs a test and collects its result in a TestResult instance. </para>
/// </summary>
/// <java-name>
/// run
/// </java-name>
[Dot42.DexImport("run", "(Ljunit/framework/TestResult;)V", AccessFlags = 1025)]
void Run(global::Junit.Framework.TestResult result) /* MethodBuilder.Create */ ;
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcsv = Google.Cloud.ServiceDirectory.V1;
using sys = System;
namespace Google.Cloud.ServiceDirectory.V1
{
/// <summary>Resource name for the <c>Service</c> resource.</summary>
public sealed partial class ServiceName : gax::IResourceName, sys::IEquatable<ServiceName>
{
/// <summary>The possible contents of <see cref="ServiceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>.
/// </summary>
ProjectLocationNamespaceService = 1,
}
private static gax::PathTemplate s_projectLocationNamespaceService = new gax::PathTemplate("projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}");
/// <summary>Creates a <see cref="ServiceName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ServiceName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static ServiceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ServiceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ServiceName"/> with the pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ServiceName"/> constructed from the provided ids.</returns>
public static ServiceName FromProjectLocationNamespaceService(string projectId, string locationId, string namespaceId, string serviceId) =>
new ServiceName(ResourceNameType.ProjectLocationNamespaceService, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), namespaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ServiceName"/> with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string namespaceId, string serviceId) =>
FormatProjectLocationNamespaceService(projectId, locationId, namespaceId, serviceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ServiceName"/> with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>.
/// </returns>
public static string FormatProjectLocationNamespaceService(string projectId, string locationId, string namespaceId, string serviceId) =>
s_projectLocationNamespaceService.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)));
/// <summary>Parses the given resource name string into a new <see cref="ServiceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ServiceName"/> if successful.</returns>
public static ServiceName Parse(string serviceName) => Parse(serviceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ServiceName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ServiceName"/> if successful.</returns>
public static ServiceName Parse(string serviceName, bool allowUnparsed) =>
TryParse(serviceName, allowUnparsed, out ServiceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ServiceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ServiceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string serviceName, out ServiceName result) => TryParse(serviceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ServiceName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ServiceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string serviceName, bool allowUnparsed, out ServiceName result)
{
gax::GaxPreconditions.CheckNotNull(serviceName, nameof(serviceName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationNamespaceService.TryParseName(serviceName, out resourceName))
{
result = FromProjectLocationNamespaceService(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(serviceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ServiceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string namespaceId = null, string projectId = null, string serviceId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
NamespaceId = namespaceId;
ProjectId = projectId;
ServiceId = serviceId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ServiceName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
public ServiceName(string projectId, string locationId, string namespaceId, string serviceId) : this(ResourceNameType.ProjectLocationNamespaceService, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), namespaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Namespace</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string NamespaceId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Service</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ServiceId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationNamespaceService: return s_projectLocationNamespaceService.Expand(ProjectId, LocationId, NamespaceId, ServiceId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ServiceName);
/// <inheritdoc/>
public bool Equals(ServiceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ServiceName a, ServiceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ServiceName a, ServiceName b) => !(a == b);
}
public partial class Service
{
/// <summary>
/// <see cref="gcsv::ServiceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::ServiceName ServiceName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::ServiceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Codec = Lucene.Net.Codecs.Codec;
using Directory = Lucene.Net.Store.Directory;
using DocValuesConsumer = Lucene.Net.Codecs.DocValuesConsumer;
using FieldInfosWriter = Lucene.Net.Codecs.FieldInfosWriter;
using FieldsConsumer = Lucene.Net.Codecs.FieldsConsumer;
using IBits = Lucene.Net.Util.IBits;
using InfoStream = Lucene.Net.Util.InfoStream;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using StoredFieldsWriter = Lucene.Net.Codecs.StoredFieldsWriter;
using TermVectorsWriter = Lucene.Net.Codecs.TermVectorsWriter;
/// <summary>
/// The <see cref="SegmentMerger"/> class combines two or more Segments, represented by an
/// <see cref="IndexReader"/>, into a single Segment. Call the merge method to combine the
/// segments.
/// </summary>
/// <seealso cref="Merge()"/>
internal sealed class SegmentMerger
{
private readonly Directory directory;
private readonly int termIndexInterval;
private readonly Codec codec;
private readonly IOContext context;
private readonly MergeState mergeState;
private readonly FieldInfos.Builder fieldInfosBuilder;
// note, just like in codec apis Directory 'dir' is NOT the same as segmentInfo.dir!!
internal SegmentMerger(IList<AtomicReader> readers, SegmentInfo segmentInfo, InfoStream infoStream, Directory dir, int termIndexInterval, CheckAbort checkAbort, FieldInfos.FieldNumbers fieldNumbers, IOContext context, bool validate)
{
// validate incoming readers
if (validate)
{
foreach (AtomicReader reader in readers)
{
reader.CheckIntegrity();
}
}
mergeState = new MergeState(readers, segmentInfo, infoStream, checkAbort);
directory = dir;
this.termIndexInterval = termIndexInterval;
this.codec = segmentInfo.Codec;
this.context = context;
this.fieldInfosBuilder = new FieldInfos.Builder(fieldNumbers);
mergeState.SegmentInfo.DocCount = SetDocMaps();
}
/// <summary>
/// <c>True</c> if any merging should happen </summary>
internal bool ShouldMerge => mergeState.SegmentInfo.DocCount > 0;
/// <summary>
/// Merges the readers into the directory passed to the constructor </summary>
/// <returns> The number of documents that were merged </returns>
/// <exception cref="CorruptIndexException"> if the index is corrupt </exception>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
[MethodImpl(MethodImplOptions.NoInlining)]
internal MergeState Merge()
{
if (!ShouldMerge)
{
throw new InvalidOperationException("Merge would result in 0 document segment");
}
// NOTE: it's important to add calls to
// checkAbort.work(...) if you make any changes to this
// method that will spend alot of time. The frequency
// of this check impacts how long
// IndexWriter.close(false) takes to actually stop the
// threads.
MergeFieldInfos();
SetMatchingSegmentReaders();
long t0 = 0;
if (mergeState.InfoStream.IsEnabled("SM"))
{
t0 = Time.NanoTime();
}
int numMerged = MergeFields();
if (mergeState.InfoStream.IsEnabled("SM"))
{
long t1 = Time.NanoTime();
mergeState.InfoStream.Message("SM", ((t1 - t0) / 1000000) + " msec to merge stored fields [" + numMerged + " docs]");
}
if (Debugging.AssertsEnabled) Debugging.Assert(numMerged == mergeState.SegmentInfo.DocCount);
SegmentWriteState segmentWriteState = new SegmentWriteState(mergeState.InfoStream, directory, mergeState.SegmentInfo, mergeState.FieldInfos, termIndexInterval, null, context);
if (mergeState.InfoStream.IsEnabled("SM"))
{
t0 = Time.NanoTime();
}
MergeTerms(segmentWriteState);
if (mergeState.InfoStream.IsEnabled("SM"))
{
long t1 = Time.NanoTime();
mergeState.InfoStream.Message("SM", ((t1 - t0) / 1000000) + " msec to merge postings [" + numMerged + " docs]");
}
if (mergeState.InfoStream.IsEnabled("SM"))
{
t0 = Time.NanoTime();
}
if (mergeState.FieldInfos.HasDocValues)
{
MergeDocValues(segmentWriteState);
}
if (mergeState.InfoStream.IsEnabled("SM"))
{
long t1 = Time.NanoTime();
mergeState.InfoStream.Message("SM", ((t1 - t0) / 1000000) + " msec to merge doc values [" + numMerged + " docs]");
}
if (mergeState.FieldInfos.HasNorms)
{
if (mergeState.InfoStream.IsEnabled("SM"))
{
t0 = Time.NanoTime();
}
MergeNorms(segmentWriteState);
if (mergeState.InfoStream.IsEnabled("SM"))
{
long t1 = Time.NanoTime();
mergeState.InfoStream.Message("SM", ((t1 - t0) / 1000000) + " msec to merge norms [" + numMerged + " docs]");
}
}
if (mergeState.FieldInfos.HasVectors)
{
if (mergeState.InfoStream.IsEnabled("SM"))
{
t0 = Time.NanoTime();
}
numMerged = MergeVectors();
if (mergeState.InfoStream.IsEnabled("SM"))
{
long t1 = Time.NanoTime();
mergeState.InfoStream.Message("SM", ((t1 - t0) / 1000000) + " msec to merge vectors [" + numMerged + " docs]");
}
if (Debugging.AssertsEnabled) Debugging.Assert(numMerged == mergeState.SegmentInfo.DocCount);
}
// write the merged infos
FieldInfosWriter fieldInfosWriter = codec.FieldInfosFormat.FieldInfosWriter;
fieldInfosWriter.Write(directory, mergeState.SegmentInfo.Name, "", mergeState.FieldInfos, context);
return mergeState;
}
private void MergeDocValues(SegmentWriteState segmentWriteState)
{
DocValuesConsumer consumer = codec.DocValuesFormat.FieldsConsumer(segmentWriteState);
bool success = false;
try
{
foreach (FieldInfo field in mergeState.FieldInfos)
{
DocValuesType type = field.DocValuesType;
if (type != DocValuesType.NONE)
{
if (type == DocValuesType.NUMERIC)
{
IList<NumericDocValues> toMerge = new List<NumericDocValues>();
IList<IBits> docsWithField = new List<IBits>();
foreach (AtomicReader reader in mergeState.Readers)
{
NumericDocValues values = reader.GetNumericDocValues(field.Name);
IBits bits = reader.GetDocsWithField(field.Name);
if (values == null)
{
values = DocValues.EMPTY_NUMERIC;
bits = new Lucene.Net.Util.Bits.MatchNoBits(reader.MaxDoc);
}
toMerge.Add(values);
docsWithField.Add(bits);
}
consumer.MergeNumericField(field, mergeState, toMerge, docsWithField);
}
else if (type == DocValuesType.BINARY)
{
IList<BinaryDocValues> toMerge = new List<BinaryDocValues>();
IList<IBits> docsWithField = new List<IBits>();
foreach (AtomicReader reader in mergeState.Readers)
{
BinaryDocValues values = reader.GetBinaryDocValues(field.Name);
IBits bits = reader.GetDocsWithField(field.Name);
if (values == null)
{
values = DocValues.EMPTY_BINARY;
bits = new Lucene.Net.Util.Bits.MatchNoBits(reader.MaxDoc);
}
toMerge.Add(values);
docsWithField.Add(bits);
}
consumer.MergeBinaryField(field, mergeState, toMerge, docsWithField);
}
else if (type == DocValuesType.SORTED)
{
IList<SortedDocValues> toMerge = new List<SortedDocValues>();
foreach (AtomicReader reader in mergeState.Readers)
{
SortedDocValues values = reader.GetSortedDocValues(field.Name);
if (values == null)
{
values = DocValues.EMPTY_SORTED;
}
toMerge.Add(values);
}
consumer.MergeSortedField(field, mergeState, toMerge);
}
else if (type == DocValuesType.SORTED_SET)
{
IList<SortedSetDocValues> toMerge = new List<SortedSetDocValues>();
foreach (AtomicReader reader in mergeState.Readers)
{
SortedSetDocValues values = reader.GetSortedSetDocValues(field.Name);
if (values == null)
{
values = DocValues.EMPTY_SORTED_SET;
}
toMerge.Add(values);
}
consumer.MergeSortedSetField(field, mergeState, toMerge);
}
else
{
throw new InvalidOperationException("type=" + type);
}
}
}
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(consumer);
}
else
{
IOUtils.DisposeWhileHandlingException(consumer);
}
}
}
private void MergeNorms(SegmentWriteState segmentWriteState)
{
DocValuesConsumer consumer = codec.NormsFormat.NormsConsumer(segmentWriteState);
bool success = false;
try
{
foreach (FieldInfo field in mergeState.FieldInfos)
{
if (field.HasNorms)
{
IList<NumericDocValues> toMerge = new List<NumericDocValues>();
IList<IBits> docsWithField = new List<IBits>();
foreach (AtomicReader reader in mergeState.Readers)
{
NumericDocValues norms = reader.GetNormValues(field.Name);
if (norms == null)
{
norms = DocValues.EMPTY_NUMERIC;
}
toMerge.Add(norms);
docsWithField.Add(new Lucene.Net.Util.Bits.MatchAllBits(reader.MaxDoc));
}
consumer.MergeNumericField(field, mergeState, toMerge, docsWithField);
}
}
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(consumer);
}
else
{
IOUtils.DisposeWhileHandlingException(consumer);
}
}
}
private void SetMatchingSegmentReaders()
{
// If the i'th reader is a SegmentReader and has
// identical fieldName -> number mapping, then this
// array will be non-null at position i:
int numReaders = mergeState.Readers.Count;
mergeState.MatchingSegmentReaders = new SegmentReader[numReaders];
// If this reader is a SegmentReader, and all of its
// field name -> number mappings match the "merged"
// FieldInfos, then we can do a bulk copy of the
// stored fields:
for (int i = 0; i < numReaders; i++)
{
AtomicReader reader = mergeState.Readers[i];
// TODO: we may be able to broaden this to
// non-SegmentReaders, since FieldInfos is now
// required? But... this'd also require exposing
// bulk-copy (TVs and stored fields) API in foreign
// readers..
if (reader is SegmentReader)
{
SegmentReader segmentReader = (SegmentReader)reader;
bool same = true;
FieldInfos segmentFieldInfos = segmentReader.FieldInfos;
foreach (FieldInfo fi in segmentFieldInfos)
{
FieldInfo other = mergeState.FieldInfos.FieldInfo(fi.Number);
if (other == null || !other.Name.Equals(fi.Name, StringComparison.Ordinal))
{
same = false;
break;
}
}
if (same)
{
mergeState.MatchingSegmentReaders[i] = segmentReader;
mergeState.MatchedCount++;
}
}
}
if (mergeState.InfoStream.IsEnabled("SM"))
{
mergeState.InfoStream.Message("SM", "merge store matchedCount=" + mergeState.MatchedCount + " vs " + mergeState.Readers.Count);
if (mergeState.MatchedCount != mergeState.Readers.Count)
{
mergeState.InfoStream.Message("SM", "" + (mergeState.Readers.Count - mergeState.MatchedCount) + " non-bulk merges");
}
}
}
public void MergeFieldInfos()
{
foreach (AtomicReader reader in mergeState.Readers)
{
FieldInfos readerFieldInfos = reader.FieldInfos;
foreach (FieldInfo fi in readerFieldInfos)
{
fieldInfosBuilder.Add(fi);
}
}
mergeState.FieldInfos = fieldInfosBuilder.Finish();
}
///
/// <returns> The number of documents in all of the readers </returns>
/// <exception cref="CorruptIndexException"> if the index is corrupt </exception>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
private int MergeFields()
{
StoredFieldsWriter fieldsWriter = codec.StoredFieldsFormat.FieldsWriter(directory, mergeState.SegmentInfo, context);
try
{
return fieldsWriter.Merge(mergeState);
}
finally
{
fieldsWriter.Dispose();
}
}
/// <summary>
/// Merge the TermVectors from each of the segments into the new one. </summary>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
private int MergeVectors()
{
TermVectorsWriter termVectorsWriter = codec.TermVectorsFormat.VectorsWriter(directory, mergeState.SegmentInfo, context);
try
{
return termVectorsWriter.Merge(mergeState);
}
finally
{
termVectorsWriter.Dispose();
}
}
// NOTE: removes any "all deleted" readers from mergeState.readers
private int SetDocMaps()
{
int numReaders = mergeState.Readers.Count;
// Remap docIDs
mergeState.DocMaps = new MergeState.DocMap[numReaders];
mergeState.DocBase = new int[numReaders];
int docBase = 0;
int i = 0;
while (i < mergeState.Readers.Count)
{
AtomicReader reader = mergeState.Readers[i];
mergeState.DocBase[i] = docBase;
MergeState.DocMap docMap = MergeState.DocMap.Build(reader);
mergeState.DocMaps[i] = docMap;
docBase += docMap.NumDocs;
i++;
}
return docBase;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void MergeTerms(SegmentWriteState segmentWriteState)
{
IList<Fields> fields = new List<Fields>();
IList<ReaderSlice> slices = new List<ReaderSlice>();
int docBase = 0;
for (int readerIndex = 0; readerIndex < mergeState.Readers.Count; readerIndex++)
{
AtomicReader reader = mergeState.Readers[readerIndex];
Fields f = reader.Fields;
int maxDoc = reader.MaxDoc;
if (f != null)
{
slices.Add(new ReaderSlice(docBase, maxDoc, readerIndex));
fields.Add(f);
}
docBase += maxDoc;
}
FieldsConsumer consumer = codec.PostingsFormat.FieldsConsumer(segmentWriteState);
bool success = false;
try
{
consumer.Merge(mergeState, new MultiFields(fields.ToArray(/*Fields.EMPTY_ARRAY*/), slices.ToArray(/*ReaderSlice.EMPTY_ARRAY*/)));
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(consumer);
}
else
{
IOUtils.DisposeWhileHandlingException(consumer);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Linq;
using Python.Runtime.Native;
namespace Python.Runtime
{
/// <summary>
/// Performs data conversions between managed types and Python types.
/// </summary>
[SuppressUnmanagedCodeSecurity]
internal class Converter
{
private Converter()
{
}
private static NumberFormatInfo nfi;
private static Type objectType;
private static Type stringType;
private static Type singleType;
private static Type doubleType;
private static Type decimalType;
private static Type int16Type;
private static Type int32Type;
private static Type int64Type;
private static Type flagsType;
private static Type boolType;
private static Type typeType;
private static IntPtr dateTimeCtor;
private static IntPtr timeSpanCtor;
private static IntPtr tzInfoCtor;
private static IntPtr pyTupleNoKind;
private static IntPtr pyTupleKind;
private static StrPtr yearPtr;
private static StrPtr monthPtr;
private static StrPtr dayPtr;
private static StrPtr hourPtr;
private static StrPtr minutePtr;
private static StrPtr secondPtr;
private static StrPtr microsecondPtr;
private static StrPtr tzinfoPtr;
private static StrPtr hoursPtr;
private static StrPtr minutesPtr;
static Converter()
{
nfi = NumberFormatInfo.InvariantInfo;
objectType = typeof(Object);
stringType = typeof(String);
int16Type = typeof(Int16);
int32Type = typeof(Int32);
int64Type = typeof(Int64);
singleType = typeof(Single);
doubleType = typeof(Double);
decimalType = typeof(Decimal);
flagsType = typeof(FlagsAttribute);
boolType = typeof(Boolean);
typeType = typeof(Type);
IntPtr dateTimeMod = Runtime.PyImport_ImportModule("datetime");
if (dateTimeMod == null) throw new PythonException();
dateTimeCtor = Runtime.PyObject_GetAttrString(dateTimeMod, "datetime");
if (dateTimeCtor == null) throw new PythonException();
timeSpanCtor = Runtime.PyObject_GetAttrString(dateTimeMod, "timedelta");
if (timeSpanCtor == null) throw new PythonException();
IntPtr tzInfoMod = PythonEngine.ModuleFromString("custom_tzinfo", @"
from datetime import timedelta, tzinfo
class GMT(tzinfo):
def __init__(self, hours, minutes):
self.hours = hours
self.minutes = minutes
def utcoffset(self, dt):
return timedelta(hours=self.hours, minutes=self.minutes)
def tzname(self, dt):
return f'GMT {self.hours:00}:{self.minutes:00}'
def dst (self, dt):
return timedelta(0)").Handle;
tzInfoCtor = Runtime.PyObject_GetAttrString(tzInfoMod, "GMT");
if (tzInfoCtor == null) throw new PythonException();
pyTupleNoKind = Runtime.PyTuple_New(7);
pyTupleKind = Runtime.PyTuple_New(8);
yearPtr = new StrPtr("year", Encoding.UTF8);
monthPtr = new StrPtr("month", Encoding.UTF8);
dayPtr = new StrPtr("day", Encoding.UTF8);
hourPtr = new StrPtr("hour", Encoding.UTF8);
minutePtr = new StrPtr("minute", Encoding.UTF8);
secondPtr = new StrPtr("second", Encoding.UTF8);
microsecondPtr = new StrPtr("microsecond", Encoding.UTF8);
tzinfoPtr = new StrPtr("tzinfo", Encoding.UTF8);
hoursPtr = new StrPtr("hours", Encoding.UTF8);
minutesPtr = new StrPtr("minutes", Encoding.UTF8);
}
/// <summary>
/// Given a builtin Python type, return the corresponding CLR type.
/// </summary>
internal static Type GetTypeByAlias(IntPtr op)
{
if (op == Runtime.PyStringType)
return stringType;
if (op == Runtime.PyUnicodeType)
return stringType;
if (op == Runtime.PyIntType)
return int32Type;
if (op == Runtime.PyLongType)
return int64Type;
if (op == Runtime.PyFloatType)
return doubleType;
if (op == Runtime.PyBoolType)
return boolType;
if (op == Runtime.PyDecimalType)
return decimalType;
return null;
}
internal static IntPtr GetPythonTypeByAlias(Type op)
{
if (op == stringType)
return Runtime.PyUnicodeType;
if (op == int16Type)
return Runtime.PyIntType;
if (op == int32Type)
return Runtime.PyIntType;
if (op == int64Type)
return Runtime.PyIntType;
if (op == doubleType)
return Runtime.PyFloatType;
if (op == singleType)
return Runtime.PyFloatType;
if (op == boolType)
return Runtime.PyBoolType;
if (op == decimalType)
return Runtime.PyDecimalType;
return IntPtr.Zero;
}
/// <summary>
/// Return a Python object for the given native object, converting
/// basic types (string, int, etc.) into equivalent Python objects.
/// This always returns a new reference. Note that the System.Decimal
/// type has no Python equivalent and converts to a managed instance.
/// </summary>
internal static IntPtr ToPython<T>(T value)
{
return ToPython(value, typeof(T));
}
private static readonly Func<object, bool> IsTransparentProxy = GetIsTransparentProxy();
private static bool Never(object _) => false;
private static Func<object, bool> GetIsTransparentProxy()
{
var remoting = typeof(int).Assembly.GetType("System.Runtime.Remoting.RemotingServices");
if (remoting is null) return Never;
var isProxy = remoting.GetMethod("IsTransparentProxy", new[] { typeof(object) });
if (isProxy is null) return Never;
return (Func<object, bool>)Delegate.CreateDelegate(
typeof(Func<object, bool>), isProxy,
throwOnBindFailure: true);
}
internal static IntPtr ToPython(object value, Type type)
{
if (value is PyObject)
{
IntPtr handle = ((PyObject)value).Handle;
Runtime.XIncref(handle);
return handle;
}
IntPtr result = IntPtr.Zero;
// Null always converts to None in Python.
if (value == null)
{
result = Runtime.PyNone;
Runtime.XIncref(result);
return result;
}
var valueType = value.GetType();
if (Type.GetTypeCode(type) == TypeCode.Object && valueType != typeof(object)) {
var encoded = PyObjectConversions.TryEncode(value, type);
if (encoded != null) {
result = encoded.Handle;
Runtime.XIncref(result);
return result;
}
}
if (valueType.IsGenericType && value is IList && !(value is INotifyPropertyChanged))
{
using (var resultlist = new PyList())
{
foreach (object o in (IEnumerable)value)
{
using (var p = new PyObject(ToPython(o, o?.GetType())))
{
resultlist.Append(p);
}
}
Runtime.XIncref(resultlist.Handle);
return resultlist.Handle;
}
}
// it the type is a python subclass of a managed type then return the
// underlying python object rather than construct a new wrapper object.
var pyderived = value as IPythonDerivedType;
if (null != pyderived)
{
if (!IsTransparentProxy(pyderived))
return ClassDerivedObject.ToPython(pyderived);
}
// hmm - from Python, we almost never care what the declared
// type is. we'd rather have the object bound to the actual
// implementing class.
type = value.GetType();
TypeCode tc = Type.GetTypeCode(type);
switch (tc)
{
case TypeCode.Object:
if (value is TimeSpan)
{
var timespan = (TimeSpan)value;
IntPtr timeSpanArgs = Runtime.PyTuple_New(1);
Runtime.PyTuple_SetItem(timeSpanArgs, 0, Runtime.PyFloat_FromDouble(timespan.TotalDays));
var returnTimeSpan = Runtime.PyObject_CallObject(timeSpanCtor, timeSpanArgs);
// clean up
Runtime.XDecref(timeSpanArgs);
return returnTimeSpan;
}
return CLRObject.GetInstHandle(value, type);
case TypeCode.String:
return Runtime.PyUnicode_FromString((string)value);
case TypeCode.Int32:
return Runtime.PyInt_FromInt32((int)value);
case TypeCode.Boolean:
if ((bool)value)
{
Runtime.XIncref(Runtime.PyTrue);
return Runtime.PyTrue;
}
Runtime.XIncref(Runtime.PyFalse);
return Runtime.PyFalse;
case TypeCode.Byte:
return Runtime.PyInt_FromInt32((int)((byte)value));
case TypeCode.Char:
return Runtime.PyUnicode_FromOrdinal((int)((char)value));
case TypeCode.Int16:
return Runtime.PyInt_FromInt32((int)((short)value));
case TypeCode.Int64:
return Runtime.PyLong_FromLongLong((long)value);
case TypeCode.Single:
// return Runtime.PyFloat_FromDouble((double)((float)value));
string ss = ((float)value).ToString(nfi);
IntPtr ps = Runtime.PyString_FromString(ss);
NewReference op = Runtime.PyFloat_FromString(new BorrowedReference(ps));;
Runtime.XDecref(ps);
return op.DangerousMoveToPointerOrNull();
case TypeCode.Double:
return Runtime.PyFloat_FromDouble((double)value);
case TypeCode.SByte:
return Runtime.PyInt_FromInt32((int)((sbyte)value));
case TypeCode.UInt16:
return Runtime.PyInt_FromInt32((int)((ushort)value));
case TypeCode.UInt32:
return Runtime.PyLong_FromUnsignedLong((uint)value);
case TypeCode.UInt64:
return Runtime.PyLong_FromUnsignedLongLong((ulong)value);
case TypeCode.Decimal:
// C# decimal to python decimal has a big impact on performance
// so we will use C# double and python float
return Runtime.PyFloat_FromDouble(decimal.ToDouble((decimal)value));
case TypeCode.DateTime:
var datetime = (DateTime)value;
var size = datetime.Kind == DateTimeKind.Unspecified ? 7 : 8;
var dateTimeArgs = datetime.Kind == DateTimeKind.Unspecified ? pyTupleNoKind : pyTupleKind;
Runtime.PyTuple_SetItem(dateTimeArgs, 0, Runtime.PyInt_FromInt32(datetime.Year));
Runtime.PyTuple_SetItem(dateTimeArgs, 1, Runtime.PyInt_FromInt32(datetime.Month));
Runtime.PyTuple_SetItem(dateTimeArgs, 2, Runtime.PyInt_FromInt32(datetime.Day));
Runtime.PyTuple_SetItem(dateTimeArgs, 3, Runtime.PyInt_FromInt32(datetime.Hour));
Runtime.PyTuple_SetItem(dateTimeArgs, 4, Runtime.PyInt_FromInt32(datetime.Minute));
Runtime.PyTuple_SetItem(dateTimeArgs, 5, Runtime.PyInt_FromInt32(datetime.Second));
// datetime.datetime 6th argument represents micro seconds
var totalSeconds = datetime.TimeOfDay.TotalSeconds;
var microSeconds = Convert.ToInt32((totalSeconds - Math.Truncate(totalSeconds)) * 1000000);
if (microSeconds == 1000000) microSeconds = 999999;
Runtime.PyTuple_SetItem(dateTimeArgs, 6, Runtime.PyInt_FromInt32(microSeconds));
if (size == 8)
{
Runtime.PyTuple_SetItem(dateTimeArgs, 7, TzInfo(datetime.Kind));
}
var returnDateTime = Runtime.PyObject_CallObject(dateTimeCtor, dateTimeArgs);
return returnDateTime;
default:
if (value is IEnumerable)
{
using (var resultlist = new PyList())
{
foreach (object o in (IEnumerable)value)
{
using (var p = new PyObject(ToPython(o, o?.GetType())))
{
resultlist.Append(p);
}
}
Runtime.XIncref(resultlist.Handle);
return resultlist.Handle;
}
}
result = CLRObject.GetInstHandle(value, type);
return result;
}
}
private static IntPtr TzInfo(DateTimeKind kind)
{
if (kind == DateTimeKind.Unspecified) return Runtime.PyNone;
var offset = kind == DateTimeKind.Local ? DateTimeOffset.Now.Offset : TimeSpan.Zero;
IntPtr tzInfoArgs = Runtime.PyTuple_New(2);
Runtime.PyTuple_SetItem(tzInfoArgs, 0, Runtime.PyFloat_FromDouble(offset.Hours));
Runtime.PyTuple_SetItem(tzInfoArgs, 1, Runtime.PyFloat_FromDouble(offset.Minutes));
var returnValue = Runtime.PyObject_CallObject(tzInfoCtor, tzInfoArgs);
Runtime.XDecref(tzInfoArgs);
return returnValue;
}
/// <summary>
/// In a few situations, we don't have any advisory type information
/// when we want to convert an object to Python.
/// </summary>
internal static IntPtr ToPythonImplicit(object value)
{
if (value == null)
{
IntPtr result = Runtime.PyNone;
Runtime.XIncref(result);
return result;
}
return ToPython(value, objectType);
}
internal static bool ToManaged(IntPtr value, Type type,
out object result, bool setError)
{
var usedImplicit = false;
return ToManaged(value, type, out result, setError, out usedImplicit);
}
/// <summary>
/// Return a managed object for the given Python object, taking funny
/// byref types into account.
/// </summary>
/// <param name="value">A Python object</param>
/// <param name="type">The desired managed type</param>
/// <param name="result">Receives the managed object</param>
/// <param name="setError">If true, call <c>Exceptions.SetError</c> with the reason for failure.</param>
/// <returns>True on success</returns>
internal static bool ToManaged(IntPtr value, Type type,
out object result, bool setError, out bool usedImplicit)
{
if (type.IsByRef)
{
type = type.GetElementType();
}
return Converter.ToManagedValue(value, type, out result, setError, out usedImplicit);
}
internal static bool ToManagedValue(BorrowedReference value, Type obType,
out object result, bool setError)
{
var usedImplicit = false;
return ToManagedValue(value.DangerousGetAddress(), obType, out result, setError, out usedImplicit);
}
internal static bool ToManagedValue(IntPtr value, Type obType,
out object result, bool setError, out bool usedImplicit)
{
usedImplicit = false;
if (obType == typeof(PyObject))
{
Runtime.XIncref(value); // PyObject() assumes ownership
result = new PyObject(value);
return true;
}
if (obType.IsGenericType && Runtime.PyObject_TYPE(value) == Runtime.PyListType)
{
var typeDefinition = obType.GetGenericTypeDefinition();
if (typeDefinition == typeof(List<>) || typeDefinition == typeof(IEnumerable<>))
{
return ToList(value, obType, out result, setError);
}
}
// Common case: if the Python value is a wrapped managed object
// instance, just return the wrapped object.
var mt = ManagedType.GetManagedObject(value);
result = null;
if (mt != null)
{
if (mt is CLRObject co)
{
object tmp = co.inst;
var type = tmp.GetType();
if (obType.IsInstanceOfType(tmp) || IsSubclassOfRawGeneric(obType, type))
{
result = tmp;
return true;
}
else
{
// check implicit conversions that receive tmp type and return obType
var conversionMethod = type.GetMethod("op_Implicit", new[] { type });
if (conversionMethod != null && conversionMethod.ReturnType == obType)
{
try{
result = conversionMethod.Invoke(null, new[] { tmp });
usedImplicit = true;
return true;
}
catch
{
// Failed to convert using implicit conversion, must catch the error to stop program from exploding on Linux
Exceptions.RaiseTypeError($"Failed to implicitly convert {type} to {obType}");
return false;
}
}
}
if (setError)
{
string typeString = tmp is null ? "null" : tmp.GetType().ToString();
Exceptions.SetError(Exceptions.TypeError, $"{typeString} value cannot be converted to {obType}");
}
return false;
}
if (mt is ClassBase cb)
{
if (!cb.type.Valid)
{
Exceptions.SetError(Exceptions.TypeError, cb.type.DeletedMessage);
return false;
}
result = cb.type.Value;
return true;
}
// shouldn't happen
return false;
}
if (value == Runtime.PyNone && !obType.IsValueType)
{
result = null;
return true;
}
if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if( value == Runtime.PyNone )
{
result = null;
return true;
}
// Set type to underlying type
obType = obType.GetGenericArguments()[0];
}
if (obType.ContainsGenericParameters)
{
if (setError)
{
Exceptions.SetError(Exceptions.TypeError, $"Cannot create an instance of the open generic type {obType}");
}
return false;
}
if (obType.IsArray)
{
return ToArray(value, obType, out result, setError);
}
if (obType.IsEnum)
{
return ToEnum(value, obType, out result, setError, out usedImplicit);
}
// Conversion to 'Object' is done based on some reasonable default
// conversions (Python string -> managed string, Python int -> Int32 etc.).
if (obType == objectType)
{
if (Runtime.IsStringType(value))
{
return ToPrimitive(value, stringType, out result, setError, out usedImplicit);
}
if (Runtime.PyBool_Check(value))
{
return ToPrimitive(value, boolType, out result, setError, out usedImplicit);
}
if (Runtime.PyInt_Check(value))
{
return ToPrimitive(value, int32Type, out result, setError, out usedImplicit);
}
if (Runtime.PyLong_Check(value))
{
return ToPrimitive(value, int64Type, out result, setError, out usedImplicit);
}
if (Runtime.PyFloat_Check(value))
{
return ToPrimitive(value, doubleType, out result, setError, out usedImplicit);
}
// give custom codecs a chance to take over conversion of sequences
IntPtr pyType = Runtime.PyObject_TYPE(value);
if (PyObjectConversions.TryDecode(value, pyType, obType, out result))
{
return true;
}
if (Runtime.PySequence_Check(value))
{
return ToArray(value, typeof(object[]), out result, setError);
}
Runtime.XIncref(value); // PyObject() assumes ownership
result = new PyObject(value);
return true;
}
// Conversion to 'Type' is done using the same mappings as above for objects.
if (obType == typeType)
{
if (value == Runtime.PyStringType)
{
result = stringType;
return true;
}
if (value == Runtime.PyBoolType)
{
result = boolType;
return true;
}
if (value == Runtime.PyIntType)
{
result = int32Type;
return true;
}
if (value == Runtime.PyLongType)
{
result = int64Type;
return true;
}
if (value == Runtime.PyFloatType)
{
result = doubleType;
return true;
}
if (value == Runtime.PyListType || value == Runtime.PyTupleType)
{
result = typeof(object[]);
return true;
}
if (setError)
{
Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Type");
}
return false;
}
var underlyingType = Nullable.GetUnderlyingType(obType);
if (underlyingType != null)
{
return ToManagedValue(value, underlyingType, out result, setError, out usedImplicit);
}
TypeCode typeCode = Type.GetTypeCode(obType);
if (typeCode == TypeCode.Object)
{
IntPtr pyType = Runtime.PyObject_TYPE(value);
if (PyObjectConversions.TryDecode(value, pyType, obType, out result))
{
return true;
}
}
if (ToPrimitive(value, obType, out result, setError, out usedImplicit))
{
return true;
}
var opImplicit = obType.GetMethod("op_Implicit", new[] { obType });
if (opImplicit != null)
{
if (ToManagedValue(value, opImplicit.ReturnType, out result, setError, out usedImplicit))
{
opImplicit = obType.GetMethod("op_Implicit", new[] { result.GetType() });
if (opImplicit != null)
{
try
{
result = opImplicit.Invoke(null, new[] { result });
}
catch
{
// Failed to convert using implicit conversion, must catch the error to stop program from exploding on Linux
Exceptions.RaiseTypeError($"Failed to implicitly convert {result.GetType()} to {obType}");
return false;
}
}
return opImplicit != null;
}
}
return false;
}
/// Determine if the comparing class is a subclass of a generic type
private static bool IsSubclassOfRawGeneric(Type generic, Type comparingClass) {
// Check this is a raw generic type first
if(!generic.IsGenericType || !generic.ContainsGenericParameters){
return false;
}
// Ensure we have the full generic type definition or it won't match
generic = generic.GetGenericTypeDefinition();
// Loop for searching for generic match in inheritance tree of comparing class
// If we have reach null we don't have a match
while (comparingClass != null) {
// Check the input for generic type definition, if doesn't exist just use the class
var comparingClassGeneric = comparingClass.IsGenericType ? comparingClass.GetGenericTypeDefinition() : null;
// If the same as generic, this is a subclass return true
if (generic == comparingClassGeneric) {
return true;
}
// Step up the inheritance tree
comparingClass = comparingClass.BaseType;
}
// The comparing class is not based on the generic
return false;
}
internal delegate bool TryConvertFromPythonDelegate(IntPtr pyObj, out object result);
/// <summary>
/// Convert a Python value to an instance of a primitive managed type.
/// </summary>
private static bool ToPrimitive(IntPtr value, Type obType, out object result, bool setError, out bool usedImplicit)
{
TypeCode tc = Type.GetTypeCode(obType);
result = null;
IntPtr op = IntPtr.Zero;
usedImplicit = false;
switch (tc)
{
case TypeCode.Object:
if (obType == typeof(TimeSpan))
{
op = Runtime.PyObject_Str(value);
TimeSpan ts;
var arr = Runtime.GetManagedString(op).Split(',');
string sts = arr.Length == 1 ? arr[0] : arr[1];
if (!TimeSpan.TryParse(sts, out ts))
{
goto type_error;
}
Runtime.XDecref(op);
int days = 0;
if (arr.Length > 1)
{
if (!int.TryParse(arr[0].Split(' ')[0].Trim(), out days))
{
goto type_error;
}
}
result = ts.Add(TimeSpan.FromDays(days));
return true;
}
else if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
if (Runtime.PyDict_Check(value))
{
var typeArguments = obType.GenericTypeArguments;
if (typeArguments.Length != 2)
{
goto type_error;
}
IntPtr key, dicValue, pos;
// references returned through key, dicValue are borrowed.
if (Runtime.PyDict_Next(value, out pos, out key, out dicValue) != 0)
{
if (!ToManaged(key, typeArguments[0], out var convertedKey, setError, out usedImplicit))
{
goto type_error;
}
if (!ToManaged(dicValue, typeArguments[1], out var convertedValue, setError, out usedImplicit))
{
goto type_error;
}
result = Activator.CreateInstance(obType, convertedKey, convertedValue);
return true;
}
// and empty dictionary we can't create a key value pair from it
goto type_error;
}
}
break;
case TypeCode.String:
string st = Runtime.GetManagedString(value);
if (st == null)
{
goto type_error;
}
result = st;
return true;
case TypeCode.Int32:
{
// Python3 always use PyLong API
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero && Exceptions.ErrorOccurred())
{
goto convert_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(op);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Int32.MaxValue || num < Int32.MinValue)
{
goto overflow;
}
result = (int)num;
return true;
}
case TypeCode.Boolean:
result = Runtime.PyObject_IsTrue(value) != 0;
return true;
case TypeCode.Byte:
{
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
op = Runtime.PyBytes_AS_STRING(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Byte.MaxValue || num < Byte.MinValue)
{
goto overflow;
}
result = (byte)num;
return true;
}
case TypeCode.SByte:
{
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
op = Runtime.PyBytes_AS_STRING(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > SByte.MaxValue || num < SByte.MinValue)
{
goto overflow;
}
result = (sbyte)num;
return true;
}
case TypeCode.Char:
{
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
op = Runtime.PyBytes_AS_STRING(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
else if (Runtime.PyObject_TypeCheck(value, Runtime.PyUnicodeType))
{
if (Runtime.PyUnicode_GetSize(value) == 1)
{
op = Runtime.PyUnicode_AsUnicode(value);
Char[] buff = new Char[1];
Marshal.Copy(op, buff, 0, 1);
result = buff[0];
return true;
}
goto type_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Char.MaxValue || num < Char.MinValue)
{
goto overflow;
}
result = (char)num;
return true;
}
case TypeCode.Int16:
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero && Exceptions.ErrorOccurred())
{
goto convert_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(op);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Int16.MaxValue || num < Int16.MinValue)
{
goto overflow;
}
result = (short)num;
return true;
}
case TypeCode.Int64:
{
if (Runtime.Is32Bit)
{
if (!Runtime.PyLong_Check(value))
{
goto type_error;
}
long num = Runtime.PyExplicitlyConvertToInt64(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
result = num;
return true;
}
else
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero && Exceptions.ErrorOccurred())
{
goto convert_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(op);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
result = (long)num;
return true;
}
}
case TypeCode.UInt16:
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero && Exceptions.ErrorOccurred())
{
goto convert_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(op);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > UInt16.MaxValue || num < UInt16.MinValue)
{
goto overflow;
}
result = (ushort)num;
return true;
}
case TypeCode.UInt32:
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero && Exceptions.ErrorOccurred())
{
goto convert_error;
}
nuint num = Runtime.PyLong_AsUnsignedSize_t(op);
if (num == unchecked((nuint)(-1)) && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > UInt32.MaxValue)
{
goto overflow;
}
result = (uint)num;
return true;
}
case TypeCode.UInt64:
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero && Exceptions.ErrorOccurred())
{
goto convert_error;
}
ulong num = Runtime.PyLong_AsUnsignedLongLong(op);
if (num == ulong.MaxValue && Exceptions.ErrorOccurred())
{
goto convert_error;
}
result = num;
return true;
}
case TypeCode.Single:
{
double num = Runtime.PyFloat_AsDouble(value);
if (num == -1.0 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Single.MaxValue || num < Single.MinValue)
{
if (!double.IsInfinity(num))
{
goto overflow;
}
}
result = (float)num;
return true;
}
case TypeCode.Double:
{
double num = Runtime.PyFloat_AsDouble(value);
if (num == -1.0 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
result = num;
return true;
}
case TypeCode.Decimal:
op = Runtime.PyObject_Str(value);
decimal m;
var sm = Runtime.GetManagedSpan(op, out var newReference);
if (!Decimal.TryParse(sm, NumberStyles.Number | NumberStyles.AllowExponent, nfi, out m))
{
newReference.Dispose();
Runtime.XDecref(op);
goto type_error;
}
newReference.Dispose();
Runtime.XDecref(op);
result = m;
return true;
case TypeCode.DateTime:
var year = Runtime.PyObject_GetAttrString(value, yearPtr);
if (year == IntPtr.Zero || year == Runtime.PyNone)
{
Runtime.XDecref(year);
// fallback to string parsing for types such as numpy
op = Runtime.PyObject_Str(value);
var sdt = Runtime.GetManagedSpan(op, out var reference);
if (!DateTime.TryParse(sdt, out var dt))
{
reference.Dispose();
Runtime.XDecref(op);
Exceptions.Clear();
goto type_error;
}
result = sdt.EndsWith("+00:00") ? dt.ToUniversalTime() : dt;
reference.Dispose();
Runtime.XDecref(op);
Exceptions.Clear();
return true;
}
var month = Runtime.PyObject_GetAttrString(value, monthPtr);
var day = Runtime.PyObject_GetAttrString(value, dayPtr);
var hour = Runtime.PyObject_GetAttrString(value, hourPtr);
var minute = Runtime.PyObject_GetAttrString(value, minutePtr);
var second = Runtime.PyObject_GetAttrString(value, secondPtr);
var microsecond = Runtime.PyObject_GetAttrString(value, microsecondPtr);
var timeKind = DateTimeKind.Unspecified;
var tzinfo = Runtime.PyObject_GetAttrString(value, tzinfoPtr);
var hours = IntPtr.MaxValue;
var minutes = IntPtr.MaxValue;
if (tzinfo != IntPtr.Zero && tzinfo != Runtime.PyNone)
{
hours = Runtime.PyObject_GetAttrString(tzinfo, hoursPtr);
minutes = Runtime.PyObject_GetAttrString(tzinfo, minutesPtr);
if (Runtime.PyInt_AsLong(hours) == 0 && Runtime.PyInt_AsLong(minutes) == 0)
{
timeKind = DateTimeKind.Utc;
}
}
var convertedHour = 0;
var convertedMinute = 0;
var convertedSecond = 0;
var milliseconds = 0;
// could be python date type
if (hour != IntPtr.Zero && hour != Runtime.PyNone)
{
convertedHour = Runtime.PyInt_AsLong(hour);
convertedMinute = Runtime.PyInt_AsLong(minute);
convertedSecond = Runtime.PyInt_AsLong(second);
milliseconds = Runtime.PyInt_AsLong(microsecond) / 1000;
}
result = new DateTime(Runtime.PyInt_AsLong(year),
Runtime.PyInt_AsLong(month),
Runtime.PyInt_AsLong(day),
convertedHour,
convertedMinute,
convertedSecond,
millisecond: milliseconds,
timeKind);
Runtime.XDecref(year);
Runtime.XDecref(month);
Runtime.XDecref(day);
Runtime.XDecref(hour);
Runtime.XDecref(minute);
Runtime.XDecref(second);
Runtime.XDecref(microsecond);
if (tzinfo != IntPtr.Zero)
{
Runtime.XDecref(tzinfo);
if(tzinfo != Runtime.PyNone)
{
Runtime.XDecref(hours);
Runtime.XDecref(minutes);
}
}
Exceptions.Clear();
return true;
default:
goto type_error;
}
convert_error:
if (op != value)
{
Runtime.XDecref(op);
}
if (!setError)
{
Exceptions.Clear();
}
return false;
type_error:
if (setError)
{
string tpName = Runtime.PyObject_GetTypeName(value);
Exceptions.SetError(Exceptions.TypeError, $"'{tpName}' value cannot be converted to {obType}");
}
return false;
overflow:
// C# level overflow error
if (op != value)
{
Runtime.XDecref(op);
}
if (setError)
{
Exceptions.SetError(Exceptions.OverflowError, "value too large to convert");
}
return false;
}
private static void SetConversionError(IntPtr value, Type target)
{
IntPtr ob = Runtime.PyObject_Repr(value);
string src = Runtime.GetManagedString(ob);
Runtime.XDecref(ob);
Exceptions.RaiseTypeError($"Cannot convert {src} to {target}");
}
/// <summary>
/// Convert a Python value to a correctly typed managed array instance.
/// The Python value must support the Python iterator protocol or and the
/// items in the sequence must be convertible to the target array type.
/// </summary>
private static bool ToArray(IntPtr value, Type obType, out object result, bool setError)
{
Type elementType = obType.GetElementType();
result = null;
IntPtr IterObject = Runtime.PyObject_GetIter(value);
if (IterObject == IntPtr.Zero || elementType.IsGenericType)
{
if (setError)
{
SetConversionError(value, obType);
}
else
{
// PyObject_GetIter will have set an error
Exceptions.Clear();
}
return false;
}
var list = MakeList(value, IterObject, obType, elementType, setError);
if (list == null)
{
return false;
}
Array items = Array.CreateInstance(elementType, list.Count);
list.CopyTo(items, 0);
result = items;
return true;
}
/// <summary>
/// Convert a Python value to a correctly typed managed list instance.
/// The Python value must support the Python sequence protocol and the
/// items in the sequence must be convertible to the target list type.
/// </summary>
private static bool ToList(IntPtr value, Type obType, out object result, bool setError)
{
var elementType = obType.GetGenericArguments()[0];
IntPtr IterObject = Runtime.PyObject_GetIter(value);
result = MakeList(value, IterObject, obType, elementType, setError);
return result != null;
}
/// <summary>
/// Helper function for ToArray and ToList that creates a IList out of iterable objects
/// </summary>
/// <param name="value"></param>
/// <param name="IterObject"></param>
/// <param name="obType"></param>
/// <param name="elementType"></param>
/// <param name="setError"></param>
/// <returns></returns>
private static IList MakeList(IntPtr value, IntPtr IterObject, Type obType, Type elementType, bool setError)
{
IList list;
try
{
// MakeGenericType can throw because elementType may not be a valid generic argument even though elementType[] is a valid array type.
// For example, if elementType is a pointer type.
// See https://docs.microsoft.com/en-us/dotnet/api/system.type.makegenerictype#System_Type_MakeGenericType_System_Type
var constructedListType = typeof(List<>).MakeGenericType(elementType);
bool IsSeqObj = Runtime.PySequence_Check(value);
if (IsSeqObj)
{
var len = Runtime.PySequence_Size(value);
list = (IList)Activator.CreateInstance(constructedListType, new Object[] { (int)len });
}
else
{
// CreateInstance can throw even if MakeGenericType succeeded.
// See https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance#System_Activator_CreateInstance_System_Type_
list = (IList)Activator.CreateInstance(constructedListType);
}
}
catch (Exception e)
{
if (setError)
{
Exceptions.SetError(e);
SetConversionError(value, obType);
}
return null;
}
IntPtr item;
var usedImplicit = false;
while ((item = Runtime.PyIter_Next(IterObject)) != IntPtr.Zero)
{
object obj;
if (!Converter.ToManaged(item, elementType, out obj, setError, out usedImplicit))
{
Runtime.XDecref(item);
return null;
}
list.Add(obj);
Runtime.XDecref(item);
}
Runtime.XDecref(IterObject);
return list;
}
/// <summary>
/// Convert a Python value to a correctly typed managed enum instance.
/// </summary>
private static bool ToEnum(IntPtr value, Type obType, out object result, bool setError, out bool usedImplicit)
{
Type etype = Enum.GetUnderlyingType(obType);
result = null;
if (!ToPrimitive(value, etype, out result, setError, out usedImplicit))
{
return false;
}
if (Enum.IsDefined(obType, result))
{
result = Enum.ToObject(obType, result);
return true;
}
if (obType.GetCustomAttributes(flagsType, true).Length > 0)
{
result = Enum.ToObject(obType, result);
return true;
}
if (setError)
{
Exceptions.SetError(Exceptions.ValueError, "invalid enumeration value");
}
return false;
}
}
public static class ConverterExtension
{
public static PyObject ToPython(this object o)
{
return new PyObject(Converter.ToPython(o, o?.GetType()));
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using NUnit.TestUtilities.Collections;
namespace NUnit.Framework.Assertions
{
/// <summary>
/// Summary description for ArrayEqualTests.
/// </summary>
[TestFixture]
public class ArrayEqualsFixture
{
#pragma warning disable 183, 184 // error number varies in different runtimes
// Used to detect runtimes where ArraySegments implement IEnumerable
private static readonly bool ArraySegmentImplementsIEnumerable = new ArraySegment<int>() is IEnumerable;
#pragma warning restore 183, 184
[Test]
public void ArrayIsEqualToItself()
{
string[] array = { "one", "two", "three" };
Assert.That( array, Is.SameAs(array) );
Assert.AreEqual( array, array );
}
[Test]
public void ArraysOfString()
{
string[] array1 = { "one", "two", "three" };
string[] array2 = { "one", "two", "three" };
Assert.IsFalse( array1 == array2 );
Assert.AreEqual(array1, array2);
Assert.AreEqual(array2, array1);
}
[Test]
public void ArraysOfInt()
{
int[] a = new int[] { 1, 2, 3 };
int[] b = new int[] { 1, 2, 3 };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void ArraysOfDouble()
{
double[] a = new double[] { 1.0, 2.0, 3.0 };
double[] b = new double[] { 1.0, 2.0, 3.0 };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void ArraysOfDecimal()
{
decimal[] a = new decimal[] { 1.0m, 2.0m, 3.0m };
decimal[] b = new decimal[] { 1.0m, 2.0m, 3.0m };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void ArrayOfIntAndArrayOfDouble()
{
int[] a = new int[] { 1, 2, 3 };
double[] b = new double[] { 1.0, 2.0, 3.0 };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void ArraysDeclaredAsDifferentTypes()
{
string[] array1 = { "one", "two", "three" };
object[] array2 = { "one", "two", "three" };
Assert.AreEqual( array1, array2, "String[] not equal to Object[]" );
Assert.AreEqual( array2, array1, "Object[] not equal to String[]" );
}
[Test]
public void ArraysOfMixedTypes()
{
DateTime now = DateTime.Now;
object[] array1 = new object[] { 1, 2.0f, 3.5d, 7.000m, "Hello", now };
object[] array2 = new object[] { 1.0d, 2, 3.5, 7, "Hello", now };
Assert.AreEqual( array1, array2 );
Assert.AreEqual(array2, array1);
}
[Test]
public void DoubleDimensionedArrays()
{
int[,] a = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[,] b = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void TripleDimensionedArrays()
{
int[, ,] expected = new int[,,] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
int[,,] actual = new int[,,] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
Assert.AreEqual(expected, actual);
}
[Test]
public void FiveDimensionedArrays()
{
int[, , , ,] expected = new int[2, 2, 2, 2, 2] { { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } }, { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } } };
int[, , , ,] actual = new int[2, 2, 2, 2, 2] { { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } }, { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } } };
Assert.AreEqual(expected, actual);
}
[Test]
public void ArraysOfArrays()
{
int[][] a = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } };
int[][] b = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void JaggedArrays()
{
int[][] expected = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 }, new int[] { 8, 9 } };
int[][] actual = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 }, new int[] { 8, 9 } };
Assert.AreEqual(expected, actual);
}
[Test]
public void ArraysPassedAsObjects()
{
object a = new int[] { 1, 2, 3 };
object b = new double[] { 1.0, 2.0, 3.0 };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void ArrayAndCollection()
{
int[] a = new int[] { 1, 2, 3 };
ICollection b = new SimpleObjectCollection( 1, 2, 3 );
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void ArraysWithDifferentRanksComparedAsCollection()
{
int[] expected = new int[] { 1, 2, 3, 4 };
int[,] actual = new int[,] { { 1, 2 }, { 3, 4 } };
Assert.AreNotEqual(expected, actual);
Assert.That(actual, Is.EqualTo(expected).AsCollection);
}
[Test]
public void ArraysWithDifferentDimensionsMatchedAsCollection()
{
int[,] expected = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
int[,] actual = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
Assert.AreNotEqual(expected, actual);
Assert.That(actual, Is.EqualTo(expected).AsCollection);
}
private static int[] underlyingArray = new int[] { 1, 2, 3, 4, 5 };
[Test]
public void ArraySegmentAndArray()
{
Assume.That(ArraySegmentImplementsIEnumerable);
Assert.That(new ArraySegment<int>(underlyingArray, 1, 3), Is.EqualTo(new int[] { 2, 3, 4 }));
}
[Test]
public void EmptyArraySegmentAndArray()
{
Assume.That(ArraySegmentImplementsIEnumerable);
Assert.That(new ArraySegment<int>(), Is.Not.EqualTo(new int[] { 2, 3, 4 }));
}
[Test]
public void ArrayAndArraySegment()
{
Assume.That(ArraySegmentImplementsIEnumerable);
Assert.That(new int[] { 2, 3, 4 }, Is.EqualTo(new ArraySegment<int>(underlyingArray, 1, 3)));
}
[Test]
public void ArrayAndEmptyArraySegment()
{
Assume.That(ArraySegmentImplementsIEnumerable);
Assert.That(new int[] { 2, 3, 4 }, Is.Not.EqualTo(new ArraySegment<int>()));
}
[Test]
public void TwoArraySegments()
{
Assume.That(ArraySegmentImplementsIEnumerable);
Assert.That(new ArraySegment<int>(underlyingArray, 1, 3), Is.EqualTo(new ArraySegment<int>(underlyingArray, 1, 3)));
}
[Test]
public void TwoEmptyArraySegments()
{
Assume.That(ArraySegmentImplementsIEnumerable);
Assert.That(new ArraySegment<int>(), Is.EqualTo(new ArraySegment<int>()));
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MTNameTable.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
#if MTNAMETABLE
using System;
using System.IO;
using System.Collections;
using System.Threading;
namespace System.Xml {
#if !SPLAY_MTNAMETABLE
// MTNameTable is a modified version of our normal NameTable
// that is thread-safe on read & write. The design is kept
// simple by using the Entry[] as the atomic update pivot point.
public class MTNameTable : XmlNameTable {
//
// Private types
//
class Entry {
internal string str;
internal int hashCode;
internal Entry next;
internal Entry( string str, int hashCode, Entry next ) {
this.str = str;
this.hashCode = hashCode;
this.next = next;
}
}
//
// Fields
//
Entry[] entries;
int count;
int hashCodeRandomizer;
//
// Constructor
//
public MTNameTable() {
entries = new Entry[32];
hashCodeRandomizer = Environment.TickCount;
}
//
// XmlNameTable public methods
//
public override string Add( string key ) {
if ( key == null ) {
throw new ArgumentNullException( "key" );
}
int len = key.Length;
if ( len == 0 ) {
return string.Empty;
}
int hashCode = len + hashCodeRandomizer;
// use key.Length to eliminate the rangecheck
for ( int i = 0; i < key.Length; i++ ) {
hashCode += ( hashCode << 7 ) ^ key[i];
}
// mix it a bit more
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
Entry[] entries = this.entries;
for ( Entry e = entries[hashCode & (entries.Length-1)];
e != null;
e = e.next ) {
if ( e.hashCode == hashCode && e.str.Equals( key ) ) {
return e.str;
}
}
return AddEntry( key, hashCode );
}
public override string Add( char[] key, int start, int len ) {
if ( len == 0 ) {
return string.Empty;
}
int hashCode = len + hashCodeRandomizer;
hashCode += ( hashCode << 7 ) ^ key[start]; // this will throw IndexOutOfRangeException in case the start index is invalid
int end = start+len;
for ( int i = start + 1; i < end; i++) {
hashCode += ( hashCode << 7 ) ^ key[i];
}
// mix it a bit more
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
Entry[] entries = this.entries;
for ( Entry e = entries[hashCode & (entries.Length-1)];
e != null;
e = e.next ) {
if ( e.hashCode == hashCode && TextEquals( e.str, key, start ) ) {
return e.str;
}
}
return AddEntry( new string( key, start, len ), hashCode );
}
public override string Get( string value ) {
if ( value == null ) {
throw new ArgumentNullException("value");
}
if ( value.Length == 0 ) {
return string.Empty;
}
int len = value.Length + hashCodeRandomizer;
int hashCode = len;
// use value.Length to eliminate the rangecheck
for ( int i = 0; i < value.Length; i++ ) {
hashCode += ( hashCode << 7 ) ^ value[i];
}
// mix it a bit more
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
Entry[] entries = this.entries;
for ( Entry e = entries[hashCode & (entries.Length-1)];
e != null;
e = e.next ) {
if ( e.hashCode == hashCode && e.str.Equals( value ) ) {
return e.str;
}
}
return null;
}
public override string Get( char[] key, int start, int len ) {
if ( len == 0 ) {
return string.Empty;
}
int hashCode = len + hashCodeRandomizer;
hashCode += ( hashCode << 7 ) ^ key[start]; // this will throw IndexOutOfRangeException in case the start index is invalid
int end = start+len;
for ( int i = start + 1; i < end; i++) {
hashCode += ( hashCode << 7 ) ^ key[i];
}
// mix it a bit more
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
Entry[] entries = this.entries;
for ( Entry e = entries[hashCode & (entries.Length-1)];
e != null;
e = e.next ) {
if ( e.hashCode == hashCode && TextEquals( e.str, key, start ) ) {
return e.str;
}
}
return null;
}
//
// Private methods
//
private string AddEntry( string str, int hashCode ) {
Entry e;
lock (this) {
Entry[] entries = this.entries;
int index = hashCode & entries.Length-1;
for ( e = entries[index]; e != null; e = e.next ) {
if ( e.hashCode == hashCode && e.str.Equals( str ) ) {
return e.str;
}
}
e = new Entry( str, hashCode, entries[index] );
entries[index] = e;
if ( count++ == mask ) {
Grow();
}
}
return e.str;
}
private void Grow() {
int newMask = mask * 2 + 1;
Entry[] oldEntries = entries;
Entry[] newEntries = new Entry[newMask+1];
// use oldEntries.Length to eliminate the rangecheck
for ( int i = 0; i < oldEntries.Length; i++ ) {
Entry e = oldEntries[i];
while ( e != null ) {
int newIndex = e.hashCode & newMask;
Entry tmp = e.next;
e.next = newEntries[newIndex];
newEntries[newIndex] = e;
e = tmp;
}
}
entries = newEntries;
mask = newMask;
}
private static bool TextEquals( string array, char[] text, int start ) {
// use array.Length to eliminate the rangecheck
for ( int i = 0; i < array.Length; i++ ) {
if ( array[i] != text[start+i] ) {
return false;
}
}
return true;
}
}
#else
// XmlNameTable implemented as a multi-threaded splay tree.
[Obsolete("This class is going away")]
public class MTNameTable : XmlNameTable {
internal MTNameTableNode rootNode;
internal ReaderWriterLock rwLock;
internal int timeout;
public MTNameTable( bool isThreadSafe, int timeout ) {
if (isThreadSafe) {
this.rwLock = new ReaderWriterLock();
this.timeout = timeout;
}
}
public MTNameTable( bool isThreadSafe ): this( isThreadSafe, Timeout.Infinite ) {
}
public MTNameTable(): this( false ) {
}
public IEnumerator GetEnumerator() {
return new MTNameTableEnumerator( this );
}
public override String Get( String value ) {
if (value == null) {
throw new ArgumentNullException("value");
}
MTNameTableName name = new MTNameTableName(value);
return Get( ref name );
}
public override String Get( char[] key, int start, int len ) {
if (key == null) {
throw new ArgumentNullException("key");
}
else {
if ((start < 0) || (len < 0) || (start > key.Length - len))
throw new ArgumentOutOfRangeException();
}
MTNameTableName name = new MTNameTableName(key, start, len);
return Get( ref name );
}
private String Get( ref MTNameTableName nn ) {
String name = null;
if (rootNode != null) {
if (rwLock != null)
rwLock.AcquireReaderLock(timeout);
MTNameTableNode currentNode = rootNode;
while (true) {
Int64 d = currentNode.Compare(ref nn);
if (d == 0) {
Promote( currentNode );
name = currentNode.value;
break;
}
else if (d < 0) {
if (currentNode.leftNode == null)
break;
currentNode = currentNode.leftNode;
}
else {
if (currentNode.rightNode == null)
break;
currentNode = currentNode.rightNode;
}
}
if (rwLock != null)
rwLock.ReleaseReaderLock();
}
return name;
}
// Find the matching string atom given a string, or
// insert a new one.
public override String Add(String value) {
if (value == null) {
throw new ArgumentNullException("value");
}
MTNameTableName name = new MTNameTableName( value );
return Add( ref name, rwLock != null ).value;
}
public override String Add(char[] key, int start, int len) {
if (key == null) {
throw new ArgumentNullException("key");
}
else {
if ((start < 0) || (len < 0) || (start > key.Length - len))
throw new ArgumentOutOfRangeException();
}
MTNameTableName name = new MTNameTableName( key, start, len );
return Add( ref name, rwLock != null ).value;
}
private MTNameTableNode Add( ref MTNameTableName name, bool fLock) {
if (fLock)
rwLock.AcquireReaderLock(timeout);
MTNameTableNode currentNode = rootNode;
while (true) {
if (currentNode == null) {
currentNode = AddRoot( ref name, fLock );
break;
}
else {
Int64 d = currentNode.Compare(ref name);
if (d == 0) {
Promote( currentNode );
break;
}
else if (d < 0) {
if (currentNode.leftNode == null) {
currentNode = AddLeft( currentNode, ref name, fLock );
break;
}
else {
currentNode = currentNode.leftNode;
}
}
else {
if (currentNode.rightNode == null) {
currentNode = AddRight( currentNode, ref name, fLock );
break;
}
else {
currentNode = currentNode.rightNode;
}
}
}
}
if (fLock)
rwLock.ReleaseReaderLock();
return currentNode;
}
// Sets the root node given a string
private MTNameTableNode AddRoot( ref MTNameTableName name, bool fLock ) {
MTNameTableNode newNode = null;
if (fLock) {
LockCookie lc = rwLock.UpgradeToWriterLock(timeout);
// recheck for failsafe against -----condition
if (rootNode == null) {
rootNode = newNode = new MTNameTableNode( ref name );
}
else {
// try again, with write-lock active
newNode = Add( ref name, false );
}
rwLock.DowngradeFromWriterLock(ref lc);
}
else {
rootNode = newNode = new MTNameTableNode( ref name );
}
return newNode;
}
// Adds the a node to the left of the specified node given a string
private MTNameTableNode AddLeft( MTNameTableNode node, ref MTNameTableName name, bool fLock ) {
MTNameTableNode newNode = null;
if (fLock) {
LockCookie lc = rwLock.UpgradeToWriterLock(timeout);
// recheck for failsafe against -----condition
if (node.leftNode == null) {
newNode = new MTNameTableNode( ref name );
node.leftNode = newNode;
newNode.parentNode = node;
}
else {
// try again, with write-lock active
newNode = Add( ref name, false );
}
rwLock.DowngradeFromWriterLock(ref lc);
}
else {
newNode = new MTNameTableNode( ref name );
node.leftNode = newNode;
newNode.parentNode = node;
}
return newNode;
}
// Adds the a node to the right of the specified node, given a string.
private MTNameTableNode AddRight( MTNameTableNode node, ref MTNameTableName name, bool fLock ) {
MTNameTableNode newNode = null;
if (fLock) {
LockCookie lc = rwLock.UpgradeToWriterLock(timeout);
// recheck for failsafe against -----condition
if (node.rightNode == null) {
newNode = new MTNameTableNode( ref name );
node.rightNode = newNode;
newNode.parentNode = node;
}
else {
// try again, with write-lock active
newNode = Add( ref name, false );
}
rwLock.DowngradeFromWriterLock(ref lc);
}
else {
newNode = new MTNameTableNode( ref name );
node.rightNode = newNode;
newNode.parentNode = node;
}
return newNode;
}
private const int threshhold = 20;
// Promote the node into the parent's position (1 ply closer to the rootNode)
private void Promote( MTNameTableNode node ) {
// count number of times promotion requested
node.counter++;
if (node != rootNode &&
node.counter > threshhold &&
node.counter > node.parentNode.counter * 2) {
if (rwLock != null) {
LockCookie lc = rwLock.UpgradeToWriterLock(timeout);
// recheck for failsafe against -----condition
if (node != rootNode &&
node.counter > threshhold &&
node.counter > node.parentNode.counter * 2) {
InternalPromote( node );
}
rwLock.DowngradeFromWriterLock(ref lc);
}
else {
InternalPromote( node );
}
}
}
private void InternalPromote( MTNameTableNode node ) {
MTNameTableNode parent = node.parentNode;
if (parent != null) {
MTNameTableNode grandParent = parent.parentNode;
if (parent.leftNode == node) {
parent.leftNode = node.rightNode;
node.rightNode = parent;
// update lineage
if (parent.leftNode != null)
parent.leftNode.parentNode = parent;
node.parentNode = grandParent;
parent.parentNode = node;
}
else {
parent.rightNode = node.leftNode;
node.leftNode = parent;
// update lineage
if (parent.rightNode != null)
parent.rightNode.parentNode = parent;
node.parentNode = grandParent;
parent.parentNode = node;
}
// fixup pointer to promoted node in grand parent
if (grandParent == null) {
rootNode = node;
}
else {
if (grandParent.leftNode == parent) {
grandParent.leftNode = node;
}
else {
grandParent.rightNode = node;
}
}
}
}
}
internal struct MTNameTableName {
internal String str;
internal char[] array;
internal int start;
internal int len;
internal Int64 hash;
public MTNameTableName( string str ) {
this.str = str;
this.hash = Hash(str);
this.array = null;
this.start = 0;
this.len = 0;
}
public MTNameTableName( char[] array, int start, int len ) {
this.array = array;
this.start = start;
this.len = len;
this.str = null;
this.hash = Hash(array, start, len);
}
static private Int64 Hash(String value) {
Int64 hash = 0;
int len = value.Length;
if (len > 0)
hash = (((Int64)value[0]) & 0xFF) << 48;
if (len > 1)
hash = hash | ((((Int64)value[1]) & 0xFF) << 32);
if (len > 2)
hash = hash | ((((Int64)value[2]) & 0xFF) << 16);
if (len > 3)
hash = hash | (((Int64)value[3]) & 0xFF);
return hash;
}
static private Int64 Hash(char[] key, int start, int len) {
Int64 hash = 0;
if (len > 0)
hash = (((Int64)key[start]) & 0xFF) << 48;
if (len > 1)
hash = hash | ((((Int64)key[start+1]) & 0xFF) << 32);
if (len > 2)
hash = hash | ((((Int64)key[start+2]) & 0xFF) << 16);
if (len > 3)
hash = hash | (((Int64)key[start+3]) & 0xFF);
return hash;
}
}
// A MTNameTable node.
internal class MTNameTableNode {
internal String value;
internal Int64 hash;
internal Int64 counter;
internal MTNameTableNode leftNode;
internal MTNameTableNode rightNode;
internal MTNameTableNode parentNode;
internal MTNameTableNode(ref MTNameTableName name ) {
if (name.str != null) {
value = name.str;
}
else {
value = new String(name.array, name.start, name.len);
}
this.hash = name.hash;
}
internal Int64 Compare( ref MTNameTableName name ) {
if (name.array != null) {
return Compare( name.hash, name.array, name.start, name.len );
}
else {
return Compare( name.hash, name.str );
}
}
private Int64 Compare(Int64 hash, string value) {
Int64 d = hash - this.hash;
if (d == 0) {
int valueLength = this.value.Length;
d = value.Length - valueLength;
// if length is not equal, break
if (d != 0)
return(Int64)d;
for (int ii = 4; ii < valueLength; ii++) {
int dd = value[ii] - this.value[ii];
if (dd != 0) {
d = dd;
break;
}
}
}
return(Int64)d;
}
private Int64 Compare(Int64 hash, char[] key, int start, int len) {
Int64 d = hash - this.hash;
if (d == 0) {
int valueLength = this.value.Length;
d = len - valueLength;
// if length is not equal, break
if (d != 0)
return(Int64)d;
for (int ii = 4; ii < valueLength; ii++) {
int dd = key[start + ii] - this.value[ii];
if (dd != 0) {
d = dd;
break;
}
}
}
return(Int64)d;
}
}
// Enumerates all the names (strings) of a MTNameTable
internal class MTNameTableEnumerator: IEnumerator {
private ArrayList names;
private int iName;
internal MTNameTableEnumerator( MTNameTable nt ) {
if (nt.rwLock != null)
nt.rwLock.AcquireReaderLock(nt.timeout);
names = new ArrayList();
Walk( nt.rootNode );
iName = -1;
if (nt.rwLock != null)
nt.rwLock.ReleaseReaderLock();
}
internal void Walk( MTNameTableNode node ) {
if (node != null) {
if (node.leftNode != null)
Walk( node.leftNode );
names.Add( node.value );
if (node.rightNode != null)
Walk( node.rightNode );
}
}
public void Reset() {
iName = -1;
}
public bool MoveNext() {
iName++;
return iName < names.Count;
}
public object Current {
get {
if (iName < names.Count)
return names[iName];
return null;
}
}
}
#endif
}
#endif
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using EverReader.Models;
namespace EverReader.Migrations
{
[DbContext(typeof(EverReaderContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.Annotation("ProductVersion", "7.0.0-beta8-15964")
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("EverReader.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.Annotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<int?>("EvernoteCredentialsId");
b.Property<bool>("HasAuthorisedEvernote");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.Annotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.Annotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.Annotation("MaxLength", 256);
b.HasKey("Id");
b.Index("NormalizedEmail")
.Annotation("Relational:Name", "EmailIndex");
b.Index("NormalizedUserName")
.Annotation("Relational:Name", "UserNameIndex");
b.Annotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("EverReader.Models.Bookmark", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BookmarkTitle");
b.Property<DateTime>("NoteCreated");
b.Property<string>("NoteGuid");
b.Property<int>("NoteLength");
b.Property<string>("NoteTitle");
b.Property<DateTime>("NoteUpdated");
b.Property<decimal>("PercentageRead");
b.Property<int>("Type");
b.Property<DateTime>("Updated");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("EverReader.Models.EFDbEvernoteCredentials", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AuthToken");
b.Property<DateTime>("Expires");
b.Property<string>("NotebookUrl");
b.Property<string>("Shard");
b.Property<string>("UserId");
b.Property<string>("WebApiUrlPrefix");
b.HasKey("Id");
});
modelBuilder.Entity("EverReader.Models.NotebookData", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Guid");
b.Property<string>("Name");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("EverReader.Models.PrivateBetaUser", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Email");
b.HasKey("Id");
});
modelBuilder.Entity("EverReader.Models.TagData", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Guid");
b.Property<string>("Name");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("EverReader.Models.TagOperationDefinition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("TagGuid");
b.Property<int>("Type");
b.HasKey("Id");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.Annotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.Annotation("MaxLength", 256);
b.HasKey("Id");
b.Index("NormalizedName")
.Annotation("Relational:Name", "RoleNameIndex");
b.Annotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId");
b.HasKey("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId");
b.HasKey("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId");
b.HasKey("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("EverReader.Models.ApplicationUser", b =>
{
b.HasOne("EverReader.Models.EFDbEvernoteCredentials")
.WithMany()
.ForeignKey("EvernoteCredentialsId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.ForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("EverReader.Models.ApplicationUser")
.WithMany()
.ForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("EverReader.Models.ApplicationUser")
.WithMany()
.ForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.ForeignKey("RoleId");
b.HasOne("EverReader.Models.ApplicationUser")
.WithMany()
.ForeignKey("UserId");
});
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="StorageModificationFunctionMapping.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Data.Metadata.Edm;
using System.Diagnostics;
using System.Globalization;
using System.Data.Common.Utils;
using System.Linq;
namespace System.Data.Mapping
{
/// <summary>
/// Describes modification function mappings for an association set.
/// </summary>
internal sealed class StorageAssociationSetModificationFunctionMapping
{
internal StorageAssociationSetModificationFunctionMapping(
AssociationSet associationSet,
StorageModificationFunctionMapping deleteFunctionMapping,
StorageModificationFunctionMapping insertFunctionMapping)
{
this.AssociationSet = EntityUtil.CheckArgumentNull(associationSet, "associationSet");
this.DeleteFunctionMapping = deleteFunctionMapping;
this.InsertFunctionMapping = insertFunctionMapping;
}
/// <summary>
/// Association set these functions handles.
/// </summary>
internal readonly AssociationSet AssociationSet;
/// <summary>
/// Delete function for this association set.
/// </summary>
internal readonly StorageModificationFunctionMapping DeleteFunctionMapping;
/// <summary>
/// Insert function for this association set.
/// </summary>
internal readonly StorageModificationFunctionMapping InsertFunctionMapping;
public override string ToString()
{
return String.Format(CultureInfo.InvariantCulture,
"AS{{{0}}}:{3}DFunc={{{1}}},{3}IFunc={{{2}}}", AssociationSet, DeleteFunctionMapping,
InsertFunctionMapping, Environment.NewLine + " ");
}
internal void Print(int index)
{
StorageEntityContainerMapping.GetPrettyPrintString(ref index);
StringBuilder sb = new StringBuilder();
sb.Append("Association Set Function Mapping");
sb.Append(" ");
sb.Append(this.ToString());
Console.WriteLine(sb.ToString());
}
}
/// <summary>
/// Describes modification function mappings for an entity type within an entity set.
/// </summary>
internal sealed class StorageEntityTypeModificationFunctionMapping
{
internal StorageEntityTypeModificationFunctionMapping(
EntityType entityType,
StorageModificationFunctionMapping deleteFunctionMapping,
StorageModificationFunctionMapping insertFunctionMapping,
StorageModificationFunctionMapping updateFunctionMapping)
{
this.EntityType = EntityUtil.CheckArgumentNull(entityType, "entityType");
this.DeleteFunctionMapping = deleteFunctionMapping;
this.InsertFunctionMapping = insertFunctionMapping;
this.UpdateFunctionMapping = updateFunctionMapping;
}
/// <summary>
/// Gets (specific) entity type these functions handle.
/// </summary>
internal readonly EntityType EntityType;
/// <summary>
/// Gets delete function for the current entity type.
/// </summary>
internal readonly StorageModificationFunctionMapping DeleteFunctionMapping;
/// <summary>
/// Gets insert function for the current entity type.
/// </summary>
internal readonly StorageModificationFunctionMapping InsertFunctionMapping;
/// <summary>
/// Gets update function for the current entity type.
/// </summary>
internal readonly StorageModificationFunctionMapping UpdateFunctionMapping;
public override string ToString()
{
return String.Format(CultureInfo.InvariantCulture,
"ET{{{0}}}:{4}DFunc={{{1}}},{4}IFunc={{{2}}},{4}UFunc={{{3}}}", EntityType, DeleteFunctionMapping,
InsertFunctionMapping, UpdateFunctionMapping, Environment.NewLine + " ");
}
internal void Print(int index)
{
StorageEntityContainerMapping.GetPrettyPrintString(ref index);
StringBuilder sb = new StringBuilder();
sb.Append("Entity Type Function Mapping");
sb.Append(" ");
sb.Append(this.ToString());
Console.WriteLine(sb.ToString());
}
}
/// <summary>
/// Describes modification function binding for change processing of entities or associations.
/// </summary>
internal sealed class StorageModificationFunctionMapping
{
internal StorageModificationFunctionMapping(
EntitySetBase entitySet,
EntityTypeBase entityType,
EdmFunction function,
IEnumerable<StorageModificationFunctionParameterBinding> parameterBindings,
FunctionParameter rowsAffectedParameter,
IEnumerable<StorageModificationFunctionResultBinding> resultBindings)
{
EntityUtil.CheckArgumentNull(entitySet, "entitySet");
this.Function = EntityUtil.CheckArgumentNull(function, "function");
this.RowsAffectedParameter = rowsAffectedParameter;
this.ParameterBindings = EntityUtil.CheckArgumentNull(parameterBindings, "parameterBindings")
.ToList().AsReadOnly();
if (null != resultBindings)
{
List<StorageModificationFunctionResultBinding> bindings = resultBindings.ToList();
if (0 < bindings.Count)
{
ResultBindings = bindings.AsReadOnly();
}
}
this.CollocatedAssociationSetEnds = GetReferencedAssociationSetEnds(entitySet as EntitySet, entityType as EntityType, parameterBindings)
.ToList()
.AsReadOnly();
}
/// <summary>
/// Gets output parameter producing number of rows affected. May be null.
/// </summary>
internal readonly FunctionParameter RowsAffectedParameter;
/// <summary>
/// Gets Metadata of function to which we should bind.
/// </summary>
internal readonly EdmFunction Function;
/// <summary>
/// Gets bindings for function parameters.
/// </summary>
internal readonly ReadOnlyCollection<StorageModificationFunctionParameterBinding> ParameterBindings;
/// <summary>
/// Gets all association set ends collocated in this mapping.
/// </summary>
internal readonly ReadOnlyCollection<AssociationSetEnd> CollocatedAssociationSetEnds;
/// <summary>
/// Gets bindings for the results of function evaluation.
/// </summary>
internal readonly ReadOnlyCollection<StorageModificationFunctionResultBinding> ResultBindings;
public override string ToString()
{
return String.Format(CultureInfo.InvariantCulture,
"Func{{{0}}}: Prm={{{1}}}, Result={{{2}}}", Function,
StringUtil.ToCommaSeparatedStringSorted(ParameterBindings),
StringUtil.ToCommaSeparatedStringSorted(ResultBindings));
}
// requires: entitySet must not be null
// Yields all referenced association set ends in this mapping.
private static IEnumerable<AssociationSetEnd> GetReferencedAssociationSetEnds(EntitySet entitySet, EntityType entityType, IEnumerable<StorageModificationFunctionParameterBinding> parameterBindings)
{
HashSet<AssociationSetEnd> ends = new HashSet<AssociationSetEnd>();
if (null != entitySet && null != entityType)
{
foreach (StorageModificationFunctionParameterBinding parameterBinding in parameterBindings)
{
AssociationSetEnd end = parameterBinding.MemberPath.AssociationSetEnd;
if (null != end)
{
ends.Add(end);
}
}
// If there is a referential constraint, it counts as an implicit mapping of
// the association set
foreach (AssociationSet assocationSet in MetadataHelper.GetAssociationsForEntitySet(entitySet))
{
ReadOnlyMetadataCollection<ReferentialConstraint> constraints = assocationSet.ElementType.ReferentialConstraints;
if (null != constraints)
{
foreach (ReferentialConstraint constraint in constraints)
{
if ((assocationSet.AssociationSetEnds[constraint.ToRole.Name].EntitySet == entitySet) &&
(constraint.ToRole.GetEntityType().IsAssignableFrom(entityType)))
{
ends.Add(assocationSet.AssociationSetEnds[constraint.FromRole.Name]);
}
}
}
}
}
return ends;
}
}
/// <summary>
/// Defines a binding from a named result set column to a member taking the value.
/// </summary>
internal sealed class StorageModificationFunctionResultBinding
{
internal StorageModificationFunctionResultBinding(string columnName, EdmProperty property)
{
this.ColumnName = EntityUtil.CheckArgumentNull(columnName, "columnName");
this.Property = EntityUtil.CheckArgumentNull(property, "property");
}
/// <summary>
/// Gets the name of the column to bind from the function result set. We use a string
/// value rather than EdmMember, since there is no metadata for function result sets.
/// </summary>
internal readonly string ColumnName;
/// <summary>
/// Gets the property to be set on the entity.
/// </summary>
internal readonly EdmProperty Property;
public override string ToString()
{
return String.Format(CultureInfo.InvariantCulture,
"{0}->{1}", ColumnName, Property);
}
}
/// <summary>
/// Binds a modification function parameter to a member of the entity or association being modified.
/// </summary>
internal sealed class StorageModificationFunctionParameterBinding
{
internal StorageModificationFunctionParameterBinding(FunctionParameter parameter, StorageModificationFunctionMemberPath memberPath, bool isCurrent)
{
this.Parameter = EntityUtil.CheckArgumentNull(parameter, "parameter");
this.MemberPath = EntityUtil.CheckArgumentNull(memberPath, "memberPath");
this.IsCurrent = isCurrent;
}
/// <summary>
/// Gets the parameter taking the value.
/// </summary>
internal readonly FunctionParameter Parameter;
/// <summary>
/// Gets the path to the entity or association member defining the value.
/// </summary>
internal readonly StorageModificationFunctionMemberPath MemberPath;
/// <summary>
/// Gets a value indicating whether the current or original
/// member value is being bound.
/// </summary>
internal readonly bool IsCurrent;
public override string ToString()
{
return String.Format(CultureInfo.InvariantCulture,
"@{0}->{1}{2}", Parameter, IsCurrent ? "+" : "-", MemberPath);
}
}
/// <summary>
/// Describes the location of a member within an entity or association type structure.
/// </summary>
internal sealed class StorageModificationFunctionMemberPath
{
internal StorageModificationFunctionMemberPath(IEnumerable<EdmMember> members, AssociationSet associationSetNavigation)
{
this.Members = new ReadOnlyCollection<EdmMember>(new List<EdmMember>(
EntityUtil.CheckArgumentNull(members, "members")));
if (null != associationSetNavigation)
{
Debug.Assert(2 == this.Members.Count, "Association bindings must always consist of the end and the key");
// find the association set end
this.AssociationSetEnd = associationSetNavigation.AssociationSetEnds[this.Members[1].Name];
}
}
/// <summary>
/// Gets the members in the path from the leaf (the member being bound)
/// to the Root of the structure.
/// </summary>
internal readonly ReadOnlyCollection<EdmMember> Members;
/// <summary>
/// Gets the association set to which we are navigating via this member. If the value
/// is null, this is not a navigation member path.
/// </summary>
internal readonly AssociationSetEnd AssociationSetEnd;
public override string ToString()
{
return String.Format(CultureInfo.InvariantCulture, "{0}{1}",
null == AssociationSetEnd ? String.Empty : "[" + AssociationSetEnd.ParentAssociationSet.ToString() + "]",
StringUtil.BuildDelimitedList(Members, null, "."));
}
}
}
| |
/*******************************************************************************
* Copyright 2008-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.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Amazon.Runtime;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Util
{
/// <summary>
/// This class defines utilities and constants that can be used by
/// all the client libraries of the SDK.
/// </summary>
public static partial class AWSSDKUtils
{
#region Internal Constants
internal const string DefaultRegion = "us-east-1";
internal const string DefaultGovRegion = "us-gov-west-1";
internal const int DefaultMaxRetry = 3;
private const int DefaultConnectionLimit = 50;
private const int DefaultMaxIdleTime = 50 * 1000; // 50 seconds
internal static readonly DateTime EPOCH_START = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public const int DefaultBufferSize = 8192;
// Default value of progress update interval for streaming is 100KB.
public const long DefaultProgressUpdateInterval = 102400;
internal static Dictionary<int, string> RFCEncodingSchemes = new Dictionary<int, string>
{
{ 3986, ValidUrlCharacters },
{ 1738, ValidUrlCharactersRFC1738 }
};
#endregion
#region Public Constants
/// <summary>
/// The user agent string header
/// </summary>
public const string UserAgentHeader = "User-Agent";
/// <summary>
/// The Set of accepted and valid Url characters per RFC3986.
/// Characters outside of this set will be encoded.
/// </summary>
public const string ValidUrlCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
/// <summary>
/// The Set of accepted and valid Url characters per RFC1738.
/// Characters outside of this set will be encoded.
/// </summary>
public const string ValidUrlCharactersRFC1738 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.";
/// <summary>
/// The set of accepted and valid Url path characters per RFC3986.
/// </summary>
private static string ValidPathCharacters = DetermineValidPathCharacters();
// Checks which path characters should not be encoded
// This set will be different for .NET 4 and .NET 4.5, as
// per http://msdn.microsoft.com/en-us/library/hh367887%28v=vs.110%29.aspx
private static string DetermineValidPathCharacters()
{
const string basePathCharacters = "/:'()!*[]";
var sb = new StringBuilder();
foreach (var c in basePathCharacters)
{
var escaped = Uri.EscapeUriString(c.ToString());
if (escaped.Length == 1 && escaped[0] == c)
sb.Append(c);
}
return sb.ToString();
}
/// <summary>
/// The string representing Url Encoded Content in HTTP requests
/// </summary>
public const string UrlEncodedContent = "application/x-www-form-urlencoded; charset=utf-8";
/// <summary>
/// The GMT Date Format string. Used when parsing date objects
/// </summary>
public const string GMTDateFormat = "ddd, dd MMM yyyy HH:mm:ss \\G\\M\\T";
/// <summary>
/// The ISO8601Date Format string. Used when parsing date objects
/// </summary>
public const string ISO8601DateFormat = "yyyy-MM-dd\\THH:mm:ss.fff\\Z";
/// <summary>
/// The ISO8601Date Format string. Used when parsing date objects
/// </summary>
public const string ISO8601DateFormatNoMS = "yyyy-MM-dd\\THH:mm:ss\\Z";
/// <summary>
/// The ISO8601 Basic date/time format string. Used when parsing date objects
/// </summary>
public const string ISO8601BasicDateTimeFormat = "yyyyMMddTHHmmssZ";
/// <summary>
/// The ISO8601 basic date format. Used during AWS4 signature computation.
/// </summary>
public const string ISO8601BasicDateFormat = "yyyyMMdd";
/// <summary>
/// The RFC822Date Format string. Used when parsing date objects
/// </summary>
public const string RFC822DateFormat = "ddd, dd MMM yyyy HH:mm:ss \\G\\M\\T";
#endregion
#region Internal Methods
/// <summary>
/// Returns an extension of a path.
/// This has the same behavior as System.IO.Path.GetExtension, but does not
/// check the path for invalid characters.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string GetExtension(string path)
{
if (path == null)
return null;
int length = path.Length;
int index = length;
while (--index >= 0)
{
char ch = path[index];
if (ch == '.')
{
if (index != length - 1)
return path.Substring(index, length - index);
else
return string.Empty;
}
else if (IsPathSeparator(ch))
break;
}
return string.Empty;
}
// Checks if the character is one \ / :
private static bool IsPathSeparator(char ch)
{
return (ch == '\\' ||
ch == '/' ||
ch == ':');
}
/*
* Determines the string to be signed based on the input parameters for
* AWS Signature Version 2
*/
internal static string CalculateStringToSignV2(IDictionary<string, string> parameters, string serviceUrl)
{
StringBuilder data = new StringBuilder("POST\n", 512);
IDictionary<string, string> sorted =
new SortedDictionary<string, string>(parameters, StringComparer.Ordinal);
Uri endpoint = new Uri(serviceUrl);
data.Append(endpoint.Host);
data.Append("\n");
string uri = endpoint.AbsolutePath;
if (uri == null || uri.Length == 0)
{
uri = "/";
}
data.Append(AWSSDKUtils.UrlEncode(uri, true));
data.Append("\n");
foreach (KeyValuePair<string, string> pair in sorted)
{
if (pair.Value != null)
{
data.Append(AWSSDKUtils.UrlEncode(pair.Key, false));
data.Append("=");
data.Append(AWSSDKUtils.UrlEncode(pair.Value, false));
data.Append("&");
}
}
string result = data.ToString();
return result.Remove(result.Length - 1);
}
/**
* Convert Dictionary of paremeters to Url encoded query string
*/
internal static string GetParametersAsString(IDictionary<string, string> parameters)
{
string[] keys = new string[parameters.Keys.Count];
parameters.Keys.CopyTo(keys, 0);
Array.Sort<string>(keys);
StringBuilder data = new StringBuilder(512);
foreach (string key in keys)
{
string value = parameters[key];
if (value != null)
{
data.Append(key);
data.Append('=');
data.Append(AWSSDKUtils.UrlEncode(value, false));
data.Append('&');
}
}
string result = data.ToString();
if (result.Length == 0)
return string.Empty;
return result.Remove(result.Length - 1);
}
/// <summary>
/// Returns a new string created by joining each of the strings in the
/// specified list together, with a comma between them.
/// </summary>
/// <parma name="strings">The list of strings to join into a single, comma delimited
/// string list.</parma>
/// <returns> A new string created by joining each of the strings in the
/// specified list together, with a comma between strings.</returns>
public static String Join(List<String> strings)
{
StringBuilder result = new StringBuilder();
Boolean first = true;
foreach (String s in strings)
{
if (!first) result.Append(", ");
result.Append(s);
first = false;
}
return result.ToString();
}
/// <summary>
/// Attempt to infer the region for a service request based on the endpoint
/// </summary>
/// <param name="url">Endpoint to the service to be called</param>
/// <returns>
/// Region parsed from the endpoint; DefaultRegion (or DefaultGovRegion)
/// if it cannot be determined/is not explicit
/// </returns>
public static string DetermineRegion(string url)
{
int delimIndex = url.IndexOf("//", StringComparison.Ordinal);
if (delimIndex >= 0)
url = url.Substring(delimIndex + 2);
if(url.EndsWith("/", StringComparison.Ordinal))
url = url.Substring(0, url.Length - 1);
int awsIndex = url.IndexOf(".amazonaws.com", StringComparison.Ordinal);
if (awsIndex < 0)
return DefaultRegion;
string serviceAndRegion = url.Substring(0, awsIndex);
int cloudSearchIndex = url.IndexOf(".cloudsearch.amazonaws.com", StringComparison.Ordinal);
if (cloudSearchIndex > 0)
serviceAndRegion = url.Substring(0, cloudSearchIndex);
int queueIndex = serviceAndRegion.IndexOf("queue", StringComparison.Ordinal);
if (queueIndex == 0)
return DefaultRegion;
if (queueIndex > 0)
return serviceAndRegion.Substring(0, queueIndex - 1);
if (serviceAndRegion.StartsWith("s3-", StringComparison.Ordinal))
serviceAndRegion = "s3." + serviceAndRegion.Substring(3);
int separatorIndex = serviceAndRegion.LastIndexOf('.');
if (separatorIndex == -1)
return DefaultRegion;
string region = serviceAndRegion.Substring(separatorIndex + 1);
if (region.Equals("external-1"))
return RegionEndpoint.USEast1.SystemName;
if (string.Equals(region, "us-gov", StringComparison.Ordinal))
return DefaultGovRegion;
return region;
}
/// <summary>
/// Attempt to infer the service name for a request (in short form, eg 'iam') from the
/// service endpoint.
/// </summary>
/// <param name="url">Endpoint to the service to be called</param>
/// <returns>
/// Short-form name of the service parsed from the endpoint; empty string if it cannot
/// be determined
/// </returns>
public static string DetermineService(string url)
{
int delimIndex = url.IndexOf("//", StringComparison.Ordinal);
if (delimIndex >= 0)
url = url.Substring(delimIndex + 2);
string[] urlParts = url.Split(new char[] {'.'}, StringSplitOptions.RemoveEmptyEntries);
if (urlParts == null || urlParts.Length == 0)
return string.Empty;
string servicePart = urlParts[0];
int hyphenated = servicePart.IndexOf('-');
string service;
if (hyphenated < 0)
{ service = servicePart; }
else
{ service = servicePart.Substring(0, hyphenated); }
// Check for SQS : return "sqs" incase service is determined to be "queue" as per the URL.
if (service.Equals("queue"))
{
return "sqs";
}
else
{
return service;
}
}
/// <summary>
/// Utility method for converting Unix epoch seconds to DateTime structure.
/// </summary>
/// <param name="seconds">The number of seconds since January 1, 1970.</param>
/// <returns>Converted DateTime structure</returns>
public static DateTime ConvertFromUnixEpochSeconds(int seconds)
{
return new DateTime(seconds * 10000000L + EPOCH_START.Ticks, DateTimeKind.Utc).ToLocalTime();
}
public static int ConvertToUnixEpochSeconds(DateTime dateTime)
{
return (int)ConvertToUnixEpochMilliSeconds(dateTime);
}
public static double ConvertToUnixEpochMilliSeconds(DateTime dateTime)
{
TimeSpan ts = new TimeSpan(dateTime.ToUniversalTime().Ticks - EPOCH_START.Ticks);
double milli = Math.Round(ts.TotalMilliseconds, 0) / 1000.0;
return milli;
}
/// <summary>
/// Helper function to format a byte array into string
/// </summary>
/// <param name="data">The data blob to process</param>
/// <param name="lowercase">If true, returns hex digits in lower case form</param>
/// <returns>String version of the data</returns>
internal static string ToHex(byte[] data, bool lowercase)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sb.Append(data[i].ToString(lowercase ? "x2" : "X2", CultureInfo.InvariantCulture));
}
return sb.ToString();
}
/// <summary>
/// Calls a specific EventHandler in a background thread
/// </summary>
/// <param name="handler"></param>
/// <param name="args"></param>
/// <param name="sender"></param>
public static void InvokeInBackground<T>(EventHandler<T> handler, T args, object sender) where T : EventArgs
{
if (handler == null) return;
var list = handler.GetInvocationList();
foreach (var call in list)
{
var eventHandler = ((EventHandler<T>)call);
if (eventHandler != null)
{
Dispatcher.Dispatch(() => eventHandler(sender, args));
}
}
}
private static BackgroundInvoker _dispatcher;
private static BackgroundInvoker Dispatcher
{
get
{
if (_dispatcher == null)
{
_dispatcher = new BackgroundInvoker();
}
return _dispatcher;
}
}
/// <summary>
/// Parses a query string of a URL and returns the parameters as a string-to-string dictionary.
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static Dictionary<string, string> ParseQueryParameters(string url)
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(url))
{
int queryIndex = url.IndexOf('?');
if (queryIndex >= 0)
{
string queryString = url.Substring(queryIndex + 1);
string[] kvps = queryString.Split(new char[] { '&' }, StringSplitOptions.None);
foreach (string kvp in kvps)
{
if (string.IsNullOrEmpty(kvp))
continue;
string[] nameValuePair = kvp.Split(new char[] { '=' }, 2);
string name = nameValuePair[0];
string value = nameValuePair.Length == 1 ? null : nameValuePair[1];
parameters[name] = value;
}
}
}
return parameters;
}
internal static bool AreEqual(object[] itemsA, object[] itemsB)
{
if (itemsA == null || itemsB == null)
return (itemsA == itemsB);
if (itemsA.Length != itemsB.Length)
return false;
var length = itemsA.Length;
for (int i = 0; i < length; i++)
{
var a = itemsA[i];
var b = itemsB[i];
if (!AreEqual(a, b))
return false;
}
return true;
}
internal static bool AreEqual(object a, object b)
{
if (a == null || b == null)
return (a == b);
if (object.ReferenceEquals(a, b))
return true;
return (a.Equals(b));
}
/// <summary>
/// Utility method for converting a string to a MemoryStream.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static MemoryStream GenerateMemoryStreamFromString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
/// <summary>
/// Utility method for copy the contents of the source stream to the destination stream.
/// </summary>
/// <param name="source"></param>
/// <param name="destination"></param>
public static void CopyStream(Stream source, Stream destination)
{
CopyStream(source, destination, DefaultBufferSize);
}
/// <summary>
/// Utility method for copy the contents of the source stream to the destination stream.
/// </summary>
/// <param name="source"></param>
/// <param name="destination"></param>
/// <param name="bufferSize"></param>
public static void CopyStream(Stream source, Stream destination, int bufferSize)
{
if (source == null)
throw new ArgumentNullException("source");
if (destination == null)
throw new ArgumentNullException("destination");
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException("bufferSize");
byte[] array = new byte[bufferSize];
int count;
while ((count = source.Read(array, 0, array.Length)) != 0)
{
destination.Write(array, 0, count);
}
}
#endregion
#region Public Methods and Properties
/// <summary>
/// Formats the current date as a GMT timestamp
/// </summary>
/// <returns>A GMT formatted string representation
/// of the current date and time
/// </returns>
public static string FormattedCurrentTimestampGMT
{
get
{
DateTime dateTime = AWSSDKUtils.CorrectedUtcNow;
DateTime formatted = new DateTime(
dateTime.Year,
dateTime.Month,
dateTime.Day,
dateTime.Hour,
dateTime.Minute,
dateTime.Second,
dateTime.Millisecond,
DateTimeKind.Local
);
return formatted.ToString(
GMTDateFormat,
CultureInfo.InvariantCulture
);
}
}
/// <summary>
/// Formats the current date as ISO 8601 timestamp
/// </summary>
/// <returns>An ISO 8601 formatted string representation
/// of the current date and time
/// </returns>
public static string FormattedCurrentTimestampISO8601
{
get
{
return GetFormattedTimestampISO8601(0);
}
}
/// <summary>
/// Gets the ISO8601 formatted timestamp that is minutesFromNow
/// in the future.
/// </summary>
/// <param name="minutesFromNow">The number of minutes from the current instant
/// for which the timestamp is needed.</param>
/// <returns>The ISO8601 formatted future timestamp.</returns>
public static string GetFormattedTimestampISO8601(int minutesFromNow)
{
DateTime dateTime = AWSSDKUtils.CorrectedUtcNow.AddMinutes(minutesFromNow);
DateTime formatted = new DateTime(
dateTime.Year,
dateTime.Month,
dateTime.Day,
dateTime.Hour,
dateTime.Minute,
dateTime.Second,
dateTime.Millisecond,
DateTimeKind.Local
);
return formatted.ToString(
AWSSDKUtils.ISO8601DateFormat,
CultureInfo.InvariantCulture
);
}
/// <summary>
/// Formats the current date as ISO 8601 timestamp
/// </summary>
/// <returns>An ISO 8601 formatted string representation
/// of the current date and time
/// </returns>
public static string FormattedCurrentTimestampRFC822
{
get
{
return GetFormattedTimestampRFC822(0);
}
}
/// <summary>
/// Gets the RFC822 formatted timestamp that is minutesFromNow
/// in the future.
/// </summary>
/// <param name="minutesFromNow">The number of minutes from the current instant
/// for which the timestamp is needed.</param>
/// <returns>The ISO8601 formatted future timestamp.</returns>
public static string GetFormattedTimestampRFC822(int minutesFromNow)
{
DateTime dateTime = AWSSDKUtils.CorrectedUtcNow.AddMinutes(minutesFromNow);
DateTime formatted = new DateTime(
dateTime.Year,
dateTime.Month,
dateTime.Day,
dateTime.Hour,
dateTime.Minute,
dateTime.Second,
dateTime.Millisecond,
DateTimeKind.Local
);
return formatted.ToString(
AWSSDKUtils.RFC822DateFormat,
CultureInfo.InvariantCulture
);
}
/// <summary>
/// URL encodes a string per RFC3986. If the path property is specified,
/// the accepted path characters {/+:} are not encoded.
/// </summary>
/// <param name="data">The string to encode</param>
/// <param name="path">Whether the string is a URL path or not</param>
/// <returns>The encoded string</returns>
public static string UrlEncode(string data, bool path)
{
return UrlEncode(3986, data, path);
}
/// <summary>
/// URL encodes a string per the specified RFC. If the path property is specified,
/// the accepted path characters {/+:} are not encoded.
/// </summary>
/// <param name="rfcNumber">RFC number determing safe characters</param>
/// <param name="data">The string to encode</param>
/// <param name="path">Whether the string is a URL path or not</param>
/// <returns>The encoded string</returns>
/// <remarks>
/// Currently recognised RFC versions are 1738 (Dec '94) and 3986 (Jan '05).
/// If the specified RFC is not recognised, 3986 is used by default.
/// </remarks>
public static string UrlEncode(int rfcNumber, string data, bool path)
{
StringBuilder encoded = new StringBuilder(data.Length * 2);
string validUrlCharacters;
if (!RFCEncodingSchemes.TryGetValue(rfcNumber, out validUrlCharacters))
validUrlCharacters = ValidUrlCharacters;
string unreservedChars = String.Concat(validUrlCharacters, (path ? ValidPathCharacters : ""));
foreach (char symbol in System.Text.Encoding.UTF8.GetBytes(data))
{
if (unreservedChars.IndexOf(symbol) != -1)
{
encoded.Append(symbol);
}
else
{
encoded.Append("%").Append(string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)symbol));
}
}
return encoded.ToString();
}
public static void Sleep(TimeSpan ts)
{
Sleep((int)ts.TotalMilliseconds);
}
/// <summary>
/// Convert bytes to a hex string
/// </summary>
/// <param name="value">Bytes to convert.</param>
/// <returns>Hexadecimal string representing the byte array.</returns>
public static string BytesToHexString(byte[] value)
{
string hex = BitConverter.ToString(value);
hex = hex.Replace("-", string.Empty);
return hex;
}
/// <summary>
/// Convert a hex string to bytes
/// </summary>
/// <param name="hex">Hexadecimal string</param>
/// <returns>Byte array corresponding to the hex string.</returns>
public static byte[] HexStringToBytes(string hex)
{
if (string.IsNullOrEmpty(hex) || hex.Length % 2 == 1)
throw new ArgumentOutOfRangeException("hex");
int count = 0;
byte[] buffer = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
{
string sub = hex.Substring(i, 2);
byte b = Convert.ToByte(sub, 16);
buffer[count] = b;
count++;
}
return buffer;
}
/// <summary>
/// Returns DateTime.UtcNow + ClockOffset when
/// <seealso cref="AWSConfigs.CorrectForClockSkew"/> is true.
/// This value should be used when constructing requests, as it
/// will represent accurate time w.r.t. AWS servers.
/// </summary>
public static DateTime CorrectedUtcNow
{
get
{
var now = DateTime.UtcNow;
if (AWSConfigs.CorrectForClockSkew)
now += AWSConfigs.ClockOffset;
return now;
}
}
#endregion
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;
namespace Avro
{
public class CodeGen
{
/// <summary>
/// Object that contains all the generated types
/// </summary>
public CodeCompileUnit CompileUnit { get; private set; }
/// <summary>
/// List of schemas to generate code for
/// </summary>
public IList<Schema> Schemas { get; private set; }
/// <summary>
/// List of protocols to generate code for
/// </summary>
public IList<Protocol> Protocols { get; private set; }
/// <summary>
/// List of generated namespaces
/// </summary>
protected Dictionary<string, CodeNamespace> namespaceLookup = new Dictionary<string, CodeNamespace>(StringComparer.Ordinal);
/// <summary>
/// Default constructor
/// </summary>
public CodeGen()
{
this.Schemas = new List<Schema>();
this.Protocols = new List<Protocol>();
}
/// <summary>
/// Adds a protocol object to generate code for
/// </summary>
/// <param name="protocol">protocol object</param>
public virtual void AddProtocol(Protocol protocol)
{
Protocols.Add(protocol);
}
/// <summary>
/// Adds a schema object to generate code for
/// </summary>
/// <param name="schema">schema object</param>
public virtual void AddSchema(Schema schema)
{
Schemas.Add(schema);
}
/// <summary>
/// Adds a namespace object for the given name into the dictionary if it doesn't exist yet
/// </summary>
/// <param name="name">name of namespace</param>
/// <returns></returns>
protected virtual CodeNamespace addNamespace(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name", "name cannot be null.");
CodeNamespace ns = null;
if (!namespaceLookup.TryGetValue(name, out ns))
{
ns = new CodeNamespace(CodeGenUtil.Instance.Mangle(name));
foreach (CodeNamespaceImport nci in CodeGenUtil.Instance.NamespaceImports)
ns.Imports.Add(nci);
CompileUnit.Namespaces.Add(ns);
namespaceLookup.Add(name, ns);
}
return ns;
}
/// <summary>
/// Generates code for the given protocol and schema objects
/// </summary>
/// <returns>CodeCompileUnit object</returns>
public virtual CodeCompileUnit GenerateCode()
{
CompileUnit = new CodeCompileUnit();
processSchemas();
processProtocols();
return CompileUnit;
}
/// <summary>
/// Generates code for the schema objects
/// </summary>
protected virtual void processSchemas()
{
foreach (Schema schema in this.Schemas)
{
SchemaNames names = generateNames(schema);
foreach (KeyValuePair<SchemaName, NamedSchema> sn in names)
{
switch (sn.Value.Tag)
{
case Schema.Type.Enumeration: processEnum(sn.Value); break;
case Schema.Type.Fixed: processFixed(sn.Value); break;
case Schema.Type.Record: processRecord(sn.Value); break;
case Schema.Type.Error: processRecord(sn.Value); break;
default:
throw new CodeGenException("Names in schema should only be of type NamedSchema, type found " + sn.Value.Tag);
}
}
}
}
/// <summary>
/// Generates code for the protocol objects
/// </summary>
protected virtual void processProtocols()
{
foreach (Protocol protocol in Protocols)
{
SchemaNames names = generateNames(protocol);
foreach (KeyValuePair<SchemaName, NamedSchema> sn in names)
{
switch (sn.Value.Tag)
{
case Schema.Type.Enumeration: processEnum(sn.Value); break;
case Schema.Type.Fixed: processFixed(sn.Value); break;
case Schema.Type.Record: processRecord(sn.Value); break;
case Schema.Type.Error: processRecord(sn.Value); break;
default:
throw new CodeGenException("Names in protocol should only be of type NamedSchema, type found " + sn.Value.Tag);
}
}
processInterface(protocol);
}
}
/// <summary>
/// Generate list of named schemas from given protocol
/// </summary>
/// <param name="protocol">protocol to process</param>
/// <returns></returns>
protected virtual SchemaNames generateNames(Protocol protocol)
{
var names = new SchemaNames();
foreach (Schema schema in protocol.Types)
addName(schema, names);
return names;
}
/// <summary>
/// Generate list of named schemas from given schema
/// </summary>
/// <param name="schema">schema to process</param>
/// <returns></returns>
protected virtual SchemaNames generateNames(Schema schema)
{
var names = new SchemaNames();
addName(schema, names);
return names;
}
/// <summary>
/// Recursively search the given schema for named schemas and adds them to the given container
/// </summary>
/// <param name="schema">schema object to search</param>
/// <param name="names">list of named schemas</param>
protected virtual void addName(Schema schema, SchemaNames names)
{
NamedSchema ns = schema as NamedSchema;
if (null != ns) if (names.Contains(ns.SchemaName)) return;
switch (schema.Tag)
{
case Schema.Type.Null:
case Schema.Type.Boolean:
case Schema.Type.Int:
case Schema.Type.Long:
case Schema.Type.Float:
case Schema.Type.Double:
case Schema.Type.Bytes:
case Schema.Type.String:
break;
case Schema.Type.Enumeration:
case Schema.Type.Fixed:
names.Add(ns);
break;
case Schema.Type.Record:
case Schema.Type.Error:
var rs = schema as RecordSchema;
names.Add(rs);
foreach (Field field in rs.Fields)
addName(field.Schema, names);
break;
case Schema.Type.Array:
var asc = schema as ArraySchema;
addName(asc.ItemSchema, names);
break;
case Schema.Type.Map:
var ms = schema as MapSchema;
addName(ms.ValueSchema, names);
break;
case Schema.Type.Union:
var us = schema as UnionSchema;
foreach (Schema usc in us.Schemas)
addName(usc, names);
break;
default:
throw new CodeGenException("Unable to add name for " + schema.Name + " type " + schema.Tag);
}
}
/// <summary>
/// Creates a class declaration for fixed schema
/// </summary>
/// <param name="schema">fixed schema</param>
/// <param name="ns">namespace object</param>
protected virtual void processFixed(Schema schema)
{
FixedSchema fixedSchema = schema as FixedSchema;
if (null == fixedSchema) throw new CodeGenException("Unable to cast schema into a fixed");
CodeTypeDeclaration ctd = new CodeTypeDeclaration();
ctd.Name = CodeGenUtil.Instance.Mangle(fixedSchema.Name);
ctd.IsClass = true;
ctd.IsPartial = true;
ctd.Attributes = MemberAttributes.Public;
ctd.BaseTypes.Add("SpecificFixed");
// create static schema field
createSchemaField(schema, ctd, true);
// Add Size field
string sizefname = "fixedSize";
var ctrfield = new CodeTypeReference(typeof(uint));
var codeField = new CodeMemberField(ctrfield, sizefname);
codeField.Attributes = MemberAttributes.Private | MemberAttributes.Static;
codeField.InitExpression = new CodePrimitiveExpression(fixedSchema.Size);
ctd.Members.Add(codeField);
// Add Size property
var property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public | MemberAttributes.Static;
property.Name = "FixedSize";
property.Type = ctrfield;
property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeReferenceExpression(schema.Name + "." + sizefname)));
ctd.Members.Add(property);
// create constructor to initiate base class SpecificFixed
CodeConstructor cc = new CodeConstructor();
cc.Attributes = MemberAttributes.Public;
cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(sizefname));
ctd.Members.Add(cc);
string nspace = fixedSchema.Namespace;
if (string.IsNullOrEmpty(nspace))
throw new CodeGenException("Namespace required for enum schema " + fixedSchema.Name);
CodeNamespace codens = addNamespace(nspace);
codens.Types.Add(ctd);
}
/// <summary>
/// Creates an enum declaration
/// </summary>
/// <param name="schema">enum schema</param>
/// <param name="ns">namespace</param>
protected virtual void processEnum(Schema schema)
{
EnumSchema enumschema = schema as EnumSchema;
if (null == enumschema) throw new CodeGenException("Unable to cast schema into an enum");
CodeTypeDeclaration ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(enumschema.Name));
ctd.IsEnum = true;
ctd.Attributes = MemberAttributes.Public;
foreach (string symbol in enumschema.Symbols)
{
if (CodeGenUtil.Instance.ReservedKeywords.Contains(symbol))
throw new CodeGenException("Enum symbol " + symbol + " is a C# reserved keyword");
CodeMemberField field = new CodeMemberField(typeof(int), symbol);
ctd.Members.Add(field);
}
string nspace = enumschema.Namespace;
if (string.IsNullOrEmpty(nspace))
throw new CodeGenException("Namespace required for enum schema " + enumschema.Name);
CodeNamespace codens = addNamespace(nspace);
codens.Types.Add(ctd);
}
protected virtual void processInterface(Protocol protocol)
{
// Create abstract class
string protocolNameMangled = CodeGenUtil.Instance.Mangle(protocol.Name);
var ctd = new CodeTypeDeclaration(protocolNameMangled);
ctd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public;
ctd.IsClass = true;
ctd.BaseTypes.Add("Avro.Specific.ISpecificProtocol");
AddProtocolDocumentation(protocol, ctd);
// Add static protocol field.
var protocolField = new CodeMemberField();
protocolField.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final;
protocolField.Name = "protocol";
protocolField.Type = new CodeTypeReference("readonly Avro.Protocol");
var cpe = new CodePrimitiveExpression(protocol.ToString());
var cmie = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Protocol)), "Parse"),
new CodeExpression[] { cpe });
protocolField.InitExpression = cmie;
ctd.Members.Add(protocolField);
// Add overridden Protocol method.
var property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
property.Name = "Protocol";
property.Type = new CodeTypeReference("Avro.Protocol");
property.HasGet = true;
property.GetStatements.Add(new CodeTypeReferenceExpression("return protocol"));
ctd.Members.Add(property);
//var requestMethod = CreateRequestMethod();
//ctd.Members.Add(requestMethod);
var requestMethod = CreateRequestMethod();
//requestMethod.Attributes |= MemberAttributes.Override;
var builder = new StringBuilder();
if (protocol.Messages.Count > 0)
{
builder.Append("switch(messageName)\n\t\t\t{");
foreach (var a in protocol.Messages)
{
builder.Append("\n\t\t\t\tcase \"").Append(a.Key).Append("\":\n");
bool unused = false;
string type = getType(a.Value.Response, false, ref unused);
builder.Append("\t\t\t\trequestor.Request<")
.Append(type)
.Append(">(messageName, args, callback);\n");
builder.Append("\t\t\t\tbreak;\n");
}
builder.Append("\t\t\t}");
}
var cseGet = new CodeSnippetExpression(builder.ToString());
requestMethod.Statements.Add(cseGet);
ctd.Members.Add(requestMethod);
AddMethods(protocol, false, ctd);
string nspace = protocol.Namespace;
if (string.IsNullOrEmpty(nspace))
throw new CodeGenException("Namespace required for enum schema " + nspace);
CodeNamespace codens = addNamespace(nspace);
codens.Types.Add(ctd);
// Create callback abstract class
ctd = new CodeTypeDeclaration(protocolNameMangled + "Callback");
ctd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public;
ctd.IsClass = true;
ctd.BaseTypes.Add(protocolNameMangled);
// Need to override
AddProtocolDocumentation(protocol, ctd);
AddMethods(protocol, true, ctd);
codens.Types.Add(ctd);
}
private static CodeMemberMethod CreateRequestMethod()
{
var requestMethod = new CodeMemberMethod();
requestMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
requestMethod.Name = "Request";
requestMethod.ReturnType = new CodeTypeReference(typeof (void));
{
var requestor = new CodeParameterDeclarationExpression(typeof (Avro.Specific.ICallbackRequestor),
"requestor");
requestMethod.Parameters.Add(requestor);
var messageName = new CodeParameterDeclarationExpression(typeof (string), "messageName");
requestMethod.Parameters.Add(messageName);
var args = new CodeParameterDeclarationExpression(typeof (object[]), "args");
requestMethod.Parameters.Add(args);
var callback = new CodeParameterDeclarationExpression(typeof (object), "callback");
requestMethod.Parameters.Add(callback);
}
return requestMethod;
}
private static void AddMethods(Protocol protocol, bool generateCallback, CodeTypeDeclaration ctd)
{
foreach (var e in protocol.Messages)
{
var name = e.Key;
var message = e.Value;
var response = message.Response;
if (generateCallback && message.Oneway.GetValueOrDefault())
continue;
var messageMember = new CodeMemberMethod();
messageMember.Name = CodeGenUtil.Instance.Mangle(name);
messageMember.Attributes = MemberAttributes.Public | MemberAttributes.Abstract;
if (message.Doc!= null && message.Doc.Trim() != string.Empty)
messageMember.Comments.Add(new CodeCommentStatement(message.Doc));
if (message.Oneway.GetValueOrDefault() || generateCallback)
{
messageMember.ReturnType = new CodeTypeReference(typeof (void));
}
else
{
bool ignored = false;
string type = getType(response, false, ref ignored);
messageMember.ReturnType = new CodeTypeReference(type);
}
foreach (Field field in message.Request.Fields)
{
bool ignored = false;
string type = getType(field.Schema, false, ref ignored);
string fieldName = CodeGenUtil.Instance.Mangle(field.Name);
var parameter = new CodeParameterDeclarationExpression(type, fieldName);
messageMember.Parameters.Add(parameter);
}
if (generateCallback)
{
bool unused = false;
var type = getType(response, false, ref unused);
var parameter = new CodeParameterDeclarationExpression("Avro.IO.ICallback<" + type + ">",
"callback");
messageMember.Parameters.Add(parameter);
}
ctd.Members.Add(messageMember);
}
}
private void AddProtocolDocumentation(Protocol protocol, CodeTypeDeclaration ctd)
{
// Add interface documentation
if (protocol.Doc != null && protocol.Doc.Trim() != string.Empty)
{
var interfaceDoc = createDocComment(protocol.Doc);
if (interfaceDoc != null)
ctd.Comments.Add(interfaceDoc);
}
}
/// <summary>
/// Creates a class declaration
/// </summary>
/// <param name="schema">record schema</param>
/// <param name="ns">namespace</param>
/// <returns></returns>
protected virtual CodeTypeDeclaration processRecord(Schema schema)
{
RecordSchema recordSchema = schema as RecordSchema;
if (null == recordSchema) throw new CodeGenException("Unable to cast schema into a record");
bool isError = recordSchema.Tag == Schema.Type.Error;
// declare the class
var ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(recordSchema.Name));
ctd.BaseTypes.Add(isError ? "SpecificException" : "ISpecificRecord");
ctd.Attributes = MemberAttributes.Public;
ctd.IsClass = true;
ctd.IsPartial = true;
createSchemaField(schema, ctd, isError);
// declare Get() to be used by the Writer classes
var cmmGet = new CodeMemberMethod();
cmmGet.Name = "Get";
cmmGet.Attributes = MemberAttributes.Public;
cmmGet.ReturnType = new CodeTypeReference("System.Object");
cmmGet.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos"));
StringBuilder getFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n");
// declare Put() to be used by the Reader classes
var cmmPut = new CodeMemberMethod();
cmmPut.Name = "Put";
cmmPut.Attributes = MemberAttributes.Public;
cmmPut.ReturnType = new CodeTypeReference(typeof(void));
cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos"));
cmmPut.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "fieldValue"));
var putFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n");
if (isError)
{
cmmGet.Attributes |= MemberAttributes.Override;
cmmPut.Attributes |= MemberAttributes.Override;
}
foreach (Field field in recordSchema.Fields)
{
// Determine type of field
bool nullibleEnum = false;
string baseType = getType(field.Schema, false, ref nullibleEnum);
var ctrfield = new CodeTypeReference(baseType);
// Create field
string privFieldName = string.Concat("_", field.Name);
var codeField = new CodeMemberField(ctrfield, privFieldName);
codeField.Attributes = MemberAttributes.Private;
// Process field documentation if it exist and add to the field
CodeCommentStatement propertyComment = null;
if (!string.IsNullOrEmpty(field.Documentation))
{
propertyComment = createDocComment(field.Documentation);
if (null != propertyComment)
codeField.Comments.Add(propertyComment);
}
// Add field to class
ctd.Members.Add(codeField);
// Create reference to the field - this.fieldname
var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), privFieldName);
var mangledName = CodeGenUtil.Instance.Mangle(field.Name);
// Create field property with get and set methods
var property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
property.Name = mangledName;
property.Type = ctrfield;
property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef));
property.SetStatements.Add(new CodeAssignStatement(fieldRef, new CodePropertySetValueReferenceExpression()));
if (null != propertyComment)
property.Comments.Add(propertyComment);
// Add field property to class
ctd.Members.Add(property);
// add to Get()
getFieldStmt.Append("\t\t\tcase ");
getFieldStmt.Append(field.Pos);
getFieldStmt.Append(": return this.");
getFieldStmt.Append(mangledName);
getFieldStmt.Append(";\n");
// add to Put()
putFieldStmt.Append("\t\t\tcase ");
putFieldStmt.Append(field.Pos);
putFieldStmt.Append(": this.");
putFieldStmt.Append(mangledName);
if (nullibleEnum)
{
putFieldStmt.Append(" = fieldValue == null ? (");
putFieldStmt.Append(baseType);
putFieldStmt.Append(")null : (");
string type = baseType.Remove(0, 16); // remove System.Nullable<
type = type.Remove(type.Length - 1); // remove >
putFieldStmt.Append(type);
putFieldStmt.Append(")fieldValue; break;\n");
}
else
{
putFieldStmt.Append(" = (");
putFieldStmt.Append(baseType);
putFieldStmt.Append(")fieldValue; break;\n");
}
}
// end switch block for Get()
getFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Get()\");\n\t\t\t}");
var cseGet = new CodeSnippetExpression(getFieldStmt.ToString());
cmmGet.Statements.Add(cseGet);
ctd.Members.Add(cmmGet);
// end switch block for Put()
putFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Put()\");\n\t\t\t}");
var csePut = new CodeSnippetExpression(putFieldStmt.ToString());
cmmPut.Statements.Add(csePut);
ctd.Members.Add(cmmPut);
string nspace = recordSchema.Namespace;
if (string.IsNullOrEmpty(nspace))
throw new CodeGenException("Namespace required for record schema " + recordSchema.Name);
CodeNamespace codens = addNamespace(nspace);
codens.Types.Add(ctd);
return ctd;
}
/// <summary>
/// Gets the string representation of the schema's data type
/// </summary>
/// <param name="schema">schema</param>
/// <param name="nullible">flag to indicate union with null</param>
/// <returns></returns>
internal static string getType(Schema schema, bool nullible, ref bool nullibleEnum)
{
switch (schema.Tag)
{
case Schema.Type.Null:
return "System.Object";
case Schema.Type.Boolean:
if (nullible) return "System.Nullable<bool>";
else return typeof(bool).ToString();
case Schema.Type.Int:
if (nullible) return "System.Nullable<int>";
else return typeof(int).ToString();
case Schema.Type.Long:
if (nullible) return "System.Nullable<long>";
else return typeof(long).ToString();
case Schema.Type.Float:
if (nullible) return "System.Nullable<float>";
else return typeof(float).ToString();
case Schema.Type.Double:
if (nullible) return "System.Nullable<double>";
else return typeof(double).ToString();
case Schema.Type.Bytes:
return typeof(byte[]).ToString();
case Schema.Type.String:
return typeof(string).ToString();
case Schema.Type.Enumeration:
var namedSchema = schema as NamedSchema;
if (null == namedSchema)
throw new CodeGenException("Unable to cast schema into a named schema");
if (nullible)
{
nullibleEnum = true;
return "System.Nullable<" + CodeGenUtil.Instance.Mangle(namedSchema.Fullname) + ">";
}
else return CodeGenUtil.Instance.Mangle(namedSchema.Fullname);
case Schema.Type.Fixed:
case Schema.Type.Record:
case Schema.Type.Error:
namedSchema = schema as NamedSchema;
if (null == namedSchema)
throw new CodeGenException("Unable to cast schema into a named schema");
return CodeGenUtil.Instance.Mangle(namedSchema.Fullname);
case Schema.Type.Array:
var arraySchema = schema as ArraySchema;
if (null == arraySchema)
throw new CodeGenException("Unable to cast schema into an array schema");
return "IList<" + getType(arraySchema.ItemSchema, false, ref nullibleEnum) + ">";
case Schema.Type.Map:
var mapSchema = schema as MapSchema;
if (null == mapSchema)
throw new CodeGenException("Unable to cast schema into a map schema");
return "IDictionary<string," + getType(mapSchema.ValueSchema, false, ref nullibleEnum) + ">";
case Schema.Type.Union:
var unionSchema = schema as UnionSchema;
if (null == unionSchema)
throw new CodeGenException("Unable to cast schema into a union schema");
Schema nullibleType = getNullableType(unionSchema);
if (null == nullibleType)
return CodeGenUtil.Object;
else
return getType(nullibleType, true, ref nullibleEnum);
}
throw new CodeGenException("Unable to generate CodeTypeReference for " + schema.Name + " type " + schema.Tag);
}
/// <summary>
/// Gets the schema of a union with null
/// </summary>
/// <param name="schema">union schema</param>
/// <returns>schema that is nullible</returns>
public static Schema getNullableType(UnionSchema schema)
{
Schema ret = null;
if (schema.Count == 2)
{
bool nullable = false;
foreach (Schema childSchema in schema.Schemas)
{
if (childSchema.Tag == Schema.Type.Null)
nullable = true;
else
ret = childSchema;
}
if (!nullable)
ret = null;
}
return ret;
}
/// <summary>
/// Creates the static schema field for class types
/// </summary>
/// <param name="schema">schema</param>
/// <param name="ctd">CodeTypeDeclaration for the class</param>
protected virtual void createSchemaField(Schema schema, CodeTypeDeclaration ctd, bool overrideFlag)
{
// create schema field
var ctrfield = new CodeTypeReference("Schema");
string schemaFname = "_SCHEMA";
var codeField = new CodeMemberField(ctrfield, schemaFname);
codeField.Attributes = MemberAttributes.Public | MemberAttributes.Static;
// create function call Schema.Parse(json)
var cpe = new CodePrimitiveExpression(schema.ToString());
var cmie = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Schema)), "Parse"),
new CodeExpression[] { cpe });
codeField.InitExpression = cmie;
ctd.Members.Add(codeField);
// create property to get static schema field
var property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public;
if (overrideFlag) property.Attributes |= MemberAttributes.Override;
property.Name = "Schema";
property.Type = ctrfield;
property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeReferenceExpression(ctd.Name + "." + schemaFname)));
ctd.Members.Add(property);
}
/// <summary>
/// Creates an XML documentation for the given comment
/// </summary>
/// <param name="comment">comment</param>
/// <returns>CodeCommentStatement object</returns>
protected virtual CodeCommentStatement createDocComment(string comment)
{
string text = string.Format("<summary>\r\n {0}\r\n </summary>", comment);
return new CodeCommentStatement(text, true);
}
/// <summary>
/// Writes the generated compile unit into one file
/// </summary>
/// <param name="outputFile">name of output file to write to</param>
public virtual void WriteCompileUnit(string outputFile)
{
var cscp = new CSharpCodeProvider();
var opts = new CodeGeneratorOptions();
opts.BracingStyle = "C";
opts.IndentString = "\t";
opts.BlankLinesBetweenMembers = false;
using (var outfile = new StreamWriter(outputFile))
{
cscp.GenerateCodeFromCompileUnit(CompileUnit, outfile, opts);
}
}
/// <summary>
/// Writes each types in each namespaces into individual files
/// </summary>
/// <param name="outputdir">name of directory to write to</param>
public virtual void WriteTypes(string outputdir)
{
var cscp = new CSharpCodeProvider();
var opts = new CodeGeneratorOptions();
opts.BracingStyle = "C";
opts.IndentString = "\t";
opts.BlankLinesBetweenMembers = false;
CodeNamespaceCollection nsc = CompileUnit.Namespaces;
for (int i = 0; i < nsc.Count; i++)
{
var ns = nsc[i];
string dir = outputdir + "\\" + CodeGenUtil.Instance.UnMangle(ns.Name).Replace('.', '\\');
Directory.CreateDirectory(dir);
var new_ns = new CodeNamespace(ns.Name);
new_ns.Comments.Add(CodeGenUtil.Instance.FileComment);
foreach (CodeNamespaceImport nci in CodeGenUtil.Instance.NamespaceImports)
new_ns.Imports.Add(nci);
var types = ns.Types;
for (int j = 0; j < types.Count; j++)
{
var ctd = types[j];
string file = dir + "\\" + CodeGenUtil.Instance.UnMangle(ctd.Name) + ".cs";
using (var writer = new StreamWriter(file, false))
{
new_ns.Types.Add(ctd);
cscp.GenerateCodeFromNamespace(new_ns, writer, opts);
new_ns.Types.Remove(ctd);
}
}
}
}
}
}
| |
using NUnit.Framework;
using Lucene.Net.Attributes;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Codecs.PerField
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Analyzer = Lucene.Net.Analysis.Analyzer;
using BaseDocValuesFormatTestCase = Lucene.Net.Index.BaseDocValuesFormatTestCase;
using BinaryDocValues = Lucene.Net.Index.BinaryDocValues;
using BinaryDocValuesField = BinaryDocValuesField;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using Field = Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig;
using Lucene46Codec = Lucene.Net.Codecs.Lucene46.Lucene46Codec;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using NumericDocValues = Lucene.Net.Index.NumericDocValues;
using NumericDocValuesField = NumericDocValuesField;
using Query = Lucene.Net.Search.Query;
using RandomCodec = Lucene.Net.Index.RandomCodec;
using Term = Lucene.Net.Index.Term;
using TermQuery = Lucene.Net.Search.TermQuery;
using TestUtil = Lucene.Net.Util.TestUtil;
using TopDocs = Lucene.Net.Search.TopDocs;
/// <summary>
/// Basic tests of PerFieldDocValuesFormat
/// </summary>
[TestFixture]
public class TestPerFieldDocValuesFormat : BaseDocValuesFormatTestCase
{
private Codec Codec_Renamed;
[SetUp]
public override void SetUp()
{
Codec_Renamed = new RandomCodec(new Random(Random().Next()), new HashSet<string>());
base.SetUp();
}
protected override Codec Codec
{
get
{
return Codec_Renamed;
}
}
protected internal override bool CodecAcceptsHugeBinaryValues(string field)
{
return TestUtil.FieldSupportsHugeBinaryDocValues(field);
}
// just a simple trivial test
// TODO: we should come up with a test that somehow checks that segment suffix
// is respected by all codec apis (not just docvalues and postings)
[Test]
public virtual void TestTwoFieldsTwoFormats()
{
Analyzer analyzer = new MockAnalyzer(Random());
Directory directory = NewDirectory();
// we don't use RandomIndexWriter because it might add more docvalues than we expect !!!!1
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
DocValuesFormat fast = DocValuesFormat.ForName("Lucene45");
DocValuesFormat slow = DocValuesFormat.ForName("SimpleText");
iwc.SetCodec(new Lucene46CodecAnonymousInnerClassHelper(this, fast, slow));
IndexWriter iwriter = new IndexWriter(directory, iwc);
Document doc = new Document();
string longTerm = "longtermlongtermlongtermlongtermlongtermlongtermlongtermlongtermlongtermlongtermlongtermlongtermlongtermlongtermlongtermlongtermlongtermlongterm";
string text = "this is the text to be indexed. " + longTerm;
doc.Add(NewTextField("fieldname", text, Field.Store.YES));
doc.Add(new NumericDocValuesField("dv1", 5));
doc.Add(new BinaryDocValuesField("dv2", new BytesRef("hello world")));
iwriter.AddDocument(doc);
iwriter.Dispose();
// Now search the index:
IndexReader ireader = DirectoryReader.Open(directory); // read-only=true
IndexSearcher isearcher = NewSearcher(ireader);
Assert.AreEqual(1, isearcher.Search(new TermQuery(new Term("fieldname", longTerm)), 1).TotalHits);
Query query = new TermQuery(new Term("fieldname", "text"));
TopDocs hits = isearcher.Search(query, null, 1);
Assert.AreEqual(1, hits.TotalHits);
BytesRef scratch = new BytesRef();
// Iterate through the results:
for (int i = 0; i < hits.ScoreDocs.Length; i++)
{
Document hitDoc = isearcher.Doc(hits.ScoreDocs[i].Doc);
Assert.AreEqual(text, hitDoc.Get("fieldname"));
Debug.Assert(ireader.Leaves.Count == 1);
NumericDocValues dv = ((AtomicReader)ireader.Leaves[0].Reader).GetNumericDocValues("dv1");
Assert.AreEqual(5, dv.Get(hits.ScoreDocs[i].Doc));
BinaryDocValues dv2 = ((AtomicReader)ireader.Leaves[0].Reader).GetBinaryDocValues("dv2");
dv2.Get(hits.ScoreDocs[i].Doc, scratch);
Assert.AreEqual(new BytesRef("hello world"), scratch);
}
ireader.Dispose();
directory.Dispose();
}
private class Lucene46CodecAnonymousInnerClassHelper : Lucene46Codec
{
private readonly TestPerFieldDocValuesFormat OuterInstance;
private DocValuesFormat Fast;
private DocValuesFormat Slow;
public Lucene46CodecAnonymousInnerClassHelper(TestPerFieldDocValuesFormat outerInstance, DocValuesFormat fast, DocValuesFormat slow)
{
this.OuterInstance = outerInstance;
this.Fast = fast;
this.Slow = slow;
}
public override DocValuesFormat GetDocValuesFormatForField(string field)
{
if ("dv1".Equals(field))
{
return Fast;
}
else
{
return Slow;
}
}
}
#region BaseDocValuesFormatTestCase
// LUCENENET NOTE: Tests in an abstract base class are not pulled into the correct
// context in Visual Studio. This fixes that with the minimum amount of code necessary
// to run them in the correct context without duplicating all of the tests.
[Test]
public override void TestOneNumber()
{
base.TestOneNumber();
}
[Test]
public override void TestOneFloat()
{
base.TestOneFloat();
}
[Test]
public override void TestTwoNumbers()
{
base.TestTwoNumbers();
}
[Test]
public override void TestTwoBinaryValues()
{
base.TestTwoBinaryValues();
}
[Test]
public override void TestTwoFieldsMixed()
{
base.TestTwoFieldsMixed();
}
[Test]
public override void TestThreeFieldsMixed()
{
base.TestThreeFieldsMixed();
}
[Test]
public override void TestThreeFieldsMixed2()
{
base.TestThreeFieldsMixed2();
}
[Test]
public override void TestTwoDocumentsNumeric()
{
base.TestTwoDocumentsNumeric();
}
[Test]
public override void TestTwoDocumentsMerged()
{
base.TestTwoDocumentsMerged();
}
[Test]
public override void TestBigNumericRange()
{
base.TestBigNumericRange();
}
[Test]
public override void TestBigNumericRange2()
{
base.TestBigNumericRange2();
}
[Test]
public override void TestBytes()
{
base.TestBytes();
}
[Test]
public override void TestBytesTwoDocumentsMerged()
{
base.TestBytesTwoDocumentsMerged();
}
[Test]
public override void TestSortedBytes()
{
base.TestSortedBytes();
}
[Test]
public override void TestSortedBytesTwoDocuments()
{
base.TestSortedBytesTwoDocuments();
}
[Test]
public override void TestSortedBytesThreeDocuments()
{
base.TestSortedBytesThreeDocuments();
}
[Test]
public override void TestSortedBytesTwoDocumentsMerged()
{
base.TestSortedBytesTwoDocumentsMerged();
}
[Test]
public override void TestSortedMergeAwayAllValues()
{
base.TestSortedMergeAwayAllValues();
}
[Test]
public override void TestBytesWithNewline()
{
base.TestBytesWithNewline();
}
[Test]
public override void TestMissingSortedBytes()
{
base.TestMissingSortedBytes();
}
[Test]
public override void TestSortedTermsEnum()
{
base.TestSortedTermsEnum();
}
[Test]
public override void TestEmptySortedBytes()
{
base.TestEmptySortedBytes();
}
[Test]
public override void TestEmptyBytes()
{
base.TestEmptyBytes();
}
[Test]
public override void TestVeryLargeButLegalBytes()
{
base.TestVeryLargeButLegalBytes();
}
[Test]
public override void TestVeryLargeButLegalSortedBytes()
{
base.TestVeryLargeButLegalSortedBytes();
}
[Test]
public override void TestCodecUsesOwnBytes()
{
base.TestCodecUsesOwnBytes();
}
[Test]
public override void TestCodecUsesOwnSortedBytes()
{
base.TestCodecUsesOwnSortedBytes();
}
[Test]
public override void TestCodecUsesOwnBytesEachTime()
{
base.TestCodecUsesOwnBytesEachTime();
}
[Test]
public override void TestCodecUsesOwnSortedBytesEachTime()
{
base.TestCodecUsesOwnSortedBytesEachTime();
}
/*
* Simple test case to show how to use the API
*/
[Test]
public override void TestDocValuesSimple()
{
base.TestDocValuesSimple();
}
[Test]
public override void TestRandomSortedBytes()
{
base.TestRandomSortedBytes();
}
[Test]
public override void TestBooleanNumericsVsStoredFields()
{
base.TestBooleanNumericsVsStoredFields();
}
[Test]
public override void TestByteNumericsVsStoredFields()
{
base.TestByteNumericsVsStoredFields();
}
[Test]
public override void TestByteMissingVsFieldCache()
{
base.TestByteMissingVsFieldCache();
}
[Test]
public override void TestShortNumericsVsStoredFields()
{
base.TestShortNumericsVsStoredFields();
}
[Test]
public override void TestShortMissingVsFieldCache()
{
base.TestShortMissingVsFieldCache();
}
[Test]
public override void TestIntNumericsVsStoredFields()
{
base.TestIntNumericsVsStoredFields();
}
[Test]
public override void TestIntMissingVsFieldCache()
{
base.TestIntMissingVsFieldCache();
}
[Test]
public override void TestLongNumericsVsStoredFields()
{
base.TestLongNumericsVsStoredFields();
}
[Test]
public override void TestLongMissingVsFieldCache()
{
base.TestLongMissingVsFieldCache();
}
[Test]
public override void TestBinaryFixedLengthVsStoredFields()
{
base.TestBinaryFixedLengthVsStoredFields();
}
[Test]
public override void TestBinaryVariableLengthVsStoredFields()
{
base.TestBinaryVariableLengthVsStoredFields();
}
[Test]
public override void TestSortedFixedLengthVsStoredFields()
{
base.TestSortedFixedLengthVsStoredFields();
}
[Test]
public override void TestSortedFixedLengthVsFieldCache()
{
base.TestSortedFixedLengthVsFieldCache();
}
[Test]
public override void TestSortedVariableLengthVsFieldCache()
{
base.TestSortedVariableLengthVsFieldCache();
}
[Test]
public override void TestSortedVariableLengthVsStoredFields()
{
base.TestSortedVariableLengthVsStoredFields();
}
[Test]
public override void TestSortedSetOneValue()
{
base.TestSortedSetOneValue();
}
[Test]
public override void TestSortedSetTwoFields()
{
base.TestSortedSetTwoFields();
}
[Test]
public override void TestSortedSetTwoDocumentsMerged()
{
base.TestSortedSetTwoDocumentsMerged();
}
[Test]
public override void TestSortedSetTwoValues()
{
base.TestSortedSetTwoValues();
}
[Test]
public override void TestSortedSetTwoValuesUnordered()
{
base.TestSortedSetTwoValuesUnordered();
}
[Test]
public override void TestSortedSetThreeValuesTwoDocs()
{
base.TestSortedSetThreeValuesTwoDocs();
}
[Test]
public override void TestSortedSetTwoDocumentsLastMissing()
{
base.TestSortedSetTwoDocumentsLastMissing();
}
[Test]
public override void TestSortedSetTwoDocumentsLastMissingMerge()
{
base.TestSortedSetTwoDocumentsLastMissingMerge();
}
[Test]
public override void TestSortedSetTwoDocumentsFirstMissing()
{
base.TestSortedSetTwoDocumentsFirstMissing();
}
[Test]
public override void TestSortedSetTwoDocumentsFirstMissingMerge()
{
base.TestSortedSetTwoDocumentsFirstMissingMerge();
}
[Test]
public override void TestSortedSetMergeAwayAllValues()
{
base.TestSortedSetMergeAwayAllValues();
}
[Test]
public override void TestSortedSetTermsEnum()
{
base.TestSortedSetTermsEnum();
}
[Test]
public override void TestSortedSetFixedLengthVsStoredFields()
{
base.TestSortedSetFixedLengthVsStoredFields();
}
[Test]
public override void TestSortedSetVariableLengthVsStoredFields()
{
base.TestSortedSetVariableLengthVsStoredFields();
}
[Test]
public override void TestSortedSetFixedLengthSingleValuedVsStoredFields()
{
base.TestSortedSetFixedLengthSingleValuedVsStoredFields();
}
[Test]
public override void TestSortedSetVariableLengthSingleValuedVsStoredFields()
{
base.TestSortedSetVariableLengthSingleValuedVsStoredFields();
}
[Test]
public override void TestSortedSetFixedLengthVsUninvertedField()
{
base.TestSortedSetFixedLengthVsUninvertedField();
}
[Test, LongRunningTest]
public override void TestSortedSetVariableLengthVsUninvertedField()
{
base.TestSortedSetVariableLengthVsUninvertedField();
}
[Test]
public override void TestGCDCompression()
{
base.TestGCDCompression();
}
[Test]
public override void TestZeros()
{
base.TestZeros();
}
[Test]
public override void TestZeroOrMin()
{
base.TestZeroOrMin();
}
[Test]
public override void TestTwoNumbersOneMissing()
{
base.TestTwoNumbersOneMissing();
}
[Test]
public override void TestTwoNumbersOneMissingWithMerging()
{
base.TestTwoNumbersOneMissingWithMerging();
}
[Test]
public override void TestThreeNumbersOneMissingWithMerging()
{
base.TestThreeNumbersOneMissingWithMerging();
}
[Test]
public override void TestTwoBytesOneMissing()
{
base.TestTwoBytesOneMissing();
}
[Test]
public override void TestTwoBytesOneMissingWithMerging()
{
base.TestTwoBytesOneMissingWithMerging();
}
[Test]
public override void TestThreeBytesOneMissingWithMerging()
{
base.TestThreeBytesOneMissingWithMerging();
}
// LUCENE-4853
[Test]
public override void TestHugeBinaryValues()
{
base.TestHugeBinaryValues();
}
// TODO: get this out of here and into the deprecated codecs (4.0, 4.2)
[Test]
public override void TestHugeBinaryValueLimit()
{
base.TestHugeBinaryValueLimit();
}
/// <summary>
/// Tests dv against stored fields with threads (binary/numeric/sorted, no missing)
/// </summary>
[Test]
public override void TestThreads()
{
base.TestThreads();
}
/// <summary>
/// Tests dv against stored fields with threads (all types + missing)
/// </summary>
[Test]
public override void TestThreads2()
{
base.TestThreads2();
}
// LUCENE-5218
[Test]
public override void TestEmptyBinaryValueOnPageSizes()
{
base.TestEmptyBinaryValueOnPageSizes();
}
#endregion
#region BaseIndexFileFormatTestCase
// LUCENENET NOTE: Tests in an abstract base class are not pulled into the correct
// context in Visual Studio. This fixes that with the minimum amount of code necessary
// to run them in the correct context without duplicating all of the tests.
[Test]
public override void TestMergeStability()
{
base.TestMergeStability();
}
#endregion
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Security.Cryptography;
using Security.Cryptography.X509Certificates;
namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
/// <summary>
/// Class to provide methods to manage the certificates.
/// </summary>
public static class CertUtils
{
/// <summary>
/// default issuer name
/// </summary>
private const string DefaultIssuer = "CN=Windows Azure Tools";
/// <summary>
/// default password.
/// </summary>
private const string DefaultPassword = "";
/// <summary>
/// Key size
/// </summary>
private const int KeySize2048 = 2048;
/// <summary>
/// Enhancement provider
/// </summary>
private const string MsEnhancedProv = "Microsoft Enhanced Cryptographic Provider v1.0";
/// <summary>
/// Client Authentication Friendly name
/// </summary>
private const string OIDClientAuthFriendlyName = "Client Authentication";
/// <summary>
/// Client Authentication Value
/// </summary>
private const string OIDClientAuthValue = "1.3.6.1.5.5.7.3.2";
/// <summary>
/// Method to generate a self signed certificate
/// </summary>
/// <param name="validForHours">number of hours for which the certificate is valid.</param>
/// <param name="subscriptionId">subscriptionId in question</param>
/// <param name="certificateNamePrefix">prefix for the certificate name</param>
/// <param name="issuer">issuer for the certificate</param>
/// <param name="password">certificate password</param>
/// <returns>certificate as an object</returns>
public static X509Certificate2 CreateSelfSignedCertificate(
int validForHours,
string subscriptionId,
string certificateNamePrefix,
string issuer = DefaultIssuer,
string password = DefaultPassword)
{
var friendlyName = GenerateCertFriendlyName(
subscriptionId,
certificateNamePrefix);
var startTime = DateTime.UtcNow.AddMinutes(-10);
var endTime = DateTime.UtcNow.AddHours(validForHours);
var key = Create2048RsaKey();
var creationParams =
new X509CertificateCreationParameters(new X500DistinguishedName(issuer))
{
TakeOwnershipOfKey = true,
StartTime = startTime,
EndTime = endTime
};
//// adding client authentication, -eku = 1.3.6.1.5.5.7.3.2,
//// This is mandatory for the upload to be successful
var oidCollection = new OidCollection();
oidCollection.Add(
new Oid(
OIDClientAuthValue,
OIDClientAuthFriendlyName));
creationParams.Extensions.Add(
new X509EnhancedKeyUsageExtension(
oidCollection,
false));
// Documentation of CreateSelfSignedCertificate states:
// If creationParameters have TakeOwnershipOfKey set to true, the certificate
// generated will own the key and the input CngKey will be disposed to ensure
// that the caller doesn't accidentally use it beyond its lifetime (which is
// now controlled by the certificate object).
// We don't dispose it ourselves in this case.
var cert = key.CreateSelfSignedCertificate(creationParams);
key = null;
cert.FriendlyName = friendlyName;
// X509 certificate needs PersistKeySet flag set.
// Reload a new X509Certificate2 instance from exported bytes in order to set the PersistKeySet flag.
var bytes = cert.Export(
X509ContentType.Pfx,
password);
// PfxValidation is not done here because these are newly created certs and assumed valid.
return NewX509Certificate2(
bytes,
password,
X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable,
false);
}
/// <summary>
/// Method to get the Certificate's base 64 encoded string
/// </summary>
/// <param name="certFileName">Certificate File Name</param>
/// <returns>Base 64 encoded string of the certificate</returns>
public static string GetCertInBase64EncodedForm(
string certFileName)
{
FileStream fileStream = null;
byte[] data = null;
string certInBase64EncodedForm = null;
try
{
fileStream = new FileStream(
certFileName,
FileMode.Open,
FileAccess.Read);
// If the file size is more than 1MB, fail the call - this is just to avoid Dos Attacks
if (fileStream.Length > 1048576)
{
throw new Exception(
"The Certficate size exceeds 1MB. Please provide a file whose size is utmost 1 MB");
}
var size = (int)fileStream.Length;
data = new byte[size];
size = fileStream.Read(
data,
0,
size);
// Check if the file is a valid certificate before sending it to service
var x509 = new X509Certificate2();
x509.Import(data);
if (string.IsNullOrEmpty(x509.Thumbprint))
{
throw new Exception("The thumbprint of Certificate is null or empty");
}
certInBase64EncodedForm = Convert.ToBase64String(data);
}
catch (Exception e)
{
certInBase64EncodedForm = null;
throw new ArgumentException(
e.Message,
certFileName,
e);
}
finally
{
if (null != fileStream)
{
fileStream.Close();
}
}
return certInBase64EncodedForm;
}
/// <summary>
/// Provides a similar API call to new X509Certificate(byte[],string,X509KeyStorageFlags)
/// </summary>
/// <param name="rawData">The bytes that represent the certificate</param>
/// <param name="password">The certificate private password</param>
/// <param name="keyStorageFlags">The certificate loading options</param>
/// <param name="shouldValidatePfx">
/// Flag to indicate if file should validated. Set to true if the
/// rawData is retrieved from an untrusted source.
/// </param>
/// <returns>An instance of the X509Certificate</returns>
public static X509Certificate2 NewX509Certificate2(
byte[] rawData,
string password,
X509KeyStorageFlags keyStorageFlags,
bool shouldValidatePfx)
{
var temporaryFileName = Path.GetTempFileName();
try
{
var contentType = X509Certificate2.GetCertContentType(rawData);
File.WriteAllBytes(
temporaryFileName,
rawData);
return new X509Certificate2(
temporaryFileName,
password,
keyStorageFlags);
}
finally
{
try
{
File.Delete(temporaryFileName);
}
catch (Exception)
{
// Not deleting the file is fine
}
}
}
/// <summary>
/// Windows Azure Service Management API requires 2048bit RSA keys.
/// The private key needs to be exportable so we can save it for sharing with team members.
/// </summary>
/// <returns>A 2048 bit RSA key</returns>
private static CngKey Create2048RsaKey()
{
var keyCreationParameters = new CngKeyCreationParameters
{
ExportPolicy = CngExportPolicies.AllowExport,
KeyCreationOptions = CngKeyCreationOptions.None,
KeyUsage = CngKeyUsages.AllUsages,
Provider = new CngProvider(MsEnhancedProv)
};
keyCreationParameters.Parameters.Add(
new CngProperty(
"Length",
BitConverter.GetBytes(KeySize2048),
CngPropertyOptions.None));
return CngKey.Create(
CngAlgorithm2.Rsa,
null,
keyCreationParameters);
}
/// <summary>
/// Generates friendly name
/// </summary>
/// <param name="subscriptionId">subscription id</param>
/// <param name="prefix">prefix, likely resource name</param>
/// <returns>friendly name</returns>
private static string GenerateCertFriendlyName(
string subscriptionId,
string prefix = "")
{
return string.Format(
"{0}{1}-{2}-vaultcredentials",
prefix,
subscriptionId,
DateTime.Now.ToString("M-d-yyyy"));
}
}
}
| |
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 StacksOfWax.SimpleApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.events
{
public class Event : global::haxe.lang.HxObject
{
public Event(global::haxe.lang.EmptyObject empty)
{
unchecked
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
{
}
}
#line default
}
public Event(global::Array args, object target, global::pony.events.Event parent)
{
unchecked
{
#line 47 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
global::pony.events.Event.__hx_ctor_pony_events_Event(this, args, target, parent);
}
#line default
}
public static void __hx_ctor_pony_events_Event(global::pony.events.Event __temp_me111, global::Array args, object target, global::pony.events.Event parent)
{
unchecked
{
#line 48 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
__temp_me111.target = target;
if (( args == default(global::Array) ))
{
#line 49 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
__temp_me111.args = new global::Array<object>(new object[]{});
}
else
{
#line 49 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
__temp_me111.args = args;
}
__temp_me111.parent = parent;
__temp_me111._stopPropagation = false;
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return new global::pony.events.Event(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return new global::pony.events.Event(((global::Array) (arr[0]) ), ((object) (arr[1]) ), ((global::pony.events.Event) (arr[2]) ));
}
#line default
}
public global::pony.events.Event parent;
public global::Array args;
public global::pony.events.Event prev;
public bool _stopPropagation;
public global::pony.events.Signal signal;
public object target;
public object currentListener;
public void _setListener(object l)
{
unchecked
{
#line 54 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this.currentListener = l;
}
#line default
}
public void stopPropagation()
{
unchecked
{
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
if (( this.parent != default(global::pony.events.Event) ))
{
#line 57 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this.parent.stopPropagation();
}
this._stopPropagation = true;
}
#line default
}
public int _get_count()
{
unchecked
{
#line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return ((int) (global::haxe.lang.Runtime.getField_f(this.currentListener, "count", 1248019663, true)) );
}
#line default
}
public int _set_count(int v)
{
unchecked
{
#line 63 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return ((int) (global::haxe.lang.Runtime.setField_f(this.currentListener, "count", 1248019663, ((double) (v) ))) );
}
#line default
}
public global::pony.events.Event _get_prev()
{
unchecked
{
#line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return ((global::pony.events.Event) (global::haxe.lang.Runtime.getField(this.currentListener, "prev", 1247723251, true)) );
}
#line default
}
public override double __hx_setField_f(string field, int hash, double @value, bool handleProperties)
{
unchecked
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
switch (hash)
{
case 209959373:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this.currentListener = ((object) (@value) );
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return @value;
}
case 116192081:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this.target = ((object) (@value) );
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return @value;
}
case 1248019663:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this._set_count(((int) (@value) ));
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return @value;
}
default:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return base.__hx_setField_f(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
switch (hash)
{
case 209959373:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this.currentListener = ((object) (@value) );
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return @value;
}
case 116192081:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this.target = ((object) (@value) );
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return @value;
}
case 881208936:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this.signal = ((global::pony.events.Signal) (@value) );
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return @value;
}
case 189842539:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this._stopPropagation = ((bool) (@value) );
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return @value;
}
case 1247723251:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this.prev = ((global::pony.events.Event) (@value) );
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return @value;
}
case 1248019663:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this._set_count(((int) (global::haxe.lang.Runtime.toInt(@value)) ));
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return @value;
}
case 1081380189:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this.args = ((global::Array) (@value) );
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return @value;
}
case 1836975402:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this.parent = ((global::pony.events.Event) (@value) );
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return @value;
}
default:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
switch (hash)
{
case 1243183740:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("get_prev"), ((int) (1243183740) ))) );
}
case 1901956402:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("set_count"), ((int) (1901956402) ))) );
}
case 235708710:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("get_count"), ((int) (235708710) ))) );
}
case 544309738:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("stopPropagation"), ((int) (544309738) ))) );
}
case 1318877239:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("_setListener"), ((int) (1318877239) ))) );
}
case 209959373:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return this.currentListener;
}
case 116192081:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return this.target;
}
case 881208936:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return this.signal;
}
case 189842539:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return this._stopPropagation;
}
case 1247723251:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
if (handleProperties)
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return this._get_prev();
}
else
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return this.prev;
}
}
case 1248019663:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return this._get_count();
}
case 1081380189:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return this.args;
}
case 1836975402:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return this.parent;
}
default:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties)
{
unchecked
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
switch (hash)
{
case 209959373:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.currentListener)) );
}
case 116192081:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return ((double) (global::haxe.lang.Runtime.toDouble(this.target)) );
}
case 1248019663:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return ((double) (this._get_count()) );
}
default:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return base.__hx_getField_f(field, hash, throwErrors, handleProperties);
}
}
}
#line default
}
public override object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
switch (hash)
{
case 1243183740:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return this._get_prev();
}
case 1901956402:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return this._set_count(((int) (global::haxe.lang.Runtime.toInt(dynargs[0])) ));
}
case 235708710:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return this._get_count();
}
case 544309738:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this.stopPropagation();
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
break;
}
case 1318877239:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
this._setListener(dynargs[0]);
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
break;
}
default:
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return base.__hx_invokeField(field, hash, dynargs);
}
}
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
return default(object);
}
#line default
}
public override void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
baseArr.push("currentListener");
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
baseArr.push("target");
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
baseArr.push("signal");
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
baseArr.push("_stopPropagation");
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
baseArr.push("prev");
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
baseArr.push("count");
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
baseArr.push("args");
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
baseArr.push("parent");
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
{
#line 35 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Event.hx"
base.__hx_getFields(baseArr);
}
}
#line default
}
public int count
{
get { return _get_count(); }
set { _set_count(value); }
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// please define BEHAVIAC_NOT_USE_UNITY in your project file if you are not using unity
#if !BEHAVIAC_NOT_USE_UNITY
// if you have compiling errors complaining the following using 'UnityEngine',
//usually, you need to define BEHAVIAC_NOT_USE_UNITY in your project file
using UnityEngine;
#endif//!BEHAVIAC_NOT_USE_UNITY
using System.Collections.Generic;
namespace behaviac
{
/**
Return values of tick/update and valid states for behaviors.
*/
[behaviac.TypeMetaInfo()]
public enum EBTStatus
{
BT_INVALID,
BT_SUCCESS,
BT_FAILURE,
BT_RUNNING,
}
/**
trigger mode to control the bt switching and back
*/
public enum TriggerMode
{
TM_Transfer,
TM_Return
}
///return false to stop traversing
public delegate bool NodeHandler_t(BehaviorTask task, Agent agent, object user_data);
/**
Base class for the BehaviorTreeTask's runtime execution management.
*/
public abstract class BehaviorTask
{
public static void DestroyTask(BehaviorTask task)
{
}
public virtual void Init(BehaviorNode node)
{
Debug.Check(node != null);
this.m_node = node;
this.m_id = this.m_node.GetId();
}
public virtual void Clear()
{
this.m_status = EBTStatus.BT_INVALID;
this.m_parent = null;
this.m_id = -1;
}
public virtual void copyto(BehaviorTask target)
{
target.m_status = this.m_status;
}
public virtual void save(ISerializableNode node)
{
//CSerializationID classId = new CSerializationID("class");
//node.setAttr(classId, this.GetClassNameString());
//CSerializationID idId = new CSerializationID("id");
//node.setAttr(idId, this.GetId());
//CSerializationID statusId = new CSerializationID("status");
//node.setAttr(statusId, this.m_status);
}
public virtual void load(ISerializableNode node)
{
}
public string GetClassNameString()
{
if (this.m_node != null)
{
return this.m_node.GetClassNameString();
}
string subBT = "SubBT";
return subBT;
}
public int GetId()
{
return this.m_id;
}
public virtual int GetNextStateId()
{
return -1;
}
public virtual BehaviorTask GetCurrentTask()
{
return null;
}
#if !BEHAVIAC_RELEASE
struct AutoProfileBlockSend
{
string classId_;
Agent agent_;
float time_;
public AutoProfileBlockSend(string taskClassid, Agent agent)
{
this.classId_ = taskClassid;
this.agent_ = agent;
#if !BEHAVIAC_NOT_USE_UNITY
this.time_ = UnityEngine.Time.realtimeSinceStartup;
#else
this.time_ = System.DateTime.Now.Millisecond;
#endif
}
public void Close()
{
#if !BEHAVIAC_NOT_USE_UNITY
float endTime = UnityEngine.Time.realtimeSinceStartup;
#else
float endTime = System.DateTime.Now.Millisecond;
#endif
//micro second
long duration = (long)(float)((endTime - this.time_) * 1000000.0f);
LogManager.Instance.Log(this.agent_, this.classId_, duration);
}
}
#endif
public EBTStatus exec(Agent pAgent)
{
EBTStatus childStatus = EBTStatus.BT_RUNNING;
return this.exec(pAgent, childStatus);
}
public EBTStatus exec(Agent pAgent, EBTStatus childStatus)
{
#if !BEHAVIAC_RELEASE
Debug.Check(this.m_node == null || this.m_node.IsValid(pAgent, this),
string.Format("Agent In BT:{0} while the Agent used for: {1}", this.m_node.GetAgentType(), pAgent.GetClassTypeName()));
string classStr = (this.m_node != null ? this.m_node.GetClassNameString() : "BT");
int nodeId = (this.m_node != null ? this.m_node.GetId() : -1);
string taskClassid = string.Format("{0}[{1}]", classStr, nodeId);
AutoProfileBlockSend profiler_block = new AutoProfileBlockSend(taskClassid, pAgent);
#endif//#if !BEHAVIAC_RELEASE
bool bEnterResult = false;
if (this.m_status == EBTStatus.BT_RUNNING)
{
bEnterResult = true;
}
else
{
//reset it to invalid when it was success/failure
this.m_status = EBTStatus.BT_INVALID;
bEnterResult = this.onenter_action(pAgent);
}
if (bEnterResult)
{
#if !BEHAVIAC_RELEASE
if (Config.IsLoggingOrSocketing)
{
string btStr = BehaviorTask.GetTickInfo(pAgent, this, "update");
//empty btStr is for internal BehaviorTreeTask
if (!string.IsNullOrEmpty(btStr))
{
LogManager.Instance.Log(pAgent, btStr, EActionResult.EAR_none, LogMode.ELM_tick);
}
}
#endif
bool bValid = this.CheckParentUpdatePreconditions(pAgent);
if (bValid)
{
this.m_status = this.update_current(pAgent, childStatus);
}
else
{
this.m_status = EBTStatus.BT_FAILURE;
if (this.GetCurrentTask() != null)
{
this.update_current(pAgent, EBTStatus.BT_FAILURE);
}
}
if (this.m_status != EBTStatus.BT_RUNNING)
{
//clear it
this.onexit_action(pAgent, this.m_status);
//this node is possibly ticked by its parent or by the topBranch who records it as currrent node
//so, we can't here reset the topBranch's current node
}
else
{
BranchTask tree = this.GetTopManageBranchTask();
if (tree != null)
{
tree.SetCurrentTask(this);
}
}
}
else
{
this.m_status = EBTStatus.BT_FAILURE;
}
#if !BEHAVIAC_RELEASE
profiler_block.Close();
#endif
return this.m_status;
}
private const int kMaxParentsCount = 512;
private static BehaviorTask[] ms_parents = new BehaviorTask[kMaxParentsCount];
private bool CheckParentUpdatePreconditions(Agent pAgent)
{
bool bValid = true;
if (this.m_bHasManagingParent)
{
bool bHasManagingParent = false;
int parentsCount = 0;
BranchTask parentBranch = this.GetParent();
ms_parents[parentsCount++] = this;
//back track the parents until the managing branch
while (parentBranch != null)
{
Debug.Check(parentsCount < kMaxParentsCount, "weird tree!");
ms_parents[parentsCount++] = parentBranch;
if (parentBranch.GetCurrentTask() == this)
{
//Debug.Check(parentBranch->GetNode()->IsManagingChildrenAsSubTrees());
bHasManagingParent = true;
break;
}
parentBranch = parentBranch.GetParent();
}
if (bHasManagingParent)
{
for (int i = parentsCount - 1; i >= 0; --i)
{
BehaviorTask pb = ms_parents[i];
bValid = pb.CheckPreconditions(pAgent, true);
if (!bValid)
{
break;
}
}
}
}
else
{
bValid = this.CheckPreconditions(pAgent, true);
}
return bValid;
}
private BranchTask GetTopManageBranchTask()
{
BranchTask tree = null;
BehaviorTask task = this.m_parent;
while (task != null)
{
if (task is BehaviorTreeTask)
{
//to overwrite the child branch
tree = (BranchTask)task;
break;
}
else if (task.m_node.IsManagingChildrenAsSubTrees())
{
//until it is Parallel/SelectorLoop, it's child is used as tree to store current task
break;
}
else if (task is BranchTask)
{
//this if must be after BehaviorTreeTask and IsManagingChildrenAsSubTrees
tree = (BranchTask)task;
}
else
{
Debug.Check(false);
}
task = task.m_parent;
}
return tree;
}
private static bool getRunningNodes_handler(BehaviorTask node, Agent pAgent, object user_data)
{
if (node.m_status == EBTStatus.BT_RUNNING)
{
((List<BehaviorTask>)user_data).Add(node);
}
return true;
}
private static bool abort_handler(BehaviorTask node, Agent pAgent, object user_data)
{
if (node.m_status == EBTStatus.BT_RUNNING)
{
node.onexit_action(pAgent, EBTStatus.BT_FAILURE);
node.m_status = EBTStatus.BT_FAILURE;
node.SetCurrentTask(null);
}
return true;
}
private static bool reset_handler(BehaviorTask node, Agent pAgent, object user_data)
{
node.m_status = EBTStatus.BT_INVALID;
node.onreset(pAgent);
node.SetCurrentTask(null);
return true;
}
private static NodeHandler_t getRunningNodes_handler_ = getRunningNodes_handler;
private static NodeHandler_t abort_handler_ = abort_handler;
private static NodeHandler_t reset_handler_ = reset_handler;
public List<BehaviorTask> GetRunningNodes(bool onlyLeaves = true)
{
List<BehaviorTask> nodes = new List<BehaviorTask>();
this.traverse(true, getRunningNodes_handler_, null, nodes);
if (onlyLeaves && nodes.Count > 0)
{
List<BehaviorTask> leaves = new List<BehaviorTask>();
for (int i = 0; i < nodes.Count; ++i)
{
if (nodes[i] is LeafTask)
{
leaves.Add(nodes[i]);
}
}
return leaves;
}
return nodes;
}
public void abort(Agent pAgent)
{
this.traverse(true, abort_handler_, pAgent, null);
}
///reset the status to invalid
public void reset(Agent pAgent)
{
//BEHAVIAC_PROFILE("BehaviorTask.reset");
this.traverse(true, reset_handler_, pAgent, null);
}
public EBTStatus GetStatus()
{
return this.m_status;
}
public void SetStatus(EBTStatus s)
{
this.m_status = s;
}
public BehaviorNode GetNode()
{
return this.m_node;
}
public void SetParent(BranchTask parent)
{
this.m_parent = parent;
}
public BranchTask GetParent()
{
return this.m_parent;
}
public abstract void traverse(bool childFirst, NodeHandler_t handler, Agent pAgent, object user_data);
/**
return false if the event handling needs to be stopped
an event can be configured to stop being checked if triggered
*/
public bool CheckEvents(string eventName, Agent pAgent, Dictionary<uint, IInstantiatedVariable> eventParams)
{
return this.m_node.CheckEvents(eventName, pAgent, eventParams);
}
public virtual void onreset(Agent pAgent)
{
}
/**
return false if the event handling needs to be stopped
return true, the event hanlding will be checked furtherly
*/
public virtual bool onevent(Agent pAgent, string eventName, Dictionary<uint, IInstantiatedVariable> eventParams)
{
if (this.m_status == EBTStatus.BT_RUNNING && this.m_node.HasEvents())
{
if (!this.CheckEvents(eventName, pAgent, eventParams))
{
return false;
}
}
return true;
}
protected BehaviorTask()
{
m_status = EBTStatus.BT_INVALID;
m_node = null;
m_parent = null;
m_bHasManagingParent = false;
}
protected virtual EBTStatus update_current(Agent pAgent, EBTStatus childStatus)
{
EBTStatus s = this.update(pAgent, childStatus);
return s;
}
protected virtual EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
return EBTStatus.BT_SUCCESS;
}
protected virtual bool onenter(Agent pAgent)
{
return true;
}
protected virtual void onexit(Agent pAgent, EBTStatus status)
{
}
public static string GetTickInfo(Agent pAgent, BehaviorTask bt, string action)
{
string result = GetTickInfo(pAgent, bt.GetNode(), action);
return result;
}
public static string GetTickInfo(Agent pAgent, BehaviorNode n, string action)
{
#if !BEHAVIAC_RELEASE
if (Config.IsLoggingOrSocketing)
{
if (!System.Object.ReferenceEquals(pAgent, null) && pAgent.IsMasked())
{
//BEHAVIAC_PROFILE("GetTickInfo", true);
string bClassName = n.GetClassNameString();
//filter out intermediate bt, whose class name is empty
if (!string.IsNullOrEmpty(bClassName))
{
string btName = GetParentTreeName(pAgent, n);
string bpstr = "";
if (!string.IsNullOrEmpty(btName))
{
bpstr = string.Format("{0}.xml->", btName);
}
int nodeId = n.GetId();
bpstr += string.Format("{0}[{1}]", bClassName, nodeId);
if (!string.IsNullOrEmpty(action))
{
bpstr += string.Format(":{0}", action);
}
return bpstr;
}
}
}
#endif
return string.Empty;
}
public static string GetParentTreeName(Agent pAgent, BehaviorNode n)
{
string btName = null;
if (n is ReferencedBehavior)
{
n = n.Parent;
}
bool bIsTree = false;
bool bIsRefTree = false;
while (n != null)
{
bIsTree = (n is BehaviorTree);
bIsRefTree = (n is ReferencedBehavior);
if (bIsTree || bIsRefTree)
{
break;
}
n = n.Parent;
}
if (bIsTree)
{
BehaviorTree bt = n as BehaviorTree;
btName = bt.GetName();
}
else if (bIsRefTree)
{
ReferencedBehavior refTree = n as ReferencedBehavior;
btName = refTree.GetReferencedTree(pAgent);
}
else
{
Debug.Check(false);
}
return btName;
}
private static string GetActionResultStr(EActionResult actionResult)
{
#if !BEHAVIAC_RELEASE
if (Config.IsLoggingOrSocketing)
{
string actionResultStr = "";
if (actionResult == EActionResult.EAR_success)
{
actionResultStr = " [success]";
}
else if (actionResult == EActionResult.EAR_failure)
{
actionResultStr = " [failure]";
}
else if (actionResult == EActionResult.EAR_all)
{
actionResultStr = " [all]";
}
else
{
//although actionResult can be EAR_none or EAR_all, but, as this is the real result of an action
//it can only be success or failure
Debug.Check(false);
}
return actionResultStr;
}
#endif
return string.Empty;
}
private static void _MY_BREAKPOINT_BREAK_(Agent pAgent, string btMsg, EActionResult actionResult)
{
#if !BEHAVIAC_RELEASE
if (Config.IsLoggingOrSocketing)
{
string actionResultStr = GetActionResultStr(actionResult);
string msg = string.Format("BehaviorTreeTask Breakpoints at: '{0}{1}'\n\nOk to continue.", btMsg, actionResultStr);
Workspace.Instance.RespondToBreak(msg, "BehaviorTreeTask Breakpoints");
}
#endif
}
//CheckBreakpoint should be after log of onenter/onexit/update, as it needs to flush msg to the client
public static void CHECK_BREAKPOINT(Agent pAgent, BehaviorNode b, string action, EActionResult actionResult)
{
#if !BEHAVIAC_RELEASE
if (Config.IsLoggingOrSocketing)
{
string bpstr = GetTickInfo(pAgent, b, action);
if (!string.IsNullOrEmpty(bpstr))
{
LogManager.Instance.Log(pAgent, bpstr, actionResult, LogMode.ELM_tick);
if (Workspace.Instance.CheckBreakpoint(pAgent, b, action, actionResult))
{
//log the current variables, otherwise, its value is not the latest
pAgent.LogVariables(false);
LogManager.Instance.Log(pAgent, bpstr, actionResult, LogMode.ELM_breaked);
LogManager.Instance.Flush(pAgent);
SocketUtils.Flush();
_MY_BREAKPOINT_BREAK_(pAgent, bpstr, actionResult);
LogManager.Instance.Log(pAgent, bpstr, actionResult, LogMode.ELM_continue);
LogManager.Instance.Flush(pAgent);
SocketUtils.Flush();
}
}
}
#endif
}
protected virtual bool CheckPreconditions(Agent pAgent, bool bIsAlive)
{
bool bResult = true;
if (this.m_node != null)
{
if (this.m_node.PreconditionsCount > 0)
{
bResult = this.m_node.CheckPreconditions(pAgent, bIsAlive);
}
}
return bResult;
}
public bool onenter_action(Agent pAgent)
{
bool bResult = this.CheckPreconditions(pAgent, false);
if (bResult)
{
this.m_bHasManagingParent = false;
this.SetCurrentTask(null);
bResult = this.onenter(pAgent);
if (!bResult)
{
return false;
}
else
{
#if !BEHAVIAC_RELEASE
//BEHAVIAC_PROFILE_DEBUGBLOCK("Debug", true);
BehaviorTask.CHECK_BREAKPOINT(pAgent, this.m_node, "enter", bResult ? EActionResult.EAR_success : EActionResult.EAR_failure);
#endif
}
}
return bResult;
}
public void onexit_action(Agent pAgent, EBTStatus status)
{
this.onexit(pAgent, status);
if (this.m_node != null)
{
Effector.EPhase phase = Effector.EPhase.E_SUCCESS;
if (status == EBTStatus.BT_FAILURE)
{
phase = Effector.EPhase.E_FAILURE;
}
else
{
Debug.Check(status == EBTStatus.BT_SUCCESS);
}
this.m_node.ApplyEffects(pAgent, phase);
}
#if !BEHAVIAC_RELEASE
if (Config.IsLoggingOrSocketing)
{
//BEHAVIAC_PROFILE_DEBUGBLOCK("Debug", true);
if (status == EBTStatus.BT_SUCCESS)
{
BehaviorTask.CHECK_BREAKPOINT(pAgent, this.m_node, "exit", EActionResult.EAR_success);
}
else
{
BehaviorTask.CHECK_BREAKPOINT(pAgent, this.m_node, "exit", EActionResult.EAR_failure);
}
}
#endif
}
public void SetHasManagingParent(bool bHasManagingParent)
{
this.m_bHasManagingParent = bHasManagingParent;
}
public virtual void SetCurrentTask(BehaviorTask task)
{
}
public EBTStatus m_status;
protected BehaviorNode m_node;
protected BranchTask m_parent;
protected int m_id;
protected bool m_bHasManagingParent;
}
// ============================================================================
public class AttachmentTask : BehaviorTask
{
protected AttachmentTask()
{
}
public override void traverse(bool childFirst, NodeHandler_t handler, Agent pAgent, object user_data)
{
handler(this, pAgent, user_data);
}
}
// ============================================================================
public class LeafTask : BehaviorTask
{
public override void traverse(bool childFirst, NodeHandler_t handler, Agent pAgent, object user_data)
{
handler(this, pAgent, user_data);
}
protected LeafTask()
{
}
}
// ============================================================================
public abstract class BranchTask : BehaviorTask
{
protected BranchTask()
{
}
public override void Clear()
{
base.Clear();
this.m_currentTask = null;
}
protected override bool onenter(Agent pAgent)
{
return true;
}
protected override void onexit(Agent pAgent, EBTStatus status)
{
//this.m_currentTask = null;
}
public override void onreset(Agent pAgent)
{
//this.m_currentTask = null;
}
private bool oneventCurrentNode(Agent pAgent, string eventName, Dictionary<uint, IInstantiatedVariable> eventParams)
{
Debug.Check(this.m_currentTask != null);
if (this.m_currentTask != null)
{
EBTStatus s = this.m_currentTask.GetStatus();
Debug.Check(s == EBTStatus.BT_RUNNING && this.m_node.HasEvents());
bool bGoOn = this.m_currentTask.onevent(pAgent, eventName, eventParams);
//give the handling back to parents
if (bGoOn && this.m_currentTask != null)
{
BranchTask parentBranch = this.m_currentTask.GetParent();
//back track the parents until the branch
while (parentBranch != null && parentBranch != this)
{
Debug.Check(parentBranch.GetStatus() == EBTStatus.BT_RUNNING);
bGoOn = parentBranch.onevent(pAgent, eventName, eventParams);
if (!bGoOn)
{
return false;
}
parentBranch = parentBranch.GetParent();
}
}
return bGoOn;
}
return false;
}
// return false if the event handling needs to be stopped return true, the event hanlding
// will be checked furtherly
public override bool onevent(Agent pAgent, string eventName, Dictionary<uint, IInstantiatedVariable> eventParams)
{
if (this.m_node.HasEvents())
{
bool bGoOn = true;
if (this.m_currentTask != null)
{
bGoOn = this.oneventCurrentNode(pAgent, eventName, eventParams);
}
if (bGoOn)
{
bGoOn = base.onevent(pAgent, eventName, eventParams);
}
return bGoOn;
}
return true;
}
private EBTStatus execCurrentTask(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_currentTask != null && this.m_currentTask.GetStatus() == EBTStatus.BT_RUNNING);
//this.m_currentTask could be cleared in ::tick, to remember it
EBTStatus status = this.m_currentTask.exec(pAgent, childStatus);
//give the handling back to parents
if (status != EBTStatus.BT_RUNNING)
{
Debug.Check(status == EBTStatus.BT_SUCCESS || status == EBTStatus.BT_FAILURE);
Debug.Check(this.m_currentTask.m_status == status);
BranchTask parentBranch = this.m_currentTask.GetParent();
this.m_currentTask = null;
//back track the parents until the branch
while (parentBranch != null)
{
if (parentBranch == this)
{
status = parentBranch.update(pAgent, status);
}
else
{
status = parentBranch.exec(pAgent, status);
}
if (status == EBTStatus.BT_RUNNING)
{
return EBTStatus.BT_RUNNING;
}
Debug.Check(parentBranch == this || parentBranch.m_status == status);
if (parentBranch == this)
{
break;
}
parentBranch = parentBranch.GetParent();
}
}
return status;
}
protected override EBTStatus update_current(Agent pAgent, EBTStatus childStatus)
{
EBTStatus status = EBTStatus.BT_INVALID;
if (this.m_currentTask != null)
{
status = this.execCurrentTask(pAgent, childStatus);
Debug.Check(status == EBTStatus.BT_RUNNING ||
(status != EBTStatus.BT_RUNNING && this.m_currentTask == null));
}
else
{
status = this.update(pAgent, childStatus);
}
return status;
}
protected EBTStatus resume_branch(Agent pAgent, EBTStatus status)
{
Debug.Check(this.m_currentTask != null);
Debug.Check(status == EBTStatus.BT_SUCCESS || status == EBTStatus.BT_FAILURE);
BranchTask parent = null;
if (this.m_currentTask.GetNode().IsManagingChildrenAsSubTrees())
{
parent = (BranchTask)this.m_currentTask;
}
else
{
parent = this.m_currentTask.GetParent();
}
//clear it as it ends and the next exec might need to set it
this.m_currentTask = null;
if (parent != null)
{
EBTStatus s = parent.exec(pAgent, status);
return s;
}
return EBTStatus.BT_INVALID;
}
protected abstract void addChild(BehaviorTask pBehavior);
//bookmark the current running node, it is different from m_activeChildIndex
private BehaviorTask m_currentTask;
public override BehaviorTask GetCurrentTask()
{
return this.m_currentTask;
}
public override void SetCurrentTask(BehaviorTask task)
{
if (task != null)
{
//if the leaf node is running, then the leaf's parent node is also as running,
//the leaf is set as the tree's current task instead of its parent
if (this.m_currentTask == null)
{
Debug.Check(this.m_currentTask != this);
this.m_currentTask = task;
task.SetHasManagingParent(true);
}
}
else
{
if (this.m_status != EBTStatus.BT_RUNNING)
{
this.m_currentTask = task;
}
}
}
}
// ============================================================================
public class CompositeTask : BranchTask
{
public override void traverse(bool childFirst, NodeHandler_t handler, Agent pAgent, object user_data)
{
if (childFirst)
{
for (int i = 0; i < this.m_children.Count; ++i)
{
BehaviorTask task = this.m_children[i];
task.traverse(childFirst, handler, pAgent, user_data);
}
handler(this, pAgent, user_data);
}
else
{
if (handler(this, pAgent, user_data))
{
for (int i = 0; i < this.m_children.Count; ++i)
{
BehaviorTask task = this.m_children[i];
task.traverse(childFirst, handler, pAgent, user_data);
}
}
}
}
protected CompositeTask()
{
m_activeChildIndex = InvalidChildIndex;
}
//~CompositeTask()
//{
// this.m_children.Clear();
//}
protected bool m_bIgnoreChildren = false;
public override void Init(BehaviorNode node)
{
base.Init(node);
if (!this.m_bIgnoreChildren)
{
Debug.Check(node.GetChildrenCount() > 0);
int childrenCount = node.GetChildrenCount();
for (int i = 0; i < childrenCount; i++)
{
BehaviorNode childNode = node.GetChild(i);
BehaviorTask childTask = childNode.CreateAndInitTask();
this.addChild(childTask);
}
}
}
public override void copyto(BehaviorTask target)
{
base.copyto(target);
Debug.Check(target is CompositeTask);
CompositeTask ttask = target as CompositeTask;
ttask.m_activeChildIndex = this.m_activeChildIndex;
Debug.Check(this.m_children.Count > 0);
Debug.Check(this.m_children.Count == ttask.m_children.Count);
int count = this.m_children.Count;
for (int i = 0; i < count; ++i)
{
BehaviorTask childTask = this.m_children[i];
BehaviorTask childTTask = ttask.m_children[i];
childTask.copyto(childTTask);
}
}
public override void save(ISerializableNode node)
{
base.save(node);
//BehaviorTasks_t.size_type count = this.m_children.Count;
//for (BehaviorTasks_t.size_type i = 0; i < count; ++i)
//{
// BehaviorTask childTask = this.m_children[i];
// CSerializationID nodeId = new CSerializationID("node");
// ISerializableNode chidlNode = node.newChild(nodeId);
// childTask.save(chidlNode);
//}
}
public override void load(ISerializableNode node)
{
base.load(node);
}
protected override void addChild(BehaviorTask pBehavior)
{
pBehavior.SetParent(this);
this.m_children.Add(pBehavior);
}
protected List<BehaviorTask> m_children = new List<BehaviorTask>();
protected BehaviorTask GetChildById(int nodeId)
{
if (this.m_children != null && this.m_children.Count > 0)
{
for (int i = 0; i < this.m_children.Count; ++i)
{
BehaviorTask c = this.m_children[i];
if (c.GetId() == nodeId)
{
return c;
}
}
}
return null;
}
//book mark the current child
protected int m_activeChildIndex = InvalidChildIndex;
protected const int InvalidChildIndex = -1;
}
// ============================================================================
public class SingeChildTask : BranchTask
{
public override void traverse(bool childFirst, NodeHandler_t handler, Agent pAgent, object user_data)
{
if (childFirst)
{
if (this.m_root != null)
{
this.m_root.traverse(childFirst, handler, pAgent, user_data);
}
handler(this, pAgent, user_data);
}
else
{
if (handler(this, pAgent, user_data))
{
if (this.m_root != null)
{
this.m_root.traverse(childFirst, handler, pAgent, user_data);
}
}
}
}
protected SingeChildTask()
{
m_root = null;
}
public override void Init(BehaviorNode node)
{
base.Init(node);
Debug.Check(node.GetChildrenCount() <= 1);
if (node.GetChildrenCount() == 1)
{
BehaviorNode childNode = node.GetChild(0);
Debug.Check(childNode != null);
if (childNode != null)
{
BehaviorTask childTask = childNode.CreateAndInitTask();
this.addChild(childTask);
}
}
else
{
Debug.Check(true);
}
}
public override void copyto(BehaviorTask target)
{
base.copyto(target);
Debug.Check(target is SingeChildTask);
SingeChildTask ttask = target as SingeChildTask;
if (this.m_root != null && ttask != null)
{
//referencebehavior/query, etc.
if (ttask.m_root == null)
{
BehaviorNode pNode = this.m_root.GetNode();
Debug.Check(pNode is BehaviorTree);
if (pNode != null)
{
ttask.m_root = pNode.CreateAndInitTask();
}
//Debug.Check(ttask.m_root is BehaviorTreeTask);
//BehaviorTreeTask btt = ttask.m_root as BehaviorTreeTask;
//btt.ModifyId(ttask);
}
Debug.Check(ttask.m_root != null);
if (ttask.m_root != null)
{
this.m_root.copyto(ttask.m_root);
}
}
}
public override void save(ISerializableNode node)
{
base.save(node);
if (this.m_root != null)
{
//CSerializationID nodeId = new CSerializationID("root");
//ISerializableNode chidlNode = node.newChild(nodeId);
//this.m_root.save(chidlNode);
}
}
public override void load(ISerializableNode node)
{
base.load(node);
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
if (this.m_root != null)
{
EBTStatus s = this.m_root.exec(pAgent, childStatus);
return s;
}
return EBTStatus.BT_FAILURE;
}
protected override void addChild(BehaviorTask pBehavior)
{
pBehavior.SetParent(this);
this.m_root = pBehavior;
}
protected BehaviorTask m_root;
}
// ============================================================================
public abstract class DecoratorTask : SingeChildTask
{
protected DecoratorTask()
{
}
protected override EBTStatus update_current(Agent pAgent, EBTStatus childStatus)
{
return base.update_current(pAgent, childStatus);
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_node is DecoratorNode);
DecoratorNode node = (DecoratorNode)this.m_node;
EBTStatus status = EBTStatus.BT_INVALID;
if (childStatus != EBTStatus.BT_RUNNING)
{
status = childStatus;
if (!node.m_bDecorateWhenChildEnds || status != EBTStatus.BT_RUNNING)
{
EBTStatus result = this.decorate(status);
if (result != EBTStatus.BT_RUNNING)
{
return result;
}
return EBTStatus.BT_RUNNING;
}
}
status = base.update(pAgent, childStatus);
if (!node.m_bDecorateWhenChildEnds || status != EBTStatus.BT_RUNNING)
{
EBTStatus result = this.decorate(status);
return result;
}
return EBTStatus.BT_RUNNING;
}
/*
called when the child's tick returns success or failure.
please note, it is not called if the child's tick returns running
*/
protected abstract EBTStatus decorate(EBTStatus status);
}
// ============================================================================
public class BehaviorTreeTask : SingeChildTask
{
private Dictionary<uint, IInstantiatedVariable> m_localVars = new Dictionary<uint, IInstantiatedVariable>();
public Dictionary<uint, IInstantiatedVariable> LocalVars
{
get
{
return m_localVars;
}
}
internal void SetVariable<VariableType>(string variableName, VariableType value)
{
uint variableId = Utils.MakeVariableId(variableName);
if (this.LocalVars.ContainsKey(variableId))
{
IInstantiatedVariable v = this.LocalVars[variableId];
CVariable<VariableType> var = (CVariable<VariableType>)v;
if (var != null)
{
var.SetValue(null, value);
return;
}
}
Debug.Check(false, string.Format("The variable \"{0}\" with type \"{1}\" can not be found!", variableName, typeof(VariableType).Name));
}
internal void AddVariables(Dictionary<uint, IInstantiatedVariable> vars)
{
if (vars != null)
{
foreach (KeyValuePair<uint, IInstantiatedVariable> pair in vars)
{
this.LocalVars[pair.Key] = pair.Value;
}
}
}
public override void Init(BehaviorNode node)
{
base.Init(node);
if (this.m_node != null)
{
Debug.Check(this.m_node is BehaviorTree);
((BehaviorTree)this.m_node).InstantiatePars(this.LocalVars);
}
}
public override void Clear()
{
this.m_root = null;
if (this.m_node != null)
{
Debug.Check(this.m_node is BehaviorTree);
((BehaviorTree)this.m_node).UnInstantiatePars(this.LocalVars);
}
base.Clear();
}
public void SetRootTask(BehaviorTask pRoot)
{
this.addChild(pRoot);
}
public void CopyTo(BehaviorTreeTask target)
{
this.copyto(target);
}
public void Save(ISerializableNode node)
{
//CSerializationID btId = new CSerializationID("BehaviorTree");
//ISerializableNode btNodeRoot = node.newChild(btId);
//Debug.Check(this.GetNode() is BehaviorTree);
//BehaviorTree bt = (BehaviorTree)this.GetNode();
//CSerializationID sourceId = new CSerializationID("source");
//btNodeRoot.setAttr(sourceId, bt.GetName());
//CSerializationID nodeId = new CSerializationID("node");
//ISerializableNode btNode = btNodeRoot.newChild(nodeId);
//this.save(btNode);
}
public void Load(ISerializableNode node)
{
this.load(node);
}
/**
return the path relative to the workspace path
*/
public string GetName()
{
Debug.Check(this.m_node is BehaviorTree);
BehaviorTree bt = this.m_node as BehaviorTree;
Debug.Check(bt != null);
return bt.GetName();
}
public EBTStatus resume(Agent pAgent, EBTStatus status)
{
EBTStatus s = base.resume_branch(pAgent, status);
return s;
}
protected override bool onenter(Agent pAgent)
{
pAgent.LogJumpTree(this.GetName());
return true;
}
protected override void onexit(Agent pAgent, EBTStatus s)
{
pAgent.ExcutingTreeTask = null;
pAgent.LogReturnTree(this.GetName());
base.onexit(pAgent, s);
}
#region FSM
private List<BehaviorTask> m_states = null;
public BehaviorTask GetChildById(int nodeId)
{
if (this.m_states != null && this.m_states.Count > 0)
{
for (int i = 0; i < this.m_states.Count; ++i)
{
BehaviorTask c = this.m_states[i];
if (c.GetId() == nodeId)
{
return c;
}
}
}
return null;
}
#endregion FSM
protected override EBTStatus update_current(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_node != null);
Debug.Check(this.m_node is BehaviorTree);
pAgent.ExcutingTreeTask = this;
BehaviorTree tree = (BehaviorTree)this.m_node;
EBTStatus status = EBTStatus.BT_RUNNING;
if (tree.IsFSM)
{
status = this.update(pAgent, childStatus);
}
else
{
status = base.update_current(pAgent, childStatus);
}
return status;
}
protected override EBTStatus update(Agent pAgent, EBTStatus childStatus)
{
Debug.Check(this.m_node != null);
Debug.Check(this.m_root != null);
if (childStatus != EBTStatus.BT_RUNNING)
{
return childStatus;
}
EBTStatus status = EBTStatus.BT_INVALID;
status = base.update(pAgent, childStatus);
Debug.Check(status != EBTStatus.BT_INVALID);
return status;
}
}
}
| |
#region Apache License, Version 2.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.
//
#endregion
using System.Collections.Generic;
using System.IO;
using NPanday.ProjectImporter.Parser.VisualStudioProjectTypes;
/// Author: Leopoldo Lee Agdeppa III
namespace NPanday.ProjectImporter.Digest.Model
{
public class ProjectDigest
{
private string assemblyName;
public string AssemblyName
{
get { return assemblyName; }
set { assemblyName = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public string ProjectName
{
get
{
if (name != null)
return name;
else if (assemblyName != null)
return assemblyName;
else
{
FileInfo f = new FileInfo(FullFileName);
return f.Name.Substring(0, f.Name.Length - f.Extension.Length);
}
}
}
private VisualStudioProjectTypeEnum projectType;
public VisualStudioProjectTypeEnum ProjectType
{
get { return projectType; }
set { projectType = value; }
}
private string fullFileName;
public string FullFileName
{
get { return fullFileName; }
set { fullFileName = value; }
}
private string fullDirectoryName;
public string FullDirectoryName
{
get { return fullDirectoryName; }
set { fullDirectoryName = value; }
}
private string language;
public string Language
{
get { return language; }
set { language = value; }
}
private string outputType;
public string OutputType
{
get { return outputType; }
set { outputType = value; }
}
private string roleType;
public string RoleType
{
get { return roleType; }
set { roleType = value; }
}
private bool silverlightApplication;
public bool SilverlightApplication
{
get { return silverlightApplication; }
set { silverlightApplication = value; }
}
private List<SilverlightApplicationReference> silverlightApplicationList;
public List<SilverlightApplicationReference> SilverlightApplicationList
{
get { return silverlightApplicationList; }
set { silverlightApplicationList = value; }
}
private Reference[] references;
public Reference[] References
{
get { return references; }
set { references = value; }
}
private ProjectReference[] projectReferences;
public ProjectReference[] ProjectReferences
{
get { return projectReferences; }
set { projectReferences = value; }
}
private bool unitTest = false;
public bool UnitTest
{
get { return unitTest; }
set { unitTest = value; }
}
public override string ToString()
{
return this.assemblyName;
}
private string rootNamespace;
public string RootNamespace
{
get { return rootNamespace; }
set { rootNamespace = value; }
}
private string startupObject;
public string StartupObject
{
get { return startupObject; }
set { startupObject = value; }
}
private string signAssembly;
public string SignAssembly
{
get { return signAssembly; }
set { signAssembly = value; }
}
private string assemblyOriginatorKeyFile;
public string AssemblyOriginatorKeyFile
{
get { return assemblyOriginatorKeyFile; }
set { assemblyOriginatorKeyFile = value; }
}
private string delaySign;
public string DelaySign
{
get { return delaySign; }
set { delaySign = value; }
}
private string optimize;
public string Optimize
{
get { return optimize; }
set { optimize = value; }
}
private string allowUnsafeBlocks;
public string AllowUnsafeBlocks
{
get { return allowUnsafeBlocks; }
set { allowUnsafeBlocks = value; }
}
private string defineConstants;
public string DefineConstants
{
get { return defineConstants; }
set { defineConstants = value; }
}
private string applicationIcon;
public string ApplicationIcon
{
get { return applicationIcon; }
set { applicationIcon = value; }
}
private string win32Resource;
public string Win32Resource
{
get { return win32Resource; }
set { win32Resource = value; }
}
private string projectGuid;
public string ProjectGuid
{
get { return projectGuid; }
set { projectGuid = value; }
}
private string configuration;
public string Configuration
{
get { return configuration; }
set { configuration = value; }
}
private string baseIntermediateOutputPath;
public string BaseIntermediateOutputPath
{
get { return baseIntermediateOutputPath; }
set { baseIntermediateOutputPath = value; }
}
private string outputPath;
public string OutputPath
{
get { return outputPath; }
set { outputPath = value; }
}
private string treatWarningsAsErrors;
public string TreatWarningsAsErrors
{
get { return treatWarningsAsErrors; }
set { treatWarningsAsErrors = value; }
}
private string platform;
public string Platform
{
get { return platform; }
set { platform = value; }
}
private string productVersion;
public string ProductVersion
{
get { return productVersion; }
set { productVersion = value; }
}
private string schemaVersion;
public string SchemaVersion
{
get { return schemaVersion; }
set { schemaVersion = value; }
}
private string appDesignerFolder;
public string AppDesignerFolder
{
get { return appDesignerFolder; }
set { appDesignerFolder = value; }
}
private string debugSymbols;
public string DebugSymbols
{
get { return debugSymbols; }
set { debugSymbols = value; }
}
private string debugType;
public string DebugType
{
get { return debugType; }
set { debugType = value; }
}
private string errorReport;
public string ErrorReport
{
get { return errorReport; }
set { errorReport = value; }
}
private string warningLevel;
public string WarningLevel
{
get { return warningLevel; }
set { warningLevel = value; }
}
private string documentationFile;
public string DocumentationFile
{
get { return documentationFile; }
set { documentationFile = value; }
}
private string postBuildEvent;
public string PostBuildEvent
{
get { return postBuildEvent; }
set { postBuildEvent = value; }
}
private string publishUrl;
public string PublishUrl
{
get { return publishUrl; }
set { publishUrl = value; }
}
private string install;
public string Install
{
get { return install; }
set { install = value; }
}
private string installFrom;
public string InstallFrom
{
get { return installFrom; }
set { installFrom = value; }
}
private string updateEnabled;
public string UpdateEnabled
{
get { return updateEnabled; }
set { updateEnabled = value; }
}
private string updateMode;
public string UpdateMode
{
get { return updateMode; }
set { updateMode = value; }
}
private string updateInterval;
public string UpdateInterval
{
get { return updateInterval; }
set { updateInterval = value; }
}
private string updateIntervalUnits;
public string UpdateIntervalUnits
{
get { return updateIntervalUnits; }
set { updateIntervalUnits = value; }
}
private string updatePeriodically;
public string UpdatePeriodically
{
get { return updatePeriodically; }
set { updatePeriodically = value; }
}
private string updateRequired;
public string UpdateRequired
{
get { return updateRequired; }
set { updateRequired = value; }
}
private string mapFileExtensions;
public string MapFileExtensions
{
get { return mapFileExtensions; }
set { mapFileExtensions = value; }
}
private string applicationVersion;
public string ApplicationVersion
{
get { return applicationVersion; }
set { applicationVersion = value; }
}
private string isWebBootstrapper;
public string IsWebBootstrapper
{
get { return isWebBootstrapper; }
set { isWebBootstrapper = value; }
}
private string bootstrapperEnabled;
public string BootstrapperEnabled
{
get { return bootstrapperEnabled; }
set { bootstrapperEnabled = value; }
}
private string preBuildEvent;
public string PreBuildEvent
{
get { return preBuildEvent; }
set { preBuildEvent = value; }
}
private string myType;
public string MyType
{
get { return myType; }
set { myType = value; }
}
private string defineDebug;
public string DefineDebug
{
get { return defineDebug; }
set { defineDebug = value; }
}
private string defineTrace;
public string DefineTrace
{
get { return defineTrace; }
set { defineTrace = value; }
}
private string noWarn;
public string NoWarn
{
get { return noWarn; }
set { noWarn = value; }
}
private string warningsAsErrors;
public string WarningsAsErrors
{
get { return warningsAsErrors; }
set { warningsAsErrors = value; }
}
private string baseApplicationManifest;
public string BaseApplicationManifest
{
get { return baseApplicationManifest; }
set { baseApplicationManifest = value; }
}
private string targetFramework;
public string TargetFramework
{
get { return targetFramework; }
set { targetFramework = value; }
}
private string targetFrameworkVersion = "v2.0";
public string TargetFrameworkVersion
{
get { return targetFrameworkVersion; }
set { targetFrameworkVersion = value; }
}
private string targetFrameworkProfile;
public string TargetFrameworkProfile
{
get { return targetFrameworkProfile; }
set { targetFrameworkProfile = value; }
}
private Compile[] compiles;
public Compile[] Compiles
{
get { return compiles; }
set { compiles = value; }
}
private Content[] contents;
public Content[] Contents
{
get { return contents; }
set { contents = value; }
}
private None[] nones;
public None[] Nones
{
get { return nones; }
set { nones = value; }
}
private WebReferenceUrl[] webReferenceUrls;
public WebReferenceUrl[] WebReferenceUrls
{
get { return webReferenceUrls; }
set { webReferenceUrls = value; }
}
private ComReference[] comReferenceList;
public ComReference[] ComReferenceList
{
get { return comReferenceList; }
set { comReferenceList = value; }
}
private WebReferences[] webReferences;
public WebReferences[] WebReferences
{
get { return webReferences; }
set { webReferences = value; }
}
private EmbeddedResource[] embeddedResources;
public EmbeddedResource[] EmbeddedResources
{
get { return embeddedResources; }
set { embeddedResources = value; }
}
private BootstrapperPackage[] bootstrapperPackages;
public BootstrapperPackage[] BootstrapperPackages
{
get { return bootstrapperPackages; }
set { bootstrapperPackages = value; }
}
private Folder[] folders;
public Folder[] Folders
{
get { return folders; }
set { folders = value; }
}
private string[] globalNamespaceImports;
public string[] GlobalNamespaceImports
{
get { return globalNamespaceImports; }
set { globalNamespaceImports = value; }
}
// used by project-importer during auto-import
// for getting sa information from the existing pom.xml
NPanday.Model.Pom.Model existingPom;
public NPanday.Model.Pom.Model ExistingPom
{
get { return existingPom; }
set { existingPom = value; }
}
private bool useMsDeploy;
public bool UseMsDeploy
{
get { return useMsDeploy; }
set { useMsDeploy = value; }
}
private string cloudConfig;
public string CloudConfig
{
get { return cloudConfig; }
set { cloudConfig = value; }
}
private string targetFrameworkIdentifier = ".NETFramework";
public string TargetFrameworkIdentifier
{
get { return targetFrameworkIdentifier; }
set { targetFrameworkIdentifier = value; }
}
private string silverlightVersion;
public string SilverlightVersion
{
get { return silverlightVersion; }
set { silverlightVersion = value; }
}
private DependencySearchConfiguration dependencySearchConfig;
internal DependencySearchConfiguration DependencySearchConfig
{
get { return dependencySearchConfig; }
set { dependencySearchConfig = value; }
}
private bool hostInBrowser;
public bool HostInBrowser
{
get { return hostInBrowser; }
set { hostInBrowser = value; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using Vexe.Editor.GUIs;
using Vexe.Editor.Helpers;
using Vexe.Runtime.Extensions;
#pragma warning disable 0414
namespace Vexe.Editor.Windows
{
public class SelectionWindow : EditorWindow
{
public static float IndentWidth;
public static GUIStyle BackgroundStyle;
public static Color TabColor;
static SelectionWindow()
{
IndentWidth = 15f;
BackgroundStyle = GUIHelper.DarkGreyStyleDuo.SecondStyle;
TabColor = GUIHelper.LightBlueColorDuo.SecondColor;
}
private bool close;
private Vector2 scroll;
private string search;
private Tab[] tabs;
private Action onClose;
private Tab currentTab;
private BaseGUI gui;
private static int lastTabIndex;
private void Initialize(Tab[] tabs, Action onClose)
{
// TODO: Use RabbitGUI when we implement BeginScrollView
gui = new TurtleGUI();
this.onClose = onClose;
this.tabs = tabs;
for (int i = 0; i < tabs.Length; i++)
{
var t = tabs[i];
t.gui = gui;
t.selectionStyle = GUIHelper.SelectionRect;
}
currentTab = lastTabIndex >= tabs.Length ? tabs[0] : tabs[lastTabIndex];
search = string.Empty;
}
public void OnGUI()
{
using (gui.Horizontal(EditorStyles.toolbar))
{
for (int i = 0; i < tabs.Length; i++)
{
var tab = tabs[i];
using (gui.ColorBlock(tab == currentTab ? TabColor : (Color?) null))
{
if (gui.Button(tab.title, EditorStyles.toolbarButton))
{
currentTab = tab;
currentTab.Refresh();
lastTabIndex = i;
}
}
}
gui.FlexibleSpace();
}
gui.Space(3f);
//GUI.SetNextControlName("SearchBox");
search = gui.ToolbarSearch(search);
//if (Event.current != null && Event.current.isKey && Event.current.keyCode == KeyCode.Tab)
//{
// Debug.Log(GUI.GetNameOfFocusedControl());
// GUI.FocusControl("SearchBox");
// Debug.Log(GUI.GetNameOfFocusedControl());
//}
gui.Splitter();
using (gui.ScrollView.Begin(ref scroll, BackgroundStyle))
currentTab.OnGUI(search, maxSize.x - minSize.x);
}
public void OnFocus()
{
if (currentTab != null)
currentTab.Refresh();
}
private void Update()
{
if (close) Close(); // Can't close out immediately in OnLostFocus
}
public static void Show(string title, Action onClose, params Tab[] tabs)
{
GetWindow<SelectionWindow>(true, title).Initialize(tabs, onClose);
}
public static void Show(string title, params Tab[] tabs)
{
Show(title, null, tabs);
}
public static void Show(Action onClose, params Tab[] tabs)
{
Show(string.Empty, onClose, tabs);
}
public static void Show(params Tab[] tabs)
{
Show(string.Empty, null, tabs);
}
public void CleanUp()
{
GUIHelper.DarkGreyStyleDuo.DestroyTextures();
}
private void OnLostFocus()
{
CleanUp();
close = true;
onClose.SafeInvoke();
}
}
public abstract class Tab
{
public string title { set; get; }
public BaseGUI gui { get; set; }
public GUIStyle selectionStyle { get; set; }
public virtual void Refresh()
{
}
public abstract void OnGUI(string search, float width);
}
public class Tab<T> : Tab
{
private readonly Func<T[]> getValues;
private readonly Action<T> setTarget;
private readonly Func<T, string> getValueName;
private readonly Func<T> getCurrent;
private readonly Func<T, StyleDuo> getStyleDuo;
private readonly T defaultValue;
private string previousSearch;
private T[] values;
private List<T> filteredValues;
public Tab(Func<T[]> getValues, Func<T> getCurrent, Action<T> setTarget, Func<T, string> getValueName, Func<T, StyleDuo> getStyleDuo, string title)
{
this.getValues = getValues;
this.setTarget = setTarget;
this.getValueName = getValueName;
this.getCurrent = getCurrent;
this.getStyleDuo = getStyleDuo ?? (x => GUIHelper.DarkGreyStyleDuo);
this.title = title;
defaultValue = (T) typeof(T).GetDefaultValue();
}
public Tab(Func<T[]> getValues, Func<T> getCurrent, Action<T> setTarget, Func<T, string> getValueName, string title)
: this(getValues, getCurrent, setTarget, getValueName, null, title)
{
}
public override void OnGUI(string search, float width)
{
// Default value
{
var isDefault = defaultValue.GenericEquals(getCurrent());
using (gui.ColorBlock(GUIHelper.RedColorDuo.FirstColor))
{
OnValueGUI(defaultValue,
string.Format("Default ({0})", typeof(T).IsClass ? "Null" : defaultValue.ToString()),
width, isDefault,
isDefault ? selectionStyle : getStyleDuo(defaultValue).NextStyle,
isDefault ? EditorStyles.whiteLargeLabel : EditorStyles.whiteLargeLabel);
}
}
if (values == null) Refresh();
if (values == null) return;
if (previousSearch != search)
{
previousSearch = search;
filteredValues = values.Where(x => Regex.IsMatch(getValueName(x), search, RegexOptions.IgnoreCase))
.ToList();
}
for (int i = 0; i < filteredValues.Count; i++)
{
var value = filteredValues[i];
var isSelected = value.GenericEquals(getCurrent());
var nextStyle = getStyleDuo(value).NextStyle;
OnValueGUI(value, getValueName(value), width, isSelected, nextStyle,
isSelected ? EditorStyles.whiteBoldLabel : EditorStyles.whiteLabel);
}
}
private void OnValueGUI(T value, string itemName, float width, bool isSelected, GUIStyle nextStyle, GUIStyle labelStyle)
{
using (gui.Horizontal(isSelected ? selectionStyle : nextStyle))
{
gui.Space(SelectionWindow.IndentWidth);
gui.Label(itemName, labelStyle);
var rect = gui.LastRect;
{
rect.width = width;
if (!isSelected)
{
GUIHelper.AddCursorRect(rect, MouseCursor.Link);
if (GUI.Button(rect, GUIContent.none, GUIStyle.none))
{
setTarget(value);
Refresh();
}
}
}
}
}
public override void Refresh()
{
values = getValues();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GraphDsl.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.Linq;
using Akka.Streams.Implementation;
using Akka.Streams.Implementation.Fusing;
namespace Akka.Streams.Dsl
{
public static partial class GraphDsl
{
public sealed class Builder<T>
{
#region internal API
internal Builder() { }
private IModule _moduleInProgress = EmptyModule.Instance;
internal void AddEdge<T1, T2>(Outlet<T1> from, Inlet<T2> to) where T2 : T1
{
_moduleInProgress = _moduleInProgress.Wire(from, to);
}
/// <summary>
/// INTERNAL API.
/// This is only used by the materialization-importing apply methods of Source,
/// Flow, Sink and Graph.
/// </summary>
internal TShape Add<TShape, TMat, TMat2>(IGraph<TShape, TMat> graph, Func<TMat, TMat2> transform) where TShape : Shape
{
if (StreamLayout.IsDebug)
StreamLayout.Validate(graph.Module);
var copy = graph.Module.CarbonCopy();
_moduleInProgress = _moduleInProgress.Compose<TMat,TMat2,TMat2>(copy.TransformMaterializedValue(transform), Keep.Right);
return (TShape)graph.Shape.CopyFromPorts(copy.Shape.Inlets, copy.Shape.Outlets);
}
/// <summary>
/// INTERNAL API.
/// This is only used by the materialization-importing apply methods of Source,
/// Flow, Sink and Graph.
/// </summary>
internal TShape Add<TShape, TMat1, TMat2, TMat3>(IGraph<TShape> graph, Func<TMat1, TMat2, TMat3> combine) where TShape : Shape
{
if (StreamLayout.IsDebug)
StreamLayout.Validate(graph.Module);
var copy = graph.Module.CarbonCopy();
_moduleInProgress = _moduleInProgress.Compose(copy, combine);
return (TShape)graph.Shape.CopyFromPorts(copy.Shape.Inlets, copy.Shape.Outlets);
}
#endregion
/// <summary>
/// Import a graph into this module, performing a deep copy, discarding its
/// materialized value and returning the copied Ports that are now to be connected.
/// </summary>
public TShape Add<TShape, TMat>(IGraph<TShape, TMat> graph)
where TShape : Shape
{
if (StreamLayout.IsDebug)
StreamLayout.Validate(graph.Module);
var copy = graph.Module.CarbonCopy();
_moduleInProgress = _moduleInProgress.Compose<object, TMat, object>(copy, Keep.Left);
return (TShape)graph.Shape.CopyFromPorts(copy.Shape.Inlets, copy.Shape.Outlets);
}
/// <summary>
/// Returns an <see cref="Outlet{T}"/> that gives access to the materialized value of this graph. Once the graph is materialized
/// this outlet will emit exactly one element which is the materialized value. It is possible to expose this
/// outlet as an externally accessible outlet of a <see cref="Source{TOut,TMat}"/>, <see cref="Sink{TIn,TMat}"/>,
/// <see cref="Flow{TIn,TOut,TMat}"/> or <see cref="BidiFlow{TIn1,TOut1,TIn2,TOut2,TMat}"/>.
///
/// It is possible to call this method multiple times to get multiple <see cref="Outlet{T}"/> instances if necessary. All of
/// the outlets will emit the materialized value.
///
/// Be careful to not to feed the result of this outlet to a stage that produces the materialized value itself (for
/// example to a <see cref="Sink.Aggregate{TIn,TOut}"/> that contributes to the materialized value) since that might lead to an unresolvable
/// dependency cycle.
/// </summary>
public Outlet<T> MaterializedValue
{
get
{
/*
* This brings the graph into a homogenous shape: if only one `add` has
* been performed so far, the moduleInProgress will be a CopiedModule
* that upon the next `composeNoMat` will be wrapped together with the
* MaterializedValueSource into a CompositeModule, leading to its
* relevant computation being an Atomic() for the CopiedModule. This is
* what we must reference, and we can only get this reference if we
* create that computation up-front: just making one up will not work
* because that computation node would not be part of the tree and
* the source would not be triggered.
*/
if (_moduleInProgress is CopiedModule)
_moduleInProgress = CompositeModule.Create((Module) _moduleInProgress, _moduleInProgress.Shape);
var source = new MaterializedValueSource<T>(_moduleInProgress.MaterializedValueComputation);
_moduleInProgress = _moduleInProgress.ComposeNoMaterialized(source.Module);
return source.Outlet;
}
}
public IModule Module => _moduleInProgress;
public ForwardOps<TOut, T> From<TOut>(Outlet<TOut> outlet)
{
return new ForwardOps<TOut, T>(this, outlet);
}
public ForwardOps<TOut, T> From<TOut>(SourceShape<TOut> source)
{
return new ForwardOps<TOut, T>(this, source.Outlet);
}
public ForwardOps<TOut, T> From<TOut>(IGraph<SourceShape<TOut>, T> source)
{
return new ForwardOps<TOut, T>(this, Add(source).Outlet);
}
public ForwardOps<TOut, T> From<TIn, TOut>(FlowShape<TIn, TOut> flow)
{
return new ForwardOps<TOut, T>(this, flow.Outlet);
}
public ForwardOps<TOut, T> From<TIn, TOut>(IGraph<FlowShape<TIn, TOut>, T> flow)
{
return new ForwardOps<TOut, T>(this, Add(flow).Outlet);
}
public ForwardOps<TOut, T> From<TIn, TOut>(UniformFanInShape<TIn, TOut> fanIn)
{
return new ForwardOps<TOut, T>(this, fanIn.Out);
}
public ForwardOps<TOut, T> From<TIn, TOut>(UniformFanOutShape<TIn, TOut> fanOut)
{
return new ForwardOps<TOut, T>(this, FindOut(this, fanOut, 0));
}
public ReverseOps<TIn, T> To<TIn>(Inlet<TIn> inlet)
{
return new ReverseOps<TIn, T>(this, inlet);
}
public ReverseOps<TIn, T> To<TIn>(SinkShape<TIn> sink)
{
return new ReverseOps<TIn, T>(this, sink.Inlet);
}
public ReverseOps<TIn, T> To<TIn, TMat>(IGraph<SinkShape<TIn>, TMat> sink)
{
return new ReverseOps<TIn, T>(this, Add(sink).Inlet);
}
public ReverseOps<TIn, T> To<TIn, TOut, TMat>(IGraph<FlowShape<TIn, TOut>, TMat> flow)
{
return new ReverseOps<TIn, T>(this, Add(flow).Inlet);
}
public ReverseOps<TIn, T> To<TIn, TOut>(FlowShape<TIn, TOut> flow)
{
return new ReverseOps<TIn, T>(this, flow.Inlet);
}
public ReverseOps<TIn, T> To<TIn, TOut>(UniformFanOutShape<TIn, TOut> fanOut)
{
return new ReverseOps<TIn, T>(this, fanOut.In);
}
public ReverseOps<TIn, T> To<TIn, TOut>(UniformFanInShape<TIn, TOut> fanOut)
{
return new ReverseOps<TIn, T>(this, FindIn(this, fanOut, 0));
}
}
public sealed class ForwardOps<TOut, TMat>
{
internal readonly Builder<TMat> Builder;
public ForwardOps(Builder<TMat> builder, Outlet<TOut> outlet)
{
Builder = builder;
Out = outlet;
}
public Outlet<TOut> Out { get; }
}
public sealed class ReverseOps<TIn, TMat>
{
internal readonly Builder<TMat> Builder;
public ReverseOps(Builder<TMat> builder, Inlet<TIn> inlet)
{
Builder = builder;
In = inlet;
}
public Inlet<TIn> In { get; }
}
internal static Outlet<TOut> FindOut<TIn, TOut, T>(Builder<T> builder, UniformFanOutShape<TIn, TOut> junction, int n)
{
var count = junction.Outlets.Count();
while (n < count)
{
var outlet = junction.Out(n);
if (builder.Module.Downstreams.ContainsKey(outlet)) n++;
else return outlet;
}
throw new ArgumentException("No more outlets on junction");
}
internal static Inlet<TIn> FindIn<TIn, TOut, T>(Builder<T> builder, UniformFanInShape<TIn, TOut> junction, int n)
{
var count = junction.Inlets.Count();
while (n < count)
{
var inlet = junction.In(n);
if (builder.Module.Upstreams.ContainsKey(inlet)) n++;
else return inlet;
}
throw new ArgumentException("No more inlets on junction");
}
}
public static class ForwardOps
{
public static GraphDsl.Builder<TMat> To<TIn, TOut, TMat>(this GraphDsl.ForwardOps<TOut, TMat> ops, Inlet<TIn> inlet)
where TIn : TOut
{
ops.Builder.AddEdge(ops.Out, inlet);
return ops.Builder;
}
public static GraphDsl.Builder<TMat> To<TIn, TOut, TMat>(this GraphDsl.ForwardOps<TOut, TMat> ops, SinkShape<TIn> sink)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(ops.Out, sink.Inlet);
return b;
}
public static GraphDsl.Builder<TMat> To<TIn, TOut, TMat>(this GraphDsl.ForwardOps<TOut, TMat> ops, FlowShape<TIn, TOut> flow)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(ops.Out, flow.Inlet);
return b;
}
public static GraphDsl.Builder<TMat> To<TIn, TOut, TMat>(this GraphDsl.ForwardOps<TOut, TMat> ops, IGraph<SinkShape<TIn>, TMat> sink)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(ops.Out, b.Add(sink).Inlet);
return b;
}
public static GraphDsl.Builder<TMat> To<TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps<TOut1, TMat> ops, UniformFanInShape<TIn, TOut2> junction)
where TIn : TOut1
{
var b = ops.Builder;
var inlet = GraphDsl.FindIn(b, junction, 0);
b.AddEdge(ops.Out, inlet);
return b;
}
public static GraphDsl.Builder<TMat> To<TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps<TOut1, TMat> ops, UniformFanOutShape<TIn, TOut2> junction)
where TIn : TOut1
{
var b = ops.Builder;
if (!b.Module.Upstreams.ContainsKey(junction.In))
{
b.AddEdge(ops.Out, junction.In);
return b;
}
throw new ArgumentException("No more inlets free on junction", nameof(junction));
}
private static Outlet<TOut2> Bind<TIn, TOut1, TOut2, TMat>(GraphDsl.ForwardOps<TOut1, TMat> ops, UniformFanOutShape<TIn, TOut2> junction) where TIn : TOut1
{
var b = ops.Builder;
b.AddEdge(ops.Out, junction.In);
return GraphDsl.FindOut(b, junction, 0);
}
public static GraphDsl.ForwardOps<TOut2, TMat> Via<TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps<TOut1, TMat> ops, FlowShape<TIn, TOut2> flow)
where TIn : TOut1
{
var b = ops.Builder;
b.AddEdge(ops.Out, flow.Inlet);
return new GraphDsl.ForwardOps<TOut2, TMat>(b, flow.Outlet);
}
public static GraphDsl.ForwardOps<TOut2, TMat> Via<TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps<TOut1, TMat> ops, IGraph<FlowShape<TIn, TOut2>, NotUsed> flow)
where TIn : TOut1
{
var b = ops.Builder;
var s = b.Add(flow);
b.AddEdge(ops.Out, s.Inlet);
return new GraphDsl.ForwardOps<TOut2, TMat>(b, s.Outlet);
}
public static GraphDsl.ForwardOps<TOut2, TMat> Via<TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps<TOut1, TMat> ops, UniformFanInShape<TIn, TOut2> junction)
where TIn : TOut1
{
var b = To(ops, junction);
return b.From(junction.Out);
}
public static GraphDsl.ForwardOps<TOut2, TMat> Via<TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps<TOut1, TMat> ops, UniformFanOutShape<TIn, TOut2> junction)
where TIn : TOut1
{
var outlet = Bind(ops, junction);
return ops.Builder.From(outlet);
}
}
public static class ReverseOps
{
public static GraphDsl.Builder<TMat> From<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, Outlet<TOut> outlet)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(outlet, ops.In);
return b;
}
public static GraphDsl.Builder<TMat> From<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, SourceShape<TOut> source)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(source.Outlet, ops.In);
return b;
}
public static GraphDsl.Builder<TMat> From<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, IGraph<SourceShape<TOut>, TMat> source)
where TIn : TOut
{
var b = ops.Builder;
var s = b.Add(source);
b.AddEdge(s.Outlet, ops.In);
return b;
}
public static GraphDsl.Builder<TMat> From<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, FlowShape<TIn, TOut> flow)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(flow.Outlet, ops.In);
return b;
}
public static GraphDsl.Builder<TMat> From<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, UniformFanInShape<TIn, TOut> junction)
where TIn : TOut
{
Bind(ops, junction);
return ops.Builder;
}
private static Inlet<TIn> Bind<TIn, TOut, TMat>(GraphDsl.ReverseOps<TIn, TMat> ops, UniformFanInShape<TIn, TOut> junction)
where TIn : TOut
{
var b = ops.Builder;
b.AddEdge(junction.Out, ops.In);
return GraphDsl.FindIn(b, junction, 0);
}
public static GraphDsl.Builder<TMat> From<TIn, TOut1, TOut2, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, UniformFanOutShape<TOut1, TOut2> junction)
where TIn : TOut2
{
var b = ops.Builder;
var count = junction.Outlets.Count();
for (var n = 0; n < count; n++)
{
var outlet = junction.Out(n);
if (!b.Module.Downstreams.ContainsKey(outlet))
{
b.AddEdge(outlet, ops.In);
return b;
}
}
throw new ArgumentException("No more inlets free on junction", nameof(junction));
}
public static GraphDsl.ReverseOps<TOut1, TMat> Via<TIn, TOut1, TOut2, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, FlowShape<TOut1, TOut2> flow)
where TIn : TOut2
{
var b = ops.Builder;
b.AddEdge(flow.Outlet, ops.In);
return new GraphDsl.ReverseOps<TOut1, TMat>(b, flow.Inlet);
}
public static GraphDsl.ReverseOps<TOut1, TMat> Via<TIn, TOut1, TOut2, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, IGraph<FlowShape<TOut1, TOut2>, TMat> flow)
where TIn : TOut2
{
var b = ops.Builder;
var f = b.Add(flow);
b.AddEdge(f.Outlet, ops.In);
return new GraphDsl.ReverseOps<TOut1, TMat>(b, f.Inlet);
}
public static GraphDsl.ReverseOps<TIn, TMat> Via<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, UniformFanInShape<TIn, TOut> junction)
where TIn : TOut
{
var inlet = Bind(ops, junction);
return ops.Builder.To(inlet);
}
public static GraphDsl.ReverseOps<TIn, TMat> Via<TIn, TOut, TMat>(this GraphDsl.ReverseOps<TIn, TMat> ops, UniformFanOutShape<TIn, TOut> junction)
where TIn : TOut
{
var b = From(ops, junction);
return b.To(junction.In);
}
}
}
| |
#region namespaces
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Xml;
using System.Windows.Forms;
using System.Reflection;
using Epi.DataSets;
using Epi.Fields;
using Epi.Windows;
using Epi.Windows.Controls;
using Epi.Windows.Dialogs;
using Epi.Windows.MakeView.Utils;
using Epi.Windows.MakeView.Dialogs;
using Epi.Windows.MakeView.Dialogs.FieldDefinitionDialogs;
#endregion
namespace Epi.Windows.MakeView.Forms
{
partial class MakeViewMainForm
{
#region Designer generated code
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MakeViewMainForm));
this.MainToolStripContainer = new System.Windows.Forms.ToolStripContainer();
this.dockManager1 = new Epi.Windows.Docking.DockManager(this.components);
this.MainMenu = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.NewProjectMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.NewProjectFromTemplateMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.NewProjectFromExcelMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.NewViewMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.NewPageMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.openProjectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.closeProjectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mnuImportTemplate = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItemPrint = new System.Windows.Forms.ToolStripMenuItem();
this.mnuCopyToPhone = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripPublishToWebEnter = new System.Windows.Forms.ToolStripMenuItem();
this.mnuPublishToWeb = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.recentProjectsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.exitMakeViewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.mnuEditCut = new System.Windows.Forms.ToolStripMenuItem();
this.mnuEditCopy = new System.Windows.Forms.ToolStripMenuItem();
this.mnuEditPaste = new System.Windows.Forms.ToolStripMenuItem();
this.deletePageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.renamePageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.statusBarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.vocabularyFieldsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fieldNamesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tabOrderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.epiInfoLogsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.insertToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pageToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.insertPageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addPageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.groupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.forToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.setDefaultFontToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.setDefaultControlFontToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.alignmentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.verticalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.horizontalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.backgroundToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pageSetupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.displayDataDictionaryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.checkCodeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.importEpi6RecFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.importCheckCodeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.makeViewFromDataTableToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.upgradeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.Import35xToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.Import6xToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.makeProjectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.makeAccessPRJToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.makeSQLPRJToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.createDataTableToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteDataTableToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyViewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.enterDataToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutEpiInfoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.MainToolStrip = new System.Windows.Forms.ToolStrip();
this.btnNew = new System.Windows.Forms.ToolStripButton();
this.btnOpen = new System.Windows.Forms.ToolStripButton();
this.toolStripButtonCloseProject = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripButtonUndo = new System.Windows.Forms.ToolStripButton();
this.toolStripButtonRedo = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparatorAfterUndoRedo = new System.Windows.Forms.ToolStripSeparator();
this.btnCheckCode = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator();
this.btnEnterData = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator();
this.QuickPublishtoolStripButton = new System.Windows.Forms.ToolStripDropDownButton();
this.toWebSurveyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toWebEnterToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator();
this.ChangeModetoolStripDropDownButton = new System.Windows.Forms.ToolStripDropDownButton();
this.EIWSToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.draftToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.finalToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.EWEToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.draftToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.finalToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.orderOfFieldEntryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.btnSave = new System.Windows.Forms.ToolStripButton();
this.btnCut = new System.Windows.Forms.ToolStripButton();
this.btnCopy = new System.Windows.Forms.ToolStripButton();
this.btnPaste = new System.Windows.Forms.ToolStripButton();
this.openProjectFromWebToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.MainToolStripContainer.ContentPanel.SuspendLayout();
this.MainToolStripContainer.TopToolStripPanel.SuspendLayout();
this.MainToolStripContainer.SuspendLayout();
this.MainMenu.SuspendLayout();
this.MainToolStrip.SuspendLayout();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
this.baseImageList.Images.SetKeyName(76, "");
this.baseImageList.Images.SetKeyName(77, "");
this.baseImageList.Images.SetKeyName(78, "");
this.baseImageList.Images.SetKeyName(79, "");
this.baseImageList.Images.SetKeyName(80, "");
this.baseImageList.Images.SetKeyName(81, "");
this.baseImageList.Images.SetKeyName(82, "");
this.baseImageList.Images.SetKeyName(83, "");
this.baseImageList.Images.SetKeyName(84, "");
this.baseImageList.Images.SetKeyName(85, "");
this.baseImageList.Images.SetKeyName(86, "");
this.baseImageList.Images.SetKeyName(87, "");
this.baseImageList.Images.SetKeyName(88, "");
this.baseImageList.Images.SetKeyName(89, "");
this.baseImageList.Images.SetKeyName(90, "");
this.baseImageList.Images.SetKeyName(91, "");
this.baseImageList.Images.SetKeyName(92, "");
this.baseImageList.Images.SetKeyName(93, "");
this.baseImageList.Images.SetKeyName(94, "");
this.baseImageList.Images.SetKeyName(95, "");
this.baseImageList.Images.SetKeyName(96, "");
//
// MainToolStripContainer
//
//
// MainToolStripContainer.ContentPanel
//
this.MainToolStripContainer.ContentPanel.Controls.Add(this.dockManager1);
resources.ApplyResources(this.MainToolStripContainer.ContentPanel, "MainToolStripContainer.ContentPanel");
resources.ApplyResources(this.MainToolStripContainer, "MainToolStripContainer");
this.MainToolStripContainer.Name = "MainToolStripContainer";
//
// MainToolStripContainer.TopToolStripPanel
//
this.MainToolStripContainer.TopToolStripPanel.Controls.Add(this.MainMenu);
this.MainToolStripContainer.TopToolStripPanel.Controls.Add(this.MainToolStrip);
//
// dockManager1
//
this.dockManager1.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.dockManager1, "dockManager1");
this.dockManager1.DockBorder = 20;
this.dockManager1.DockType = Epi.Windows.Docking.DockContainerType.Document;
this.dockManager1.FastDrawing = true;
this.dockManager1.Name = "dockManager1";
this.dockManager1.ShowIcons = true;
this.dockManager1.SplitterWidth = 4;
this.dockManager1.VisualStyle = Epi.Windows.Docking.DockVisualStyle.VS2003;
//
// MainMenu
//
resources.ApplyResources(this.MainMenu, "MainMenu");
this.MainMenu.ImageScalingSize = new System.Drawing.Size(20, 20);
this.MainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.viewToolStripMenuItem,
this.insertToolStripMenuItem,
this.forToolStripMenuItem,
this.toolsToolStripMenuItem,
this.helpToolStripMenuItem});
this.MainMenu.Name = "MainMenu";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.NewProjectMenuItem,
this.NewProjectFromTemplateMenuItem,
this.NewProjectFromExcelMenuItem,
this.NewViewMenuItem,
this.NewPageMenuItem,
this.toolStripSeparator9,
this.openProjectToolStripMenuItem,
this.openProjectFromWebToolStripMenuItem,
this.closeProjectToolStripMenuItem,
this.mnuImportTemplate,
this.toolStripMenuItemPrint,
this.mnuCopyToPhone,
this.toolStripPublishToWebEnter,
this.mnuPublishToWeb,
this.toolStripSeparator3,
this.recentProjectsToolStripMenuItem,
this.toolStripSeparator5,
this.exitMakeViewToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem");
//
// NewProjectMenuItem
//
resources.ApplyResources(this.NewProjectMenuItem, "NewProjectMenuItem");
this.NewProjectMenuItem.Name = "NewProjectMenuItem";
this.NewProjectMenuItem.Click += new System.EventHandler(this.NewProjectMenuItem_Click);
//
// NewProjectFromTemplateMenuItem
//
resources.ApplyResources(this.NewProjectFromTemplateMenuItem, "NewProjectFromTemplateMenuItem");
this.NewProjectFromTemplateMenuItem.Name = "NewProjectFromTemplateMenuItem";
this.NewProjectFromTemplateMenuItem.Click += new System.EventHandler(this.NewProjectFromTemplateMenuItem_Click);
//
// NewProjectFromExcelMenuItem
//
this.NewProjectFromExcelMenuItem.Name = "NewProjectFromExcelMenuItem";
resources.ApplyResources(this.NewProjectFromExcelMenuItem, "NewProjectFromExcelMenuItem");
this.NewProjectFromExcelMenuItem.Click += new System.EventHandler(this.NewProjectFromExcelMenuItem_Click);
//
// NewViewMenuItem
//
resources.ApplyResources(this.NewViewMenuItem, "NewViewMenuItem");
this.NewViewMenuItem.Name = "NewViewMenuItem";
this.NewViewMenuItem.Click += new System.EventHandler(this.NewViewMenuItem_Click);
//
// NewPageMenuItem
//
resources.ApplyResources(this.NewPageMenuItem, "NewPageMenuItem");
this.NewPageMenuItem.Name = "NewPageMenuItem";
this.NewPageMenuItem.Click += new System.EventHandler(this.NewPageMenuItem_Click);
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
resources.ApplyResources(this.toolStripSeparator9, "toolStripSeparator9");
//
// openProjectToolStripMenuItem
//
resources.ApplyResources(this.openProjectToolStripMenuItem, "openProjectToolStripMenuItem");
this.openProjectToolStripMenuItem.Name = "openProjectToolStripMenuItem";
this.openProjectToolStripMenuItem.Click += new System.EventHandler(this.OpenProject_Click);
//
// closeProjectToolStripMenuItem
//
resources.ApplyResources(this.closeProjectToolStripMenuItem, "closeProjectToolStripMenuItem");
this.closeProjectToolStripMenuItem.Name = "closeProjectToolStripMenuItem";
this.closeProjectToolStripMenuItem.Click += new System.EventHandler(this.closeProjectToolStripMenuItem_Click);
//
// mnuImportTemplate
//
this.mnuImportTemplate.Name = "mnuImportTemplate";
resources.ApplyResources(this.mnuImportTemplate, "mnuImportTemplate");
this.mnuImportTemplate.Click += new System.EventHandler(this.mnuImportTemplate_Click);
//
// toolStripMenuItemPrint
//
resources.ApplyResources(this.toolStripMenuItemPrint, "toolStripMenuItemPrint");
this.toolStripMenuItemPrint.Name = "toolStripMenuItemPrint";
this.toolStripMenuItemPrint.Click += new System.EventHandler(this.toolStripMenuItemPrint_Click);
//
// mnuCopyToPhone
//
resources.ApplyResources(this.mnuCopyToPhone, "mnuCopyToPhone");
this.mnuCopyToPhone.Image = global::Epi.Windows.MakeView.Properties.Resources.android_icon;
this.mnuCopyToPhone.Name = "mnuCopyToPhone";
this.mnuCopyToPhone.Click += new System.EventHandler(this.mnuCopyToPhone_Click);
//
// toolStripPublishToWebEnter
//
resources.ApplyResources(this.toolStripPublishToWebEnter, "toolStripPublishToWebEnter");
this.toolStripPublishToWebEnter.Image = global::Epi.Windows.MakeView.Properties.Resources.mail_send;
this.toolStripPublishToWebEnter.Name = "toolStripPublishToWebEnter";
this.toolStripPublishToWebEnter.Click += new System.EventHandler(this.toolStripPublishToWebEnter_Click);
//
// mnuPublishToWeb
//
resources.ApplyResources(this.mnuPublishToWeb, "mnuPublishToWeb");
this.mnuPublishToWeb.Image = global::Epi.Windows.MakeView.Properties.Resources.mail_send;
this.mnuPublishToWeb.Name = "mnuPublishToWeb";
this.mnuPublishToWeb.Click += new System.EventHandler(this.publishNewSurveyToolStripMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
//
// recentProjectsToolStripMenuItem
//
this.recentProjectsToolStripMenuItem.Name = "recentProjectsToolStripMenuItem";
resources.ApplyResources(this.recentProjectsToolStripMenuItem, "recentProjectsToolStripMenuItem");
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5");
//
// exitMakeViewToolStripMenuItem
//
this.exitMakeViewToolStripMenuItem.Name = "exitMakeViewToolStripMenuItem";
resources.ApplyResources(this.exitMakeViewToolStripMenuItem, "exitMakeViewToolStripMenuItem");
this.exitMakeViewToolStripMenuItem.Click += new System.EventHandler(this.exitMakeViewToolStripMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem,
this.toolStripSeparator8,
this.mnuEditCut,
this.mnuEditCopy,
this.mnuEditPaste,
this.deletePageToolStripMenuItem,
this.renamePageToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
resources.ApplyResources(this.editToolStripMenuItem, "editToolStripMenuItem");
this.editToolStripMenuItem.Click += new System.EventHandler(this.editToolStripMenuItem_Click);
//
// undoToolStripMenuItem
//
resources.ApplyResources(this.undoToolStripMenuItem, "undoToolStripMenuItem");
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.Click += new System.EventHandler(this.toolStripButtonUndo_Click);
//
// redoToolStripMenuItem
//
resources.ApplyResources(this.redoToolStripMenuItem, "redoToolStripMenuItem");
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.Click += new System.EventHandler(this.toolStripButtonRedo_Click);
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
resources.ApplyResources(this.toolStripSeparator8, "toolStripSeparator8");
//
// mnuEditCut
//
this.mnuEditCut.Name = "mnuEditCut";
resources.ApplyResources(this.mnuEditCut, "mnuEditCut");
this.mnuEditCut.Click += new System.EventHandler(this.editCut_Click);
//
// mnuEditCopy
//
this.mnuEditCopy.Name = "mnuEditCopy";
resources.ApplyResources(this.mnuEditCopy, "mnuEditCopy");
this.mnuEditCopy.Click += new System.EventHandler(this.editCopy_Click);
//
// mnuEditPaste
//
this.mnuEditPaste.Name = "mnuEditPaste";
resources.ApplyResources(this.mnuEditPaste, "mnuEditPaste");
this.mnuEditPaste.Click += new System.EventHandler(this.editPaste_Click);
//
// deletePageToolStripMenuItem
//
resources.ApplyResources(this.deletePageToolStripMenuItem, "deletePageToolStripMenuItem");
this.deletePageToolStripMenuItem.Name = "deletePageToolStripMenuItem";
this.deletePageToolStripMenuItem.Click += new System.EventHandler(this.deletePageToolStripMenuItem_Click);
//
// renamePageToolStripMenuItem
//
resources.ApplyResources(this.renamePageToolStripMenuItem, "renamePageToolStripMenuItem");
this.renamePageToolStripMenuItem.Name = "renamePageToolStripMenuItem";
this.renamePageToolStripMenuItem.Click += new System.EventHandler(this.renamePageToolStripMenuItem_Click);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statusBarToolStripMenuItem,
this.vocabularyFieldsToolStripMenuItem,
this.fieldNamesToolStripMenuItem,
this.tabOrderToolStripMenuItem,
this.epiInfoLogsToolStripMenuItem});
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
resources.ApplyResources(this.viewToolStripMenuItem, "viewToolStripMenuItem");
//
// statusBarToolStripMenuItem
//
this.statusBarToolStripMenuItem.Checked = true;
this.statusBarToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.statusBarToolStripMenuItem.Name = "statusBarToolStripMenuItem";
resources.ApplyResources(this.statusBarToolStripMenuItem, "statusBarToolStripMenuItem");
this.statusBarToolStripMenuItem.Click += new System.EventHandler(this.statusBarToolStripMenuItem_Click);
//
// vocabularyFieldsToolStripMenuItem
//
this.vocabularyFieldsToolStripMenuItem.CheckOnClick = true;
this.vocabularyFieldsToolStripMenuItem.Name = "vocabularyFieldsToolStripMenuItem";
resources.ApplyResources(this.vocabularyFieldsToolStripMenuItem, "vocabularyFieldsToolStripMenuItem");
this.vocabularyFieldsToolStripMenuItem.Click += new System.EventHandler(this.VocabularyFieldsToolStripMenuItem_Click);
//
// fieldNamesToolStripMenuItem
//
this.fieldNamesToolStripMenuItem.CheckOnClick = true;
this.fieldNamesToolStripMenuItem.Name = "fieldNamesToolStripMenuItem";
resources.ApplyResources(this.fieldNamesToolStripMenuItem, "fieldNamesToolStripMenuItem");
this.fieldNamesToolStripMenuItem.Click += new System.EventHandler(this.fieldNamesToolStripMenuItem_Click);
//
// tabOrderToolStripMenuItem
//
this.tabOrderToolStripMenuItem.CheckOnClick = true;
this.tabOrderToolStripMenuItem.Name = "tabOrderToolStripMenuItem";
resources.ApplyResources(this.tabOrderToolStripMenuItem, "tabOrderToolStripMenuItem");
this.tabOrderToolStripMenuItem.Click += new System.EventHandler(this.tabOrderToolStripMenuItem_Click);
//
// epiInfoLogsToolStripMenuItem
//
this.epiInfoLogsToolStripMenuItem.Name = "epiInfoLogsToolStripMenuItem";
resources.ApplyResources(this.epiInfoLogsToolStripMenuItem, "epiInfoLogsToolStripMenuItem");
this.epiInfoLogsToolStripMenuItem.Click += new System.EventHandler(this.epiInfoLogsToolStripMenuItem_Click);
//
// insertToolStripMenuItem
//
this.insertToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.pageToolStripMenuItem1,
this.groupToolStripMenuItem});
this.insertToolStripMenuItem.Name = "insertToolStripMenuItem";
resources.ApplyResources(this.insertToolStripMenuItem, "insertToolStripMenuItem");
//
// pageToolStripMenuItem1
//
this.pageToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.insertPageToolStripMenuItem,
this.addPageToolStripMenuItem});
resources.ApplyResources(this.pageToolStripMenuItem1, "pageToolStripMenuItem1");
this.pageToolStripMenuItem1.Name = "pageToolStripMenuItem1";
//
// insertPageToolStripMenuItem
//
this.insertPageToolStripMenuItem.Name = "insertPageToolStripMenuItem";
resources.ApplyResources(this.insertPageToolStripMenuItem, "insertPageToolStripMenuItem");
this.insertPageToolStripMenuItem.Click += new System.EventHandler(this.insertPageToolStripMenuItem_Click);
//
// addPageToolStripMenuItem
//
this.addPageToolStripMenuItem.Name = "addPageToolStripMenuItem";
resources.ApplyResources(this.addPageToolStripMenuItem, "addPageToolStripMenuItem");
this.addPageToolStripMenuItem.Click += new System.EventHandler(this.NewPageMenuItem_Click);
//
// groupToolStripMenuItem
//
resources.ApplyResources(this.groupToolStripMenuItem, "groupToolStripMenuItem");
this.groupToolStripMenuItem.Name = "groupToolStripMenuItem";
this.groupToolStripMenuItem.Click += new System.EventHandler(this.groupToolStripMenuItem_Click);
//
// forToolStripMenuItem
//
this.forToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.setDefaultFontToolStripMenuItem,
this.setDefaultControlFontToolStripMenuItem,
this.alignmentToolStripMenuItem,
this.backgroundToolStripMenuItem,
this.settingsToolStripMenuItem,
this.pageSetupToolStripMenuItem});
this.forToolStripMenuItem.Name = "forToolStripMenuItem";
resources.ApplyResources(this.forToolStripMenuItem, "forToolStripMenuItem");
//
// setDefaultFontToolStripMenuItem
//
resources.ApplyResources(this.setDefaultFontToolStripMenuItem, "setDefaultFontToolStripMenuItem");
this.setDefaultFontToolStripMenuItem.Name = "setDefaultFontToolStripMenuItem";
this.setDefaultFontToolStripMenuItem.Click += new System.EventHandler(this.setDefaultFontToolStripMenuItem_Click);
//
// setDefaultControlFontToolStripMenuItem
//
resources.ApplyResources(this.setDefaultControlFontToolStripMenuItem, "setDefaultControlFontToolStripMenuItem");
this.setDefaultControlFontToolStripMenuItem.Name = "setDefaultControlFontToolStripMenuItem";
this.setDefaultControlFontToolStripMenuItem.Click += new System.EventHandler(this.setDefaultControlFontToolStripMenuItem_Click);
//
// alignmentToolStripMenuItem
//
this.alignmentToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.verticalToolStripMenuItem,
this.horizontalToolStripMenuItem});
resources.ApplyResources(this.alignmentToolStripMenuItem, "alignmentToolStripMenuItem");
this.alignmentToolStripMenuItem.Name = "alignmentToolStripMenuItem";
//
// verticalToolStripMenuItem
//
this.verticalToolStripMenuItem.Name = "verticalToolStripMenuItem";
resources.ApplyResources(this.verticalToolStripMenuItem, "verticalToolStripMenuItem");
this.verticalToolStripMenuItem.Click += new System.EventHandler(this.verticalToolStripMenuItem_Click);
//
// horizontalToolStripMenuItem
//
this.horizontalToolStripMenuItem.Name = "horizontalToolStripMenuItem";
resources.ApplyResources(this.horizontalToolStripMenuItem, "horizontalToolStripMenuItem");
this.horizontalToolStripMenuItem.Click += new System.EventHandler(this.horizontalToolStripMenuItem_Click);
//
// backgroundToolStripMenuItem
//
resources.ApplyResources(this.backgroundToolStripMenuItem, "backgroundToolStripMenuItem");
this.backgroundToolStripMenuItem.Name = "backgroundToolStripMenuItem";
this.backgroundToolStripMenuItem.Click += new System.EventHandler(this.backgroundToolStripMenuItem_Click);
//
// settingsToolStripMenuItem
//
resources.ApplyResources(this.settingsToolStripMenuItem, "settingsToolStripMenuItem");
this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem";
this.settingsToolStripMenuItem.Click += new System.EventHandler(this.settingsToolStripMenuItem_Click);
//
// pageSetupToolStripMenuItem
//
resources.ApplyResources(this.pageSetupToolStripMenuItem, "pageSetupToolStripMenuItem");
this.pageSetupToolStripMenuItem.Name = "pageSetupToolStripMenuItem";
this.pageSetupToolStripMenuItem.Click += new System.EventHandler(this.pageSetupToolStripMenuItem_Click);
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.displayDataDictionaryToolStripMenuItem,
this.checkCodeToolStripMenuItem,
this.toolStripSeparator7,
this.importEpi6RecFileToolStripMenuItem,
this.importCheckCodeToolStripMenuItem,
this.makeViewFromDataTableToolStripMenuItem,
this.upgradeToolStripMenuItem,
this.makeProjectToolStripMenuItem,
this.createDataTableToolStripMenuItem,
this.deleteDataTableToolStripMenuItem,
this.copyViewToolStripMenuItem,
this.enterDataToolStripMenuItem,
this.toolStripSeparator6,
this.optionsToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
resources.ApplyResources(this.toolsToolStripMenuItem, "toolsToolStripMenuItem");
//
// displayDataDictionaryToolStripMenuItem
//
resources.ApplyResources(this.displayDataDictionaryToolStripMenuItem, "displayDataDictionaryToolStripMenuItem");
this.displayDataDictionaryToolStripMenuItem.Name = "displayDataDictionaryToolStripMenuItem";
this.displayDataDictionaryToolStripMenuItem.Click += new System.EventHandler(this.displayDataDictionaryToolStripMenuItem_Click);
//
// checkCodeToolStripMenuItem
//
resources.ApplyResources(this.checkCodeToolStripMenuItem, "checkCodeToolStripMenuItem");
this.checkCodeToolStripMenuItem.Name = "checkCodeToolStripMenuItem";
this.checkCodeToolStripMenuItem.Click += new System.EventHandler(this.checkCodeToolStripMenuItem_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
resources.ApplyResources(this.toolStripSeparator7, "toolStripSeparator7");
//
// importEpi6RecFileToolStripMenuItem
//
resources.ApplyResources(this.importEpi6RecFileToolStripMenuItem, "importEpi6RecFileToolStripMenuItem");
this.importEpi6RecFileToolStripMenuItem.Name = "importEpi6RecFileToolStripMenuItem";
//
// importCheckCodeToolStripMenuItem
//
resources.ApplyResources(this.importCheckCodeToolStripMenuItem, "importCheckCodeToolStripMenuItem");
this.importCheckCodeToolStripMenuItem.Name = "importCheckCodeToolStripMenuItem";
//
// makeViewFromDataTableToolStripMenuItem
//
resources.ApplyResources(this.makeViewFromDataTableToolStripMenuItem, "makeViewFromDataTableToolStripMenuItem");
this.makeViewFromDataTableToolStripMenuItem.Name = "makeViewFromDataTableToolStripMenuItem";
this.makeViewFromDataTableToolStripMenuItem.Click += new System.EventHandler(this.makeViewFromDataTableToolStripMenuItem_Click);
//
// upgradeToolStripMenuItem
//
this.upgradeToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.Import35xToolStripMenuItem,
this.Import6xToolStripMenuItem});
this.upgradeToolStripMenuItem.Name = "upgradeToolStripMenuItem";
resources.ApplyResources(this.upgradeToolStripMenuItem, "upgradeToolStripMenuItem");
//
// Import35xToolStripMenuItem
//
this.Import35xToolStripMenuItem.Name = "Import35xToolStripMenuItem";
resources.ApplyResources(this.Import35xToolStripMenuItem, "Import35xToolStripMenuItem");
this.Import35xToolStripMenuItem.Click += new System.EventHandler(this.Import35xToolStripMenuItem_Click);
//
// Import6xToolStripMenuItem
//
resources.ApplyResources(this.Import6xToolStripMenuItem, "Import6xToolStripMenuItem");
this.Import6xToolStripMenuItem.Name = "Import6xToolStripMenuItem";
//
// makeProjectToolStripMenuItem
//
this.makeProjectToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.makeAccessPRJToolStripMenuItem,
this.makeSQLPRJToolStripMenuItem});
this.makeProjectToolStripMenuItem.Name = "makeProjectToolStripMenuItem";
resources.ApplyResources(this.makeProjectToolStripMenuItem, "makeProjectToolStripMenuItem");
//
// makeAccessPRJToolStripMenuItem
//
this.makeAccessPRJToolStripMenuItem.Name = "makeAccessPRJToolStripMenuItem";
resources.ApplyResources(this.makeAccessPRJToolStripMenuItem, "makeAccessPRJToolStripMenuItem");
this.makeAccessPRJToolStripMenuItem.Click += new System.EventHandler(this.makeAccessProjectToolStripMenuItem_Click);
//
// makeSQLPRJToolStripMenuItem
//
this.makeSQLPRJToolStripMenuItem.Name = "makeSQLPRJToolStripMenuItem";
resources.ApplyResources(this.makeSQLPRJToolStripMenuItem, "makeSQLPRJToolStripMenuItem");
this.makeSQLPRJToolStripMenuItem.Click += new System.EventHandler(this.makeSQLProjectToolStripMenuItem_Click);
//
// createDataTableToolStripMenuItem
//
resources.ApplyResources(this.createDataTableToolStripMenuItem, "createDataTableToolStripMenuItem");
this.createDataTableToolStripMenuItem.Name = "createDataTableToolStripMenuItem";
this.createDataTableToolStripMenuItem.Click += new System.EventHandler(this.createDataTableToolStripMenuItem_Click);
//
// deleteDataTableToolStripMenuItem
//
resources.ApplyResources(this.deleteDataTableToolStripMenuItem, "deleteDataTableToolStripMenuItem");
this.deleteDataTableToolStripMenuItem.Name = "deleteDataTableToolStripMenuItem";
this.deleteDataTableToolStripMenuItem.Click += new System.EventHandler(this.deleteDataTableToolStripMenuItem_Click);
//
// copyViewToolStripMenuItem
//
resources.ApplyResources(this.copyViewToolStripMenuItem, "copyViewToolStripMenuItem");
this.copyViewToolStripMenuItem.Name = "copyViewToolStripMenuItem";
this.copyViewToolStripMenuItem.Click += new System.EventHandler(this.copyViewToolStripMenuItem_Click);
//
// enterDataToolStripMenuItem
//
resources.ApplyResources(this.enterDataToolStripMenuItem, "enterDataToolStripMenuItem");
this.enterDataToolStripMenuItem.Name = "enterDataToolStripMenuItem";
this.enterDataToolStripMenuItem.Click += new System.EventHandler(this.btnEnterData_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6");
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
resources.ApplyResources(this.optionsToolStripMenuItem, "optionsToolStripMenuItem");
this.optionsToolStripMenuItem.Click += new System.EventHandler(this.optionsToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.contentsToolStripMenuItem,
this.aboutEpiInfoToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
resources.ApplyResources(this.helpToolStripMenuItem, "helpToolStripMenuItem");
//
// contentsToolStripMenuItem
//
this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem";
resources.ApplyResources(this.contentsToolStripMenuItem, "contentsToolStripMenuItem");
this.contentsToolStripMenuItem.Click += new System.EventHandler(this.contentsToolStripMenuItem_Click);
//
// aboutEpiInfoToolStripMenuItem
//
this.aboutEpiInfoToolStripMenuItem.Name = "aboutEpiInfoToolStripMenuItem";
resources.ApplyResources(this.aboutEpiInfoToolStripMenuItem, "aboutEpiInfoToolStripMenuItem");
this.aboutEpiInfoToolStripMenuItem.Click += new System.EventHandler(this.aboutEpiInfoToolStripMenuItem_Click);
//
// MainToolStrip
//
resources.ApplyResources(this.MainToolStrip, "MainToolStrip");
this.MainToolStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.MainToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnNew,
this.btnOpen,
this.toolStripButtonCloseProject,
this.toolStripSeparator2,
this.toolStripButtonUndo,
this.toolStripButtonRedo,
this.toolStripSeparatorAfterUndoRedo,
this.btnCheckCode,
this.toolStripSeparator12,
this.btnEnterData,
this.toolStripSeparator10,
this.QuickPublishtoolStripButton,
this.toolStripSeparator11,
this.ChangeModetoolStripDropDownButton});
this.MainToolStrip.Name = "MainToolStrip";
this.MainToolStrip.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.MainToolStrip_ItemClicked);
//
// btnNew
//
resources.ApplyResources(this.btnNew, "btnNew");
this.btnNew.Name = "btnNew";
this.btnNew.Click += new System.EventHandler(this.NewProjectMenuItem_Click);
//
// btnOpen
//
resources.ApplyResources(this.btnOpen, "btnOpen");
this.btnOpen.Name = "btnOpen";
this.btnOpen.Click += new System.EventHandler(this.OpenProject_Click);
//
// toolStripButtonCloseProject
//
resources.ApplyResources(this.toolStripButtonCloseProject, "toolStripButtonCloseProject");
this.toolStripButtonCloseProject.Name = "toolStripButtonCloseProject";
this.toolStripButtonCloseProject.Click += new System.EventHandler(this.closeProjectToolStripMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// toolStripButtonUndo
//
this.toolStripButtonUndo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.toolStripButtonUndo, "toolStripButtonUndo");
this.toolStripButtonUndo.Name = "toolStripButtonUndo";
this.toolStripButtonUndo.Click += new System.EventHandler(this.toolStripButtonUndo_Click);
//
// toolStripButtonRedo
//
this.toolStripButtonRedo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.toolStripButtonRedo, "toolStripButtonRedo");
this.toolStripButtonRedo.Name = "toolStripButtonRedo";
this.toolStripButtonRedo.Click += new System.EventHandler(this.toolStripButtonRedo_Click);
//
// toolStripSeparatorAfterUndoRedo
//
this.toolStripSeparatorAfterUndoRedo.Name = "toolStripSeparatorAfterUndoRedo";
resources.ApplyResources(this.toolStripSeparatorAfterUndoRedo, "toolStripSeparatorAfterUndoRedo");
//
// btnCheckCode
//
resources.ApplyResources(this.btnCheckCode, "btnCheckCode");
this.btnCheckCode.Name = "btnCheckCode";
this.btnCheckCode.Click += new System.EventHandler(this.btnCheckCode_Click);
//
// toolStripSeparator12
//
this.toolStripSeparator12.Name = "toolStripSeparator12";
resources.ApplyResources(this.toolStripSeparator12, "toolStripSeparator12");
//
// btnEnterData
//
resources.ApplyResources(this.btnEnterData, "btnEnterData");
this.btnEnterData.Name = "btnEnterData";
this.btnEnterData.Click += new System.EventHandler(this.btnEnterData_Click);
//
// toolStripSeparator10
//
this.toolStripSeparator10.Name = "toolStripSeparator10";
resources.ApplyResources(this.toolStripSeparator10, "toolStripSeparator10");
//
// QuickPublishtoolStripButton
//
this.QuickPublishtoolStripButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toWebSurveyToolStripMenuItem,
this.toWebEnterToolStripMenuItem});
resources.ApplyResources(this.QuickPublishtoolStripButton, "QuickPublishtoolStripButton");
this.QuickPublishtoolStripButton.Image = global::Epi.Windows.MakeView.Properties.Resources.Publish;
this.QuickPublishtoolStripButton.Name = "QuickPublishtoolStripButton";
//
// toWebSurveyToolStripMenuItem
//
this.toWebSurveyToolStripMenuItem.Name = "toWebSurveyToolStripMenuItem";
resources.ApplyResources(this.toWebSurveyToolStripMenuItem, "toWebSurveyToolStripMenuItem");
this.toWebSurveyToolStripMenuItem.Click += new System.EventHandler(this.toWebSurveyToolStripMenuItem_Click);
//
// toWebEnterToolStripMenuItem
//
this.toWebEnterToolStripMenuItem.Name = "toWebEnterToolStripMenuItem";
resources.ApplyResources(this.toWebEnterToolStripMenuItem, "toWebEnterToolStripMenuItem");
this.toWebEnterToolStripMenuItem.Click += new System.EventHandler(this.toWebEnterToolStripMenuItem_Click);
//
// toolStripSeparator11
//
this.toolStripSeparator11.Name = "toolStripSeparator11";
resources.ApplyResources(this.toolStripSeparator11, "toolStripSeparator11");
//
// ChangeModetoolStripDropDownButton
//
this.ChangeModetoolStripDropDownButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.ChangeModetoolStripDropDownButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.EIWSToolStripMenuItem,
this.EWEToolStripMenuItem});
resources.ApplyResources(this.ChangeModetoolStripDropDownButton, "ChangeModetoolStripDropDownButton");
this.ChangeModetoolStripDropDownButton.Name = "ChangeModetoolStripDropDownButton";
this.ChangeModetoolStripDropDownButton.Click += new System.EventHandler(this.ChangeModetoolStripDropDownButton_Click);
//
// EIWSToolStripMenuItem
//
this.EIWSToolStripMenuItem.CheckOnClick = true;
this.EIWSToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.draftToolStripMenuItem1,
this.finalToolStripMenuItem1});
this.EIWSToolStripMenuItem.Name = "EIWSToolStripMenuItem";
resources.ApplyResources(this.EIWSToolStripMenuItem, "EIWSToolStripMenuItem");
this.EIWSToolStripMenuItem.Click += new System.EventHandler(this.draftToolStripMenuItem_Click);
//
// draftToolStripMenuItem1
//
this.draftToolStripMenuItem1.Name = "draftToolStripMenuItem1";
resources.ApplyResources(this.draftToolStripMenuItem1, "draftToolStripMenuItem1");
this.draftToolStripMenuItem1.Click += new System.EventHandler(this.draftToolStripMenuItem1_Click);
//
// finalToolStripMenuItem1
//
this.finalToolStripMenuItem1.Name = "finalToolStripMenuItem1";
resources.ApplyResources(this.finalToolStripMenuItem1, "finalToolStripMenuItem1");
this.finalToolStripMenuItem1.Click += new System.EventHandler(this.finalToolStripMenuItem1_Click);
//
// EWEToolStripMenuItem
//
this.EWEToolStripMenuItem.CheckOnClick = true;
this.EWEToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.draftToolStripMenuItem2,
this.finalToolStripMenuItem2});
this.EWEToolStripMenuItem.Name = "EWEToolStripMenuItem";
resources.ApplyResources(this.EWEToolStripMenuItem, "EWEToolStripMenuItem");
this.EWEToolStripMenuItem.Click += new System.EventHandler(this.finalToolStripMenuItem_Click);
//
// draftToolStripMenuItem2
//
this.draftToolStripMenuItem2.Name = "draftToolStripMenuItem2";
resources.ApplyResources(this.draftToolStripMenuItem2, "draftToolStripMenuItem2");
this.draftToolStripMenuItem2.Click += new System.EventHandler(this.draftToolStripMenuItem2_Click);
//
// finalToolStripMenuItem2
//
this.finalToolStripMenuItem2.Name = "finalToolStripMenuItem2";
resources.ApplyResources(this.finalToolStripMenuItem2, "finalToolStripMenuItem2");
this.finalToolStripMenuItem2.Click += new System.EventHandler(this.finalToolStripMenuItem2_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// saveToolStripMenuItem
//
resources.ApplyResources(this.saveToolStripMenuItem, "saveToolStripMenuItem");
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
//
// orderOfFieldEntryToolStripMenuItem
//
resources.ApplyResources(this.orderOfFieldEntryToolStripMenuItem, "orderOfFieldEntryToolStripMenuItem");
this.orderOfFieldEntryToolStripMenuItem.Name = "orderOfFieldEntryToolStripMenuItem";
this.orderOfFieldEntryToolStripMenuItem.Click += new System.EventHandler(this.orderOfFieldEntryToolStripMenuItem_Click);
//
// btnSave
//
this.btnSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.btnSave, "btnSave");
this.btnSave.Name = "btnSave";
//
// btnCut
//
this.btnCut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.btnCut, "btnCut");
this.btnCut.Name = "btnCut";
//
// btnCopy
//
this.btnCopy.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.btnCopy, "btnCopy");
this.btnCopy.Name = "btnCopy";
//
// btnPaste
//
this.btnPaste.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.btnPaste, "btnPaste");
this.btnPaste.Name = "btnPaste";
//
// openProjectFromWebToolStripMenuItem
//
this.openProjectFromWebToolStripMenuItem.Name = "openProjectFromWebToolStripMenuItem";
resources.ApplyResources(this.openProjectFromWebToolStripMenuItem, "openProjectFromWebToolStripMenuItem");
this.openProjectFromWebToolStripMenuItem.Click += new System.EventHandler(this.OpenProjectFromWebToolStripMenuItem_Click);
//
// MakeViewMainForm
//
this.AllowDrop = true;
resources.ApplyResources(this, "$this");
this.Controls.Add(this.MainToolStripContainer);
this.Name = "MakeViewMainForm";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form_Closing);
this.Load += new System.EventHandler(this.Form_Load);
this.Controls.SetChildIndex(this.MainToolStripContainer, 0);
this.MainToolStripContainer.ContentPanel.ResumeLayout(false);
this.MainToolStripContainer.TopToolStripPanel.ResumeLayout(false);
this.MainToolStripContainer.TopToolStripPanel.PerformLayout();
this.MainToolStripContainer.ResumeLayout(false);
this.MainToolStripContainer.PerformLayout();
this.MainMenu.ResumeLayout(false);
this.MainMenu.PerformLayout();
this.MainToolStrip.ResumeLayout(false);
this.MainToolStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
void toolStripButtonRedo_Click(object sender, EventArgs e)
{
mediator.Redo();
}
void toolStripButtonUndo_Click(object sender, EventArgs e)
{
mediator.Undo();
}
#endregion Designer Generated Code
private bool canCommandBeGenerated;
/// <summary>
/// project explorer
/// </summary>
public ProjectExplorer projectExplorer;
private Canvas canvas;
/// <summary>
/// mediator
/// </summary>
public PresentationLogic.GuiMediator mediator;
private System.ComponentModel.IContainer components = null;
private ToolStripContainer MainToolStripContainer;
private MenuStrip MainMenu;
private ToolStrip MainToolStrip;
private Epi.Windows.Docking.DockManager dockManager1;
private ToolStripButton btnNew;
private ToolStripButton btnOpen;
private ToolStripButton btnSave;
private ToolStripSeparator toolStripSeparator1;
private ToolStripButton btnCut;
private ToolStripButton btnCopy;
private ToolStripButton btnPaste;
private ToolStripSeparator toolStripSeparator2;
private ToolStripButton btnCheckCode;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem openProjectToolStripMenuItem;
private ToolStripSeparator toolStripSeparator3;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripSeparator toolStripSeparator4;
private ToolStripSeparator toolStripSeparatorAfterUndoRedo;
private ToolStripMenuItem recentProjectsToolStripMenuItem;
private ToolStripSeparator toolStripSeparator5;
private ToolStripMenuItem exitMakeViewToolStripMenuItem;
private ToolStripMenuItem editToolStripMenuItem;
private ToolStripMenuItem viewToolStripMenuItem;
private ToolStripMenuItem insertToolStripMenuItem;
private ToolStripMenuItem forToolStripMenuItem;
private ToolStripMenuItem toolsToolStripMenuItem;
private ToolStripMenuItem helpToolStripMenuItem;
private ToolStripMenuItem mnuEditCut;
private ToolStripMenuItem mnuEditCopy;
private ToolStripMenuItem mnuEditPaste;
private ToolStripMenuItem deletePageToolStripMenuItem;
private ToolStripMenuItem renamePageToolStripMenuItem;
private ToolStripMenuItem orderOfFieldEntryToolStripMenuItem;
private ToolStripMenuItem pageToolStripMenuItem1;
private ToolStripMenuItem groupToolStripMenuItem;
private ToolStripMenuItem setDefaultFontToolStripMenuItem;
private ToolStripMenuItem alignmentToolStripMenuItem;
private ToolStripMenuItem backgroundToolStripMenuItem;
private ToolStripMenuItem settingsToolStripMenuItem;
private ToolStripMenuItem pageSetupToolStripMenuItem;
private ToolStripMenuItem displayDataDictionaryToolStripMenuItem;
private ToolStripMenuItem importEpi6RecFileToolStripMenuItem;
private ToolStripMenuItem importCheckCodeToolStripMenuItem;
private ToolStripMenuItem makeViewFromDataTableToolStripMenuItem;
private ToolStripMenuItem createDataTableToolStripMenuItem;
private ToolStripMenuItem deleteDataTableToolStripMenuItem;
private ToolStripMenuItem copyViewToolStripMenuItem;
private ToolStripMenuItem enterDataToolStripMenuItem;
private ToolStripSeparator toolStripSeparator6;
private ToolStripMenuItem optionsToolStripMenuItem;
private ToolStripMenuItem insertPageToolStripMenuItem;
private ToolStripMenuItem addPageToolStripMenuItem;
private ToolStripMenuItem verticalToolStripMenuItem;
private ToolStripMenuItem horizontalToolStripMenuItem;
private ToolStripMenuItem contentsToolStripMenuItem;
private ToolStripMenuItem aboutEpiInfoToolStripMenuItem;
private ToolStripMenuItem closeProjectToolStripMenuItem;
private ToolStripButton toolStripButtonCloseProject;
private ToolStripMenuItem statusBarToolStripMenuItem;
private ToolStripMenuItem epiInfoLogsToolStripMenuItem;
private Font currentFont;
private ToolStripMenuItem vocabularyFieldsToolStripMenuItem;
private ToolStripMenuItem checkCodeToolStripMenuItem;
private ToolStripSeparator toolStripSeparator7;
private ToolStripMenuItem undoToolStripMenuItem;
private ToolStripMenuItem redoToolStripMenuItem;
private ToolStripSeparator toolStripSeparator8;
private ToolStripMenuItem NewProjectMenuItem;
private ToolStripMenuItem NewProjectFromTemplateMenuItem;
private ToolStripMenuItem NewViewMenuItem;
private ToolStripMenuItem NewPageMenuItem;
private ToolStripSeparator toolStripSeparator9;
private ToolStripMenuItem mnuCopyToPhone;
private ToolStripMenuItem setDefaultControlFontToolStripMenuItem;
private ToolStripButton toolStripButtonUndo;
private ToolStripButton toolStripButtonRedo;
private ToolStripMenuItem mnuPublishToWeb;
private ToolStripMenuItem mnuImportTemplate;
private ToolStripMenuItem makeProjectToolStripMenuItem;
private ToolStripMenuItem makeAccessPRJToolStripMenuItem;
private ToolStripMenuItem makeSQLPRJToolStripMenuItem;
private ToolStripMenuItem upgradeToolStripMenuItem;
private ToolStripMenuItem Import35xToolStripMenuItem;
private ToolStripMenuItem Import6xToolStripMenuItem;
private ToolStripSeparator toolStripSeparator10;
private ToolStripSeparator toolStripSeparator11;
private ToolStripDropDownButton ChangeModetoolStripDropDownButton;
private ToolStripMenuItem EIWSToolStripMenuItem;
private ToolStripMenuItem EWEToolStripMenuItem;
private ToolStripMenuItem toolStripPublishToWebEnter;
private ToolStripDropDownButton QuickPublishtoolStripButton;
private ToolStripMenuItem toWebSurveyToolStripMenuItem;
private ToolStripMenuItem toWebEnterToolStripMenuItem;
private ToolStripButton btnEnterData;
private ToolStripMenuItem draftToolStripMenuItem1;
private ToolStripMenuItem finalToolStripMenuItem1;
private ToolStripMenuItem draftToolStripMenuItem2;
private ToolStripMenuItem finalToolStripMenuItem2;
private ToolStripMenuItem toolStripMenuItemPrint;
private ToolStripMenuItem fieldNamesToolStripMenuItem;
private ToolStripMenuItem tabOrderToolStripMenuItem;
private ToolStripSeparator toolStripSeparator12;
private ToolStripMenuItem NewProjectFromExcelMenuItem;
private ToolStripMenuItem openProjectFromWebToolStripMenuItem;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.