context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
#region License
/* Copyright (c) 2006 Leslie Sanford
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contact
/*
* Leslie Sanford
* Email: jabberdabber@hotmail.com
*/
#endregion
using System;
using System.Collections;
using System.Diagnostics;
namespace Sanford.Collections
{
/// <summary>
/// Represents the priority queue data structure.
/// </summary>
public class PriorityQueue : ICollection
{
#region PriorityQueue Members
#region Fields
// The maximum level of the skip list.
private const int LevelMaxValue = 16;
// The probability value used to randomly select the next level value.
private const double Probability = 0.5;
// The current level of the skip list.
private int currentLevel = 1;
// The header node of the skip list.
private Node header = new Node(null, LevelMaxValue);
// Used to generate node levels.
private Random rand = new Random();
// The number of elements in the PriorityQueue.
private int count = 0;
// The version of this PriorityQueue.
private long version = 0;
// Used for comparing and sorting elements.
private IComparer comparer;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the PriorityQueue class.
/// </summary>
/// <remarks>
/// The PriorityQueue will cast its elements to the IComparable
/// interface when making comparisons.
/// </remarks>
public PriorityQueue()
{
comparer = new DefaultComparer();
}
/// <summary>
/// Initializes a new instance of the PriorityQueue class with the
/// specified IComparer.
/// </summary>
/// <param name="comparer">
/// The IComparer to use for comparing and ordering elements.
/// </param>
/// <remarks>
/// If the specified IComparer is null, the PriorityQueue will cast its
/// elements to the IComparable interface when making comparisons.
/// </remarks>
public PriorityQueue(IComparer comparer)
{
// If no comparer was provided.
if(comparer == null)
{
// Use the DefaultComparer.
this.comparer = new DefaultComparer();
}
// Else a comparer was provided.
else
{
// Use the provided comparer.
this.comparer = comparer;
}
}
#endregion
#region Methods
/// <summary>
/// Enqueues the specified element into the PriorityQueue.
/// </summary>
/// <param name="element">
/// The element to enqueue into the PriorityQueue.
/// </param>
/// <exception cref="ArgumentNullException">
/// If element is null.
/// </exception>
public virtual void Enqueue(object element)
{
#region Require
if(element == null)
{
throw new ArgumentNullException("element");
}
#endregion
Node x = header;
Node[] update = new Node[LevelMaxValue];
int nextLevel = NextLevel();
// Find the place in the queue to insert the new element.
for(int i = currentLevel - 1; i >= 0; i--)
{
while(x[i] != null && comparer.Compare(x[i].Element, element) > 0)
{
x = x[i];
}
update[i] = x;
}
// If the new node's level is greater than the current level.
if(nextLevel > currentLevel)
{
for(int i = currentLevel; i < nextLevel; i++)
{
update[i] = header;
}
// Update level.
currentLevel = nextLevel;
}
// Create new node.
Node newNode = new Node(element, nextLevel);
// Insert the new node into the list.
for(int i = 0; i < nextLevel; i++)
{
newNode[i] = update[i][i];
update[i][i] = newNode;
}
// Keep track of the number of elements in the PriorityQueue.
count++;
version++;
#region Ensure
Debug.Assert(Contains(element), "Contains Test", "Contains test for element " + element.ToString() + " failed.");
#endregion
#region Invariant
AssertValid();
#endregion
}
/// <summary>
/// Removes the element at the head of the PriorityQueue.
/// </summary>
/// <returns>
/// The element at the head of the PriorityQueue.
/// </returns>
/// <exception cref="InvalidOperationException">
/// If Count is zero.
/// </exception>
public virtual object Dequeue()
{
#region Require
if(Count == 0)
{
throw new InvalidOperationException(
"Cannot dequeue into an empty PriorityQueue.");
}
#endregion
// Get the first item in the queue.
object element = header[0].Element;
// Keep track of the node that is about to be removed.
Node oldNode = header[0];
// Update the header so that its pointers that pointed to the
// node to be removed now point to the node that comes after it.
for(int i = 0; i < currentLevel && header[i] == oldNode; i++)
{
header[i] = oldNode[i];
}
// Update the current level of the list in case the node that
// was removed had the highest level.
while(currentLevel > 1 && header[currentLevel - 1] == null)
{
currentLevel--;
}
// Keep track of how many items are in the queue.
count--;
version++;
#region Ensure
Debug.Assert(count >= 0);
#endregion
#region Invariant
AssertValid();
#endregion
return element;
}
/// <summary>
/// Removes the specified element from the PriorityQueue.
/// </summary>
/// <param name="element">
/// The element to remove.
/// </param>
/// <exception cref="ArgumentNullException">
/// If element is null
/// </exception>
public virtual void Remove(object element)
{
#region Require
if(element == null)
{
throw new ArgumentNullException("element");
}
#endregion
Node x = header;
Node[] update = new Node[LevelMaxValue];
int nextLevel = NextLevel();
// Find the specified element.
for(int i = currentLevel - 1; i >= 0; i--)
{
while(x[i] != null && comparer.Compare(x[i].Element, element) > 0)
{
x = x[i];
}
update[i] = x;
}
x = x[0];
// If the specified element was found.
if(x != null && comparer.Compare(x.Element, element) == 0)
{
// Remove element.
for(int i = 0; i < currentLevel && update[i][i] == x; i++)
{
update[i][i] = x[i];
}
// Update list level.
while(currentLevel > 1 && header[currentLevel - 1] == null)
{
currentLevel--;
}
// Keep track of the number of elements in the PriorityQueue.
count--;
version++;
}
#region Invariant
AssertValid();
#endregion
}
/// <summary>
/// Returns a value indicating whether the specified element is in the
/// PriorityQueue.
/// </summary>
/// <param name="element">
/// The element to test.
/// </param>
/// <returns>
/// <b>true</b> if the element is in the PriorityQueue; otherwise
/// <b>false</b>.
/// </returns>
public virtual bool Contains(object element)
{
#region Guard
if(element == null)
{
return false;
}
#endregion
bool found;
Node x = header;
// Find the specified element.
for(int i = currentLevel - 1; i >= 0; i--)
{
while(x[i] != null && comparer.Compare(x[i].Element, element) > 0)
{
x = x[i];
}
}
x = x[0];
// If the element is in the PriorityQueue.
if(x != null && comparer.Compare(x.Element, element) == 0)
{
found = true;
}
// Else the element is not in the PriorityQueue.
else
{
found = false;
}
return found;
}
/// <summary>
/// Returns the element at the head of the PriorityQueue without
/// removing it.
/// </summary>
/// <returns>
/// The element at the head of the PriorityQueue.
/// </returns>
public virtual object Peek()
{
#region Require
if(Count == 0)
{
throw new InvalidOperationException(
"Cannot peek into an empty PriorityQueue.");
}
#endregion
return header[0].Element;
}
/// <summary>
/// Removes all elements from the PriorityQueue.
/// </summary>
public virtual void Clear()
{
header = new Node(null, LevelMaxValue);
currentLevel = 1;
count = 0;
version++;
#region Invariant
AssertValid();
#endregion
}
/// <summary>
/// Returns a synchronized wrapper of the specified PriorityQueue.
/// </summary>
/// <param name="queue">
/// The PriorityQueue to synchronize.
/// </param>
/// <returns>
/// A synchronized PriorityQueue.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If queue is null.
/// </exception>
public static PriorityQueue Synchronized(PriorityQueue queue)
{
#region Require
if(queue == null)
{
throw new ArgumentNullException("queue");
}
#endregion
return new SynchronizedPriorityQueue(queue);
}
// Generates a random level for the next node.
private int NextLevel()
{
int nextLevel = 1;
while(rand.NextDouble() < Probability &&
nextLevel < LevelMaxValue &&
nextLevel <= currentLevel)
{
nextLevel++;
}
return nextLevel;
}
// Makes sure none of the PriorityQueue's invariants have been violated.
[Conditional("DEBUG")]
private void AssertValid()
{
int n = 0;
Node x = header[0];
while(x != null)
{
if(x[0] != null)
{
Debug.Assert(comparer.Compare(x.Element, x[0].Element) >= 0, "Order test");
}
x = x[0];
n++;
}
Debug.Assert(n == Count, "Count test.");
for(int i = 1; i < currentLevel; i++)
{
Debug.Assert(header[i] != null, "Level non-null test.");
}
for(int i = currentLevel; i < LevelMaxValue; i++)
{
Debug.Assert(header[i] == null, "Level null test.");
}
}
[Conditional("DEBUG")]
public static void Test()
{
Random r = new Random();
PriorityQueue queue = new PriorityQueue();
int count = 1000;
int element;
for(int i = 0; i < count; i++)
{
element = r.Next();
queue.Enqueue(element);
Debug.Assert(queue.Contains(element), "Contains Test");
}
Debug.Assert(queue.Count == count, "Count Test");
int previousElement = (int)queue.Peek();
int peekElement;
for(int i = 0; i < count; i++)
{
peekElement = (int)queue.Peek();
element = (int)queue.Dequeue();
Debug.Assert(element == peekElement, "Peek Test");
Debug.Assert(element <= previousElement, "Order Test");
previousElement = element;
}
Debug.Assert(queue.Count == 0);
}
#endregion
#region Private Classes
#region SynchronizedPriorityQueue Class
// A synchronized wrapper for the PriorityQueue class.
private class SynchronizedPriorityQueue : PriorityQueue
{
private PriorityQueue queue;
private object root;
public SynchronizedPriorityQueue(PriorityQueue queue)
{
#region Require
if(queue == null)
{
throw new ArgumentNullException("queue");
}
#endregion
this.queue = queue;
root = queue.SyncRoot;
}
public override void Enqueue(object element)
{
lock(root)
{
queue.Enqueue(element);
}
}
public override object Dequeue()
{
lock(root)
{
return queue.Dequeue();
}
}
public override void Remove(object element)
{
lock(root)
{
queue.Remove(element);
}
}
public override void Clear()
{
lock(root)
{
queue.Clear();
}
}
public override bool Contains(object element)
{
lock(root)
{
return queue.Contains(element);
}
}
public override object Peek()
{
lock(root)
{
return queue.Peek();
}
}
public override void CopyTo(Array array, int index)
{
lock(root)
{
queue.CopyTo(array, index);
}
}
public override int Count
{
get
{
lock(root)
{
return queue.Count;
}
}
}
public override bool IsSynchronized
{
get
{
return true;
}
}
public override object SyncRoot
{
get
{
return root;
}
}
public override IEnumerator GetEnumerator()
{
lock(root)
{
return queue.GetEnumerator();
}
}
}
#endregion
#region DefaultComparer Class
// The IComparer to use of no comparer was provided.
private class DefaultComparer : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
#region Require
if(!(y is IComparable))
{
throw new ArgumentException(
"Item does not implement IComparable.");
}
#endregion
IComparable a = x as IComparable;
Debug.Assert(a != null);
return a.CompareTo(y);
}
#endregion
}
#endregion
#region Node Class
// Represents a node in the list of nodes.
private class Node
{
private Node[] forward;
private object element;
public Node(object element, int level)
{
this.forward = new Node[level];
this.element = element;
}
public Node this[int index]
{
get
{
return forward[index];
}
set
{
forward[index] = value;
}
}
public object Element
{
get
{
return element;
}
}
}
#endregion
#region PriorityQueueEnumerator Class
// Implements the IEnumerator interface for the PriorityQueue class.
private class PriorityQueueEnumerator : IEnumerator
{
private PriorityQueue owner;
private Node head;
private Node currentNode;
private bool moveResult;
private long version;
public PriorityQueueEnumerator(PriorityQueue owner)
{
this.owner = owner;
this.version = owner.version;
head = owner.header;
Reset();
}
#region IEnumerator Members
public void Reset()
{
#region Require
if(version != owner.version)
{
throw new InvalidOperationException(
"The PriorityQueue was modified after the enumerator was created.");
}
#endregion
currentNode = head;
moveResult = true;
}
public object Current
{
get
{
#region Require
if(currentNode == head || currentNode == null)
{
throw new InvalidOperationException(
"The enumerator is positioned before the first " +
"element of the collection or after the last element.");
}
#endregion
return currentNode.Element;
}
}
public bool MoveNext()
{
#region Require
if(version != owner.version)
{
throw new InvalidOperationException(
"The PriorityQueue was modified after the enumerator was created.");
}
#endregion
if(moveResult)
{
currentNode = currentNode[0];
}
if(currentNode == null)
{
moveResult = false;
}
return moveResult;
}
#endregion
}
#endregion
#endregion
#endregion
#region ICollection Members
public virtual bool IsSynchronized
{
get
{
return false;
}
}
public virtual int Count
{
get
{
return count;
}
}
public virtual void CopyTo(Array array, int index)
{
#region Require
if(array == null)
{
throw new ArgumentNullException("array");
}
else if(index < 0)
{
throw new ArgumentOutOfRangeException("index", index,
"Array index out of range.");
}
else if(array.Rank > 1)
{
throw new ArgumentException(
"Array has more than one dimension.", "array");
}
else if(index >= array.Length)
{
throw new ArgumentException(
"index is equal to or greater than the length of array.", "index");
}
else if(Count > array.Length - index)
{
throw new ArgumentException(
"The number of elements in the PriorityQueue is greater " +
"than the available space from index to the end of the " +
"destination array.", "index");
}
#endregion
int i = index;
foreach(object element in this)
{
array.SetValue(element, i);
i++;
}
}
public virtual object SyncRoot
{
get
{
return this;
}
}
#endregion
#region IEnumerable Members
public virtual IEnumerator GetEnumerator()
{
return new PriorityQueueEnumerator(this);
}
#endregion
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Math.Raw;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Math.EC.Custom.Djb
{
internal class Curve25519FieldElement
: ECFieldElement
{
public static readonly BigInteger Q = Curve25519.q;
// Calculated as ECConstants.TWO.modPow(Q.shiftRight(2), Q)
private static readonly uint[] PRECOMP_POW2 = new uint[]{ 0x4a0ea0b0, 0xc4ee1b27, 0xad2fe478, 0x2f431806,
0x3dfbd7a7, 0x2b4d0099, 0x4fc1df0b, 0x2b832480 };
protected internal readonly uint[] x;
public Curve25519FieldElement(BigInteger x)
{
if (x == null || x.SignValue < 0 || x.CompareTo(Q) >= 0)
throw new ArgumentException("value invalid for Curve25519FieldElement", "x");
this.x = Curve25519Field.FromBigInteger(x);
}
public Curve25519FieldElement()
{
this.x = Nat256.Create();
}
protected internal Curve25519FieldElement(uint[] x)
{
this.x = x;
}
public override bool IsZero
{
get { return Nat256.IsZero(x); }
}
public override bool IsOne
{
get { return Nat256.IsOne(x); }
}
public override bool TestBitZero()
{
return Nat256.GetBit(x, 0) == 1;
}
public override BigInteger ToBigInteger()
{
return Nat256.ToBigInteger(x);
}
public override string FieldName
{
get { return "Curve25519Field"; }
}
public override int FieldSize
{
get { return Q.BitLength; }
}
public override ECFieldElement Add(ECFieldElement b)
{
uint[] z = Nat256.Create();
Curve25519Field.Add(x, ((Curve25519FieldElement)b).x, z);
return new Curve25519FieldElement(z);
}
public override ECFieldElement AddOne()
{
uint[] z = Nat256.Create();
Curve25519Field.AddOne(x, z);
return new Curve25519FieldElement(z);
}
public override ECFieldElement Subtract(ECFieldElement b)
{
uint[] z = Nat256.Create();
Curve25519Field.Subtract(x, ((Curve25519FieldElement)b).x, z);
return new Curve25519FieldElement(z);
}
public override ECFieldElement Multiply(ECFieldElement b)
{
uint[] z = Nat256.Create();
Curve25519Field.Multiply(x, ((Curve25519FieldElement)b).x, z);
return new Curve25519FieldElement(z);
}
public override ECFieldElement Divide(ECFieldElement b)
{
//return Multiply(b.Invert());
uint[] z = Nat256.Create();
Mod.Invert(Curve25519Field.P, ((Curve25519FieldElement)b).x, z);
Curve25519Field.Multiply(z, x, z);
return new Curve25519FieldElement(z);
}
public override ECFieldElement Negate()
{
uint[] z = Nat256.Create();
Curve25519Field.Negate(x, z);
return new Curve25519FieldElement(z);
}
public override ECFieldElement Square()
{
uint[] z = Nat256.Create();
Curve25519Field.Square(x, z);
return new Curve25519FieldElement(z);
}
public override ECFieldElement Invert()
{
//return new Curve25519FieldElement(ToBigInteger().ModInverse(Q));
uint[] z = Nat256.Create();
Mod.Invert(Curve25519Field.P, x, z);
return new Curve25519FieldElement(z);
}
/**
* return a sqrt root - the routine verifies that the calculation returns the right value - if
* none exists it returns null.
*/
public override ECFieldElement Sqrt()
{
/*
* Q == 8m + 5, so we use Pocklington's method for this case.
*
* First, raise this element to the exponent 2^252 - 2^1 (i.e. m + 1)
*
* Breaking up the exponent's binary representation into "repunits", we get:
* { 251 1s } { 1 0s }
*
* Therefore we need an addition chain containing 251 (the lengths of the repunits)
* We use: 1, 2, 3, 4, 7, 11, 15, 30, 60, 120, 131, [251]
*/
uint[] x1 = this.x;
if (Nat256.IsZero(x1) || Nat256.IsOne(x1))
return this;
uint[] x2 = Nat256.Create();
Curve25519Field.Square(x1, x2);
Curve25519Field.Multiply(x2, x1, x2);
uint[] x3 = x2;
Curve25519Field.Square(x2, x3);
Curve25519Field.Multiply(x3, x1, x3);
uint[] x4 = Nat256.Create();
Curve25519Field.Square(x3, x4);
Curve25519Field.Multiply(x4, x1, x4);
uint[] x7 = Nat256.Create();
Curve25519Field.SquareN(x4, 3, x7);
Curve25519Field.Multiply(x7, x3, x7);
uint[] x11 = x3;
Curve25519Field.SquareN(x7, 4, x11);
Curve25519Field.Multiply(x11, x4, x11);
uint[] x15 = x7;
Curve25519Field.SquareN(x11, 4, x15);
Curve25519Field.Multiply(x15, x4, x15);
uint[] x30 = x4;
Curve25519Field.SquareN(x15, 15, x30);
Curve25519Field.Multiply(x30, x15, x30);
uint[] x60 = x15;
Curve25519Field.SquareN(x30, 30, x60);
Curve25519Field.Multiply(x60, x30, x60);
uint[] x120 = x30;
Curve25519Field.SquareN(x60, 60, x120);
Curve25519Field.Multiply(x120, x60, x120);
uint[] x131 = x60;
Curve25519Field.SquareN(x120, 11, x131);
Curve25519Field.Multiply(x131, x11, x131);
uint[] x251 = x11;
Curve25519Field.SquareN(x131, 120, x251);
Curve25519Field.Multiply(x251, x120, x251);
uint[] t1 = x251;
Curve25519Field.Square(t1, t1);
uint[] t2 = x120;
Curve25519Field.Square(t1, t2);
if (Nat256.Eq(x1, t2))
{
return new Curve25519FieldElement(t1);
}
/*
* If the first guess is incorrect, we multiply by a precomputed power of 2 to get the second guess,
* which is ((4x)^(m + 1))/2 mod Q
*/
Curve25519Field.Multiply(t1, PRECOMP_POW2, t1);
Curve25519Field.Square(t1, t2);
if (Nat256.Eq(x1, t2))
{
return new Curve25519FieldElement(t1);
}
return null;
}
public override bool Equals(object obj)
{
return Equals(obj as Curve25519FieldElement);
}
public override bool Equals(ECFieldElement other)
{
return Equals(other as Curve25519FieldElement);
}
public virtual bool Equals(Curve25519FieldElement other)
{
if (this == other)
return true;
if (null == other)
return false;
return Nat256.Eq(x, other.x);
}
public override int GetHashCode()
{
return Q.GetHashCode() ^ Arrays.GetHashCode(x, 0, 8);
}
}
}
#endif
| |
/*
* Copyright (C) 2007-2014 ARGUS TV
* http://www.argus-tv.com
*
* 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, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Make; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
using System;
using System.Collections.Generic;
namespace ArgusTV.DataContracts
{
/// <summary>
/// An upcoming recording.
/// </summary>
public partial class UpcomingRecording : IProgramSummary
{
/// <summary>
/// Default constructor.
/// </summary>
public UpcomingRecording()
{
this.ConflictingPrograms = new List<Guid>();
}
/// <summary>
/// The card that was allocated for the required channel. If this is null the program
/// has not been allocated and won't be recorded.
/// </summary>
public CardChannelAllocation CardChannelAllocation { get; set;}
/// <summary>
/// The program that will be recorded.
/// </summary>
public UpcomingProgram Program { get; set; }
/// <summary>
/// The list of programs that this program conflicts with. If CardChannelAllocation is
/// null these are the programs that block the recording of this program, otherwise
/// these are the programs that are blocked by this recording.
/// </summary>
public List<Guid> ConflictingPrograms { get; set; }
/// <summary>
/// The actual start time of the recording. This overrules ActualStartTime in the
/// Program and may contain a different time.
/// </summary>
public DateTime ActualStartTime { get; set; }
/// <summary>
/// The actual stop time of the recording. This overrules ActualStopTime in the
/// Program and may contain a different time.
/// </summary>
public DateTime ActualStopTime { get; set; }
/// <summary>
/// The actual start time of the recording (UTC). This overrules ActualStartTime in the
/// Program and may contain a different time.
/// </summary>
public DateTime ActualStartTimeUtc { get; set; }
/// <summary>
/// The actual stop time of the recording (UTC). This overrules ActualStopTime in the
/// Program and may contain a different time.
/// </summary>
public DateTime ActualStopTimeUtc { get; set; }
#region IProgramSummary Members
/// <summary>
/// The program's title.
/// </summary>
public string Title
{
get { return this.Program.Title; }
set { this.Program.Title = value; }
}
/// <summary>
/// The program's start time.
/// </summary>
public DateTime StartTime
{
get { return this.Program.StartTime; }
set { this.Program.StartTime = value; }
}
/// <summary>
/// The program's stop time.
/// </summary>
public DateTime StopTime
{
get { return this.Program.StopTime; }
set { this.Program.StopTime = value; }
}
/// <summary>
/// The program's start time (UTC).
/// </summary>
public DateTime StartTimeUtc
{
get { return this.Program.StartTimeUtc; }
set { this.Program.StartTimeUtc = value; }
}
/// <summary>
/// The program's stop time (UTC).
/// </summary>
public DateTime StopTimeUtc
{
get { return this.Program.StopTimeUtc; }
set { this.Program.StopTimeUtc = value; }
}
/// <summary>
/// The program's episode title.
/// </summary>
public string SubTitle
{
get { return this.Program.SubTitle; }
set { this.Program.SubTitle = value; }
}
/// <summary>
/// The program's category.
/// </summary>
public string Category
{
get { return this.Program.Category; }
set { this.Program.Category = value; }
}
/// <summary>
/// Is this program a repeat?
/// </summary>
public bool IsRepeat
{
get { return this.Program.IsRepeat; }
set { this.Program.IsRepeat = value; }
}
/// <summary>
/// Is this program a premiere?
/// </summary>
public bool IsPremiere
{
get { return this.Program.IsPremiere; }
set { this.Program.IsPremiere = value; }
}
/// <summary>
/// The program's flags defining things like aspect ratio, SD or HD,...
/// </summary>
public GuideProgramFlags Flags
{
get { return this.Program.Flags; }
set { this.Program.Flags = value; }
}
/// <summary>
/// A string to display the episode number in a UI.
/// </summary>
public string EpisodeNumberDisplay
{
get { return this.Program.EpisodeNumberDisplay; }
set { this.Program.EpisodeNumberDisplay = value; }
}
/// <summary>
/// The parental rating of the program.
/// </summary>
public string Rating
{
get { return this.Program.Rating; }
set { this.Program.Rating = value; }
}
/// <summary>
/// If set, a star-rating of the program, normalized to a value between 0 and 1.
/// </summary>
public double? StarRating
{
get { return this.Program.StarRating; }
set { this.Program.StarRating = value; }
}
/// <summary>
/// Create a single string containing the full program title (with episode information).
/// </summary>
/// <returns>A string with the full program title.</returns>
public string CreateProgramTitle()
{
return this.Program.CreateProgramTitle();
}
/// <summary>
/// Create a single string with episode information (episode title and/or number).
/// </summary>
/// <returns>A string with all episode information.</returns>
public string CreateEpisodeTitle()
{
return this.Program.CreateEpisodeTitle();
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
namespace Spiffy.Monitoring
{
partial class EventContext : ITimedContext
{
const string TimeElapsedKey = "TimeElapsed";
public EventContext(string component, string operation)
{
GlobalEventContext.Instance.CopyTo(this);
_timestamp = DateTime.UtcNow;
SetToInfo();
Initialize(component, operation);
// reserve this spot for later...
this[TimeElapsedKey] = 0;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public EventContext() : this(null, null)
{
string component = "[Unknown]";
string operation = "[Unknown]";
StackFrame stackFrame = null;
var stackTrace = (StackTrace)Activator.CreateInstance(typeof(StackTrace));
var frames = stackTrace.GetFrames();
foreach (var f in frames)
{
var assembly = f.GetMethod().DeclaringType?.GetTypeInfo().Assembly;
if (assembly != null && !FrameworkAssembly(assembly))
{
stackFrame = f;
break;
}
}
var method = stackFrame?.GetMethod();
if (method != null)
{
var declaringType = method.DeclaringType;
if (declaringType != null)
{
component = declaringType.Name;
}
operation = method.Name;
}
Initialize(component, operation);
}
public double ElapsedMilliseconds => _timer.ElapsedMilliseconds;
bool FrameworkAssembly(Assembly assembly)
{
return assembly == AssemblyFor<object>() ||
assembly == AssemblyFor<EventContext>();
}
Assembly AssemblyFor<T>()
{
return typeof(T).GetTypeInfo().Assembly;
}
public string Component { get; private set; }
public string Operation { get; private set; }
public Level Level { get; private set; }
readonly Dictionary<string, object> _values = new Dictionary<string, object>();
readonly Dictionary<string, uint> _counts = new Dictionary<string, uint>();
readonly object _valuesSyncObject = new object();
readonly object _countsSyncObject = new object();
readonly DateTime _timestamp;
readonly AutoTimer _timer = new AutoTimer();
public IDisposable Time(string key)
{
return Timers.Accumulate(key);
}
public TimerCollection Timers { get; } = new TimerCollection();
public void Count(string key)
{
lock (_countsSyncObject)
{
if (_counts.ContainsKey(key))
{
_counts[key]++;
}
else
{
_counts[key] = 1;
}
}
}
public object this[string key]
{
get
{
lock (_valuesSyncObject)
{
return _values[key];
}
}
set
{
lock (_valuesSyncObject)
{
_values[key] = value;
}
}
}
/// <summary>
/// Data that is attached to the EventContext but is not published. This could be useful for
/// stashing relevant contextual information, e.g. metric labels.
/// </summary>
public ConcurrentDictionary<string, string> PrivateData { get; } = new ConcurrentDictionary<string, string>();
public void AddValues(params KeyValuePair<string, object>[] values)
{
lock (_valuesSyncObject)
{
foreach (var kvp in values)
{
_values[kvp.Key] = kvp.Value;
}
}
}
public void AddValues(IEnumerable<KeyValuePair<string, object>> values)
{
AddValues(values.ToArray());
}
public bool Contains(string key)
{
lock (_valuesSyncObject)
{
return _values.ContainsKey(key);
}
}
public void AppendToValue(string key, string content, string delimiter)
{
lock (_valuesSyncObject)
{
if (_values.ContainsKey(key))
{
_values[key] = string.Join(delimiter, _values[key].ToString(), content);
}
else
{
_values.Add(key, content);
}
}
}
public void SetLevel(Level level)
{
this["Level"] = Level = level;
}
public void SetToInfo()
{
SetLevel(Level.Info);
}
public void SetToError(string reason = null)
{
SetLevel(Level.Error);
if (reason != null)
{
this["ErrorReason"] = reason;
}
}
public void SetToWarning(string reason = null)
{
SetLevel(Level.Warning);
if (reason != null)
{
this["WarningReason"] = reason;
}
}
public bool IsSuppressed { get; private set; }
public void Suppress()
{
IsSuppressed = true;
}
volatile bool _disposed = false;
public void Dispose()
{
if (!_disposed)
{
if(!IsSuppressed)
{
var logActions = Configuration.GetLoggingActions();
if (logActions.Any())
{
var logEvent = Render();
foreach (var logAction in logActions)
{
try
{
logAction(logEvent);
}
// ReSharper disable once EmptyGeneralCatchClause -- intentionally squashed
catch
{
}
}
}
}
_disposed = true;
}
}
public void Initialize(string component, string operation)
{
Component = component;
Operation = operation;
this["Component"] = Component;
this["Operation"] = Operation;
}
private LogEvent Render()
{
Dictionary<string, string> kvps;
lock (_valuesSyncObject)
{
kvps = _values.ToDictionary(
kvp => kvp.Key,
kvp => GetValue(kvp.Value));
}
foreach (var kvp in GetCountValues())
{
kvps.Add(kvp.Key, kvp.Value);
}
foreach (var kvp in GetTimeValues())
{
kvps.Add(kvp.Key, kvp.Value);
}
GenerateKeysIfNecessary(kvps);
ReplaceKeysThatHaveWhiteSpace(kvps);
ReplaceKeysThatHaveDots(kvps);
EncapsulateValuesIfNecessary(kvps);
var timeElapsedMs = _timer.ElapsedMilliseconds;
var formattedTimeElapsed = GetTimeFor(timeElapsedMs);
this[TimeElapsedKey] = formattedTimeElapsed;
kvps[TimeElapsedKey] = formattedTimeElapsed;
return new LogEvent(
Level,
_timestamp,
TimeSpan.FromMilliseconds(timeElapsedMs),
GetSplunkFormattedTime(),
GetKeyValuePairsAsDelimitedString(kvps),
kvps,
PrivateData);
}
private static void EncapsulateValuesIfNecessary(Dictionary<string, string> keyValuePairs)
{
foreach (var kvp in keyValuePairs
.Where(k => !k.Value.StartsWithQuote() && (
k.Value.ContainsWhiteSpace() ||
k.Value.Contains(',') ||
k.Value.Contains('&')))
.ToList())
{
keyValuePairs[kvp.Key] = kvp.Value.WrappedInQuotes();
}
}
private static void ReplaceKeysThatHaveWhiteSpace(Dictionary<string, string> keyValuePairs)
{
foreach (var kvp in keyValuePairs
.Where(k => k.Key.ContainsWhiteSpace())
.ToList())
{
keyValuePairs.Remove(kvp.Key);
keyValuePairs[kvp.Key.RemoveWhiteSpace()] = kvp.Value;
}
}
private static void ReplaceKeysThatHaveDots(Dictionary<string, string> keyValuePairs)
{
foreach (var kvp in keyValuePairs
.Where(k => k.Key.Contains("."))
.ToList())
{
keyValuePairs.Remove(kvp.Key);
keyValuePairs[kvp.Key.Replace(".", "_")] = kvp.Value;
}
}
private void GenerateKeysIfNecessary(Dictionary<string, string> keyValuePairs)
{
foreach (var kvp in keyValuePairs
.Where(k => k.Key.IsNullOrWhiteSpace())
.ToList())
{
keyValuePairs.Remove(kvp.Key);
keyValuePairs[string.Format("GeneratedKey({0})", Guid.NewGuid())] = kvp.Value;
}
}
private static string GetKeyValuePairsAsDelimitedString(Dictionary<string, string> keyValuePairs)
{
return string.Join(" ", keyValuePairs
.OrderBy(pair => pair.Value.Length <= Configuration.DeprioritizedValueLength ? 0 : 1)
.Select(kvp =>
string.Format("{0}={1}", kvp.Key, kvp.Value)).ToArray());
}
private static string GetValue(object value)
{
if (value == null)
{
return "{null}";
}
var valueStr = value.ToString();
// there are a certain few fields that Splunk chokes on in values.
// escape them individually to minimize visual noise (as opposed to doing a full encode)
valueStr = valueStr.Replace("=", ":");
valueStr = valueStr.Replace("\"", "''");
if (Configuration.RemoveNewLines)
{
valueStr = valueStr
.Replace("\r", String.Empty)
.Replace("\n", "\\n");
}
return valueStr;
}
private string GetSplunkFormattedTime()
{
return _timestamp.ToString("yyyy-MM-dd HH:mm:ss.fffK").WrappedInBrackets();
}
private IEnumerable<KeyValuePair<string, string>> GetCountValues()
{
var counts = new Dictionary<string, string>();
lock (_countsSyncObject)
{
foreach (var kvp in _counts)
{
counts[$"{kvp.Key}"] = kvp.Value.ToString();
}
}
return counts;
}
private IEnumerable<KeyValuePair<string, string>> GetTimeValues()
{
var times = new Dictionary<string, string>();
foreach (var kvp in Timers.ShallowClone())
{
times[$"{TimeElapsedKey}_{kvp.Key}"] = GetTimeFor(kvp.Value.ElapsedMilliseconds);
if (kvp.Value.Count > 1)
{
times[$"Count_{kvp.Key}"] = kvp.Value.Count.ToString();
}
}
return times;
}
private static string GetTimeFor(double milliseconds)
{
return $"{milliseconds:F1}";
}
}
}
| |
// 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.Threading.Tasks;
namespace System.Net.Sockets
{
// The System.Net.Sockets.TcpClient class provide TCP services at a higher level
// of abstraction than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpClient
// is used to create a Client connection to a remote host.
public partial class TcpClient : IDisposable
{
private readonly AddressFamily _family;
private Socket _clientSocket;
private NetworkStream _dataStream;
private bool _cleanedUp = false;
private bool _active;
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient() : this(AddressFamily.InterNetwork)
{
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient(AddressFamily family)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpClient", family);
}
// Validate parameter
if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "TCP"), nameof(family));
}
_family = family;
InitializeClientSocket();
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpClient", null);
}
}
// Used by TcpListener.Accept().
internal TcpClient(Socket acceptedSocket)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpClient", acceptedSocket);
}
_clientSocket = acceptedSocket;
_active = true;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpClient", null);
}
}
// Used by the class to indicate that a connection has been made.
protected bool Active
{
get { return _active; }
set { _active = value; }
}
public int Available { get { return AvailableCore; } }
// Used by the class to provide the underlying network socket.
[DebuggerBrowsable(DebuggerBrowsableState.Never)] // TODO: Remove once https://github.com/dotnet/corefx/issues/5868 is addressed.
public Socket Client
{
get
{
Socket s = ClientCore;
Debug.Assert(s != null);
return s;
}
set
{
ClientCore = value;
}
}
public bool Connected { get { return ConnectedCore; } }
public bool ExclusiveAddressUse
{
get { return ExclusiveAddressUseCore; }
set { ExclusiveAddressUseCore = value; }
}
public Task ConnectAsync(IPAddress address, int port)
{
return Task.Factory.FromAsync(
(targetAddess, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddess, targetPort, callback, state),
asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
address,
port,
state: this);
}
public Task ConnectAsync(string host, int port)
{
return ConnectAsyncCore(host, port);
}
public Task ConnectAsync(IPAddress[] addresses, int port)
{
return ConnectAsyncCore(addresses, port);
}
private IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "BeginConnect", address);
}
IAsyncResult result = Client.BeginConnect(address, port, requestCallback, state);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "BeginConnect", null);
}
return result;
}
private void EndConnect(IAsyncResult asyncResult)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "EndConnect", asyncResult);
}
Client.EndConnect(asyncResult);
_active = true;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "EndConnect", null);
}
}
// Returns the stream used to read and write data to the remote host.
public NetworkStream GetStream()
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "GetStream", "");
}
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (!Connected)
{
throw new InvalidOperationException(SR.net_notconnected);
}
if (_dataStream == null)
{
_dataStream = new NetworkStream(Client, true);
}
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "GetStream", _dataStream);
}
return _dataStream;
}
// Disposes the Tcp connection.
protected virtual void Dispose(bool disposing)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "Dispose", "");
}
if (_cleanedUp)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Dispose", "");
}
return;
}
if (disposing)
{
IDisposable dataStream = _dataStream;
if (dataStream != null)
{
dataStream.Dispose();
}
else
{
// If the NetworkStream wasn't created, the Socket might
// still be there and needs to be closed. In the case in which
// we are bound to a local IPEndPoint this will remove the
// binding and free up the IPEndPoint for later uses.
Socket chkClientSocket = _clientSocket;
if (chkClientSocket != null)
{
try
{
chkClientSocket.InternalShutdown(SocketShutdown.Both);
}
finally
{
chkClientSocket.Dispose();
_clientSocket = null;
}
}
}
GC.SuppressFinalize(this);
}
_cleanedUp = true;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Dispose", "");
}
}
public void Dispose()
{
Dispose(true);
}
~TcpClient()
{
#if DEBUG
GlobalLog.SetThreadSource(ThreadKinds.Finalization);
using (GlobalLog.SetThreadKind(ThreadKinds.System | ThreadKinds.Async))
{
#endif
Dispose(false);
#if DEBUG
}
#endif
}
// Gets or sets the size of the receive buffer in bytes.
public int ReceiveBufferSize
{
get { return ReceiveBufferSizeCore; }
set { ReceiveBufferSizeCore = value; }
}
// Gets or sets the size of the send buffer in bytes.
public int SendBufferSize
{
get { return SendBufferSizeCore; }
set { SendBufferSizeCore = value; }
}
// Gets or sets the receive time out value of the connection in milliseconds.
public int ReceiveTimeout
{
get { return ReceiveTimeoutCore; }
set { ReceiveTimeoutCore = value; }
}
// Gets or sets the send time out value of the connection in milliseconds.
public int SendTimeout
{
get { return SendTimeoutCore; }
set { SendTimeoutCore = value; }
}
// Gets or sets the value of the connection's linger option.
public LingerOption LingerState
{
get { return LingerStateCore; }
set { LingerStateCore = value; }
}
// Enables or disables delay when send or receive buffers are full.
public bool NoDelay
{
get { return NoDelayCore; }
set { NoDelayCore = value; }
}
private Socket CreateSocket()
{
return new Socket(_family, SocketType.Stream, ProtocolType.Tcp);
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Runtime
{
using System;
using System.Runtime.CompilerServices;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
[ExtendClass(typeof(System.String))]
public class StringImpl
{
//
// State
//
//
// Aliasing to mark fields in mscorlib as well-known.
//
#pragma warning disable 649
[TS.AssumeReferenced] [TS.WellKnownField( "StringImpl_ArrayLength" )] [AliasForBaseField] internal int m_arrayLength;
[TS.AssumeReferenced] [TS.WellKnownField( "StringImpl_StringLength" )] [AliasForBaseField] internal int m_stringLength;
[TS.AssumeReferenced] [TS.WellKnownField( "StringImpl_FirstChar" )] [AliasForBaseField] internal char m_firstChar;
#pragma warning restore 649
//
// Constructor Methods
//
[DiscardTargetImplementation]
[TS.WellKnownMethod( "StringImpl_ctor_charArray_int_int" )]
public unsafe StringImpl( char[] value ,
int startIndex ,
int length )
{
//// BCLDebug.Assert( startIndex >= 0 && startIndex <= this.Length , "StartIndex is out of range!" );
//// BCLDebug.Assert( length >= 0 && startIndex <= this.Length - length, "length is out of range!" );
if(length < 0 || length > m_stringLength ||
startIndex < 0 || (startIndex + length) > value.Length )
{
ThreadImpl.ThrowIndexOutOfRangeException();
}
if(length > 0)
{
fixed(char* dest = &this.m_firstChar)
{
fixed(char* src = &value[startIndex])
{
wstrcpy( dest, src, length );
}
}
}
}
[DiscardTargetImplementation]
[TS.WellKnownMethod( "StringImpl_ctor_charArray" )]
public StringImpl( char[] value ) : this( value, 0, value.Length )
{
}
[DiscardTargetImplementation]
[TS.WellKnownMethod( "StringImpl_ctor_char_int" )]
public unsafe StringImpl( char c ,
int count )
{
if(count < 0 || count > m_stringLength)
{
ThreadImpl.ThrowIndexOutOfRangeException();
}
fixed(char* dest = &this.m_firstChar)
{
char* ptr = dest;
while(--count >= 0)
{
*ptr++ = c;
}
}
}
//--//
//
// Helper Methods
//
[TS.WellKnownMethod( "StringImpl_FastAllocateString" )]
private static StringImpl FastAllocateString( int length )
{
StringImpl res = (StringImpl)(object)TypeSystemManager.Instance.AllocateString( TS.VTable.GetFromType( typeof(string) ), length + 1 );
res.m_stringLength = length;
return res;
}
//
// Aliasing to mark methods in mscorlib as well-known.
//
public unsafe int LastIndexOf( char value, int startIndex, int count )
{
int retVal = -1;
if(m_stringLength == 0 ) return -1;
if(startIndex < 0 ) throw new ArgumentOutOfRangeException();
if(count < 0 ) throw new ArgumentOutOfRangeException();
if(startIndex >= m_stringLength) throw new ArgumentOutOfRangeException();
if(count > startIndex + 1) throw new ArgumentOutOfRangeException();
int end = startIndex - count + 1;
fixed(char* ptr = (string)(object)this)
{
for(int index = startIndex; index >= end; index--)
{
if(ptr[index] == value)
{
retVal = index;
break;
}
}
}
return retVal;
}
public unsafe int IndexOf( char value, int startIndex, int count )
{
int retVal = -1;
if(m_stringLength == 0 ) return -1;
if(startIndex < 0 ) throw new ArgumentOutOfRangeException();
if(count < 0 ) throw new ArgumentOutOfRangeException();
if(startIndex + count > m_stringLength) throw new ArgumentOutOfRangeException();
int end = count + startIndex;
fixed(char* ptr = (string)(object)this)
{
for(int index = startIndex; index < end; index++)
{
if(ptr[index] == value)
{
retVal = index;
break;
}
}
}
return retVal;
}
public unsafe int IndexOfAny( char[] anyOf, int startIndex, int count )
{
if(startIndex + count > m_stringLength) throw new IndexOutOfRangeException();
UInt64[] mask = new UInt64[2];
char minC = char.MaxValue, maxC = char.MinValue;
int minIdx = startIndex, maxIdx = startIndex + count - 1;
int cAny = anyOf.Length;
for(int i = cAny; --i >= 0; )
{
char c = anyOf[i];
if(c < minC) minC = c;
if(c > maxC) maxC = c;
if(c < 128)
{
if(c < 64) mask[0] |= 1ul << c;
else mask[1] |= 1ul << ( c - 64 );
}
}
fixed(char* pS = (string)(object)this)
{
count += startIndex;
for(int i = startIndex; i < count; i++)
{
char c = pS[i];
if(c == minC) return i;
if(c == maxC) return i;
if(c > minC && c < maxC)
{
if(c < 128)
{
if(c < 64) { if(0 != ( mask[0] & 1ul << c )) return i; }
else { if(0 != ( mask[1] & 1ul << ( c - 64 ) )) return i; }
}
else
{
for(int j = cAny; --j >= 0; )
{
if(c == anyOf[j])
{
return i + startIndex;
}
}
}
}
}
}
return -1;
}
//
// Aliasing to access private methods in mscorlib.
//
[AliasForBaseMethod( "wstrcpy" )]
[MethodImpl( MethodImplOptions.InternalCall )]
private static extern unsafe void wstrcpy( char* dmem, char* smem, int charCount );
//--//
//
// This is used to cast between an object and and ArrayImpl, which is not possible in C#.
//
[TS.GenerateUnsafeCast]
internal extern static StringImpl CastAsString( object target );
//
// This is used to cast between an object and and ArrayImpl, which is not possible in C#.
//
[TS.GenerateUnsafeCast]
internal extern String CastThisAsString();
//--//
//
// Access Methods
//
[System.Runtime.CompilerServices.IndexerName( "Chars" )]
public unsafe char this[int index]
{
get
{
if(index >= 0 && index < m_stringLength)
{
fixed(char* ptr = (string)(object)this)
{
return ptr[index];
}
}
throw new IndexOutOfRangeException();
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Xml.Linq;
class DynamicActivityTypeDescriptor : ICustomTypeDescriptor
{
PropertyDescriptorCollection cachedProperties;
Activity owner;
public DynamicActivityTypeDescriptor(Activity owner)
{
this.owner = owner;
this.Properties = new ActivityPropertyCollection(this);
}
public string Name
{
get;
set;
}
public KeyedCollection<string, DynamicActivityProperty> Properties
{
get;
private set;
}
public AttributeCollection GetAttributes()
{
return TypeDescriptor.GetAttributes(this.owner, true);
}
public string GetClassName()
{
if (this.Name != null)
{
return this.Name;
}
return TypeDescriptor.GetClassName(this.owner, true);
}
public string GetComponentName()
{
return TypeDescriptor.GetComponentName(this.owner, true);
}
public TypeConverter GetConverter()
{
return TypeDescriptor.GetConverter(this.owner, true);
}
public EventDescriptor GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this.owner, true);
}
public PropertyDescriptor GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(this.owner, true);
}
public object GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this.owner, editorBaseType, true);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this.owner, attributes, true);
}
public EventDescriptorCollection GetEvents()
{
return TypeDescriptor.GetEvents(this.owner, true);
}
public PropertyDescriptorCollection GetProperties()
{
return GetProperties(null);
}
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
PropertyDescriptorCollection result = this.cachedProperties;
if (result != null)
{
return result;
}
PropertyDescriptorCollection dynamicProperties;
if (attributes != null)
{
dynamicProperties = TypeDescriptor.GetProperties(this.owner, attributes, true);
}
else
{
dynamicProperties = TypeDescriptor.GetProperties(this.owner, true);
}
// initial capacity is Properties + Name + Body
List<PropertyDescriptor> propertyDescriptors = new List<PropertyDescriptor>(this.Properties.Count + 2);
for (int i = 0; i < dynamicProperties.Count; i++)
{
PropertyDescriptor dynamicProperty = dynamicProperties[i];
if (dynamicProperty.IsBrowsable)
{
propertyDescriptors.Add(dynamicProperty);
}
}
foreach (DynamicActivityProperty property in Properties)
{
if (string.IsNullOrEmpty(property.Name))
{
throw FxTrace.Exception.AsError(new ValidationException(SR.ActivityPropertyRequiresName(this.owner.DisplayName)));
}
if (property.Type == null)
{
throw FxTrace.Exception.AsError(new ValidationException(SR.ActivityPropertyRequiresType(this.owner.DisplayName)));
}
propertyDescriptors.Add(new DynamicActivityPropertyDescriptor(property, this.owner.GetType()));
}
result = new PropertyDescriptorCollection(propertyDescriptors.ToArray());
this.cachedProperties = result;
return result;
}
public object GetPropertyOwner(PropertyDescriptor pd)
{
return this.owner;
}
class DynamicActivityPropertyDescriptor : PropertyDescriptor
{
AttributeCollection attributes;
DynamicActivityProperty activityProperty;
Type componentType;
public DynamicActivityPropertyDescriptor(DynamicActivityProperty activityProperty, Type componentType)
: base(activityProperty.Name, null)
{
this.activityProperty = activityProperty;
this.componentType = componentType;
}
public override Type ComponentType
{
get
{
return this.componentType;
}
}
public override AttributeCollection Attributes
{
get
{
if (this.attributes == null)
{
AttributeCollection inheritedAttributes = base.Attributes;
Collection<Attribute> propertyAttributes = this.activityProperty.Attributes;
Attribute[] totalAttributes = new Attribute[inheritedAttributes.Count + propertyAttributes.Count + 1];
inheritedAttributes.CopyTo(totalAttributes, 0);
propertyAttributes.CopyTo(totalAttributes, inheritedAttributes.Count);
totalAttributes[inheritedAttributes.Count + propertyAttributes.Count] = new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden);
this.attributes = new AttributeCollection(totalAttributes);
}
return this.attributes;
}
}
public override bool IsReadOnly
{
get
{
return false;
}
}
public override Type PropertyType
{
get
{
return this.activityProperty.Type;
}
}
public override object GetValue(object component)
{
IDynamicActivity owner = component as IDynamicActivity;
if (owner == null || !owner.Properties.Contains(this.activityProperty))
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.InvalidDynamicActivityProperty(this.Name)));
}
return this.activityProperty.Value;
}
public override void SetValue(object component, object value)
{
IDynamicActivity owner = component as IDynamicActivity;
if (owner == null || !owner.Properties.Contains(this.activityProperty))
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.InvalidDynamicActivityProperty(this.Name)));
}
this.activityProperty.Value = value;
}
public override bool CanResetValue(object component)
{
return false;
}
public override void ResetValue(object component)
{
}
public override bool ShouldSerializeValue(object component)
{
return false;
}
protected override void FillAttributes(IList attributeList)
{
if (attributeList == null)
{
throw FxTrace.Exception.ArgumentNull("attributeList");
}
attributeList.Add(new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden));
}
}
class ActivityPropertyCollection : KeyedCollection<string, DynamicActivityProperty>
{
DynamicActivityTypeDescriptor parent;
public ActivityPropertyCollection(DynamicActivityTypeDescriptor parent)
: base()
{
this.parent = parent;
}
protected override void InsertItem(int index, DynamicActivityProperty item)
{
if (item == null)
{
throw FxTrace.Exception.ArgumentNull("item");
}
if (this.Contains(item.Name))
{
throw FxTrace.Exception.AsError(new ArgumentException(SR.DynamicActivityDuplicatePropertyDetected(item.Name), "item"));
}
InvalidateCache();
base.InsertItem(index, item);
}
protected override void SetItem(int index, DynamicActivityProperty item)
{
if (item == null)
{
throw FxTrace.Exception.ArgumentNull("item");
}
// We don't want self-assignment to throw. Note that if this[index] has the same
// name as item, no other element in the collection can.
if (!this[index].Name.Equals(item.Name) && this.Contains(item.Name))
{
throw FxTrace.Exception.AsError(new ArgumentException(SR.DynamicActivityDuplicatePropertyDetected(item.Name), "item"));
}
InvalidateCache();
base.SetItem(index, item);
}
protected override void RemoveItem(int index)
{
InvalidateCache();
base.RemoveItem(index);
}
protected override void ClearItems()
{
InvalidateCache();
base.ClearItems();
}
protected override string GetKeyForItem(DynamicActivityProperty item)
{
return item.Name;
}
void InvalidateCache()
{
this.parent.cachedProperties = null;
}
}
}
}
| |
#region License
/*
* Cookie.cs
*
* This code is derived from Cookie.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2004,2009 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2019 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Lawrence Pit <loz@cable.a2000.nl>
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
* - Daniel Nauck <dna@mono-project.de>
* - Sebastien Pouliot <sebastien@ximian.com>
*/
#endregion
using System;
using System.Globalization;
using System.Text;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides a set of methods and properties used to manage an HTTP cookie.
/// </summary>
/// <remarks>
/// <para>
/// This class refers to the following specifications:
/// </para>
/// <list type="bullet">
/// <item>
/// <term>
/// <see href="http://web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html">Netscape specification</see>
/// </term>
/// </item>
/// <item>
/// <term>
/// <see href="https://tools.ietf.org/html/rfc2109">RFC 2109</see>
/// </term>
/// </item>
/// <item>
/// <term>
/// <see href="https://tools.ietf.org/html/rfc2965">RFC 2965</see>
/// </term>
/// </item>
/// <item>
/// <term>
/// <see href="https://tools.ietf.org/html/rfc6265">RFC 6265</see>
/// </term>
/// </item>
/// </list>
/// <para>
/// This class cannot be inherited.
/// </para>
/// </remarks>
[Serializable]
public sealed class Cookie
{
#region Private Fields
private string _comment;
private Uri _commentUri;
private bool _discard;
private string _domain;
private static readonly int[] _emptyPorts;
private DateTime _expires;
private bool _httpOnly;
private string _name;
private string _path;
private string _port;
private int[] _ports;
private static readonly char[] _reservedCharsForValue;
private string _sameSite;
private bool _secure;
private DateTime _timeStamp;
private string _value;
private int _version;
#endregion
#region Static Constructor
static Cookie ()
{
_emptyPorts = new int[0];
_reservedCharsForValue = new[] { ';', ',' };
}
#endregion
#region Internal Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Cookie"/> class.
/// </summary>
internal Cookie ()
{
init (String.Empty, String.Empty, String.Empty, String.Empty);
}
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Cookie"/> class with
/// the specified name and value.
/// </summary>
/// <param name="name">
/// <para>
/// A <see cref="string"/> that specifies the name of the cookie.
/// </para>
/// <para>
/// The name must be a token defined in
/// <see href="http://tools.ietf.org/html/rfc2616#section-2.2">
/// RFC 2616</see>.
/// </para>
/// </param>
/// <param name="value">
/// A <see cref="string"/> that specifies the value of the cookie.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> is an empty string.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="name"/> starts with a dollar sign.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="name"/> contains an invalid character.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="value"/> is a string not enclosed in double quotes
/// that contains an invalid character.
/// </para>
/// </exception>
public Cookie (string name, string value)
: this (name, value, String.Empty, String.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Cookie"/> class with
/// the specified name, value, and path.
/// </summary>
/// <param name="name">
/// <para>
/// A <see cref="string"/> that specifies the name of the cookie.
/// </para>
/// <para>
/// The name must be a token defined in
/// <see href="http://tools.ietf.org/html/rfc2616#section-2.2">
/// RFC 2616</see>.
/// </para>
/// </param>
/// <param name="value">
/// A <see cref="string"/> that specifies the value of the cookie.
/// </param>
/// <param name="path">
/// A <see cref="string"/> that specifies the value of the Path
/// attribute of the cookie.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> is an empty string.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="name"/> starts with a dollar sign.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="name"/> contains an invalid character.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="value"/> is a string not enclosed in double quotes
/// that contains an invalid character.
/// </para>
/// </exception>
public Cookie (string name, string value, string path)
: this (name, value, path, String.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Cookie"/> class with
/// the specified name, value, path, and domain.
/// </summary>
/// <param name="name">
/// <para>
/// A <see cref="string"/> that specifies the name of the cookie.
/// </para>
/// <para>
/// The name must be a token defined in
/// <see href="http://tools.ietf.org/html/rfc2616#section-2.2">
/// RFC 2616</see>.
/// </para>
/// </param>
/// <param name="value">
/// A <see cref="string"/> that specifies the value of the cookie.
/// </param>
/// <param name="path">
/// A <see cref="string"/> that specifies the value of the Path
/// attribute of the cookie.
/// </param>
/// <param name="domain">
/// A <see cref="string"/> that specifies the value of the Domain
/// attribute of the cookie.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> is an empty string.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="name"/> starts with a dollar sign.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="name"/> contains an invalid character.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="value"/> is a string not enclosed in double quotes
/// that contains an invalid character.
/// </para>
/// </exception>
public Cookie (string name, string value, string path, string domain)
{
if (name == null)
throw new ArgumentNullException ("name");
if (name.Length == 0)
throw new ArgumentException ("An empty string.", "name");
if (name[0] == '$') {
var msg = "It starts with a dollar sign.";
throw new ArgumentException (msg, "name");
}
if (!name.IsToken ()) {
var msg = "It contains an invalid character.";
throw new ArgumentException (msg, "name");
}
if (value == null)
value = String.Empty;
if (value.Contains (_reservedCharsForValue)) {
if (!value.IsEnclosedIn ('"')) {
var msg = "A string not enclosed in double quotes.";
throw new ArgumentException (msg, "value");
}
}
init (name, value, path ?? String.Empty, domain ?? String.Empty);
}
#endregion
#region Internal Properties
internal bool ExactDomain {
get {
return _domain.Length == 0 || _domain[0] != '.';
}
}
internal int MaxAge {
get {
if (_expires == DateTime.MinValue)
return 0;
var expires = _expires.Kind != DateTimeKind.Local
? _expires.ToLocalTime ()
: _expires;
var span = expires - DateTime.Now;
return span > TimeSpan.Zero
? (int) span.TotalSeconds
: 0;
}
set {
_expires = value > 0
? DateTime.Now.AddSeconds ((double) value)
: DateTime.Now;
}
}
internal int[] Ports {
get {
return _ports ?? _emptyPorts;
}
}
internal string SameSite {
get {
return _sameSite;
}
set {
_sameSite = value;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the value of the Comment attribute of the cookie.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the comment to document
/// intended use of the cookie.
/// </para>
/// <para>
/// <see langword="null"/> if not present.
/// </para>
/// <para>
/// The default value is <see langword="null"/>.
/// </para>
/// </value>
public string Comment {
get {
return _comment;
}
internal set {
_comment = value;
}
}
/// <summary>
/// Gets the value of the CommentURL attribute of the cookie.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Uri"/> that represents the URI that provides
/// the comment to document intended use of the cookie.
/// </para>
/// <para>
/// <see langword="null"/> if not present.
/// </para>
/// <para>
/// The default value is <see langword="null"/>.
/// </para>
/// </value>
public Uri CommentUri {
get {
return _commentUri;
}
internal set {
_commentUri = value;
}
}
/// <summary>
/// Gets a value indicating whether the client discards the cookie
/// unconditionally when the client terminates.
/// </summary>
/// <value>
/// <para>
/// <c>true</c> if the client discards the cookie unconditionally
/// when the client terminates; otherwise, <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </value>
public bool Discard {
get {
return _discard;
}
internal set {
_discard = value;
}
}
/// <summary>
/// Gets or sets the value of the Domain attribute of the cookie.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the domain name that
/// the cookie is valid for.
/// </para>
/// <para>
/// An empty string if this attribute is not needed.
/// </para>
/// </value>
public string Domain {
get {
return _domain;
}
set {
_domain = value ?? String.Empty;
}
}
/// <summary>
/// Gets or sets a value indicating whether the cookie has expired.
/// </summary>
/// <value>
/// <para>
/// <c>true</c> if the cookie has expired; otherwise, <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </value>
public bool Expired {
get {
return _expires != DateTime.MinValue && _expires <= DateTime.Now;
}
set {
_expires = value ? DateTime.Now : DateTime.MinValue;
}
}
/// <summary>
/// Gets or sets the value of the Expires attribute of the cookie.
/// </summary>
/// <value>
/// <para>
/// A <see cref="DateTime"/> that represents the date and time that
/// the cookie expires on.
/// </para>
/// <para>
/// <see cref="DateTime.MinValue"/> if this attribute is not needed.
/// </para>
/// <para>
/// The default value is <see cref="DateTime.MinValue"/>.
/// </para>
/// </value>
public DateTime Expires {
get {
return _expires;
}
set {
_expires = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether non-HTTP APIs can access
/// the cookie.
/// </summary>
/// <value>
/// <para>
/// <c>true</c> if non-HTTP APIs cannot access the cookie; otherwise,
/// <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </value>
public bool HttpOnly {
get {
return _httpOnly;
}
set {
_httpOnly = value;
}
}
/// <summary>
/// Gets or sets the name of the cookie.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the name of the cookie.
/// </para>
/// <para>
/// The name must be a token defined in
/// <see href="http://tools.ietf.org/html/rfc2616#section-2.2">
/// RFC 2616</see>.
/// </para>
/// </value>
/// <exception cref="ArgumentNullException">
/// The value specified for a set operation is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// The value specified for a set operation is an empty string.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// The value specified for a set operation starts with a dollar sign.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// The value specified for a set operation contains an invalid character.
/// </para>
/// </exception>
public string Name {
get {
return _name;
}
set {
if (value == null)
throw new ArgumentNullException ("value");
if (value.Length == 0)
throw new ArgumentException ("An empty string.", "value");
if (value[0] == '$') {
var msg = "It starts with a dollar sign.";
throw new ArgumentException (msg, "value");
}
if (!value.IsToken ()) {
var msg = "It contains an invalid character.";
throw new ArgumentException (msg, "value");
}
_name = value;
}
}
/// <summary>
/// Gets or sets the value of the Path attribute of the cookie.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the subset of URI on
/// the origin server that the cookie applies to.
/// </value>
public string Path {
get {
return _path;
}
set {
_path = value ?? String.Empty;
}
}
/// <summary>
/// Gets the value of the Port attribute of the cookie.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the list of TCP ports
/// that the cookie applies to.
/// </para>
/// <para>
/// <see langword="null"/> if not present.
/// </para>
/// <para>
/// The default value is <see langword="null"/>.
/// </para>
/// </value>
public string Port {
get {
return _port;
}
internal set {
int[] ports;
if (!tryCreatePorts (value, out ports))
return;
_port = value;
_ports = ports;
}
}
/// <summary>
/// Gets or sets a value indicating whether the security level of
/// the cookie is secure.
/// </summary>
/// <remarks>
/// When this property is <c>true</c>, the cookie may be included in
/// the request only if the request is transmitted over HTTPS.
/// </remarks>
/// <value>
/// <para>
/// <c>true</c> if the security level of the cookie is secure;
/// otherwise, <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </value>
public bool Secure {
get {
return _secure;
}
set {
_secure = value;
}
}
/// <summary>
/// Gets the time when the cookie was issued.
/// </summary>
/// <value>
/// A <see cref="DateTime"/> that represents the time when
/// the cookie was issued.
/// </value>
public DateTime TimeStamp {
get {
return _timeStamp;
}
}
/// <summary>
/// Gets or sets the value of the cookie.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the cookie.
/// </value>
/// <exception cref="ArgumentException">
/// The value specified for a set operation is a string not enclosed in
/// double quotes that contains an invalid character.
/// </exception>
public string Value {
get {
return _value;
}
set {
if (value == null)
value = String.Empty;
if (value.Contains (_reservedCharsForValue)) {
if (!value.IsEnclosedIn ('"')) {
var msg = "A string not enclosed in double quotes.";
throw new ArgumentException (msg, "value");
}
}
_value = value;
}
}
/// <summary>
/// Gets the value of the Version attribute of the cookie.
/// </summary>
/// <value>
/// <para>
/// An <see cref="int"/> that represents the version of HTTP state
/// management that the cookie conforms to.
/// </para>
/// <para>
/// 0 or 1. 0 if not present.
/// </para>
/// <para>
/// The default value is 0.
/// </para>
/// </value>
public int Version {
get {
return _version;
}
internal set {
if (value < 0 || value > 1)
return;
_version = value;
}
}
#endregion
#region Private Methods
private static int hash (int i, int j, int k, int l, int m)
{
return i
^ (j << 13 | j >> 19)
^ (k << 26 | k >> 6)
^ (l << 7 | l >> 25)
^ (m << 20 | m >> 12);
}
private void init (string name, string value, string path, string domain)
{
_name = name;
_value = value;
_path = path;
_domain = domain;
_expires = DateTime.MinValue;
_timeStamp = DateTime.Now;
}
private string toResponseStringVersion0 ()
{
var buff = new StringBuilder (64);
buff.AppendFormat ("{0}={1}", _name, _value);
if (_expires != DateTime.MinValue) {
buff.AppendFormat (
"; Expires={0}",
_expires.ToUniversalTime ().ToString (
"ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'",
CultureInfo.CreateSpecificCulture ("en-US")
)
);
}
if (!_path.IsNullOrEmpty ())
buff.AppendFormat ("; Path={0}", _path);
if (!_domain.IsNullOrEmpty ())
buff.AppendFormat ("; Domain={0}", _domain);
if (!_sameSite.IsNullOrEmpty ())
buff.AppendFormat ("; SameSite={0}", _sameSite);
if (_secure)
buff.Append ("; Secure");
if (_httpOnly)
buff.Append ("; HttpOnly");
return buff.ToString ();
}
private string toResponseStringVersion1 ()
{
var buff = new StringBuilder (64);
buff.AppendFormat ("{0}={1}; Version={2}", _name, _value, _version);
if (_expires != DateTime.MinValue)
buff.AppendFormat ("; Max-Age={0}", MaxAge);
if (!_path.IsNullOrEmpty ())
buff.AppendFormat ("; Path={0}", _path);
if (!_domain.IsNullOrEmpty ())
buff.AppendFormat ("; Domain={0}", _domain);
if (_port != null) {
if (_port != "\"\"")
buff.AppendFormat ("; Port={0}", _port);
else
buff.Append ("; Port");
}
if (_comment != null)
buff.AppendFormat ("; Comment={0}", HttpUtility.UrlEncode (_comment));
if (_commentUri != null) {
var url = _commentUri.OriginalString;
buff.AppendFormat (
"; CommentURL={0}", !url.IsToken () ? url.Quote () : url
);
}
if (_discard)
buff.Append ("; Discard");
if (_secure)
buff.Append ("; Secure");
return buff.ToString ();
}
private static bool tryCreatePorts (string value, out int[] result)
{
result = null;
var arr = value.Trim ('"').Split (',');
var len = arr.Length;
var res = new int[len];
for (var i = 0; i < len; i++) {
var s = arr[i].Trim ();
if (s.Length == 0) {
res[i] = Int32.MinValue;
continue;
}
if (!Int32.TryParse (s, out res[i]))
return false;
}
result = res;
return true;
}
#endregion
#region Internal Methods
internal bool EqualsWithoutValue (Cookie cookie)
{
var caseSensitive = StringComparison.InvariantCulture;
var caseInsensitive = StringComparison.InvariantCultureIgnoreCase;
return _name.Equals (cookie._name, caseInsensitive)
&& _path.Equals (cookie._path, caseSensitive)
&& _domain.Equals (cookie._domain, caseInsensitive)
&& _version == cookie._version;
}
internal bool EqualsWithoutValueAndVersion (Cookie cookie)
{
var caseSensitive = StringComparison.InvariantCulture;
var caseInsensitive = StringComparison.InvariantCultureIgnoreCase;
return _name.Equals (cookie._name, caseInsensitive)
&& _path.Equals (cookie._path, caseSensitive)
&& _domain.Equals (cookie._domain, caseInsensitive);
}
internal string ToRequestString (Uri uri)
{
if (_name.Length == 0)
return String.Empty;
if (_version == 0)
return String.Format ("{0}={1}", _name, _value);
var buff = new StringBuilder (64);
buff.AppendFormat ("$Version={0}; {1}={2}", _version, _name, _value);
if (!_path.IsNullOrEmpty ())
buff.AppendFormat ("; $Path={0}", _path);
else if (uri != null)
buff.AppendFormat ("; $Path={0}", uri.GetAbsolutePath ());
else
buff.Append ("; $Path=/");
if (!_domain.IsNullOrEmpty ()) {
if (uri == null || uri.Host != _domain)
buff.AppendFormat ("; $Domain={0}", _domain);
}
if (_port != null) {
if (_port != "\"\"")
buff.AppendFormat ("; $Port={0}", _port);
else
buff.Append ("; $Port");
}
return buff.ToString ();
}
/// <summary>
/// Returns a string that represents the current cookie instance.
/// </summary>
/// <returns>
/// A <see cref="string"/> that is suitable for the Set-Cookie response
/// header.
/// </returns>
internal string ToResponseString ()
{
return _name.Length == 0
? String.Empty
: _version == 0
? toResponseStringVersion0 ()
: toResponseStringVersion1 ();
}
internal static bool TryCreate (
string name, string value, out Cookie result
)
{
result = null;
try {
result = new Cookie (name, value);
}
catch {
return false;
}
return true;
}
#endregion
#region Public Methods
/// <summary>
/// Determines whether the current cookie instance is equal to
/// the specified <see cref="object"/> instance.
/// </summary>
/// <param name="comparand">
/// <para>
/// An <see cref="object"/> instance to compare with
/// the current cookie instance.
/// </para>
/// <para>
/// An reference to a <see cref="Cookie"/> instance.
/// </para>
/// </param>
/// <returns>
/// <c>true</c> if the current cookie instance is equal to
/// <paramref name="comparand"/>; otherwise, <c>false</c>.
/// </returns>
public override bool Equals (object comparand)
{
var cookie = comparand as Cookie;
if (cookie == null)
return false;
var caseSensitive = StringComparison.InvariantCulture;
var caseInsensitive = StringComparison.InvariantCultureIgnoreCase;
return _name.Equals (cookie._name, caseInsensitive)
&& _value.Equals (cookie._value, caseSensitive)
&& _path.Equals (cookie._path, caseSensitive)
&& _domain.Equals (cookie._domain, caseInsensitive)
&& _version == cookie._version;
}
/// <summary>
/// Gets a hash code for the current cookie instance.
/// </summary>
/// <returns>
/// An <see cref="int"/> that represents the hash code.
/// </returns>
public override int GetHashCode ()
{
return hash (
StringComparer.InvariantCultureIgnoreCase.GetHashCode (_name),
_value.GetHashCode (),
_path.GetHashCode (),
StringComparer.InvariantCultureIgnoreCase.GetHashCode (_domain),
_version
);
}
/// <summary>
/// Returns a string that represents the current cookie instance.
/// </summary>
/// <returns>
/// A <see cref="string"/> that is suitable for the Cookie request header.
/// </returns>
public override string ToString ()
{
return ToRequestString (null);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.DiaSymReader;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
using Roslyn.Test.PdbUtilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public abstract class ExpressionCompilerTestBase : CSharpTestBase, IDisposable
{
private readonly ArrayBuilder<IDisposable> _runtimeInstances = ArrayBuilder<IDisposable>.GetInstance();
public override void Dispose()
{
base.Dispose();
foreach (var instance in _runtimeInstances)
{
instance.Dispose();
}
_runtimeInstances.Free();
}
internal RuntimeInstance CreateRuntimeInstance(
Compilation compilation,
bool includeSymbols = true)
{
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
return CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
references.AddIntrinsicAssembly(),
exeBytes,
includeSymbols ? new SymReader(pdbBytes, exeBytes) : null);
}
internal RuntimeInstance CreateRuntimeInstance(
string assemblyName,
ImmutableArray<MetadataReference> references,
byte[] exeBytes,
ISymUnmanagedReader symReader,
bool includeLocalSignatures = true)
{
var exeReference = AssemblyMetadata.CreateFromImage(exeBytes).GetReference(display: assemblyName);
var modulesBuilder = ArrayBuilder<ModuleInstance>.GetInstance();
// Create modules for the references
modulesBuilder.AddRange(references.Select(r => r.ToModuleInstance(fullImage: null, symReader: null, includeLocalSignatures: includeLocalSignatures)));
// Create a module for the exe.
modulesBuilder.Add(exeReference.ToModuleInstance(exeBytes, symReader, includeLocalSignatures: includeLocalSignatures));
var modules = modulesBuilder.ToImmutableAndFree();
modules.VerifyAllModules();
var instance = new RuntimeInstance(modules);
_runtimeInstances.Add(instance);
return instance;
}
internal static void GetContextState(
RuntimeInstance runtime,
string methodOrTypeName,
out ImmutableArray<MetadataBlock> blocks,
out Guid moduleVersionId,
out ISymUnmanagedReader symReader,
out int methodOrTypeToken,
out int localSignatureToken)
{
var moduleInstances = runtime.Modules;
blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock);
var compilation = blocks.ToCompilation();
var methodOrType = GetMethodOrTypeBySignature(compilation, methodOrTypeName);
var module = (PEModuleSymbol)methodOrType.ContainingModule;
var id = module.Module.GetModuleVersionIdOrThrow();
var moduleInstance = moduleInstances.First(m => m.ModuleVersionId == id);
moduleVersionId = id;
symReader = (ISymUnmanagedReader)moduleInstance.SymReader;
Handle methodOrTypeHandle;
if (methodOrType.Kind == SymbolKind.Method)
{
methodOrTypeHandle = ((PEMethodSymbol)methodOrType).Handle;
localSignatureToken = moduleInstance.GetLocalSignatureToken((MethodDefinitionHandle)methodOrTypeHandle);
}
else
{
methodOrTypeHandle = ((PENamedTypeSymbol)methodOrType).Handle;
localSignatureToken = -1;
}
MetadataReader reader = null; // null should be ok
methodOrTypeToken = reader.GetToken(methodOrTypeHandle);
}
internal static EvaluationContext CreateMethodContext(
RuntimeInstance runtime,
string methodName,
int atLineNumber = -1)
{
ImmutableArray<MetadataBlock> blocks;
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
int ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber);
return EvaluationContext.CreateMethodContext(
default(CSharpMetadataContext),
blocks,
symReader,
moduleVersionId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: ilOffset,
localSignatureToken: localSignatureToken);
}
internal static EvaluationContext CreateTypeContext(
RuntimeInstance runtime,
string typeName)
{
ImmutableArray<MetadataBlock> blocks;
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int typeToken;
int localSignatureToken;
GetContextState(runtime, typeName, out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
return EvaluationContext.CreateTypeContext(
default(CSharpMetadataContext),
blocks,
moduleVersionId,
typeToken);
}
internal CompilationTestData Evaluate(
string source,
OutputKind outputKind,
string methodName,
string expr,
int atLineNumber = -1,
bool includeSymbols = true)
{
ResultProperties resultProperties;
string error;
var result = Evaluate(source, outputKind, methodName, expr, out resultProperties, out error, atLineNumber, DefaultInspectionContext.Instance, includeSymbols);
Assert.Null(error);
return result;
}
internal CompilationTestData Evaluate(
string source,
OutputKind outputKind,
string methodName,
string expr,
out ResultProperties resultProperties,
out string error,
int atLineNumber = -1,
InspectionContext inspectionContext = null,
bool includeSymbols = true)
{
var compilation0 = CreateCompilationWithMscorlib(
source,
options: (outputKind == OutputKind.DynamicallyLinkedLibrary) ? TestOptions.DebugDll : TestOptions.DebugExe);
var runtime = CreateRuntimeInstance(compilation0, includeSymbols);
var context = CreateMethodContext(runtime, methodName, atLineNumber);
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
inspectionContext ?? DefaultInspectionContext.Instance,
expr,
DkmEvaluationFlags.TreatAsExpression,
DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
return testData;
}
/// <summary>
/// Verify all type parameters from the method
/// are from that method or containing types.
/// </summary>
internal static void VerifyTypeParameters(MethodSymbol method)
{
Assert.True(method.IsContainingSymbolOfAllTypeParameters(method.ReturnType));
AssertEx.All(method.TypeParameters, typeParameter => method.IsContainingSymbolOfAllTypeParameters(typeParameter));
AssertEx.All(method.TypeArguments, typeArgument => method.IsContainingSymbolOfAllTypeParameters(typeArgument));
AssertEx.All(method.Parameters, parameter => method.IsContainingSymbolOfAllTypeParameters(parameter.Type));
VerifyTypeParameters(method.ContainingType);
}
internal static void VerifyLocal(
CompilationTestData testData,
string typeName,
LocalAndMethod localAndMethod,
string expectedMethodName,
string expectedLocalName,
DkmClrCompilationResultFlags expectedFlags = DkmClrCompilationResultFlags.None,
string expectedILOpt = null,
bool expectedGeneric = false,
[CallerFilePath]string expectedValueSourcePath = null,
[CallerLineNumber]int expectedValueSourceLine = 0)
{
ExpressionCompilerTestHelpers.VerifyLocal<MethodSymbol>(
testData,
typeName,
localAndMethod,
expectedMethodName,
expectedLocalName,
expectedFlags,
VerifyTypeParameters,
expectedILOpt,
expectedGeneric,
expectedValueSourcePath,
expectedValueSourceLine);
}
/// <summary>
/// Verify all type parameters from the type
/// are from that type or containing types.
/// </summary>
internal static void VerifyTypeParameters(NamedTypeSymbol type)
{
AssertEx.All(type.TypeParameters, typeParameter => type.IsContainingSymbolOfAllTypeParameters(typeParameter));
AssertEx.All(type.TypeArguments, typeArgument => type.IsContainingSymbolOfAllTypeParameters(typeArgument));
var container = type.ContainingType;
if ((object)container != null)
{
VerifyTypeParameters(container);
}
}
internal static Symbol GetMethodOrTypeBySignature(Compilation compilation, string signature)
{
string methodOrTypeName = signature;
string[] parameterTypeNames = null;
var parameterListStart = methodOrTypeName.IndexOf('(');
if (parameterListStart > -1)
{
parameterTypeNames = methodOrTypeName.Substring(parameterListStart).Trim('(', ')').Split(',');
methodOrTypeName = methodOrTypeName.Substring(0, parameterListStart);
}
var candidates = compilation.GetMembers(methodOrTypeName);
Assert.Equal(parameterTypeNames == null, candidates.Length == 1);
Symbol methodOrType = null;
foreach (var candidate in candidates)
{
methodOrType = candidate;
if ((parameterTypeNames == null) ||
parameterTypeNames.SequenceEqual(methodOrType.GetParameters().Select(p => p.Type.Name)))
{
// Found a match.
break;
}
}
Assert.False(methodOrType == null, "Could not find method or type with signature '" + signature + "'.");
return methodOrType;
}
}
}
| |
//
// SetupService.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml;
using ICSharpCode.SharpZipLib.Zip;
using Mono.Addins.Database;
using Mono.Addins.Description;
using Mono.Addins.Setup.ProgressMonitoring;
using Mono.PkgConfig;
namespace Mono.Addins.Setup
{
/// <summary>
/// Provides tools for managing add-ins
/// </summary>
/// <remarks>
/// This class can be used to manage the add-ins of an application. It allows installing and uninstalling
/// add-ins, taking into account add-in dependencies. It provides methods for installing add-ins from on-line
/// repositories and tools for generating those repositories.
/// </remarks>
public class SetupService
{
RepositoryRegistry repositories;
string applicationNamespace;
string installDirectory;
AddinStore store;
AddinSystemConfiguration config;
const string addinFilesDir = "_addin_files";
AddinRegistry registry;
/// <summary>
/// Initializes a new instance
/// </summary>
/// <remarks>
/// If the add-in manager is initialized (AddinManager.Initialize has been called), then this instance
/// will manage the add-in registry of the initialized engine.
/// </remarks>
public SetupService ()
{
if (AddinManager.IsInitialized)
registry = AddinManager.Registry;
else
registry = AddinRegistry.GetGlobalRegistry ();
repositories = new RepositoryRegistry (this);
store = new AddinStore (this);
AddAddinRepositoryProvider ("MonoAddins", new MonoAddinsRepositoryProvider (this));
}
/// <summary>
/// Initializes a new instance
/// </summary>
/// <param name="registry">
/// Add-in registry to manage
/// </param>
public SetupService (AddinRegistry registry)
{
this.registry = registry;
repositories = new RepositoryRegistry (this);
store = new AddinStore (this);
AddAddinRepositoryProvider ("MonoAddins", new MonoAddinsRepositoryProvider (this));
}
/// <summary>
/// The add-in registry being managed
/// </summary>
public AddinRegistry Registry {
get { return registry; }
}
internal string RepositoryCachePath {
get { return Path.Combine (registry.RegistryPath, "repository-cache"); }
}
string RootConfigFile {
get { return Path.Combine (registry.RegistryPath, "addins-setup-v2.config"); }
}
/// <summary>
/// This should only be used for migration purposes
/// </summary>
string RootConfigFileOld {
get { return Path.Combine (registry.RegistryPath, "addins-setup.config"); }
}
/// <summary>
/// Default add-in namespace of the application (optional). If set, only add-ins that belong to that namespace
/// will be shown in add-in lists.
/// </summary>
public string ApplicationNamespace {
get { return applicationNamespace; }
set { applicationNamespace = value; }
}
/// <summary>
/// Directory where to install add-ins. If not specified, the 'addins' subdirectory of the
/// registry location is used.
/// </summary>
public string InstallDirectory {
get {
if (installDirectory != null && installDirectory.Length > 0)
return installDirectory;
else
return registry.DefaultAddinsFolder;
}
set { installDirectory = value; }
}
/// <summary>
/// Returns a RepositoryRegistry which can be used to manage on-line repository references
/// </summary>
public RepositoryRegistry Repositories {
get { return repositories; }
}
internal AddinStore Store {
get { return store; }
}
/// <summary>
/// Resolves add-in dependencies.
/// </summary>
/// <param name="statusMonitor">
/// Progress monitor where to show progress status
/// </param>
/// <param name="addins">
/// List of add-ins to check
/// </param>
/// <param name="resolved">
/// Packages that need to be installed.
/// </param>
/// <param name="toUninstall">
/// Packages that need to be uninstalled.
/// </param>
/// <param name="unresolved">
/// Add-in dependencies that could not be resolved.
/// </param>
/// <returns>
/// True if all dependencies could be resolved.
/// </returns>
/// <remarks>
/// This method can be used to get a list of all packages that have to be installed in order to install
/// an add-in or set of add-ins. The list of packages to install will include the package that provides the
/// add-in, and all packages that provide the add-in dependencies. In some cases, packages may need to
/// be installed (for example, when an installed add-in needs to be upgraded).
/// </remarks>
public bool ResolveDependencies (IProgressStatus statusMonitor, AddinRepositoryEntry [] addins, out PackageCollection resolved, out PackageCollection toUninstall, out DependencyCollection unresolved)
{
return store.ResolveDependencies (statusMonitor, addins, out resolved, out toUninstall, out unresolved);
}
/// <summary>
/// Resolves add-in dependencies.
/// </summary>
/// <param name="statusMonitor">
/// Progress monitor where to show progress status
/// </param>
/// <param name="packages">
/// Packages that need to be installed.
/// </param>
/// <param name="toUninstall">
/// Packages that need to be uninstalled.
/// </param>
/// <param name="unresolved">
/// Add-in dependencies that could not be resolved.
/// </param>
/// <returns>
/// True if all dependencies could be resolved.
/// </returns>
/// <remarks>
/// This method can be used to get a list of all packages that have to be installed in order to satisfy
/// the dependencies of a package or set of packages. The 'packages' argument must have the list of packages
/// to be resolved. When resolving dependencies, if there is any additional package that needs to be installed,
/// it will be added to the same 'packages' collection. In some cases, packages may need to
/// be installed (for example, when an installed add-in needs to be upgraded). Those packages will be added
/// to the 'toUninstall' collection. Packages that could not be resolved are added to the 'unresolved'
/// collection.
/// </remarks>
public bool ResolveDependencies (IProgressStatus statusMonitor, PackageCollection packages, out PackageCollection toUninstall, out DependencyCollection unresolved)
{
return store.ResolveDependencies (statusMonitor, packages, out toUninstall, out unresolved);
}
/// <summary>
/// Installs add-in packages
/// </summary>
/// <param name="statusMonitor">
/// Progress monitor where to show progress status
/// </param>
/// <param name="files">
/// Paths to the packages to install
/// </param>
/// <returns>
/// True if the installation succeeded
/// </returns>
public bool Install (IProgressStatus statusMonitor, params string [] files)
{
return store.Install (statusMonitor, files);
}
/// <summary>
/// Installs add-in packages from on-line repositories
/// </summary>
/// <param name="statusMonitor">
/// Progress monitor where to show progress status
/// </param>
/// <param name="addins">
/// References to the add-ins to be installed
/// </param>
/// <returns>
/// True if the installation succeeded
/// </returns>
public bool Install (IProgressStatus statusMonitor, params AddinRepositoryEntry [] addins)
{
return store.Install (statusMonitor, addins);
}
/// <summary>
/// Installs add-in packages
/// </summary>
/// <param name="statusMonitor">
/// Progress monitor where to show progress status
/// </param>
/// <param name="packages">
/// Packages to install
/// </param>
/// <returns>
/// True if the installation succeeded
/// </returns>
public bool Install (IProgressStatus statusMonitor, PackageCollection packages)
{
return store.Install (statusMonitor, packages);
}
/// <summary>
/// Uninstalls an add-in.
/// </summary>
/// <param name="statusMonitor">
/// Progress monitor where to show progress status
/// </param>
/// <param name="id">
/// Full identifier of the add-in to uninstall.
/// </param>
public void Uninstall (IProgressStatus statusMonitor, string id)
{
store.Uninstall (statusMonitor, id);
}
/// <summary>
/// Uninstalls a set of add-ins
/// </summary>
/// <param name='statusMonitor'>
/// Progress monitor where to show progress status
/// </param>
/// <param name='ids'>
/// Full identifiers of the add-ins to uninstall.
/// </param>
public void Uninstall (IProgressStatus statusMonitor, IEnumerable<string> ids)
{
store.Uninstall (statusMonitor, ids);
}
/// <summary>
/// Gets information about an add-in
/// </summary>
/// <param name="addin">
/// The add-in
/// </param>
/// <returns>
/// Add-in header data
/// </returns>
public static AddinHeader GetAddinHeader (Addin addin)
{
return AddinInfo.ReadFromDescription (addin.Description);
}
Dictionary<string, AddinRepositoryProvider> providersList = new Dictionary<string, AddinRepositoryProvider> ();
public AddinRepositoryProvider GetAddinRepositoryProvider (string providerId)
{
if (string.IsNullOrEmpty (providerId))
providerId = "MonoAddins";
if (providersList.TryGetValue (providerId, out var addinRepositoryProvider))
return addinRepositoryProvider;
throw new KeyNotFoundException (providerId);
}
public void AddAddinRepositoryProvider (string providerId, AddinRepositoryProvider provider)
{
providersList [providerId] = provider;
}
public void RemoveAddinRepositoryProvider (string providerId)
{
providersList.Remove (providerId);
}
/// <summary>
/// Gets a list of add-ins which depend on an add-in
/// </summary>
/// <param name="id">
/// Full identifier of an add-in.
/// </param>
/// <param name="recursive">
/// When set to True, dependencies will be gathered recursivelly
/// </param>
/// <returns>
/// List of dependent add-ins.
/// </returns>
/// <remarks>
/// This methods returns a list of add-ins which have the add-in identified by 'id' as a direct
/// (or indirect if recursive=True) dependency.
/// </remarks>
public Addin [] GetDependentAddins (string id, bool recursive)
{
return store.GetDependentAddins (id, recursive);
}
/// <summary>
/// Packages an add-in
/// </summary>
/// <param name="statusMonitor">
/// Progress monitor where to show progress status
/// </param>
/// <param name="targetDirectory">
/// Directory where to generate the package
/// </param>
/// <param name="filePaths">
/// Paths to the add-ins to be packaged. Paths can be either the main assembly of an add-in, or an add-in
/// manifest (.addin or .addin.xml).
/// </param>
/// <remarks>
/// This method can be used to create a package for an add-in, which can then be pushed to an on-line
/// repository. The package will include the main assembly or manifest of the add-in and any external
/// file declared in the add-in metadata.
/// </remarks>
public string [] BuildPackage (IProgressStatus statusMonitor, string targetDirectory, params string [] filePaths)
{
return BuildPackage (statusMonitor, false, targetDirectory, filePaths);
}
/// <summary>
/// Packages an add-in
/// </summary>
/// <param name="statusMonitor">
/// Progress monitor where to show progress status
/// </param>
/// <param name="debugSymbols">
/// True if debug symbols (.pdb or .mdb) should be included in the package, if they exist
/// </param>
/// <param name="targetDirectory">
/// Directory where to generate the package
/// </param>
/// <param name="filePaths">
/// Paths to the add-ins to be packaged. Paths can be either the main assembly of an add-in, or an add-in
/// manifest (.addin or .addin.xml).
/// </param>
/// <remarks>
/// This method can be used to create a package for an add-in, which can then be pushed to an on-line
/// repository. The package will include the main assembly or manifest of the add-in and any external
/// file declared in the add-in metadata.
/// </remarks>
public string [] BuildPackage (IProgressStatus statusMonitor, bool debugSymbols, string targetDirectory, params string [] filePaths)
{
List<string> outFiles = new List<string> ();
foreach (string file in filePaths) {
string f = BuildPackageInternal (statusMonitor, debugSymbols, targetDirectory, file, PackageFormat.Mpack);
if (f != null)
outFiles.Add (f);
}
return outFiles.ToArray ();
}
/// <summary>
/// Packages an add-in
/// </summary>
/// <param name="statusMonitor">
/// Progress monitor where to show progress status
/// </param>
/// <param name="debugSymbols">
/// True if debug symbols (.pdb or .mdb) should be included in the package, if they exist
/// </param>
/// <param name="targetDirectory">
/// Directory where to generate the package
/// </param>
/// <param name="format">
/// Which format to produce .mpack or .vsix
/// </param>
/// <param name="filePaths">
/// Paths to the add-ins to be packaged. Paths can be either the main assembly of an add-in, or an add-in
/// manifest (.addin or .addin.xml).
/// </param>
/// <remarks>
/// This method can be used to create a package for an add-in, which can then be pushed to an on-line
/// repository. The package will include the main assembly or manifest of the add-in and any external
/// file declared in the add-in metadata.
/// </remarks>
public string [] BuildPackage (IProgressStatus statusMonitor, bool debugSymbols, string targetDirectory, PackageFormat format, params string [] filePaths)
{
List<string> outFiles = new List<string> ();
foreach (string file in filePaths) {
string f = BuildPackageInternal (statusMonitor, debugSymbols, targetDirectory, file, format);
if (f != null)
outFiles.Add (f);
}
return outFiles.ToArray ();
}
string BuildPackageInternal (IProgressStatus monitor, bool debugSymbols, string targetDirectory, string filePath, PackageFormat format)
{
AddinDescription conf = registry.GetAddinDescription (monitor, filePath);
if (conf == null) {
monitor.ReportError ("Could not read add-in file: " + filePath, null);
return null;
}
string basePath = Path.GetDirectoryName (Path.GetFullPath (filePath));
if (targetDirectory == null)
targetDirectory = basePath;
// Generate the file name
string localId;
if (conf.LocalId.Length == 0)
localId = Path.GetFileNameWithoutExtension (filePath);
else
localId = conf.LocalId;
string ext;
var name = Addin.GetFullId (conf.Namespace, localId, null);
string version = conf.Version;
switch (format) {
case PackageFormat.Mpack:
ext = ".mpack";
break;
case PackageFormat.Vsix:
ext = ".vsix";
break;
case PackageFormat.NuGet:
ext = ".nupkg";
if (string.IsNullOrEmpty (version)) {
monitor.ReportError ("Add-in doesn't have a version", null);
return null;
}
version = GetNuGetVersion (version);
break;
default:
throw new NotSupportedException (format.ToString ());
}
string outFilePath = Path.Combine (targetDirectory, name);
if (!string.IsNullOrEmpty (version))
outFilePath += "." + version;
outFilePath += ext;
ZipOutputStream s = new ZipOutputStream (File.Create (outFilePath));
s.SetLevel (5);
if (format == PackageFormat.Vsix) {
XmlDocument doc = new XmlDocument ();
doc.PreserveWhitespace = false;
doc.LoadXml (conf.SaveToVsixXml ().OuterXml);
AddXmlFile (s, doc, "extension.vsixmanifest");
}
if (format == PackageFormat.NuGet) {
var doc = GenerateNuspec (conf);
AddXmlFile (s, doc, Addin.GetIdName (conf.AddinId).ToLower () + ".nuspec");
}
// Generate a stripped down description of the add-in in a file, since the complete
// description may be declared as assembly attributes
XmlDocument infoDoc = new XmlDocument ();
infoDoc.PreserveWhitespace = false;
infoDoc.LoadXml (conf.SaveToXml ().OuterXml);
CleanDescription (infoDoc.DocumentElement);
AddXmlFile (s, infoDoc, "addin.info");
// Now add the add-in files
var files = new HashSet<string> ();
files.Add (Path.GetFileName (Util.NormalizePath (filePath)));
foreach (string f in conf.AllFiles) {
var file = Util.NormalizePath (f);
files.Add (file);
if (debugSymbols) {
if (File.Exists (Path.ChangeExtension (file, ".pdb")))
files.Add (Path.ChangeExtension (file, ".pdb"));
else if (File.Exists (file + ".mdb"))
files.Add (file + ".mdb");
}
}
foreach (var prop in conf.Properties) {
try {
var file = Util.NormalizePath (prop.Value);
if (File.Exists (Path.Combine (basePath, file))) {
files.Add (file);
}
} catch {
// Ignore errors
}
}
//add satellite assemblies for assemblies in the list
var satelliteFinder = new SatelliteAssemblyFinder ();
foreach (var f in files.ToList ()) {
foreach (var satellite in satelliteFinder.FindSatellites (Path.Combine (basePath, f))) {
var relativeSatellite = satellite.Substring (basePath.Length + 1);
files.Add (relativeSatellite);
}
}
monitor.Log ("Creating package " + Path.GetFileName (outFilePath));
foreach (string file in files) {
string fp = Path.Combine (basePath, file);
using (FileStream fs = File.OpenRead (fp)) {
byte [] buffer = new byte [fs.Length];
fs.Read (buffer, 0, buffer.Length);
var fileName = Path.DirectorySeparatorChar == '\\' ? file.Replace ('\\', '/') : file;
if (format == PackageFormat.NuGet)
fileName = Path.Combine ("addin", fileName);
var entry = new ZipEntry (fileName) { Size = fs.Length };
s.PutNextEntry (entry);
s.Write (buffer, 0, buffer.Length);
s.CloseEntry ();
}
}
if (format == PackageFormat.Vsix) {
files.Add ("addin.info");
files.Add ("extension.vsixmanifest");
XmlDocument doc = new XmlDocument ();
doc.PreserveWhitespace = false;
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration ("1.0", "UTF-8", null);
XmlElement root = doc.DocumentElement;
doc.InsertBefore (xmlDeclaration, root);
HashSet<string> alreadyAddedExtensions = new HashSet<string> ();
var typesEl = doc.CreateElement ("Types");
typesEl.SetAttribute ("xmlns", "http://schemas.openxmlformats.org/package/2006/content-types");
foreach (var file in files) {
var extension = Path.GetExtension (file);
if (string.IsNullOrEmpty (extension))
continue;
if (extension.StartsWith (".", StringComparison.Ordinal))
extension = extension.Substring (1);
if (alreadyAddedExtensions.Contains (extension))
continue;
alreadyAddedExtensions.Add (extension);
var typeEl = doc.CreateElement ("Default");
typeEl.SetAttribute ("Extension", extension);
typeEl.SetAttribute ("ContentType", GetContentType (extension));
typesEl.AppendChild (typeEl);
}
doc.AppendChild (typesEl);
AddXmlFile (s, doc, "[Content_Types].xml");
}
s.Finish ();
s.Close ();
return outFilePath;
}
private static void AddXmlFile (ZipOutputStream s, XmlDocument doc, string fileName)
{
MemoryStream ms = new MemoryStream ();
XmlTextWriter tw = new XmlTextWriter (ms, System.Text.Encoding.UTF8);
tw.Formatting = Formatting.Indented;
doc.WriteTo (tw);
tw.Flush ();
byte [] data = ms.ToArray ();
var infoEntry = new ZipEntry (fileName) { Size = data.Length };
s.PutNextEntry (infoEntry);
s.Write (data, 0, data.Length);
s.CloseEntry ();
}
XmlDocument GenerateNuspec (AddinDescription conf)
{
XmlDocument doc = new XmlDocument ();
var nugetNs = "http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd";
var rootElement = doc.CreateElement ("package", nugetNs);
doc.AppendChild (rootElement);
var metadataElement = doc.CreateElement ("metadata", nugetNs);
rootElement.AppendChild (metadataElement);
var prop = doc.CreateElement ("id", nugetNs);
prop.InnerText = Addin.GetIdName (conf.AddinId);
metadataElement.AppendChild (prop);
prop = doc.CreateElement ("version", nugetNs);
prop.InnerText = GetNuGetVersion (conf.Version);
metadataElement.AppendChild (prop);
prop = doc.CreateElement ("packageTypes", nugetNs);
prop.InnerText = "VisualStudioMacExtension";
metadataElement.AppendChild (prop);
if (!string.IsNullOrEmpty (conf.Author)) {
prop = doc.CreateElement ("authors", nugetNs);
prop.InnerText = conf.Author;
metadataElement.AppendChild (prop);
}
if (!string.IsNullOrEmpty (conf.Description)) {
prop = doc.CreateElement ("description", nugetNs);
prop.InnerText = conf.Description;
metadataElement.AppendChild (prop);
}
if (!string.IsNullOrEmpty (conf.Name)) {
prop = doc.CreateElement ("title", nugetNs);
prop.InnerText = conf.Name;
metadataElement.AppendChild (prop);
}
var depsElement = doc.CreateElement ("dependencies", nugetNs);
metadataElement.AppendChild (depsElement);
foreach (var dep in conf.MainModule.Dependencies.OfType<AddinDependency> ()) {
var depElem = doc.CreateElement ("dependency", nugetNs);
depElem.SetAttribute ("id", Addin.GetFullId (conf.Namespace, dep.AddinId, null));
depElem.SetAttribute ("version", GetNuGetVersion (dep.Version));
depsElement.AppendChild (depElem);
}
return doc;
}
static string GetNuGetVersion (string version)
{
if (Version.TryParse (version, out var parsedVersion)) {
// NuGet versions always have at least 3 components
if (parsedVersion.Build == -1)
version += ".0";
}
return version;
}
static string GetContentType (string extension)
{
switch (extension) {
case "txt": return "text/plain";
case "pkgdef": return "text/plain";
case "xml": return "text/xml";
case "vsixmanifest": return "text/xml";
case "htm or html": return "text/html";
case "rtf": return "application/rtf";
case "pdf": return "application/pdf";
case "gif": return "image/gif";
case "jpg or jpeg": return "image/jpg";
case "tiff": return "image/tiff";
case "vsix": return "application/zip";
case "zip": return "application/zip";
case "dll": return "application/octet-stream";
case "info": return "text/xml";//Mono.Addins info file
default: return "application/octet-stream";
}
}
class SatelliteAssemblyFinder
{
Dictionary<string, List<string>> cultureSubdirCache = new Dictionary<string, List<string>> ();
HashSet<string> cultureNames = new HashSet<string> (StringComparer.OrdinalIgnoreCase);
public SatelliteAssemblyFinder ()
{
foreach (var cultureName in CultureInfo.GetCultures (CultureTypes.AllCultures)) {
cultureNames.Add (cultureName.Name);
}
}
List<string> GetCultureSubdirectories (string directory)
{
if (!cultureSubdirCache.TryGetValue (directory, out List<string> cultureDirs)) {
cultureDirs = Directory.EnumerateDirectories (directory)
.Where (d => cultureNames.Contains (Path.GetFileName ((d))))
.ToList ();
cultureSubdirCache [directory] = cultureDirs;
}
return cultureDirs;
}
public IEnumerable<string> FindSatellites (string assemblyPath)
{
if (!assemblyPath.EndsWith (".dll", StringComparison.OrdinalIgnoreCase)) {
yield break;
}
var satelliteName = Path.GetFileNameWithoutExtension (assemblyPath) + ".resources.dll";
foreach (var cultureDir in GetCultureSubdirectories (Path.GetDirectoryName (assemblyPath))) {
string cultureName = Path.GetFileName (cultureDir);
string satellitePath = Path.Combine (cultureDir, satelliteName);
if (File.Exists (satellitePath)) {
yield return satellitePath;
}
}
}
}
void CleanDescription (XmlElement parent)
{
ArrayList todelete = new ArrayList ();
foreach (XmlNode nod in parent.ChildNodes) {
XmlElement elem = nod as XmlElement;
if (elem == null) {
todelete.Add (nod);
continue;
}
if (elem.LocalName == "Module")
CleanDescription (elem);
else if (elem.LocalName != "Dependencies" && elem.LocalName != "Runtime" && elem.LocalName != "Header")
todelete.Add (elem);
}
foreach (XmlNode e in todelete)
parent.RemoveChild (e);
}
/// <summary>
/// Generates an on-line repository
/// </summary>
/// <param name="statusMonitor">
/// Progress monitor where to show progress status
/// </param>
/// <param name="path">
/// Path to the directory that contains the add-ins and that is going to be published
/// </param>
/// <remarks>
/// This method generates the index files required to publish a directory as an online repository
/// of add-ins.
/// </remarks>
public void BuildRepository (IProgressStatus statusMonitor, string path)
{
string mainPath = Path.Combine (path, "main.mrep");
var allAddins = new List<PackageRepositoryEntry> ();
Repository rootrep = (Repository)AddinStore.ReadObject (mainPath, typeof (Repository));
if (rootrep == null)
rootrep = new Repository ();
IProgressMonitor monitor = ProgressStatusMonitor.GetProgressMonitor (statusMonitor);
BuildRepository (monitor, rootrep, path, "root.mrep", allAddins);
AddinStore.WriteObject (mainPath, rootrep);
GenerateIndexPage (rootrep, allAddins, path);
monitor.Log.WriteLine ("Updated main.mrep");
}
void BuildRepository (IProgressMonitor monitor, Repository rootrep, string rootPath, string relFilePath, List<PackageRepositoryEntry> allAddins)
{
DateTime lastModified = DateTime.MinValue;
string mainFile = Path.Combine (rootPath, relFilePath);
string mainPath = Path.GetDirectoryName (mainFile);
string supportFileDir = Path.Combine (mainPath, addinFilesDir);
if (File.Exists (mainFile))
lastModified = File.GetLastWriteTime (mainFile);
Repository mainrep = (Repository)AddinStore.ReadObject (mainFile, typeof (Repository));
if (mainrep == null) {
mainrep = new Repository ();
}
ReferenceRepositoryEntry repEntry = (ReferenceRepositoryEntry)rootrep.FindEntry (relFilePath);
DateTime rootLastModified = repEntry != null ? repEntry.LastModified : DateTime.MinValue;
bool modified = false;
monitor.Log.WriteLine ("Checking directory: " + mainPath);
foreach (string file in Directory.EnumerateFiles (mainPath, "*.mpack")) {
DateTime date = File.GetLastWriteTime (file);
string fname = Path.GetFileName (file);
PackageRepositoryEntry entry = (PackageRepositoryEntry)mainrep.FindEntry (fname);
if (entry != null && date > rootLastModified) {
mainrep.RemoveEntry (entry);
DeleteSupportFiles (supportFileDir, entry.Addin);
entry = null;
}
if (entry == null) {
entry = new PackageRepositoryEntry ();
AddinPackage p = (AddinPackage)Package.FromFile (file);
entry.Addin = (AddinInfo)p.Addin;
entry.Url = fname;
entry.Addin.Properties.SetPropertyValue ("DownloadSize", new FileInfo (file).Length.ToString ());
ExtractSupportFiles (supportFileDir, file, entry.Addin);
mainrep.AddEntry (entry);
modified = true;
monitor.Log.WriteLine ("Added addin: " + fname);
}
allAddins.Add (entry);
}
var toRemove = new List<PackageRepositoryEntry> ();
foreach (PackageRepositoryEntry entry in mainrep.Addins) {
if (!File.Exists (Path.Combine (mainPath, entry.Url))) {
toRemove.Add (entry);
modified = true;
}
}
foreach (PackageRepositoryEntry entry in toRemove) {
DeleteSupportFiles (supportFileDir, entry.Addin);
mainrep.RemoveEntry (entry);
}
if (modified) {
AddinStore.WriteObject (mainFile, mainrep);
monitor.Log.WriteLine ("Updated " + relFilePath);
lastModified = File.GetLastWriteTime (mainFile);
}
if (repEntry != null) {
if (repEntry.LastModified < lastModified)
repEntry.LastModified = lastModified;
} else if (modified) {
repEntry = new ReferenceRepositoryEntry ();
repEntry.LastModified = lastModified;
repEntry.Url = relFilePath;
rootrep.AddEntry (repEntry);
}
foreach (string dir in Directory.EnumerateDirectories (mainPath)) {
if (Path.GetFileName (dir) == addinFilesDir)
continue;
string based = dir.Substring (rootPath.Length + 1);
BuildRepository (monitor, rootrep, rootPath, Path.Combine (based, "main.mrep"), allAddins);
}
}
void DeleteSupportFiles (string targetDir, AddinInfo ainfo)
{
foreach (var prop in ainfo.Properties) {
if (prop.Value.StartsWith (addinFilesDir + Path.DirectorySeparatorChar)) {
string file = Path.Combine (targetDir, Path.GetFileName (prop.Value));
if (File.Exists (file))
File.Delete (file);
}
}
if (Directory.Exists (targetDir) && !Directory.EnumerateFileSystemEntries (targetDir).Any ())
Directory.Delete (targetDir, true);
}
void ExtractSupportFiles (string targetDir, string file, AddinInfo ainfo)
{
Random r = new Random ();
ZipFile zfile = new ZipFile (file);
try {
foreach (var prop in ainfo.Properties) {
ZipEntry ze = zfile.GetEntry (prop.Value);
if (ze != null) {
string fname;
do {
fname = Path.Combine (targetDir, r.Next ().ToString ("x") + Path.GetExtension (prop.Value));
} while (File.Exists (fname));
if (!Directory.Exists (targetDir))
Directory.CreateDirectory (targetDir);
using (var f = File.OpenWrite (fname)) {
using (Stream s = zfile.GetInputStream (ze)) {
byte [] buffer = new byte [8092];
int nr = 0;
while ((nr = s.Read (buffer, 0, buffer.Length)) > 0)
f.Write (buffer, 0, nr);
}
}
prop.Value = Path.Combine (addinFilesDir, Path.GetFileName (fname));
}
}
} finally {
zfile.Close ();
}
}
void GenerateIndexPage (Repository rep, List<PackageRepositoryEntry> addins, string basePath)
{
StreamWriter sw = new StreamWriter (Path.Combine (basePath, "index.html"));
sw.WriteLine ("<html><body>");
sw.WriteLine ("<h1>Add-in Repository</h1>");
if (rep.Name != null && rep.Name != "")
sw.WriteLine ("<h2>" + rep.Name + "</h2>");
sw.WriteLine ("<p>This is a list of add-ins available in this repository.</p>");
sw.WriteLine ("<table border=1><thead><tr><th>Add-in</th><th>Version</th><th>Description</th></tr></thead>");
foreach (PackageRepositoryEntry entry in addins) {
sw.WriteLine ("<tr><td>" + entry.Addin.Name + "</td><td>" + entry.Addin.Version + "</td><td>" + entry.Addin.Description + "</td></tr>");
}
sw.WriteLine ("</table>");
sw.WriteLine ("</body></html>");
sw.Close ();
}
internal AddinSystemConfiguration Configuration {
get {
if (config == null) {
if (File.Exists (RootConfigFile))
config = (AddinSystemConfiguration)AddinStore.ReadObject (RootConfigFile, typeof (AddinSystemConfiguration));
else
config = (AddinSystemConfiguration)AddinStore.ReadObject (RootConfigFileOld, typeof (AddinSystemConfiguration));
if (config == null)
config = new AddinSystemConfiguration ();
}
return config;
}
}
internal void SaveConfiguration ()
{
if (config != null) {
AddinStore.WriteObject (RootConfigFile, config);
}
}
internal void ResetConfiguration ()
{
if (File.Exists (RootConfigFile))
File.Delete (RootConfigFile);
if (File.Exists (RootConfigFileOld))
File.Delete (RootConfigFileOld);
ResetAddinInfo ();
}
internal void ResetAddinInfo ()
{
if (Directory.Exists (RepositoryCachePath))
Directory.Delete (RepositoryCachePath, true);
}
/// <summary>
/// Gets a reference to an extensible application
/// </summary>
/// <param name="name">
/// Name of the application
/// </param>
/// <returns>
/// The Application object. Null if not found.
/// </returns>
public static Application GetExtensibleApplication (string name)
{
return GetExtensibleApplication (name, null);
}
/// <summary>
/// Gets a reference to an extensible application
/// </summary>
/// <param name="name">
/// Name of the application
/// </param>
/// <param name="searchPaths">
/// Custom paths where to look for the application.
/// </param>
/// <returns>
/// The Application object. Null if not found.
/// </returns>
public static Application GetExtensibleApplication (string name, IEnumerable<string> searchPaths)
{
AddinsPcFileCache pcc = GetAddinsPcFileCache (searchPaths);
PackageInfo pi = pcc.GetPackageInfoByName (name, searchPaths);
if (pi != null)
return new Application (pi);
else
return null;
}
/// <summary>
/// Gets a lis of all known extensible applications
/// </summary>
/// <returns>
/// A list of applications.
/// </returns>
public static Application [] GetExtensibleApplications ()
{
return GetExtensibleApplications (null);
}
/// <summary>
/// Gets a lis of all known extensible applications
/// </summary>
/// <param name="searchPaths">
/// Custom paths where to look for applications.
/// </param>
/// <returns>
/// A list of applications.
/// </returns>
public static Application [] GetExtensibleApplications (IEnumerable<string> searchPaths)
{
List<Application> list = new List<Application> ();
AddinsPcFileCache pcc = GetAddinsPcFileCache (searchPaths);
foreach (PackageInfo pinfo in pcc.GetPackages (searchPaths)) {
if (pinfo.IsValidPackage)
list.Add (new Application (pinfo));
}
return list.ToArray ();
}
static AddinsPcFileCache pcFileCache;
static AddinsPcFileCache GetAddinsPcFileCache (IEnumerable<string> searchPaths)
{
if (pcFileCache == null) {
pcFileCache = new AddinsPcFileCache ();
if (searchPaths != null)
pcFileCache.Update (searchPaths);
else
pcFileCache.Update ();
}
return pcFileCache;
}
}
class AddinsPcFileCacheContext : IPcFileCacheContext
{
public bool IsCustomDataComplete (string pcfile, PackageInfo pkg)
{
return true;
}
public void StoreCustomData (Mono.PkgConfig.PcFile pcfile, PackageInfo pkg)
{
}
public void ReportError (string message, System.Exception ex)
{
Console.WriteLine (message);
Console.WriteLine (ex);
}
}
class AddinsPcFileCache : PcFileCache
{
public AddinsPcFileCache () : base (new AddinsPcFileCacheContext ())
{
}
protected override string CacheDirectory {
get {
string path = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
path = Path.Combine (path, "mono.addins");
return path;
}
}
protected override void ParsePackageInfo (PcFile file, PackageInfo pinfo)
{
string rootPath = file.GetVariable ("MonoAddinsRoot");
string regPath = file.GetVariable ("MonoAddinsRegistry");
string addinsPath = file.GetVariable ("MonoAddinsInstallPath");
string databasePath = file.GetVariable ("MonoAddinsCachePath");
string testCmd = file.GetVariable ("MonoAddinsTestCommand");
if (string.IsNullOrEmpty (rootPath) || string.IsNullOrEmpty (regPath))
return;
pinfo.SetData ("MonoAddinsRoot", rootPath);
pinfo.SetData ("MonoAddinsRegistry", regPath);
pinfo.SetData ("MonoAddinsInstallPath", addinsPath);
pinfo.SetData ("MonoAddinsCachePath", databasePath);
pinfo.SetData ("MonoAddinsTestCommand", testCmd);
}
}
/// <summary>
/// A registered extensible application
/// </summary>
public class Application
{
AddinRegistry registry;
string description;
string name;
string testCommand;
string startupPath;
string registryPath;
string addinsPath;
string databasePath;
internal Application (PackageInfo pinfo)
{
name = pinfo.Name;
description = pinfo.Description;
startupPath = pinfo.GetData ("MonoAddinsRoot");
registryPath = pinfo.GetData ("MonoAddinsRegistry");
addinsPath = pinfo.GetData ("MonoAddinsInstallPath");
databasePath = pinfo.GetData ("MonoAddinsCachePath");
testCommand = pinfo.GetData ("MonoAddinsTestCommand");
}
/// <summary>
/// Add-in registry of the application
/// </summary>
public AddinRegistry Registry {
get {
if (registry == null)
registry = new AddinRegistry (RegistryPath, StartupPath, AddinsPath, AddinCachePath);
return registry;
}
}
/// <summary>
/// Description of the application
/// </summary>
public string Description {
get {
return description;
}
}
/// <summary>
/// Name of the application
/// </summary>
public string Name {
get {
return name;
}
}
/// <summary>
/// Path to the add-in registry
/// </summary>
public string RegistryPath {
get {
return registryPath;
}
}
/// <summary>
/// Path to the directory that contains the main executable assembly of the application
/// </summary>
public string StartupPath {
get {
return startupPath;
}
}
/// <summary>
/// Command to be used to execute the application in add-in development mode.
/// </summary>
public string TestCommand {
get {
return testCommand;
}
}
/// <summary>
/// Path to the default add-ins directory for the aplpication
/// </summary>
public string AddinsPath {
get {
return addinsPath;
}
}
/// <summary>
/// Path to the add-in cache for the application
/// </summary>
public string AddinCachePath {
get {
return databasePath;
}
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetDataPoliciesSpectraS3Request : Ds3Request
{
private bool? _alwaysForcePutJobCreation;
public bool? AlwaysForcePutJobCreation
{
get { return _alwaysForcePutJobCreation; }
set { WithAlwaysForcePutJobCreation(value); }
}
private bool? _alwaysMinimizeSpanningAcrossMedia;
public bool? AlwaysMinimizeSpanningAcrossMedia
{
get { return _alwaysMinimizeSpanningAcrossMedia; }
set { WithAlwaysMinimizeSpanningAcrossMedia(value); }
}
private ChecksumType.Type? _checksumType;
public ChecksumType.Type? ChecksumType
{
get { return _checksumType; }
set { WithChecksumType(value); }
}
private bool? _endToEndCrcRequired;
public bool? EndToEndCrcRequired
{
get { return _endToEndCrcRequired; }
set { WithEndToEndCrcRequired(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private string _name;
public string Name
{
get { return _name; }
set { WithName(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
public GetDataPoliciesSpectraS3Request WithAlwaysForcePutJobCreation(bool? alwaysForcePutJobCreation)
{
this._alwaysForcePutJobCreation = alwaysForcePutJobCreation;
if (alwaysForcePutJobCreation != null)
{
this.QueryParams.Add("always_force_put_job_creation", alwaysForcePutJobCreation.ToString());
}
else
{
this.QueryParams.Remove("always_force_put_job_creation");
}
return this;
}
public GetDataPoliciesSpectraS3Request WithAlwaysMinimizeSpanningAcrossMedia(bool? alwaysMinimizeSpanningAcrossMedia)
{
this._alwaysMinimizeSpanningAcrossMedia = alwaysMinimizeSpanningAcrossMedia;
if (alwaysMinimizeSpanningAcrossMedia != null)
{
this.QueryParams.Add("always_minimize_spanning_across_media", alwaysMinimizeSpanningAcrossMedia.ToString());
}
else
{
this.QueryParams.Remove("always_minimize_spanning_across_media");
}
return this;
}
public GetDataPoliciesSpectraS3Request WithChecksumType(ChecksumType.Type? checksumType)
{
this._checksumType = checksumType;
if (checksumType != null)
{
this.QueryParams.Add("checksum_type", checksumType.ToString());
}
else
{
this.QueryParams.Remove("checksum_type");
}
return this;
}
public GetDataPoliciesSpectraS3Request WithEndToEndCrcRequired(bool? endToEndCrcRequired)
{
this._endToEndCrcRequired = endToEndCrcRequired;
if (endToEndCrcRequired != null)
{
this.QueryParams.Add("end_to_end_crc_required", endToEndCrcRequired.ToString());
}
else
{
this.QueryParams.Remove("end_to_end_crc_required");
}
return this;
}
public GetDataPoliciesSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetDataPoliciesSpectraS3Request WithName(string name)
{
this._name = name;
if (name != null)
{
this.QueryParams.Add("name", name);
}
else
{
this.QueryParams.Remove("name");
}
return this;
}
public GetDataPoliciesSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetDataPoliciesSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetDataPoliciesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDataPoliciesSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDataPoliciesSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/data_policy";
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.ReminderService;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.TestHelper;
using Xunit;
using Xunit.Sdk;
namespace UnitTests.General
{
public class ConsistentRingProviderTests_Silo : TestClusterPerTest
{
private const int numAdditionalSilos = 3;
private readonly TimeSpan failureTimeout = TimeSpan.FromSeconds(30);
private readonly TimeSpan endWait = TimeSpan.FromMinutes(5);
enum Fail { First, Random, Last }
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.AddSiloBuilderConfigurator<Configurator>();
builder.AddClientBuilderConfigurator<Configurator>();
}
private class Configurator : ISiloConfigurator, IClientBuilderConfigurator
{
public void Configure(ISiloBuilder hostBuilder)
{
hostBuilder.AddMemoryGrainStorage("MemoryStore")
.AddMemoryGrainStorageAsDefault()
.UseInMemoryReminderService();
}
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder.Configure<GatewayOptions>(
options => options.GatewayListRefreshPeriod = TimeSpan.FromMilliseconds(100));
}
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_Basic()
{
await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
VerificationScenario(0);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1F_Random()
{
await FailureTest(Fail.Random, 1);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1F_Beginning()
{
await FailureTest(Fail.First, 1);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1F_End()
{
await FailureTest(Fail.Last, 1);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_2F_Random()
{
await FailureTest(Fail.Random, 2);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_2F_Beginning()
{
await FailureTest(Fail.First, 2);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_2F_End()
{
await FailureTest(Fail.Last, 2);
}
private async Task FailureTest(Fail failCode, int numOfFailures)
{
await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
List<SiloHandle> failures = await getSilosToFail(failCode, numOfFailures);
foreach (SiloHandle fail in failures) // verify before failure
{
VerificationScenario(PickKey(fail.SiloAddress)); // fail.SiloAddress.GetConsistentHashCode());
}
logger.Info("FailureTest {0}, Code {1}, Stopping silos: {2}", numOfFailures, failCode, Utils.EnumerableToString(failures, handle => handle.SiloAddress.ToString()));
List<uint> keysToTest = new List<uint>();
foreach (SiloHandle fail in failures) // verify before failure
{
keysToTest.Add(PickKey(fail.SiloAddress)); //fail.SiloAddress.GetConsistentHashCode());
await this.HostedCluster.StopSiloAsync(fail);
}
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
AssertEventually(() =>
{
foreach (var key in keysToTest) // verify after failure
{
VerificationScenario(key);
}
}, failureTimeout);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1J()
{
await JoinTest(1);
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_2J()
{
await JoinTest(2);
}
private async Task JoinTest(int numOfJoins)
{
logger.Info("JoinTest {0}", numOfJoins);
await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos - numOfJoins);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
List<SiloHandle> silos = await this.HostedCluster.StartAdditionalSilosAsync(numOfJoins);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
foreach (SiloHandle sh in silos)
{
VerificationScenario(PickKey(sh.SiloAddress));
}
Thread.Sleep(TimeSpan.FromSeconds(15));
}
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1F1J()
{
await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
List<SiloHandle> failures = await getSilosToFail(Fail.Random, 1);
uint keyToCheck = PickKey(failures[0].SiloAddress);// failures[0].SiloAddress.GetConsistentHashCode();
List<SiloHandle> joins = null;
// kill a silo and join a new one in parallel
logger.Info("Killing silo {0} and joining a silo", failures[0].SiloAddress);
var tasks = new Task[2]
{
Task.Factory.StartNew(() => this.HostedCluster.StopSiloAsync(failures[0])),
this.HostedCluster.StartAdditionalSilosAsync(1).ContinueWith(t => joins = t.GetAwaiter().GetResult())
};
Task.WaitAll(tasks, endWait);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
AssertEventually(() =>
{
VerificationScenario(keyToCheck); // verify failed silo's key
VerificationScenario(PickKey(joins[0].SiloAddress)); // verify newly joined silo's key
}, failureTimeout);
}
// failing the secondary in this scenario exposed the bug in DomainGrain ... so, we keep it as a separate test than Ring_1F1J
[Fact, TestCategory("Functional"), TestCategory("Ring")]
public async Task Ring_1Fsec1J()
{
await this.HostedCluster.StartAdditionalSilosAsync(numAdditionalSilos);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
//List<SiloHandle> failures = getSilosToFail(Fail.Random, 1);
SiloHandle fail = this.HostedCluster.SecondarySilos.First();
uint keyToCheck = PickKey(fail.SiloAddress); //fail.SiloAddress.GetConsistentHashCode();
List<SiloHandle> joins = null;
// kill a silo and join a new one in parallel
logger.Info("Killing secondary silo {0} and joining a silo", fail.SiloAddress);
var tasks = new Task[2]
{
Task.Factory.StartNew(() => this.HostedCluster.StopSiloAsync(fail)),
this.HostedCluster.StartAdditionalSilosAsync(1).ContinueWith(t => joins = t.GetAwaiter().GetResult())
};
Task.WaitAll(tasks, endWait);
await this.HostedCluster.WaitForLivenessToStabilizeAsync();
AssertEventually(() =>
{
VerificationScenario(keyToCheck); // verify failed silo's key
VerificationScenario(PickKey(joins[0].SiloAddress));
}, failureTimeout);
}
private uint PickKey(SiloAddress responsibleSilo)
{
int iteration = 10000;
var testHooks = this.Client.GetTestHooks(this.HostedCluster.Primary);
for (int i = 0; i < iteration; i++)
{
double next = random.NextDouble();
uint randomKey = (uint)((double)RangeFactory.RING_SIZE * next);
SiloAddress s = testHooks.GetConsistentRingPrimaryTargetSilo(randomKey).Result;
if (responsibleSilo.Equals(s))
return randomKey;
}
throw new Exception(String.Format("Could not pick a key that silo {0} will be responsible for. Primary.Ring = \n{1}",
responsibleSilo, testHooks.GetConsistentRingProviderDiagnosticInfo().Result));
}
private void VerificationScenario(uint testKey)
{
// setup
List<SiloAddress> silos = new List<SiloAddress>();
foreach (var siloHandle in this.HostedCluster.GetActiveSilos())
{
long hash = siloHandle.SiloAddress.GetConsistentHashCode();
int index = silos.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1;
silos.Insert(index, siloHandle.SiloAddress);
}
// verify parameter key
VerifyKey(testKey, silos);
// verify some other keys as well, apart from the parameter key
// some random keys
for (int i = 0; i < 3; i++)
{
VerifyKey((uint)random.Next(), silos);
}
// lowest key
uint lowest = (uint)(silos.First().GetConsistentHashCode() - 1);
VerifyKey(lowest, silos);
// highest key
uint highest = (uint)(silos.Last().GetConsistentHashCode() + 1);
VerifyKey(lowest, silos);
}
private void VerifyKey(uint key, List<SiloAddress> silos)
{
var testHooks = this.Client.GetTestHooks(this.HostedCluster.Primary);
SiloAddress truth = testHooks.GetConsistentRingPrimaryTargetSilo(key).Result; //expected;
//if (truth == null) // if the truth isn't passed, we compute it here
//{
// truth = silos.Find(siloAddr => (key <= siloAddr.GetConsistentHashCode()));
// if (truth == null)
// {
// truth = silos.First();
// }
//}
// lookup for 'key' should return 'truth' on all silos
foreach (var siloHandle in this.HostedCluster.GetActiveSilos()) // do this for each silo
{
testHooks = this.Client.GetTestHooks(siloHandle);
SiloAddress s = testHooks.GetConsistentRingPrimaryTargetSilo((uint)key).Result;
Assert.Equal(truth, s);
}
}
private async Task<List<SiloHandle>> getSilosToFail(Fail fail, int numOfFailures)
{
List<SiloHandle> failures = new List<SiloHandle>();
int count = 0;
// Figure out the primary directory partition and the silo hosting the ReminderTableGrain.
var tableGrain = this.GrainFactory.GetGrain<IReminderTableGrain>(InMemoryReminderTable.ReminderTableGrainId);
// Ping the grain to make sure it is active.
await tableGrain.ReadRows((GrainReference)tableGrain);
var tableGrainId = ((GrainReference)tableGrain).GrainId;
SiloAddress reminderTableGrainPrimaryDirectoryAddress = (await TestUtils.GetDetailedGrainReport(this.HostedCluster.InternalGrainFactory, tableGrainId, this.HostedCluster.Primary)).PrimaryForGrain;
// ask a detailed report from the directory partition owner, and get the actionvation addresses
var addresses = (await TestUtils.GetDetailedGrainReport(this.HostedCluster.InternalGrainFactory, tableGrainId, this.HostedCluster.GetSiloForAddress(reminderTableGrainPrimaryDirectoryAddress))).LocalDirectoryActivationAddresses;
ActivationAddress reminderGrainActivation = addresses.FirstOrDefault();
SortedList<int, SiloHandle> ids = new SortedList<int, SiloHandle>();
foreach (var siloHandle in this.HostedCluster.GetActiveSilos())
{
SiloAddress siloAddress = siloHandle.SiloAddress;
if (siloAddress.Equals(this.HostedCluster.Primary.SiloAddress))
{
continue;
}
// Don't fail primary directory partition and the silo hosting the ReminderTableGrain.
if (siloAddress.Equals(reminderTableGrainPrimaryDirectoryAddress) || siloAddress.Equals(reminderGrainActivation.Silo))
{
continue;
}
ids.Add(siloHandle.SiloAddress.GetConsistentHashCode(), siloHandle);
}
int index;
// we should not fail the primary!
// we can't guarantee semantics of 'Fail' if it evalutes to the primary's address
switch (fail)
{
case Fail.First:
index = 0;
while (count++ < numOfFailures)
{
while (failures.Contains(ids.Values[index]))
{
index++;
}
failures.Add(ids.Values[index]);
}
break;
case Fail.Last:
index = ids.Count - 1;
while (count++ < numOfFailures)
{
while (failures.Contains(ids.Values[index]))
{
index--;
}
failures.Add(ids.Values[index]);
}
break;
case Fail.Random:
default:
while (count++ < numOfFailures)
{
SiloHandle r = ids.Values[random.Next(ids.Count)];
while (failures.Contains(r))
{
r = ids.Values[random.Next(ids.Count)];
}
failures.Add(r);
}
break;
}
return failures;
}
// for debugging only
private void printSilos(string msg)
{
SortedList<int, SiloAddress> ids = new SortedList<int, SiloAddress>(numAdditionalSilos + 2);
foreach (var siloHandle in this.HostedCluster.GetActiveSilos())
{
ids.Add(siloHandle.SiloAddress.GetConsistentHashCode(), siloHandle.SiloAddress);
}
logger.Info("{0} list of silos: ", msg);
foreach (var id in ids.Keys.ToList())
{
logger.Info("{0} -> {1}", ids[id], id);
}
}
private static void AssertEventually(Action assertion, TimeSpan timeout)
{
AssertEventually(assertion, timeout, TimeSpan.FromMilliseconds(500));
}
private static void AssertEventually(Action assertion, TimeSpan timeout, TimeSpan delayBetweenIterations)
{
var sw = Stopwatch.StartNew();
while (true)
{
try
{
assertion();
return;
}
catch (XunitException)
{
if (sw.ElapsedMilliseconds > timeout.TotalMilliseconds)
{
throw;
}
}
if (delayBetweenIterations > TimeSpan.Zero)
{
Thread.Sleep(delayBetweenIterations);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.Sql;
using System.Linq;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Serialization.Formatters.Binary;
using MySql.Data.MySqlClient;
using Analysis.EDM;
namespace SirCachealot.Database
{
class MySqlDBlockStore : MarshalByRefObject, DBlockStore
{
private MySqlConnection mySql;
private MySqlCommand mySqlComm;
public long QueryCount;
public long DBlockCount;
public UInt32[] GetUIDsByCluster(string clusterName, UInt32[] fromUIDs)
{
QueryCount++;
return GetByStringParameter("CLUSTER", clusterName, fromUIDs);
}
public UInt32[] GetUIDsByCluster(string clusterName)
{
QueryCount++;
return GetByStringParameter("CLUSTER", clusterName);
}
public UInt32[] GetUIDsByBlock(string clusterName, int clusterIndex, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE CLUSTER = ?cluster AND CLUSTERINDEX = ?index AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?cluster", clusterName);
mySqlComm.Parameters.AddWithValue("?index", clusterIndex);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByBlock(string clusterName, int clusterIndex)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE CLUSTER = ?cluster AND CLUSTERINDEX = ?index";
mySqlComm.Parameters.AddWithValue("?cluster", clusterName);
mySqlComm.Parameters.AddWithValue("?index", clusterIndex);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByTag(string tag, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT DISTINCT UID FROM DBLOCKS, TAGS WHERE TAGS.TAG = ?tag AND " +
"TAGS.CLUSTER = DBLOCKS.CLUSTER AND " +
"TAGS.CLUSTERINDEX = DBLOCKS.CLUSTERINDEX AND UID IN " + MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?tag", tag);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByTag(string tag)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT DISTINCT UID FROM DBLOCKS, TAGS WHERE TAGS.TAG = ?tag AND " +
"TAGS.CLUSTER = DBLOCKS.CLUSTER AND " +
"TAGS.CLUSTERINDEX = DBLOCKS.CLUSTERINDEX";
mySqlComm.Parameters.AddWithValue("?tag", tag);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByAnalysisTag(string tag, UInt32[] fromUIDs)
{
QueryCount++;
return GetByStringParameter("ATAG", tag, fromUIDs);
}
public UInt32[] GetUIDsByAnalysisTag(string tag)
{
QueryCount++;
return GetByStringParameter("ATAG", tag);
}
public UInt32[] GetUIDsByMachineState(bool eState, bool bState, bool rfState, bool mwState, uint[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE ESTATE = ?eState AND BSTATE = ?bState " +
"AND RFSTATE = ?rfState AND MWSTATE = ?mwState AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?eState", eState);
mySqlComm.Parameters.AddWithValue("?bState", bState);
mySqlComm.Parameters.AddWithValue("?rfState", rfState);
mySqlComm.Parameters.AddWithValue("?mwState", mwState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByMachineState(bool eState, bool bState, bool rfState, bool mwState)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE ESTATE = ?eState AND BSTATE = ?bState " +
"AND RFSTATE = ?rfState AND MWSTATE = ?mwState";
mySqlComm.Parameters.AddWithValue("?eState", eState);
mySqlComm.Parameters.AddWithValue("?bState", bState);
mySqlComm.Parameters.AddWithValue("?rfState", rfState);
mySqlComm.Parameters.AddWithValue("?mwState", mwState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByEState(bool eState, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE ESTATE = ?eState AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?eState", eState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByEState(bool eState)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE ESTATE = ?eState";
mySqlComm.Parameters.AddWithValue("?eState", eState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByBState(bool bState, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE BSTATE = ?bState AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?bState", bState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByBState(bool bState)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE BSTATE = ?bState";
mySqlComm.Parameters.AddWithValue("?bState", bState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByRFState(bool rfState, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE RFSTATE = ?rfState AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?rfState", rfState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByRFState(bool rfState)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE RFSTATE = ?rfState";
mySqlComm.Parameters.AddWithValue("?rfState", rfState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByMWState(bool mwState, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE MWSTATE = ?mwState AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?mwState", mwState);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByMWState(bool mwState)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE MWSTATE = ?mwState";
mySqlComm.Parameters.AddWithValue("?mwState", mwState);
return GetUIDsFromCommand(mySqlComm);
}
public uint[] GetUIDsByDateRange(DateTime start, DateTime end, uint[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE BLOCKTIME >= ?start AND BLOCKTIME < ?end AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?start", start);
mySqlComm.Parameters.AddWithValue("?end", end);
return GetUIDsFromCommand(mySqlComm);
}
public uint[] GetUIDsByDateRange(DateTime start, DateTime end)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE BLOCKTIME >= ?start AND BLOCKTIME < ?end";
mySqlComm.Parameters.AddWithValue("?start", start);
mySqlComm.Parameters.AddWithValue("?end", end);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByVoltageRange(double low, double high, UInt32[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE EPLUS >= ?low AND EPLUS < ?high AND UID IN " +
MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?low", low);
mySqlComm.Parameters.AddWithValue("?high", high);
return GetUIDsFromCommand(mySqlComm);
}
public UInt32[] GetUIDsByVoltageRange(double low, double high)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE EPLUS >= ?low AND EPLUS < ?high";
mySqlComm.Parameters.AddWithValue("?low", low);
mySqlComm.Parameters.AddWithValue("?high", high);
return GetUIDsFromCommand(mySqlComm);
}
public uint[] GetUIDsByPredicate(PredicateFunction func, uint[] fromUIDs)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE UID IN " + MakeSQLArrayString(fromUIDs);
UInt32[] uids = GetUIDsFromCommand(mySqlComm);
List<UInt32> matchedUIDs = new List<UInt32>();
foreach (UInt32 uid in uids)
{
DemodulatedBlock db = GetDBlock(uid);
if (func(db)) matchedUIDs.Add(uid);
}
return matchedUIDs.ToArray();
}
public DemodulatedBlock GetDBlock(uint uid)
{
DBlockCount++;
byte[] dbb;
MySqlDataReader rd = executeReader("SELECT DBDAT FROM DBLOCKDATA WHERE UID = " + uid);
DemodulatedBlock db;
if (rd.Read())
{
dbb = (byte[])rd["DBDAT"];
db = deserializeDBlockFromByteArray(dbb);
rd.Close();
}
else
{
rd.Close();
throw new BlockNotFoundException();
}
return db;
}
// this method temporarily is locked so that only one thread at a time can execute.
// I need to fix a db problem concerning the UIDs before unlocking it.
// Hopefully it won't hurt the performance too badly.
private object dbAddLock = new object();
public UInt32 AddDBlock(DemodulatedBlock db)
{
lock (dbAddLock)
{
mySqlComm = mySql.CreateCommand();
// extract the data that we're going to put in the sql database
string clusterName = db.Config.Settings["cluster"] as string;
int clusterIndex = (int)db.Config.Settings["clusterIndex"];
string aTag = "";
bool eState = (bool)db.Config.Settings["eState"];
bool bState = (bool)db.Config.Settings["bState"];
bool rfState = (bool)db.Config.Settings["rfState"];
// for some blocks, no mw state config
bool mwState = true;
if (db.Config.Settings.StringKeyList.Contains("mwState")) mwState = (bool)db.Config.Settings["mwState"];
DateTime timeStamp = db.TimeStamp;
double ePlus = (double)db.Config.Settings["ePlus"];
double eMinus = (double)db.Config.Settings["eMinus"];
byte[] dBlockBytes = serializeDBlockAsByteArray(db);
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"INSERT INTO DBLOCKS " +
"VALUES(?uint, ?cluster, ?clusterIndex, ?aTag, ?eState, ?bState, ?rfState, ?mwState, ?ts, " +
"?ePlus, ?eMinus);";
// the uid column is defined auto_increment
mySqlComm.Parameters.AddWithValue("?uint", null);
mySqlComm.Parameters.AddWithValue("?cluster", clusterName);
mySqlComm.Parameters.AddWithValue("?clusterIndex", clusterIndex);
mySqlComm.Parameters.AddWithValue("?aTag", aTag);
mySqlComm.Parameters.AddWithValue("?eState", eState);
mySqlComm.Parameters.AddWithValue("?bState", bState);
mySqlComm.Parameters.AddWithValue("?rfState", rfState);
mySqlComm.Parameters.AddWithValue("?mwState", mwState);
mySqlComm.Parameters.AddWithValue("?ts", timeStamp);
mySqlComm.Parameters.AddWithValue("?ePlus", ePlus);
mySqlComm.Parameters.AddWithValue("?eMinus", eMinus);
mySqlComm.ExecuteNonQuery();
mySqlComm.Parameters.Clear();
UInt32 uid = (UInt32)mySqlComm.LastInsertedId;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"INSERT INTO DBLOCKDATA VALUES(?uint, ?dblock);";
mySqlComm.Parameters.AddWithValue("?uint", uid);
mySqlComm.Parameters.AddWithValue("?dblock", dBlockBytes);
mySqlComm.ExecuteNonQuery();
mySqlComm.Parameters.Clear();
return uid;
}
}
public void RemoveDBlock(UInt32 uid)
{
executeNonQuery("DELETE FROM DBLOCKS WHERE UID = " + uid);
executeNonQuery("DELETE FROM DBLOCKDATA WHERE UID = " + uid);
}
public UInt32[] GetAllUIDs()
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS";
return GetUIDsFromCommand(mySqlComm);
}
public void AddTagToBlock(string clusterName, int blockIndex, string tag)
{
QueryCount++;
executeNonQuery("INSERT INTO TAGS VALUES('" + clusterName + "', " + blockIndex + ", '" + tag + "')");
}
public void RemoveTagFromBlock(string clusterName, int blockIndex, string tag)
{
QueryCount++;
executeNonQuery(
"DELETE FROM TAGS WHERE CLUSTER = '" + clusterName + "' AND CLUSTERINDEX = " + blockIndex +
" AND TAG = '" + tag + "'"
);
}
public UInt32[] GetTaggedIndicesForCluster(string clusterName, string tag)
{
QueryCount++;
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT DISTINCT TAGS.CLUSTERINDEX FROM TAGS, DBLOCKS WHERE TAGS.CLUSTER = ?cluster AND " +
"TAGS.TAG = ?tag AND TAGS.CLUSTER = DBLOCKS.CLUSTER AND TAGS.CLUSTERINDEX = " +
"DBLOCKS.CLUSTERINDEX";
mySqlComm.Parameters.AddWithValue("?cluster", clusterName);
mySqlComm.Parameters.AddWithValue("?tag", tag);
return GetUIntsFromCommand(mySqlComm, "CLUSTERINDEX");
}
private string MakeSQLArrayString(UInt32[] uids)
{
StringBuilder sqlArray = new StringBuilder("(");
for (int i = 0; i < uids.Length - 1; i++)
{
sqlArray.Append(uids[i]);
sqlArray.Append(", ");
}
sqlArray.Append(uids[uids.Length - 1]);
sqlArray.Append(")");
return sqlArray.ToString();
}
private UInt32[] GetByStringParameter(string parameter, string val)
{
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = "SELECT UID FROM DBLOCKS WHERE " + parameter + " = ?val";
mySqlComm.Parameters.AddWithValue("?val", val);
return GetUIDsFromCommand(mySqlComm);
}
private UInt32[] GetByStringParameter(string parameter, string val, UInt32[] fromUIDs)
{
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText =
"SELECT UID FROM DBLOCKS WHERE " + parameter +
" = ?val AND UID IN " + MakeSQLArrayString(fromUIDs);
mySqlComm.Parameters.AddWithValue("?val", val);
return GetUIDsFromCommand(mySqlComm);
}
private UInt32[] GetUIDsFromCommand(MySqlCommand cm)
{
return GetUIntsFromCommand(cm, "UID");
}
private UInt32[] GetUIntsFromCommand(MySqlCommand cm, string column)
{
MySqlDataReader rd = cm.ExecuteReader();
List<UInt32> uids = new List<UInt32>();
while (rd.Read()) uids.Add((UInt32)rd[column]);
rd.Close();
return uids.ToArray();
}
internal void Start(string username, string password)
{
// This creates a shared connection that is used for all query methods. As a result, the query
// methods are probably not currently thread-safe (maybe, need to check).
string hostIP = "155.198.208.81";
string kConnectionString = "server=" + hostIP + ";user=" + username + ";port=3306;password=" + password + ";default command timeout=300;";
mySql = new MySqlConnection(kConnectionString);
mySql.Open();
mySqlComm = mySql.CreateCommand();
}
internal List<string> GetDatabaseList()
{
MySqlDataReader rd = executeReader("SHOW DATABASES;");
List<string> databases = new List<string>();
while (rd.Read()) databases.Add(rd.GetString(0));
rd.Close();
return databases;
}
internal void Connect(string dbName)
{
executeNonQuery("USE " + dbName + ";");
}
internal void CreateDatabase(string dbName)
{
executeNonQuery("CREATE DATABASE " + dbName + ";");
Connect(dbName);
executeNonQuery(
"CREATE TABLE DBLOCKS (UID INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
"CLUSTER VARCHAR(30), CLUSTERINDEX INT UNSIGNED, " +
"ATAG VARCHAR(30), ESTATE BOOL, BSTATE BOOL, RFSTATE BOOL, MWSTATE BOOL, BLOCKTIME DATETIME, " +
"EPLUS DOUBLE, EMINUS DOUBLE, PRIMARY KEY (UID))"
);
executeNonQuery(
"CREATE TABLE TAGS (CLUSTER VARCHAR(30), CLUSTERINDEX INT UNSIGNED, TAG VARCHAR(30))"
);
executeNonQuery(
"CREATE TABLE DBLOCKDATA (UID INT UNSIGNED NOT NULL, DBDAT MEDIUMBLOB, PRIMARY KEY (UID))"
);
}
internal void Stop()
{
mySql.Close();
}
private int executeNonQuery(string command)
{
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = command;
return mySqlComm.ExecuteNonQuery();
}
private MySqlDataReader executeReader(string command)
{
mySqlComm = mySql.CreateCommand();
mySqlComm.CommandText = command;
return mySqlComm.ExecuteReader();
}
private byte[] serializeDBlockAsByteArray(DemodulatedBlock db)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, db);
byte[] buffer = new Byte[ms.Length];
ms.Seek(0, SeekOrigin.Begin);
ms.Read(buffer, 0, (int)ms.Length);
ms.Close();
return buffer;
}
private DemodulatedBlock deserializeDBlockFromByteArray(byte[] ba)
{
MemoryStream ms = new MemoryStream(ba);
BinaryFormatter bf = new BinaryFormatter();
return (DemodulatedBlock)bf.Deserialize(ms);
}
}
}
| |
//
// DatabaseSource.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2005-2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.Data;
using Hyena.Query;
using Hyena.Data.Sqlite;
using Hyena.Collections;
using Banshee.Base;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Configuration;
using Banshee.Query;
namespace Banshee.Sources
{
public abstract class DatabaseSource : Source, ITrackModelSource, IFilterableSource, IDurationAggregator, IFileSizeAggregator
{
public event EventHandler FiltersChanged;
protected delegate void TrackRangeHandler (DatabaseTrackListModel model, RangeCollection.Range range);
protected DatabaseTrackListModel track_model;
protected DatabaseAlbumListModel album_model;
protected DatabaseArtistListModel artist_model;
protected DatabaseQueryFilterModel<string> genre_model;
private RateLimiter reload_limiter;
public DatabaseSource (string generic_name, string name, string id, int order) : this (generic_name, name, id, order, null)
{
}
public DatabaseSource (string generic_name, string name, string id, int order, Source parent) : base (generic_name, name, order, id)
{
if (parent != null) {
SetParentSource (parent);
}
DatabaseSourceInitialize ();
}
protected DatabaseSource () : base ()
{
}
public void UpdateCounts ()
{
DatabaseTrackModel.UpdateUnfilteredAggregates ();
ever_counted = true;
OnUpdated ();
}
public abstract void Save ();
protected override void Initialize ()
{
base.Initialize ();
DatabaseSourceInitialize ();
}
protected virtual bool HasArtistAlbum {
get { return true; }
}
public DatabaseTrackListModel DatabaseTrackModel {
get { return track_model ?? (track_model = (Parent as DatabaseSource ?? this).CreateTrackModelFor (this)); }
protected set { track_model = value; }
}
private IDatabaseTrackModelCache track_cache;
protected IDatabaseTrackModelCache TrackCache {
get {
return track_cache ?? (track_cache = new DatabaseTrackModelCache<DatabaseTrackInfo> (
ServiceManager.DbConnection, UniqueId, DatabaseTrackModel, TrackProvider));
}
set { track_cache = value; }
}
protected DatabaseTrackModelProvider<DatabaseTrackInfo> TrackProvider {
get { return DatabaseTrackInfo.Provider; }
}
private void DatabaseSourceInitialize ()
{
InitializeTrackModel ();
current_filters_schema = CreateSchema<string[]> ("current_filters");
DatabaseSource filter_src = Parent as DatabaseSource ?? this;
foreach (IFilterListModel filter in filter_src.CreateFiltersFor (this)) {
AvailableFilters.Add (filter);
DefaultFilters.Add (filter);
}
reload_limiter = new RateLimiter (RateLimitedReload);
}
protected virtual DatabaseTrackListModel CreateTrackModelFor (DatabaseSource src)
{
return new DatabaseTrackListModel (ServiceManager.DbConnection, TrackProvider, src);
}
protected virtual IEnumerable<IFilterListModel> CreateFiltersFor (DatabaseSource src)
{
if (!HasArtistAlbum) {
yield break;
}
DatabaseArtistListModel artist_model = new DatabaseArtistListModel (src, src.DatabaseTrackModel, ServiceManager.DbConnection, src.UniqueId);
DatabaseAlbumListModel album_model = new DatabaseAlbumListModel (src, src.DatabaseTrackModel, ServiceManager.DbConnection, src.UniqueId);
DatabaseQueryFilterModel<string> genre_model = new DatabaseQueryFilterModel<string> (src, src.DatabaseTrackModel, ServiceManager.DbConnection,
Catalog.GetString ("All Genres ({0})"), src.UniqueId, BansheeQuery.GenreField, "Genre");
if (this == src) {
this.artist_model = artist_model;
this.album_model = album_model;
this.genre_model = genre_model;
}
yield return artist_model;
yield return album_model;
yield return genre_model;
}
protected virtual void AfterInitialized ()
{
DatabaseTrackModel.Initialize (TrackCache);
OnSetupComplete ();
}
protected virtual void InitializeTrackModel ()
{
}
protected bool NeedsReloadWhenFieldsChanged (Hyena.Query.QueryField [] fields)
{
if (fields == null) {
return true;
}
foreach (QueryField field in fields)
if (NeedsReloadWhenFieldChanged (field))
return true;
return false;
}
private List<QueryField> query_fields;
private QueryNode last_query;
protected virtual bool NeedsReloadWhenFieldChanged (Hyena.Query.QueryField field)
{
if (field == null)
return true;
// If it's the artist or album name, then we care, since it affects the browser
if (field == Banshee.Query.BansheeQuery.ArtistField || field == Banshee.Query.BansheeQuery.AlbumField) {
return true;
}
ISortableColumn sort_column = (TrackModel is DatabaseTrackListModel)
? (TrackModel as DatabaseTrackListModel).SortColumn : null;
// If it's the field we're sorting by, then yes, we care
if (sort_column != null && sort_column.Field == field) {
return true;
}
// Make sure the query isn't dependent on this field
QueryNode query = (TrackModel is DatabaseTrackListModel)
? (TrackModel as DatabaseTrackListModel).Query : null;
if (query != null) {
if (query != last_query) {
query_fields = new List<QueryField> (query.GetFields ());
last_query = query;
}
if (query_fields.Contains (field))
return true;
}
return false;
}
#region Public Properties
public override int Count {
get { return ever_counted ? DatabaseTrackModel.UnfilteredCount : SavedCount; }
}
public override int FilteredCount {
get { return DatabaseTrackModel.Count; }
}
public TimeSpan Duration {
get { return DatabaseTrackModel.Duration; }
}
public long FileSize {
get { return DatabaseTrackModel.FileSize; }
}
public override string FilterQuery {
set {
base.FilterQuery = value;
DatabaseTrackModel.UserQuery = FilterQuery;
ThreadAssist.SpawnFromMain (delegate {
Reload ();
});
}
}
public virtual bool CanAddTracks {
get { return true; }
}
public virtual bool CanRemoveTracks {
get { return true; }
}
public virtual bool CanDeleteTracks {
get { return true; }
}
public virtual bool ConfirmRemoveTracks {
get { return true; }
}
public virtual bool CanRepeat {
get { return true; }
}
public virtual bool CanShuffle {
get { return true; }
}
public override string TrackModelPath {
get { return DBusServiceManager.MakeObjectPath (DatabaseTrackModel); }
}
public TrackListModel TrackModel {
get { return DatabaseTrackModel; }
}
public virtual bool ShowBrowser {
get { return true; }
}
public virtual bool Indexable {
get { return false; }
}
private int saved_count;
protected int SavedCount {
get { return saved_count; }
set { saved_count = value; }
}
public override bool AcceptsInputFromSource (Source source)
{
return CanAddTracks && source != this;
}
public override bool AcceptsUserInputFromSource (Source source)
{
return base.AcceptsUserInputFromSource (source) && CanAddTracks;
}
public override bool HasViewableTrackProperties {
get { return true; }
}
public override bool HasEditableTrackProperties {
get { return true; }
}
#endregion
#region Filters (aka Browsers)
private IList<IFilterListModel> available_filters;
public IList<IFilterListModel> AvailableFilters {
get { return available_filters ?? (available_filters = new List<IFilterListModel> ()); }
protected set { available_filters = value; }
}
private IList<IFilterListModel> default_filters;
public IList<IFilterListModel> DefaultFilters {
get { return default_filters ?? (default_filters = new List<IFilterListModel> ()); }
protected set { default_filters = value; }
}
private IList<IFilterListModel> current_filters;
public IList<IFilterListModel> CurrentFilters {
get {
if (current_filters == null) {
current_filters = new List<IFilterListModel> ();
string [] current = current_filters_schema.Get ();
if (current != null) {
foreach (string filter_name in current) {
foreach (IFilterListModel filter in AvailableFilters) {
if (filter.FilterName == filter_name) {
current_filters.Add (filter);
break;
}
}
}
} else {
foreach (IFilterListModel filter in DefaultFilters) {
current_filters.Add (filter);
}
}
}
return current_filters;
}
protected set { current_filters = value; }
}
public void ReplaceFilter (IFilterListModel old_filter, IFilterListModel new_filter)
{
int i = current_filters.IndexOf (old_filter);
if (i != -1) {
current_filters[i] = new_filter;
SaveCurrentFilters ();
}
}
public void AppendFilter (IFilterListModel filter)
{
if (current_filters.IndexOf (filter) == -1) {
current_filters.Add (filter);
SaveCurrentFilters ();
}
}
public void RemoveFilter (IFilterListModel filter)
{
if (current_filters.Remove (filter)) {
SaveCurrentFilters ();
}
}
private void SaveCurrentFilters ()
{
Reload ();
if (current_filters == null) {
current_filters_schema.Set (null);
} else {
string [] filters = new string [current_filters.Count];
int i = 0;
foreach (IFilterListModel filter in CurrentFilters) {
filters[i++] = filter.FilterName;
}
current_filters_schema.Set (filters);
}
EventHandler handler = FiltersChanged;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
private SchemaEntry<string[]> current_filters_schema;
#endregion
#region Public Methods
public virtual void Reload ()
{
ever_counted = ever_reloaded = true;
reload_limiter.Execute ();
}
protected void RateLimitedReload ()
{
lock (track_model) {
DatabaseTrackModel.Reload ();
}
OnUpdated ();
Save ();
}
public virtual bool HasDependencies {
get { return false; }
}
public void RemoveTrack (int index)
{
if (index != -1) {
RemoveTrackRange (track_model, new RangeCollection.Range (index, index));
OnTracksRemoved ();
}
}
public void RemoveTrack (DatabaseTrackInfo track)
{
RemoveTrack (track_model.IndexOf (track));
}
public virtual void RemoveSelectedTracks ()
{
RemoveSelectedTracks (track_model);
}
public virtual void RemoveSelectedTracks (DatabaseTrackListModel model)
{
WithTrackSelection (model, RemoveTrackRange);
OnTracksRemoved ();
}
public virtual void DeleteSelectedTracks ()
{
DeleteSelectedTracks (track_model);
}
protected virtual void DeleteSelectedTracks (DatabaseTrackListModel model)
{
if (model == null)
return;
WithTrackSelection (model, DeleteTrackRange);
OnTracksDeleted ();
}
public virtual bool AddSelectedTracks (Source source)
{
if (!AcceptsInputFromSource (source))
return false;
DatabaseTrackListModel model = (source as ITrackModelSource).TrackModel as DatabaseTrackListModel;
if (model == null) {
return false;
}
WithTrackSelection (model, AddTrackRange);
OnTracksAdded ();
OnUserNotifyUpdated ();
return true;
}
public virtual bool AddAllTracks (Source source)
{
if (!AcceptsInputFromSource (source) || source.Count == 0)
return false;
DatabaseTrackListModel model = (source as ITrackModelSource).TrackModel as DatabaseTrackListModel;
lock (model) {
AddTrackRange (model, new RangeCollection.Range (0, source.Count));
}
OnTracksAdded ();
OnUserNotifyUpdated ();
return true;
}
public virtual void RateSelectedTracks (int rating)
{
RateSelectedTracks (track_model, rating);
}
public virtual void RateSelectedTracks (DatabaseTrackListModel model, int rating)
{
Selection selection = model.Selection;
if (selection.Count == 0)
return;
lock (model) {
foreach (RangeCollection.Range range in selection.Ranges) {
RateTrackRange (model, range, rating);
}
}
OnTracksChanged (BansheeQuery.RatingField);
// In case we updated the currently playing track
DatabaseTrackInfo track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (track != null) {
track.Refresh ();
ServiceManager.PlayerEngine.TrackInfoUpdated ();
}
}
public override SourceMergeType SupportedMergeTypes {
get { return SourceMergeType.All; }
}
public override void MergeSourceInput (Source source, SourceMergeType mergeType)
{
if (mergeType == SourceMergeType.Source || mergeType == SourceMergeType.All) {
AddAllTracks (source);
} else if (mergeType == SourceMergeType.ModelSelection) {
AddSelectedTracks (source);
}
}
#endregion
#region Protected Methods
protected virtual void OnTracksAdded ()
{
Reload ();
}
protected void OnTracksChanged ()
{
OnTracksChanged (null);
}
protected virtual void OnTracksChanged (params QueryField [] fields)
{
HandleTracksChanged (this, new TrackEventArgs (fields));
foreach (PrimarySource psource in PrimarySources) {
psource.NotifyTracksChanged (fields);
}
}
protected virtual void OnTracksDeleted ()
{
PruneArtistsAlbums ();
HandleTracksDeleted (this, new TrackEventArgs ());
foreach (PrimarySource psource in PrimarySources) {
psource.NotifyTracksDeleted ();
}
}
protected virtual void OnTracksRemoved ()
{
PruneArtistsAlbums ();
Reload ();
}
// If we are a PrimarySource, return ourself and our children, otherwise if our Parent
// is one, do so for it, otherwise do so for all PrimarySources.
private IEnumerable<PrimarySource> PrimarySources {
get {
PrimarySource psource;
if ((psource = this as PrimarySource) != null) {
yield return psource;
} else {
if ((psource = Parent as PrimarySource) != null) {
yield return psource;
} else {
foreach (Source source in ServiceManager.SourceManager.Sources) {
if ((psource = source as PrimarySource) != null) {
yield return psource;
}
}
}
}
}
}
protected HyenaSqliteCommand rate_track_range_command;
protected HyenaSqliteCommand RateTrackRangeCommand {
get {
if (rate_track_range_command == null) {
if (track_model.CachesJoinTableEntries) {
rate_track_range_command = new HyenaSqliteCommand (String.Format (@"
UPDATE CoreTracks SET Rating = ?, DateUpdatedStamp = ? WHERE
TrackID IN (SELECT TrackID FROM {0} WHERE
{1} IN (SELECT ItemID FROM CoreCache WHERE ModelID = {2} LIMIT ?, ?))",
track_model.JoinTable, track_model.JoinPrimaryKey, track_model.CacheId
));
} else {
rate_track_range_command = new HyenaSqliteCommand (String.Format (@"
UPDATE CoreTracks SET Rating = ?, DateUpdatedStamp = ? WHERE TrackID IN (
SELECT ItemID FROM CoreCache WHERE ModelID = {0} LIMIT ?, ?)",
track_model.CacheId
));
}
}
return rate_track_range_command;
}
}
private bool ever_reloaded = false, ever_counted = false;
public override void Activate ()
{
if (!ever_reloaded)
Reload ();
}
public override void Deactivate ()
{
DatabaseTrackModel.InvalidateCache (false);
foreach (IFilterListModel filter in AvailableFilters) {
filter.InvalidateCache (false);
}
}
protected virtual void RemoveTrackRange (DatabaseTrackListModel model, RangeCollection.Range range)
{
Log.ErrorFormat ("RemoveTrackRange not implemented by {0}", this);
}
protected virtual void DeleteTrackRange (DatabaseTrackListModel model, RangeCollection.Range range)
{
Log.ErrorFormat ("DeleteTrackRange not implemented by {0}", this);
}
protected virtual void AddTrackRange (DatabaseTrackListModel model, RangeCollection.Range range)
{
Log.ErrorFormat ("AddTrackRange not implemented by {0}", this);
}
protected virtual void AddTrack (DatabaseTrackInfo track)
{
Log.ErrorFormat ("AddTrack not implemented by {0}", this);
}
protected virtual void RateTrackRange (DatabaseTrackListModel model, RangeCollection.Range range, int rating)
{
ServiceManager.DbConnection.Execute (RateTrackRangeCommand,
rating, DateTime.Now, range.Start, range.End - range.Start + 1);
}
protected void WithTrackSelection (DatabaseTrackListModel model, TrackRangeHandler handler)
{
Selection selection = model.Selection;
if (selection.Count == 0)
return;
lock (model) {
foreach (RangeCollection.Range range in selection.Ranges) {
handler (model, range);
}
}
}
protected HyenaSqliteCommand prune_command;
protected HyenaSqliteCommand PruneCommand {
get {
return prune_command ?? (prune_command = new HyenaSqliteCommand (String.Format (
@"DELETE FROM CoreCache WHERE ModelID = ? AND ItemID NOT IN (SELECT ArtistID FROM CoreTracks WHERE TrackID IN (SELECT {0}));
DELETE FROM CoreCache WHERE ModelID = ? AND ItemID NOT IN (SELECT AlbumID FROM CoreTracks WHERE TrackID IN (SELECT {0}));",
track_model.TrackIdsSql
),
artist_model.CacheId, artist_model.CacheId, 0, artist_model.Count,
album_model.CacheId, album_model.CacheId, 0, album_model.Count
));
}
}
protected void InvalidateCaches ()
{
track_model.InvalidateCache (true);
foreach (IFilterListModel filter in CurrentFilters) {
filter.InvalidateCache (true);
}
}
protected virtual void PruneArtistsAlbums ()
{
//Console.WriteLine ("Pruning with {0}", PruneCommand.Text);
//ServiceManager.DbConnection.Execute (PruneCommand);
}
protected virtual void HandleTracksAdded (Source sender, TrackEventArgs args)
{
}
protected virtual void HandleTracksChanged (Source sender, TrackEventArgs args)
{
}
protected virtual void HandleTracksDeleted (Source sender, TrackEventArgs args)
{
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RecoveryPointsOperations operations.
/// </summary>
internal partial class RecoveryPointsOperations : IServiceOperations<RecoveryServicesBackupClient>, IRecoveryPointsOperations
{
/// <summary>
/// Initializes a new instance of the RecoveryPointsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RecoveryPointsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Lists the backup copies for the backed up item.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item whose backup copies are to be fetched.
/// </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>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RecoveryPointResource>>> ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ODataQuery<BMSRPQueryObject> odataQuery = default(ODataQuery<BMSRPQueryObject>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fabricName");
}
if (containerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "containerName");
}
if (protectedItemName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "protectedItemName");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("containerName", containerName);
tracingParameters.Add("protectedItemName", protectedItemName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
_url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName));
_url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName));
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}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RecoveryPointResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<RecoveryPointResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Provides the information of the backed up data identified using
/// RecoveryPointID. This is an asynchronous operation. To know the status of
/// the operation, call the GetProtectedItemOperationResult API.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item name whose backup data needs to be fetched.
/// </param>
/// <param name='recoveryPointId'>
/// RecoveryPointID represents the backed up data to be fetched.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RecoveryPointResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, string recoveryPointId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fabricName");
}
if (containerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "containerName");
}
if (protectedItemName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "protectedItemName");
}
if (recoveryPointId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "recoveryPointId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("containerName", containerName);
tracingParameters.Add("protectedItemName", protectedItemName);
tracingParameters.Add("recoveryPointId", recoveryPointId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
_url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName));
_url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName));
_url = _url.Replace("{recoveryPointId}", System.Uri.EscapeDataString(recoveryPointId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RecoveryPointResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RecoveryPointResource>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the backup copies for the backed up item.
/// </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>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RecoveryPointResource>>> 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 += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RecoveryPointResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<RecoveryPointResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using JustCli.Dto;
namespace JustCli
{
// Works with -a or --action params.
public class CommandContext
{
private readonly string CommandName;
private readonly Dictionary<string, string> ArgValues = new Dictionary<string, string>();
public CommandContext(string[] args, IEnumerable<IArgValueSource> additionalArgValueSources = null)
{
if (args.Length == 0)
{
throw new ArgumentOutOfRangeException("args");
}
CommandName = args[0];
ExtractArgumentsValuesFromAdditionalSources(additionalArgValueSources);
if (args.Length == 1)
{
return;
}
// if not an argument name then something wrong.
if (!IsArgumentName(args[1]))
{
throw new ArgumentException("Cannot find argument.");
}
ExtractArgumentsValuesFromCommandline(args);
}
private void ExtractArgumentsValuesFromAdditionalSources(
IEnumerable<IArgValueSource> additionalArgValueSources)
{
if (additionalArgValueSources == null)
{
return;
}
foreach (var additionalArgValueSource in additionalArgValueSources)
{
foreach (var additionalArgValuePair in additionalArgValueSource.GetArgValues())
{
ArgValues[$"--{additionalArgValuePair.Key}"] = additionalArgValuePair.Value;
}
}
}
private void ExtractArgumentsValuesFromCommandline(
string[] args)
{
var argName = string.Empty;
var argValue = string.Empty;
for (var i = 1; i < args.Length; i++)
{
var element = args[i];
if (IsArgumentName(element))
{
if (!string.IsNullOrEmpty(argName) && !ArgValues.ContainsKey(argName))
{
ArgValues[argName] = argValue;
}
argName = element;
argValue = string.Empty;
}
else
{
argValue = string.IsNullOrEmpty(argValue)
? element
: argValue + " " + element;
}
}
// put last pair
ArgValues[argName] = argValue;
}
// TODO: try method and write down an error message
public object GetArgValue(ArgumentInfo argumentInfo)
{
return GetArgValue(argumentInfo.ShortName, argumentInfo.LongName, argumentInfo.DefaultValue, argumentInfo.ArgumentType);
}
private object GetArgValue(string shortName, string longName, object defaultValue, Type propertyType)
{
var stringValue = GetArgumentValue(shortName, longName);
if (stringValue == null)
{
if (defaultValue == null)
{
throw new Exception(string.Format("The argument [{0}] is not presented in command line.", longName));
}
if (!(defaultValue is string))
{
return defaultValue;
}
var defaultValueString = (string) defaultValue;
// special case: we cannot set default value for datetime. Have to use string.
if (propertyType == typeof(DateTime))
{
if (defaultValueString.ToLower() == "minvalue")
{
return DateTime.MinValue;
}
if (defaultValueString.ToLower() == "maxvalue")
{
return DateTime.MaxValue;
}
DateTime defaultValueDate;
if (DateTime.TryParse(defaultValueString, CultureInfo.InvariantCulture, DateTimeStyles.None, out defaultValueDate))
{
return defaultValueDate;
}
throw new Exception(string.Format("Default value for The argument [{0}] is not valid.", longName));
}
// special case: we cannot set default value for GUID. Have to use string.
if (propertyType == typeof(Guid))
{
if (defaultValueString.ToLower() == "empty")
{
return Guid.Empty;
}
Guid defaultValueGuid;
if (Guid.TryParse(defaultValueString, out defaultValueGuid))
{
return defaultValueGuid;
}
throw new Exception(string.Format("Default value for The argument [{0}] is not valid.", longName));
}
if (propertyType != typeof(string))
{
try
{
return ConvertFromString(defaultValueString, propertyType, true);
}
catch (Exception e)
{
throw new Exception(
string.Format(
"The argument [{0}] is not set up. The default value [{1}] cannot be cast to [{2}].",
longName, defaultValueString, propertyType.Name),
e);
}
}
// if property is string
return defaultValueString;
}
// special case: flag attributes.
// if attribute is bool and attribute is in the command line (value = string.empty)
// then flag = true.
if (propertyType == typeof (bool) && stringValue == string.Empty)
{
return true;
}
try
{
return ConvertFromString(stringValue, propertyType);
}
catch (Exception e)
{
throw new Exception(
string.Format(
"The argument [{0}] is not set up. The value [{1}] cannot be cast to [{2}].",
longName, stringValue, propertyType.Name),
e);
}
}
// TODO: try method and write down an error message
private static object ConvertFromString(string stringValue, Type toType, bool useInvariantCulture = false)
{
var typeConverter = TypeDescriptor.GetConverter(toType);
if (useInvariantCulture)
{
var value = typeConverter.ConvertFromString(null, CultureInfo.InvariantCulture, stringValue);
return value;
}
else
{
var value = typeConverter.ConvertFromString(stringValue);
return value;
}
}
private string GetArgumentValue(string shortName, string longName)
{
string value;
if (ArgValues.TryGetValue(string.Format("-{0}", shortName), out value))
{
return value;
}
if (ArgValues.TryGetValue(string.Format("--{0}", longName), out value))
{
return value;
}
return null;
}
private static bool IsArgumentName(string arg)
{
return arg.StartsWith("-");
}
}
}
| |
using YAF.Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using JCG = J2N.Collections.Generic;
namespace YAF.Lucene.Net.Analysis
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// An <see cref="Analyzer"/> builds <see cref="Analysis.TokenStream"/>s, which analyze text. It thus represents a
/// policy for extracting index terms from text.
/// <para/>
/// In order to define what analysis is done, subclasses must define their
/// <see cref="TokenStreamComponents"/> in <see cref="CreateComponents(string, TextReader)"/>.
/// The components are then reused in each call to <see cref="GetTokenStream(string, TextReader)"/>.
/// <para/>
/// Simple example:
/// <code>
/// Analyzer analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
/// {
/// Tokenizer source = new FooTokenizer(reader);
/// TokenStream filter = new FooFilter(source);
/// filter = new BarFilter(filter);
/// return new TokenStreamComponents(source, filter);
/// });
/// </code>
/// For more examples, see the <see cref="Lucene.Net.Analysis"/> namespace documentation.
/// <para/>
/// For some concrete implementations bundled with Lucene, look in the analysis modules:
/// <list type="bullet">
/// <item><description>Common:
/// Analyzers for indexing content in different languages and domains.</description></item>
/// <item><description>ICU:
/// Exposes functionality from ICU to Apache Lucene.</description></item>
/// <item><description>Kuromoji:
/// Morphological analyzer for Japanese text.</description></item>
/// <item><description>Morfologik:
/// Dictionary-driven lemmatization for the Polish language.</description></item>
/// <item><description>Phonetic:
/// Analysis for indexing phonetic signatures (for sounds-alike search).</description></item>
/// <item><description>Smart Chinese:
/// Analyzer for Simplified Chinese, which indexes words.</description></item>
/// <item><description>Stempel:
/// Algorithmic Stemmer for the Polish Language.</description></item>
/// <item><description>UIMA:
/// Analysis integration with Apache UIMA.</description></item>
/// </list>
/// </summary>
public abstract class Analyzer : IDisposable
{
private readonly ReuseStrategy reuseStrategy;
// non readonly as it gets nulled if closed; internal for access by ReuseStrategy's final helper methods:
internal DisposableThreadLocal<object> storedValue = new DisposableThreadLocal<object>();
/// <summary>
/// Create a new <see cref="Analyzer"/>, reusing the same set of components per-thread
/// across calls to <see cref="GetTokenStream(string, TextReader)"/>.
/// </summary>
public Analyzer()
: this(GLOBAL_REUSE_STRATEGY)
{
}
/// <summary>
/// Expert: create a new Analyzer with a custom <see cref="ReuseStrategy"/>.
/// <para/>
/// NOTE: if you just want to reuse on a per-field basis, its easier to
/// use a subclass of <see cref="AnalyzerWrapper"/> such as
/// <c>Lucene.Net.Analysis.Common.Miscellaneous.PerFieldAnalyzerWrapper</c>
/// instead.
/// </summary>
public Analyzer(ReuseStrategy reuseStrategy)
{
this.reuseStrategy = reuseStrategy;
}
/// <summary>
/// Creates a new instance with the ability to specify the body of the <see cref="CreateComponents(string, TextReader)"/>
/// method through the <paramref name="createComponents"/> parameter.
/// Simple example:
/// <code>
/// var analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
/// {
/// Tokenizer source = new FooTokenizer(reader);
/// TokenStream filter = new FooFilter(source);
/// filter = new BarFilter(filter);
/// return new TokenStreamComponents(source, filter);
/// });
/// </code>
/// <para/>
/// LUCENENET specific
/// </summary>
/// <param name="createComponents">
/// A delegate method that represents (is called by) the <see cref="CreateComponents(string, TextReader)"/>
/// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and
/// returns the <see cref="TokenStreamComponents"/> for this analyzer.
/// </param>
/// <returns> A new <see cref="AnonymousAnalyzer"/> instance.</returns>
public static Analyzer NewAnonymous(Func<string, TextReader, TokenStreamComponents> createComponents)
{
return NewAnonymous(createComponents, GLOBAL_REUSE_STRATEGY);
}
/// <summary>
/// Creates a new instance with the ability to specify the body of the <see cref="CreateComponents(string, TextReader)"/>
/// method through the <paramref name="createComponents"/> parameter and allows the use of a <see cref="ReuseStrategy"/>.
/// Simple example:
/// <code>
/// var analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
/// {
/// Tokenizer source = new FooTokenizer(reader);
/// TokenStream filter = new FooFilter(source);
/// filter = new BarFilter(filter);
/// return new TokenStreamComponents(source, filter);
/// }, reuseStrategy);
/// </code>
/// <para/>
/// LUCENENET specific
/// </summary>
/// <param name="createComponents">
/// An delegate method that represents (is called by) the <see cref="CreateComponents(string, TextReader)"/>
/// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and
/// returns the <see cref="TokenStreamComponents"/> for this analyzer.
/// </param>
/// <param name="reuseStrategy">A custom <see cref="ReuseStrategy"/> instance.</param>
/// <returns> A new <see cref="AnonymousAnalyzer"/> instance.</returns>
public static Analyzer NewAnonymous(Func<string, TextReader, TokenStreamComponents> createComponents, ReuseStrategy reuseStrategy)
{
return NewAnonymous(createComponents, null, reuseStrategy);
}
/// <summary>
/// Creates a new instance with the ability to specify the body of the <see cref="CreateComponents(string, TextReader)"/>
/// method through the <paramref name="createComponents"/> parameter and the body of the <see cref="InitReader(string, TextReader)"/>
/// method through the <paramref name="initReader"/> parameter.
/// Simple example:
/// <code>
/// var analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
/// {
/// Tokenizer source = new FooTokenizer(reader);
/// TokenStream filter = new FooFilter(source);
/// filter = new BarFilter(filter);
/// return new TokenStreamComponents(source, filter);
/// }, initReader: (fieldName, reader) =>
/// {
/// return new HTMLStripCharFilter(reader);
/// });
/// </code>
/// <para/>
/// LUCENENET specific
/// </summary>
/// <param name="createComponents">
/// A delegate method that represents (is called by) the <see cref="CreateComponents(string, TextReader)"/>
/// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and
/// returns the <see cref="TokenStreamComponents"/> for this analyzer.
/// </param>
/// <param name="initReader">A delegate method that represents (is called by) the <see cref="InitReader(string, TextReader)"/>
/// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and
/// returns the <see cref="TextReader"/> that can be modified or wrapped by the <paramref name="initReader"/> method.</param>
/// <returns> A new <see cref="AnonymousAnalyzer"/> instance.</returns>
public static Analyzer NewAnonymous(Func<string, TextReader, TokenStreamComponents> createComponents, Func<string, TextReader, TextReader> initReader)
{
return NewAnonymous(createComponents, initReader, GLOBAL_REUSE_STRATEGY);
}
/// <summary>
/// Creates a new instance with the ability to specify the body of the <see cref="CreateComponents(string, TextReader)"/>
/// method through the <paramref name="createComponents"/> parameter, the body of the <see cref="InitReader(string, TextReader)"/>
/// method through the <paramref name="initReader"/> parameter, and allows the use of a <see cref="ReuseStrategy"/>.
/// Simple example:
/// <code>
/// var analyzer = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
/// {
/// Tokenizer source = new FooTokenizer(reader);
/// TokenStream filter = new FooFilter(source);
/// filter = new BarFilter(filter);
/// return new TokenStreamComponents(source, filter);
/// }, initReader: (fieldName, reader) =>
/// {
/// return new HTMLStripCharFilter(reader);
/// }, reuseStrategy);
/// </code>
/// <para/>
/// LUCENENET specific
/// </summary>
/// <param name="createComponents">
/// A delegate method that represents (is called by) the <see cref="CreateComponents(string, TextReader)"/>
/// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and
/// returns the <see cref="TokenStreamComponents"/> for this analyzer.
/// </param>
/// <param name="initReader">A delegate method that represents (is called by) the <see cref="InitReader(string, TextReader)"/>
/// method. It accepts a <see cref="string"/> fieldName and a <see cref="TextReader"/> reader and
/// returns the <see cref="TextReader"/> that can be modified or wrapped by the <paramref name="initReader"/> method.</param>
/// <param name="reuseStrategy">A custom <see cref="ReuseStrategy"/> instance.</param>
/// <returns> A new <see cref="AnonymousAnalyzer"/> instance.</returns>
public static Analyzer NewAnonymous(Func<string, TextReader, TokenStreamComponents> createComponents, Func<string, TextReader, TextReader> initReader, ReuseStrategy reuseStrategy)
{
return new AnonymousAnalyzer(createComponents, initReader, reuseStrategy);
}
/// <summary>
/// Creates a new <see cref="TokenStreamComponents"/> instance for this analyzer.
/// </summary>
/// <param name="fieldName">
/// the name of the fields content passed to the
/// <see cref="TokenStreamComponents"/> sink as a reader </param>
/// <param name="reader">
/// the reader passed to the <see cref="Tokenizer"/> constructor </param>
/// <returns> the <see cref="TokenStreamComponents"/> for this analyzer. </returns>
protected internal abstract TokenStreamComponents CreateComponents(string fieldName, TextReader reader);
/// <summary>
/// Returns a <see cref="TokenStream"/> suitable for <paramref name="fieldName"/>, tokenizing
/// the contents of <c>text</c>.
/// <para/>
/// This method uses <see cref="CreateComponents(string, TextReader)"/> to obtain an
/// instance of <see cref="TokenStreamComponents"/>. It returns the sink of the
/// components and stores the components internally. Subsequent calls to this
/// method will reuse the previously stored components after resetting them
/// through <see cref="TokenStreamComponents.SetReader(TextReader)"/>.
/// <para/>
/// <b>NOTE:</b> After calling this method, the consumer must follow the
/// workflow described in <see cref="Analysis.TokenStream"/> to properly consume its contents.
/// See the <see cref="Lucene.Net.Analysis"/> namespace documentation for
/// some examples demonstrating this.
/// </summary>
/// <param name="fieldName"> the name of the field the created <see cref="Analysis.TokenStream"/> is used for </param>
/// <param name="reader"> the reader the streams source reads from </param>
/// <returns> <see cref="Analysis.TokenStream"/> for iterating the analyzed content of <see cref="TextReader"/> </returns>
/// <exception cref="ObjectDisposedException"> if the Analyzer is disposed. </exception>
/// <exception cref="IOException"> if an i/o error occurs (may rarely happen for strings). </exception>
/// <seealso cref="GetTokenStream(string, string)"/>
public TokenStream GetTokenStream(string fieldName, TextReader reader)
{
TokenStreamComponents components = reuseStrategy.GetReusableComponents(this, fieldName);
TextReader r = InitReader(fieldName, reader);
if (components == null)
{
components = CreateComponents(fieldName, r);
reuseStrategy.SetReusableComponents(this, fieldName, components);
}
else
{
components.SetReader(r);
}
return components.TokenStream;
}
/// <summary>
/// Returns a <see cref="Analysis.TokenStream"/> suitable for <paramref name="fieldName"/>, tokenizing
/// the contents of <paramref name="text"/>.
/// <para/>
/// This method uses <see cref="CreateComponents(string, TextReader)"/> to obtain an
/// instance of <see cref="TokenStreamComponents"/>. It returns the sink of the
/// components and stores the components internally. Subsequent calls to this
/// method will reuse the previously stored components after resetting them
/// through <see cref="TokenStreamComponents.SetReader(TextReader)"/>.
/// <para/>
/// <b>NOTE:</b> After calling this method, the consumer must follow the
/// workflow described in <see cref="Analysis.TokenStream"/> to properly consume its contents.
/// See the <see cref="Lucene.Net.Analysis"/> namespace documentation for
/// some examples demonstrating this.
/// </summary>
/// <param name="fieldName">the name of the field the created <see cref="Analysis.TokenStream"/> is used for</param>
/// <param name="text">the <see cref="string"/> the streams source reads from </param>
/// <returns><see cref="Analysis.TokenStream"/> for iterating the analyzed content of <c>reader</c></returns>
/// <exception cref="ObjectDisposedException"> if the Analyzer is disposed. </exception>
/// <exception cref="IOException"> if an i/o error occurs (may rarely happen for strings). </exception>
/// <seealso cref="GetTokenStream(string, TextReader)"/>
public TokenStream GetTokenStream(string fieldName, string text)
{
TokenStreamComponents components = reuseStrategy.GetReusableComponents(this, fieldName);
ReusableStringReader strReader =
(components == null || components.reusableStringReader == null)
? new ReusableStringReader()
: components.reusableStringReader;
strReader.SetValue(text);
var r = InitReader(fieldName, strReader);
if (components == null)
{
components = CreateComponents(fieldName, r);
reuseStrategy.SetReusableComponents(this, fieldName, components);
}
else
{
components.SetReader(r);
}
components.reusableStringReader = strReader;
return components.TokenStream;
}
/// <summary>
/// Override this if you want to add a <see cref="CharFilter"/> chain.
/// <para/>
/// The default implementation returns <paramref name="reader"/>
/// unchanged.
/// </summary>
/// <param name="fieldName"> <see cref="Index.IIndexableField"/> name being indexed </param>
/// <param name="reader"> original <see cref="TextReader"/> </param>
/// <returns> reader, optionally decorated with <see cref="CharFilter"/>(s) </returns>
protected internal virtual TextReader InitReader(string fieldName, TextReader reader)
{
return reader;
}
/// <summary>
/// Invoked before indexing a <see cref="Index.IIndexableField"/> instance if
/// terms have already been added to that field. This allows custom
/// analyzers to place an automatic position increment gap between
/// <see cref="Index.IIndexableField"/> instances using the same field name. The default value
/// position increment gap is 0. With a 0 position increment gap and
/// the typical default token position increment of 1, all terms in a field,
/// including across <see cref="Index.IIndexableField"/> instances, are in successive positions, allowing
/// exact <see cref="Search.PhraseQuery"/> matches, for instance, across <see cref="Index.IIndexableField"/> instance boundaries.
/// </summary>
/// <param name="fieldName"> <see cref="Index.IIndexableField"/> name being indexed. </param>
/// <returns> position increment gap, added to the next token emitted from <see cref="GetTokenStream(string, TextReader)"/>.
/// this value must be <c>>= 0</c>.</returns>
public virtual int GetPositionIncrementGap(string fieldName)
{
return 0;
}
/// <summary>
/// Just like <see cref="GetPositionIncrementGap"/>, except for
/// <see cref="Token"/> offsets instead. By default this returns 1.
/// this method is only called if the field
/// produced at least one token for indexing.
/// </summary>
/// <param name="fieldName"> the field just indexed </param>
/// <returns> offset gap, added to the next token emitted from <see cref="GetTokenStream(string, TextReader)"/>.
/// this value must be <c>>= 0</c>. </returns>
public virtual int GetOffsetGap(string fieldName)
{
return 1;
}
/// <summary>
/// Returns the used <see cref="ReuseStrategy"/>.
/// </summary>
public ReuseStrategy Strategy
{
get
{
return reuseStrategy;
}
}
/// <summary>
/// Frees persistent resources used by this <see cref="Analyzer"/>
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Frees persistent resources used by this <see cref="Analyzer"/>
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (storedValue != null)
{
storedValue.Dispose();
storedValue = null;
}
}
}
// LUCENENET specific - de-nested TokenStreamComponents and ReuseStrategy
// so they don't need to be qualified when used outside of Analyzer subclasses.
/// <summary>
/// A predefined <see cref="ReuseStrategy"/> that reuses the same components for
/// every field.
/// </summary>
public static readonly ReuseStrategy GLOBAL_REUSE_STRATEGY =
#pragma warning disable 612, 618
new GlobalReuseStrategy();
#pragma warning restore 612, 618
/// <summary>
/// Implementation of <see cref="ReuseStrategy"/> that reuses the same components for
/// every field. </summary>
[Obsolete("this implementation class will be hidden in Lucene 5.0. Use Analyzer.GLOBAL_REUSE_STRATEGY instead!")]
public sealed class GlobalReuseStrategy : ReuseStrategy
{
/// <summary>
/// Sole constructor. (For invocation by subclass constructors, typically implicit.) </summary>
[Obsolete("Don't create instances of this class, use Analyzer.GLOBAL_REUSE_STRATEGY")]
public GlobalReuseStrategy()
{ }
public override TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName)
{
return (TokenStreamComponents)GetStoredValue(analyzer);
}
public override void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components)
{
SetStoredValue(analyzer, components);
}
}
/// <summary>
/// A predefined <see cref="ReuseStrategy"/> that reuses components per-field by
/// maintaining a Map of <see cref="TokenStreamComponents"/> per field name.
/// </summary>
public static readonly ReuseStrategy PER_FIELD_REUSE_STRATEGY =
#pragma warning disable 612, 618
new PerFieldReuseStrategy();
#pragma warning restore 612, 618
/// <summary>
/// Implementation of <see cref="ReuseStrategy"/> that reuses components per-field by
/// maintaining a Map of <see cref="TokenStreamComponents"/> per field name.
/// </summary>
[Obsolete("this implementation class will be hidden in Lucene 5.0. Use Analyzer.PER_FIELD_REUSE_STRATEGY instead!")]
public class PerFieldReuseStrategy : ReuseStrategy
{
/// <summary>
/// Sole constructor. (For invocation by subclass constructors, typically implicit.)
/// </summary>
[Obsolete("Don't create instances of this class, use Analyzer.PER_FIELD_REUSE_STRATEGY")]
public PerFieldReuseStrategy()
{
}
public override TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName)
{
var componentsPerField = (IDictionary<string, TokenStreamComponents>)GetStoredValue(analyzer);
if (componentsPerField != null)
{
TokenStreamComponents ret;
componentsPerField.TryGetValue(fieldName, out ret);
return ret;
}
return null;
}
public override void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components)
{
var componentsPerField = (IDictionary<string, TokenStreamComponents>)GetStoredValue(analyzer);
if (componentsPerField == null)
{
// LUCENENET-615: This needs to support nullable keys
componentsPerField = new JCG.Dictionary<string, TokenStreamComponents>();
SetStoredValue(analyzer, componentsPerField);
}
componentsPerField[fieldName] = components;
}
}
/// <summary>
/// LUCENENET specific helper class to mimick Java's ability to create anonymous classes.
/// Clearly, the design of <see cref="Analyzer"/> took this feature of Java into consideration.
/// Since it doesn't exist in .NET, we can use a delegate method to call the constructor of
/// this concrete instance to fake it (by calling an overload of
/// <see cref="Analyzer.NewAnonymous(Func{string, TextReader, TokenStreamComponents})"/>).
/// </summary>
private class AnonymousAnalyzer : Analyzer
{
private readonly Func<string, TextReader, TokenStreamComponents> createComponents;
private readonly Func<string, TextReader, TextReader> initReader;
public AnonymousAnalyzer(Func<string, TextReader, TokenStreamComponents> createComponents, Func<string, TextReader, TextReader> initReader, ReuseStrategy reuseStrategy)
: base(reuseStrategy)
{
if (createComponents == null)
throw new ArgumentNullException("createComponents");
this.createComponents = createComponents;
this.initReader = initReader;
}
protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
return this.createComponents(fieldName, reader);
}
protected internal override TextReader InitReader(string fieldName, TextReader reader)
{
if (this.initReader != null)
{
return this.initReader(fieldName, reader);
}
return base.InitReader(fieldName, reader);
}
}
}
/// <summary>
/// This class encapsulates the outer components of a token stream. It provides
/// access to the source (<see cref="Analysis.Tokenizer"/>) and the outer end (sink), an
/// instance of <see cref="TokenFilter"/> which also serves as the
/// <see cref="Analysis.TokenStream"/> returned by
/// <see cref="Analyzer.GetTokenStream(string, TextReader)"/>.
/// </summary>
public class TokenStreamComponents
{
/// <summary>
/// Original source of the tokens.
/// </summary>
protected readonly Tokenizer m_source;
/// <summary>
/// Sink tokenstream, such as the outer tokenfilter decorating
/// the chain. This can be the source if there are no filters.
/// </summary>
protected readonly TokenStream m_sink;
/// <summary>
/// Internal cache only used by <see cref="Analyzer.GetTokenStream(string, string)"/>. </summary>
internal ReusableStringReader reusableStringReader;
/// <summary>
/// Creates a new <see cref="TokenStreamComponents"/> instance.
/// </summary>
/// <param name="source">
/// the analyzer's tokenizer </param>
/// <param name="result">
/// the analyzer's resulting token stream </param>
public TokenStreamComponents(Tokenizer source, TokenStream result)
{
this.m_source = source;
this.m_sink = result;
}
/// <summary>
/// Creates a new <see cref="TokenStreamComponents"/> instance.
/// </summary>
/// <param name="source">
/// the analyzer's tokenizer </param>
public TokenStreamComponents(Tokenizer source)
{
this.m_source = source;
this.m_sink = source;
}
/// <summary>
/// Resets the encapsulated components with the given reader. If the components
/// cannot be reset, an Exception should be thrown.
/// </summary>
/// <param name="reader">
/// a reader to reset the source component </param>
/// <exception cref="IOException">
/// if the component's reset method throws an <seealso cref="IOException"/> </exception>
protected internal virtual void SetReader(TextReader reader)
{
m_source.SetReader(reader);
}
/// <summary>
/// Returns the sink <see cref="Analysis.TokenStream"/>
/// </summary>
/// <returns> the sink <see cref="Analysis.TokenStream"/> </returns>
public virtual TokenStream TokenStream
{
get
{
return m_sink;
}
}
/// <summary>
/// Returns the component's <see cref="Analysis.Tokenizer"/>
/// </summary>
/// <returns> Component's <see cref="Analysis.Tokenizer"/> </returns>
public virtual Tokenizer Tokenizer
{
get
{
return m_source;
}
}
}
/// <summary>
/// Strategy defining how <see cref="TokenStreamComponents"/> are reused per call to
/// <see cref="Analyzer.GetTokenStream(string, TextReader)"/>.
/// </summary>
public abstract class ReuseStrategy
{
/// <summary>
/// Gets the reusable <see cref="TokenStreamComponents"/> for the field with the given name.
/// </summary>
/// <param name="analyzer"> <see cref="Analyzer"/> from which to get the reused components. Use
/// <see cref="GetStoredValue(Analyzer)"/> and <see cref="SetStoredValue(Analyzer, object)"/>
/// to access the data on the <see cref="Analyzer"/>. </param>
/// <param name="fieldName"> Name of the field whose reusable <see cref="TokenStreamComponents"/>
/// are to be retrieved </param>
/// <returns> Reusable <see cref="TokenStreamComponents"/> for the field, or <c>null</c>
/// if there was no previous components for the field </returns>
public abstract TokenStreamComponents GetReusableComponents(Analyzer analyzer, string fieldName);
/// <summary>
/// Stores the given <see cref="TokenStreamComponents"/> as the reusable components for the
/// field with the give name.
/// </summary>
/// <param name="analyzer"> Analyzer </param>
/// <param name="fieldName"> Name of the field whose <see cref="TokenStreamComponents"/> are being set </param>
/// <param name="components"> <see cref="TokenStreamComponents"/> which are to be reused for the field </param>
public abstract void SetReusableComponents(Analyzer analyzer, string fieldName, TokenStreamComponents components);
/// <summary>
/// Returns the currently stored value.
/// </summary>
/// <returns> Currently stored value or <c>null</c> if no value is stored </returns>
/// <exception cref="ObjectDisposedException"> if the <see cref="Analyzer"/> is closed. </exception>
protected internal object GetStoredValue(Analyzer analyzer)
{
if (analyzer.storedValue == null)
{
throw new ObjectDisposedException(this.GetType().GetTypeInfo().FullName, "this Analyzer is closed");
}
return analyzer.storedValue.Get();
}
/// <summary>
/// Sets the stored value.
/// </summary>
/// <param name="analyzer"> Analyzer </param>
/// <param name="storedValue"> Value to store </param>
/// <exception cref="ObjectDisposedException"> if the <see cref="Analyzer"/> is closed. </exception>
protected internal void SetStoredValue(Analyzer analyzer, object storedValue)
{
if (analyzer.storedValue == null)
{
throw new ObjectDisposedException("this Analyzer is closed");
}
analyzer.storedValue.Set(storedValue);
}
}
}
| |
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 Apress.Recipes.WebApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using QuantConnect.Data;
using QuantConnect.Logging;
namespace QuantConnect.Indicators
{
/// <summary>
/// Abstract Indicator base, meant to contain non-generic fields of indicator base to support non-typed inputs
/// </summary>
public abstract partial class IndicatorBase : IIndicator
{
/// <summary>
/// Gets the current state of this indicator. If the state has not been updated
/// then the time on the value will equal DateTime.MinValue.
/// </summary>
public IndicatorDataPoint Current { get; protected set; }
/// <summary>
/// Gets a name for this indicator
/// </summary>
public string Name { get; protected set; }
/// <summary>
/// Gets the number of samples processed by this indicator
/// </summary>
public long Samples { get; internal set; }
/// <summary>
/// Gets a flag indicating when this indicator is ready and fully initialized
/// </summary>
public abstract bool IsReady { get; }
/// <summary>
/// Event handler that fires after this indicator is updated
/// </summary>
public event IndicatorUpdatedHandler Updated;
/// <summary>
/// Resets this indicator to its initial state
/// </summary>
public abstract void Reset();
/// <summary>
/// Initializes a new instance of the Indicator class.
/// </summary>
protected IndicatorBase()
{
Current = new IndicatorDataPoint(DateTime.MinValue, 0m);
}
/// <summary>
/// Initializes a new instance of the Indicator class using the specified name.
/// </summary>
/// <param name="name">The name of this indicator</param>
protected IndicatorBase(string name)
{
Name = name;
Current = new IndicatorDataPoint(DateTime.MinValue, 0m);
}
/// <summary>
/// Event invocator for the Updated event
/// </summary>
/// <param name="consolidated">This is the new piece of data produced by this indicator</param>
protected virtual void OnUpdated(IndicatorDataPoint consolidated)
{
Updated?.Invoke(this, consolidated);
}
/// <summary>
/// Updates the state of this indicator with the given value and returns true
/// if this indicator is ready, false otherwise
/// </summary>
/// <param name="input">The value to use to update this indicator</param>
/// <returns>True if this indicator is ready, false otherwise</returns>
public abstract bool Update(IBaseData input);
/// <summary>
/// ToString Overload for Indicator Base
/// </summary>
/// <returns>String representation of the indicator</returns>
public override string ToString()
{
return Current.Value.ToStringInvariant("#######0.0####");
}
/// <summary>
/// Provides a more detailed string of this indicator in the form of {Name} - {Value}
/// </summary>
/// <returns>A detailed string of this indicator's current state</returns>
public string ToDetailedString()
{
return $"{Name} - {this}";
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo(IIndicator other)
{
if (ReferenceEquals(other, null))
{
// everything is greater than null via MSDN
return 1;
}
return Current.CompareTo(other.Current);
}
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance precedes <paramref name="obj"/> in the sort order. Zero This instance occurs in the same position in the sort order as <paramref name="obj"/>. Greater than zero This instance follows <paramref name="obj"/> in the sort order.
/// </returns>
/// <param name="obj">An object to compare with this instance. </param><exception cref="T:System.ArgumentException"><paramref name="obj"/> is not the same type as this instance. </exception><filterpriority>2</filterpriority>
public int CompareTo(object obj)
{
var other = obj as IndicatorBase;
if (other == null)
{
throw new ArgumentException("Object must be of type " + GetType().GetBetterTypeName());
}
return CompareTo(other);
}
}
/// <summary>
/// Provides a base type for all indicators
/// </summary>
/// <typeparam name="T">The type of data input into this indicator</typeparam>
[DebuggerDisplay("{ToDetailedString()}")]
public abstract class IndicatorBase<T> : IndicatorBase
where T : IBaseData
{
/// <summary>the most recent input that was given to this indicator</summary>
private Dictionary<SecurityIdentifier, T> _previousInput = new Dictionary<SecurityIdentifier, T>();
/// <summary>
/// Initializes a new instance of the Indicator class using the specified name.
/// </summary>
/// <param name="name">The name of this indicator</param>
protected IndicatorBase(string name)
{
Name = name;
Current = new IndicatorDataPoint(DateTime.MinValue, 0m);
}
/// <summary>
/// Updates the state of this indicator with the given value and returns true
/// if this indicator is ready, false otherwise
/// </summary>
/// <param name="input">The value to use to update this indicator</param>
/// <returns>True if this indicator is ready, false otherwise</returns>
public override bool Update(IBaseData input)
{
T _previousSymbolInput = default(T);
if (_previousInput.TryGetValue(input.Symbol.ID, out _previousSymbolInput) && input.EndTime < _previousSymbolInput.EndTime)
{
// if we receive a time in the past, log and return
Log.Error($"This is a forward only indicator: {Name} Input: {input.EndTime:u} Previous: {_previousSymbolInput.EndTime:u}. It will not be updated with this input.");
return IsReady;
}
if (!ReferenceEquals(input, _previousSymbolInput))
{
// compute a new value and update our previous time
Samples++;
if (!(input is T))
{
throw new ArgumentException($"IndicatorBase.Update() 'input' expected to be of type {typeof(T)} but is of type {input.GetType()}");
}
_previousInput[input.Symbol.ID] = (T)input;
var nextResult = ValidateAndComputeNextValue((T)input);
if (nextResult.Status == IndicatorStatus.Success)
{
Current = new IndicatorDataPoint(input.EndTime, nextResult.Value);
// let others know we've produced a new data point
OnUpdated(Current);
}
}
return IsReady;
}
/// <summary>
/// Updates the state of this indicator with the given value and returns true
/// if this indicator is ready, false otherwise
/// </summary>
/// <param name="time">The time associated with the value</param>
/// <param name="value">The value to use to update this indicator</param>
/// <returns>True if this indicator is ready, false otherwise</returns>
public bool Update(DateTime time, decimal value)
{
if (typeof(T) == typeof(IndicatorDataPoint))
{
return Update((T)(object)new IndicatorDataPoint(time, value));
}
var suggestions = new List<string>
{
"Update(TradeBar)",
"Update(QuoteBar)"
};
if (typeof(T) == typeof(IBaseData))
{
suggestions.Add("Update(Tick)");
}
throw new NotSupportedException($"{GetType().Name} does not support the `Update(DateTime, decimal)` method. Use one of the following methods instead: {string.Join(", ", suggestions)}");
}
/// <summary>
/// Resets this indicator to its initial state
/// </summary>
public override void Reset()
{
Samples = 0;
_previousInput.Clear();
Current = new IndicatorDataPoint(DateTime.MinValue, default(decimal));
}
/// <summary>
/// Computes the next value of this indicator from the given state
/// </summary>
/// <param name="input">The input given to the indicator</param>
/// <returns>A new value for this indicator</returns>
protected abstract decimal ComputeNextValue(T input);
/// <summary>
/// Computes the next value of this indicator from the given state
/// and returns an instance of the <see cref="IndicatorResult"/> class
/// </summary>
/// <param name="input">The input given to the indicator</param>
/// <returns>An IndicatorResult object including the status of the indicator</returns>
protected virtual IndicatorResult ValidateAndComputeNextValue(T input)
{
// default implementation always returns IndicatorStatus.Success
return new IndicatorResult(ComputeNextValue(input));
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <returns>
/// true if the specified object is equal to the current object; otherwise, false.
/// </returns>
/// <param name="obj">The object to compare with the current object. </param>
public override bool Equals(object obj)
{
// this implementation acts as a liason to prevent inconsistency between the operators
// == and != against primitive types. the core impl for equals between two indicators
// is still reference equality, however, when comparing value types (floats/int, ect..)
// we'll use value type semantics on Current.Value
// because of this, we shouldn't need to override GetHashCode as well since we're still
// solely relying on reference semantics (think hashset/dictionary impls)
if (ReferenceEquals(obj, null)) return false;
var type = obj.GetType();
while (type != null && type != typeof(object))
{
var cur = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
if (typeof(IndicatorBase<>) == cur)
{
return ReferenceEquals(this, obj);
}
type = type.BaseType;
}
try
{
// the obj is not an indicator, so let's check for value types, try converting to decimal
var converted = obj.ConvertInvariant<decimal>();
return Current.Value == converted;
}
catch (InvalidCastException)
{
// conversion failed, return false
return false;
}
}
/// <summary>
/// Get Hash Code for this Object
/// </summary>
/// <returns>Integer Hash Code</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Core.Flighting;
using Adxstudio.Xrm.Data;
using Adxstudio.Xrm.Feedback;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Sdk;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Text;
using Adxstudio.Xrm.Web;
using Microsoft.Xrm.Client.Messages;
namespace Adxstudio.Xrm.Blogs
{
public class BlogPostDataAdapter : RatingDataAdapter, IBlogPostDataAdapter, ICommentDataAdapter
{
private BlogPostDataAdapter(EntityReference blogPost, IDataAdapterDependencies dependencies, BlogSecurityInfo security) : base(blogPost, dependencies)
{
if (blogPost == null) throw new ArgumentNullException("blogPost");
if (dependencies == null) throw new ArgumentNullException("dependencies");
if (security == null) throw new ArgumentNullException("security");
if (blogPost.LogicalName != "adx_blogpost")
{
throw new ArgumentException(string.Format("Value must have logical name {0}.", blogPost.LogicalName), "blogPost");
}
BlogPostReference = blogPost;
BlogDependencies = dependencies;
Security = security;
}
public BlogPostDataAdapter(EntityReference blogPost, IDataAdapterDependencies dependencies) : this(blogPost, dependencies, new BlogSecurityInfo(blogPost, dependencies)) { }
public BlogPostDataAdapter(Entity blogPost, IDataAdapterDependencies dependencies) : this(blogPost.ToEntityReference(), dependencies, new BlogSecurityInfo(blogPost, dependencies)) { }
public BlogPostDataAdapter(IBlogPost blogPost, IDataAdapterDependencies dependencies) : this(blogPost.Entity, dependencies)
{
BlogPost = blogPost;
}
public BlogPostDataAdapter(EntityReference blogPost, string portalName = null) : this(blogPost, new PortalConfigurationDataAdapterDependencies(portalName)) { }
public BlogPostDataAdapter(Entity blogPost, string portalName = null) : this(blogPost, new PortalConfigurationDataAdapterDependencies(portalName)) { }
public BlogPostDataAdapter(IBlogPost blogPost, string portalName = null) : this(blogPost, new PortalConfigurationDataAdapterDependencies(portalName)) { }
protected EntityReference BlogPostReference { get; private set; }
protected IDataAdapterDependencies BlogDependencies { get; private set; }
protected IBlogPost BlogPost { get; private set; }
protected BlogSecurityInfo Security { get; private set; }
protected enum StateCode
{
Active = 0
}
public IDictionary<string, object> GetCommentAttributes(string content, string authorName = null, string authorEmail = null, string authorUrl = null, HttpContext context = null)
{
var post = Select();
if (post == null)
{
throw new InvalidOperationException("Unable to load adx_blogpost {0}. Please ensure that this record exists, and is accessible by the current user.".FormatWith(BlogPostReference.Id));
}
var postedOn = DateTime.UtcNow;
var attributes = new Dictionary<string, object>
{
{ "regardingobjectid", post.Entity.ToEntityReference() },
{ "createdon", postedOn },
{ "adx_approved", post.CommentPolicy == BlogCommentPolicy.Open || post.CommentPolicy == BlogCommentPolicy.OpenToAuthenticatedUsers },
{ "title", StringHelper.GetCommentTitleFromContent(content) },
{ "adx_createdbycontact", authorName },
{ "adx_contactemail", authorEmail },
{ "comments", content },
{ "source", new OptionSetValue((int)FeedbackSource.Portal) }
};
var portalUser = BlogDependencies.GetPortalUser();
if (portalUser != null && portalUser.LogicalName == "contact")
{
attributes[FeedbackMetadataAttributes.UserIdAttributeName] = portalUser;
}
else if (context != null && context.Profile != null)
{
attributes[FeedbackMetadataAttributes.VisitorAttributeName] = context.Profile.UserName;
}
if (authorUrl != null)
{
authorUrl = authorUrl.Contains(Uri.SchemeDelimiter) ? authorUrl : "{0}{1}{2}".FormatWith(Uri.UriSchemeHttp, Uri.SchemeDelimiter, authorUrl);
if (Uri.IsWellFormedUriString(authorUrl, UriKind.Absolute))
{
attributes["adx_authorurl"] = authorUrl;
}
}
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Blog, HttpContext.Current, "create_comment_blog", post.CommentCount, post.Entity.ToEntityReference(), "create");
}
return attributes;
}
public IBlogPost Select()
{
var serviceContext = BlogDependencies.GetServiceContext();
var query = serviceContext.CreateQuery("adx_blogpost")
.Where(post => post.GetAttributeValue<Guid>("adx_blogpostid") == BlogPostReference.Id);
if (!Security.UserHasAuthorPermission)
{
query = query.Where(post => post.GetAttributeValue<bool?>("adx_published") == true);
}
var entity = query.FirstOrDefault();
if (entity == null)
{
return null;
}
var securityProvider = BlogDependencies.GetSecurityProvider();
if (!securityProvider.TryAssert(serviceContext, entity, CrmEntityRight.Read))
{
return null;
}
var urlProvider = BlogDependencies.GetUrlProvider();
var tagPathGenerator = new BlogArchiveApplicationPathGenerator(BlogDependencies);
return new BlogPostFactory(serviceContext, urlProvider, BlogDependencies.GetWebsite(), tagPathGenerator).Create(new[] { entity }).FirstOrDefault();
}
public virtual IEnumerable<IComment> SelectComments()
{
return SelectComments(0);
}
public virtual IEnumerable<IComment> SelectComments(int startRowIndex, int maximumRows = -1)
{
var comments = new List<Comment>();
if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback) || maximumRows == 0)
{
return comments;
}
var includeUnapprovedComments = Security.UserHasAuthorPermission;
var query =
Cms.OrganizationServiceContextExtensions.SelectCommentsByPage(
Cms.OrganizationServiceContextExtensions.GetPageInfo(startRowIndex, maximumRows), BlogPostReference.Id,
includeUnapprovedComments);
var commentsEntitiesResult = Dependencies.GetServiceContext().RetrieveMultiple(query);
comments.AddRange(
commentsEntitiesResult.Entities.Select(
commentEntity =>
new Comment(commentEntity,
new Lazy<ApplicationPath>(() => Dependencies.GetEditPath(commentEntity.ToEntityReference()), LazyThreadSafetyMode.None),
new Lazy<ApplicationPath>(() => Dependencies.GetDeletePath(commentEntity.ToEntityReference()), LazyThreadSafetyMode.None),
new Lazy<bool>(() => includeUnapprovedComments, LazyThreadSafetyMode.None), null, RatingsEnabled)));
return comments;
}
public virtual int SelectCommentCount()
{
var serviceContext = BlogDependencies.GetServiceContext();
var includeUnapprovedComments = Security.UserHasAuthorPermission;
return serviceContext.FetchCount("feedback", "feedbackid", addCondition =>
{
addCondition("regardingobjectid", "eq", BlogPostReference.Id.ToString());
if (!includeUnapprovedComments)
{
addCondition("adx_approved", "eq", "true");
}
});
}
public string GetCommentLogicalName()
{
return "feedback";
}
public string GetCommentContentAttributeName()
{
return "comments";
}
public ICommentPolicyReader GetCommentPolicyReader()
{
var blogPost = Select();
return new BlogCommentPolicyReader(blogPost);
}
public override bool RatingsEnabled
{
get
{
var blogpost = Select();
return blogpost != null && (blogpost.Entity.GetAttributeValue<bool?>("adx_enableratings") ?? false);
}
}
public override IRatingInfo GetRatingInfo()
{
var blogPost = BlogPost ?? Select();
return blogPost.RatingInfo;
}
}
}
| |
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Menu Builder Helper Class
//-----------------------------------------------------------------------------
/// @class MenuBuilder
/// @brief Create Dynamic Context and MenuBar Menus
///
///
/// Summary : The MenuBuilder script class exists merely as a helper for creating
/// popup menu's for use in torque editors. It is setup as a single
/// object with dynamic fields starting with item[0]..[n] that describe
/// how to create the menu in question. An example is below.
///
/// isPopup : isPopup is a persistent field on PopupMenu console class which
/// when specified to true will allow you to perform .showPopup(x,y)
/// commands which allow popupmenu's to be used/reused as menubar menus
/// as well as context menus.
///
/// barPosition : barPosition indicates which index on the menu bar (0 = leftmost)
/// to place this menu if it is attached. Use the attachToMenuBar() command
/// to attach a menu.
///
/// barName : barName specifies the visible name of a menu item that is attached
/// to the global menubar.
///
/// canvas : The GuiCanvas object the menu should be attached to. This defaults to
/// the global Canvas object if unspecified.
///
/// Remarks : If you wish to use a menu as a context popup menu, isPopup must be
/// specified as true at the creation time of the menu.
///
///
/// @li @b item[n] (String) TAB (String) TAB (String) : <c>A Menu Item Definition.</c>
/// @code item[0] = "Open File..." TAB "Ctrl O" TAB "Something::OpenFile"; @endcode
///
/// @li @b isPopup (bool) : <c>If Specified the menu will be considered a popup menu and should be used via .showPopup()</c>
/// @code isPopup = true; @endcode
///
///
/// Example : Creating a @b MenuBar Menu
/// @code
/// %%editMenu = new PopupMenu()
/// {
/// barPosition = 3;
/// barName = "View";
/// superClass = "MenuBuilder";
/// item[0] = "Undo" TAB "Ctrl Z" TAB "levelBuilderUndo(1);";
/// item[1] = "Redo" TAB "Ctrl Y" TAB "levelBuilderRedo(1);";
/// item[2] = "-";
/// };
///
/// %%editMenu.attachToMenuBar( 1, "Edit" );
///
/// @endcode
///
///
/// Example : Creating a @b Context (Popup) Menu
/// @code
/// %%contextMenu = new PopupMenu()
/// {
/// superClass = MenuBuilder;
/// isPopup = true;
/// item[0] = "My Super Cool Item" TAB "Ctrl 2" TAB "echo(\"Clicked Super Cool Item\");";
/// item[1] = "-";
/// };
///
/// %%contextMenu.showPopup();
/// @endcode
///
///
/// Example : Modifying a Menu
/// @code
/// %%editMenu = new PopupMenu()
/// {
/// item[0] = "Foo" TAB "Ctrl F" TAB "echo(\"clicked Foo\")";
/// item[1] = "-";
/// };
/// %%editMenu.addItem( 2, "Bar" TAB "Ctrl B" TAB "echo(\"clicked Bar\")" );
/// %%editMenu.removeItem( 0 );
/// %%editMenu.addItem( 0, "Modified Foo" TAB "Ctrl F" TAB "echo(\"clicked modified Foo\")" );
/// @endcode
///
///
/// @see PopupMenu
///
//-----------------------------------------------------------------------------
// Adds one item to the menu.
// if %item is skipped or "", we will use %item[#], which was set when the menu was created.
// if %item is provided, then we update %item[#].
function MenuBuilder::addItem(%this, %pos, %item)
{
if(%item $= "")
%item = %this.item[%pos];
if(%item !$= %this.item[%pos])
%this.item[%pos] = %item;
%name = getField(%item, 0);
%accel = getField(%item, 1);
%cmd = getField(%item, 2);
// We replace the [this] token with our object ID
%cmd = strreplace( %cmd, "[this]", %this );
%this.item[%pos] = setField( %item, 2, %cmd );
if(isObject(%accel))
{
// If %accel is an object, we want to add a sub menu
%this.insertSubmenu(%pos, %name, %accel);
}
else
{
%this.insertItem(%pos, %name !$= "-" ? %name : "", %accel, %cmd);
}
}
function MenuBuilder::appendItem(%this, %item)
{
%this.addItem(%this.getItemCount(), %item);
}
function MenuBuilder::onAdd(%this)
{
if(! isObject(%this.canvas))
%this.canvas = Canvas;
for(%i = 0;%this.item[%i] !$= "";%i++)
{
%this.addItem(%i);
}
}
function MenuBuilder::onRemove(%this)
{
%this.removeFromMenuBar();
}
//////////////////////////////////////////////////////////////////////////
function MenuBuilder::onSelectItem(%this, %id, %text)
{
%cmd = getField(%this.item[%id], 2);
if(%cmd !$= "")
{
eval( %cmd );
return true;
}
return false;
}
/// Sets a new name on an existing menu item.
function MenuBuilder::setItemName( %this, %id, %name )
{
%item = %this.item[%id];
%accel = getField(%item, 1);
%this.setItem( %id, %name, %accel );
}
/// Sets a new command on an existing menu item.
function MenuBuilder::setItemCommand( %this, %id, %command )
{
%this.item[%id] = setField( %this.item[%id], 2, %command );
}
/// (SimID this)
/// Wraps the attachToMenuBar call so that it does not require knowledge of
/// barName or barIndex to be removed/attached. This makes the individual
/// MenuBuilder items very easy to add and remove dynamically from a bar.
///
function MenuBuilder::attachToMenuBar( %this )
{
if( %this.barName $= "" )
{
error("MenuBuilder::attachToMenuBar - Menu property 'barName' not specified.");
return false;
}
if( %this.barPosition < 0 )
{
error("MenuBuilder::attachToMenuBar - Menu " SPC %this.barName SPC "property 'barPosition' is invalid, must be zero or greater.");
return false;
}
Parent::attachToMenuBar( %this, %this.canvas, %this.barPosition, %this.barName );
}
//////////////////////////////////////////////////////////////////////////
// Callbacks from PopupMenu. These callbacks are now passed on to submenus
// in C++, which was previously not the case. Thus, no longer anything to
// do in these. I am keeping the callbacks in case they are needed later.
function MenuBuilder::onAttachToMenuBar(%this, %canvas, %pos, %title)
{
}
function MenuBuilder::onRemoveFromMenuBar(%this, %canvas)
{
}
//////////////////////////////////////////////////////////////////////////
/// Method called to setup default state for the menu. Expected to be overriden
/// on an individual menu basis. See the mission editor for an example.
function MenuBuilder::setupDefaultState(%this)
{
for(%i = 0;%this.item[%i] !$= "";%i++)
{
%name = getField(%this.item[%i], 0);
%accel = getField(%this.item[%i], 1);
%cmd = getField(%this.item[%i], 2);
// Pass on to sub menus
if(isObject(%accel))
%accel.setupDefaultState();
}
}
/// Method called to easily enable or disable all items in a menu.
function MenuBuilder::enableAllItems(%this, %enable)
{
for(%i = 0; %this.item[%i] !$= ""; %i++)
{
%this.enableItem(%i, %enable);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Reflection.Emit;
namespace System.Linq.Expressions.Interpreter
{
/// <summary>
/// Contains compiler state corresponding to a LabelTarget
/// See also LabelScopeInfo.
/// </summary>
internal sealed class LabelInfo
{
// The tree node representing this label
private readonly LabelTarget _node;
// The BranchLabel label, will be mutated if Node is redefined
private BranchLabel _label;
// The blocks where this label is defined. If it has more than one item,
// the blocks can't be jumped to except from a child block
// If there's only 1 block (the common case) it's stored here, if there's multiple blocks it's stored
// as a HashSet<LabelScopeInfo>
private object _definitions;
// Blocks that jump to this block
private readonly List<LabelScopeInfo> _references = new List<LabelScopeInfo>();
// True if at least one jump is across blocks
// If we have any jump across blocks to this label, then the
// LabelTarget can only be defined in one place
private bool _acrossBlockJump;
internal LabelInfo(LabelTarget node)
{
_node = node;
}
internal BranchLabel GetLabel(LightCompiler compiler)
{
EnsureLabel(compiler);
return _label;
}
internal void Reference(LabelScopeInfo block)
{
_references.Add(block);
if (HasDefinitions)
{
ValidateJump(block);
}
}
internal void Define(LabelScopeInfo block)
{
// Prevent the label from being shadowed, which enforces cleaner
// trees. Also we depend on this for simplicity (keeping only one
// active IL Label per LabelInfo)
for (LabelScopeInfo j = block; j != null; j = j.Parent)
{
if (j.ContainsTarget(_node))
{
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Label target already defined: {0}", _node.Name));
}
}
AddDefinition(block);
block.AddLabelInfo(_node, this);
// Once defined, validate all jumps
if (HasDefinitions && !HasMultipleDefinitions)
{
foreach (var r in _references)
{
ValidateJump(r);
}
}
else
{
// Was just redefined, if we had any across block jumps, they're
// now invalid
if (_acrossBlockJump)
{
throw new InvalidOperationException("Ambiguous jump");
}
// For local jumps, we need a new IL label
// This is okay because:
// 1. no across block jumps have been made or will be made
// 2. we don't allow the label to be shadowed
_label = null;
}
}
private void ValidateJump(LabelScopeInfo reference)
{
// look for a simple jump out
for (LabelScopeInfo j = reference; j != null; j = j.Parent)
{
if (DefinedIn(j))
{
// found it, jump is valid!
return;
}
if (j.Kind == LabelScopeKind.Finally || j.Kind == LabelScopeKind.Filter)
{
break;
}
}
_acrossBlockJump = true;
if (HasMultipleDefinitions)
{
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Ambiguous jump {0}", _node.Name));
}
// We didn't find an outward jump. Look for a jump across blocks
LabelScopeInfo def = FirstDefinition();
LabelScopeInfo common = CommonNode(def, reference, b => b.Parent);
// Validate that we aren't jumping across a finally
for (LabelScopeInfo j = reference; j != common; j = j.Parent)
{
if (j.Kind == LabelScopeKind.Finally)
{
throw new InvalidOperationException("Control cannot leave finally");
}
if (j.Kind == LabelScopeKind.Filter)
{
throw new InvalidOperationException("Control cannot leave filter test");
}
}
// Valdiate that we aren't jumping into a catch or an expression
for (LabelScopeInfo j = def; j != common; j = j.Parent)
{
if (!j.CanJumpInto)
{
if (j.Kind == LabelScopeKind.Expression)
{
throw new InvalidOperationException("Control cannot enter an expression");
}
else
{
throw new InvalidOperationException("Control cannot enter try");
}
}
}
}
internal void ValidateFinish()
{
// Make sure that if this label was jumped to, it is also defined
if (_references.Count > 0 && !HasDefinitions)
{
throw new InvalidOperationException("label target undefined");
}
}
private void EnsureLabel(LightCompiler compiler)
{
if (_label == null)
{
_label = compiler.Instructions.MakeLabel();
}
}
private bool DefinedIn(LabelScopeInfo scope)
{
if (_definitions == scope)
{
return true;
}
HashSet<LabelScopeInfo> definitions = _definitions as HashSet<LabelScopeInfo>;
if (definitions != null)
{
return definitions.Contains(scope);
}
return false;
}
private bool HasDefinitions
{
get
{
return _definitions != null;
}
}
private LabelScopeInfo FirstDefinition()
{
LabelScopeInfo scope = _definitions as LabelScopeInfo;
if (scope != null)
{
return scope;
}
foreach (var x in (HashSet<LabelScopeInfo>)_definitions)
{
return x;
}
throw new InvalidOperationException();
}
private void AddDefinition(LabelScopeInfo scope)
{
if (_definitions == null)
{
_definitions = scope;
}
else
{
HashSet<LabelScopeInfo> set = _definitions as HashSet<LabelScopeInfo>;
if (set == null)
{
_definitions = set = new HashSet<LabelScopeInfo>() { (LabelScopeInfo)_definitions };
}
set.Add(scope);
}
}
private bool HasMultipleDefinitions
{
get
{
return _definitions is HashSet<LabelScopeInfo>;
}
}
internal static T CommonNode<T>(T first, T second, Func<T, T> parent) where T : class
{
var cmp = EqualityComparer<T>.Default;
if (cmp.Equals(first, second))
{
return first;
}
var set = new HashSet<T>(cmp);
for (T t = first; t != null; t = parent(t))
{
set.Add(t);
}
for (T t = second; t != null; t = parent(t))
{
if (set.Contains(t))
{
return t;
}
}
return null;
}
}
internal enum LabelScopeKind
{
// any "statement like" node that can be jumped into
Statement,
// these correspond to the node of the same name
Block,
Switch,
Lambda,
Try,
// these correspond to the part of the try block we're in
Catch,
Finally,
Filter,
// the catch-all value for any other expression type
// (means we can't jump into it)
Expression,
}
//
// Tracks scoping information for LabelTargets. Logically corresponds to a
// "label scope". Even though we have arbitrary goto support, we still need
// to track what kinds of nodes that gotos are jumping through, both to
// emit property IL ("leave" out of a try block), and for validation, and
// to allow labels to be duplicated in the tree, as long as the jumps are
// considered "up only" jumps.
//
// We create one of these for every Expression that can be jumped into, as
// well as creating them for the first expression we can't jump into. The
// "Kind" property indicates what kind of scope this is.
//
internal sealed class LabelScopeInfo
{
private HybridReferenceDictionary<LabelTarget, LabelInfo> _labels; // lazily allocated, we typically use this only once every 6th-7th block
internal readonly LabelScopeKind Kind;
internal readonly LabelScopeInfo Parent;
internal LabelScopeInfo(LabelScopeInfo parent, LabelScopeKind kind)
{
Parent = parent;
Kind = kind;
}
/// <summary>
/// Returns true if we can jump into this node
/// </summary>
internal bool CanJumpInto
{
get
{
switch (Kind)
{
case LabelScopeKind.Block:
case LabelScopeKind.Statement:
case LabelScopeKind.Switch:
case LabelScopeKind.Lambda:
return true;
}
return false;
}
}
internal bool ContainsTarget(LabelTarget target)
{
if (_labels == null)
{
return false;
}
return _labels.ContainsKey(target);
}
internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo info)
{
if (_labels == null)
{
info = null;
return false;
}
return _labels.TryGetValue(target, out info);
}
internal void AddLabelInfo(LabelTarget target, LabelInfo info)
{
Debug.Assert(CanJumpInto);
if (_labels == null)
{
_labels = new HybridReferenceDictionary<LabelTarget, LabelInfo>();
}
_labels[target] = info;
}
}
}
| |
using Itinero.Optimization.Models.Mapping;
using Itinero.Optimization.Models.Mapping.Rewriters.VisitPosition;
using Itinero.Optimization.Models.Vehicles;
using Itinero.Optimization.Models.Visits;
using Itinero.Optimization.Models.Visits.Costs;
using Xunit;
namespace Itinero.Optimization.Tests.Models.Mapping.Rewriters.VisitPosition
{
public class VisitPositionRewriterTests
{
[Fact]
public void VisitPositionRewriter_N2_ShouldReturnNewCosts()
{
var visitPositionRewriter = new VisitPositionRewriter(new VisitPositionRewriterSettings()
{
AngleFunc = p => 90
});
var mockModelMapping = new MockModelMapping();
var mappedModel = new MappedModel()
{
Visits = new []
{
new Visit(),
new Visit()
},
TravelCosts = new []
{
new TravelCostMatrix()
{
Costs = new []
{
new []{ 0f, 10, 20, 20 },
new []{ 10f, 0, 20, 20 },
new []{ 20f, 20, 0, 10 },
new []{ 20f, 20, 10, 0 }
},
Directed = true
}
}
};
var rewrittenModel = visitPositionRewriter.Rewrite(mappedModel, mockModelMapping);
Assert.NotNull(rewrittenModel);
Assert.NotNull(rewrittenModel.TravelCosts);
Assert.Single(rewrittenModel.TravelCosts);
var travelCosts = rewrittenModel.TravelCosts[0];
Assert.NotNull(travelCosts);
var cost = travelCosts.Costs;
Assert.NotNull(cost);
Assert.Equal(4, cost.Length);
Assert.Equal(4, cost[0].Length);
Assert.Equal(4, cost[1].Length);
Assert.Equal(4, cost[2].Length);
Assert.Equal(4, cost[3].Length);
}
[Fact]
public void VisitPositionRewriter_N2_Bidirectional_AllLeft_ShouldRemoveLeftWeights()
{
var visitPositionRewriter = new VisitPositionRewriter(new VisitPositionRewriterSettings()
{
AngleFunc = p => 90
});
var mockModelMapping = new MockModelMapping();
var mappedModel = new MappedModel()
{
Visits = new[]
{
new Visit(),
new Visit()
},
TravelCosts = new[]
{
new TravelCostMatrix()
{
Costs = new[]
{
new[] {0f, 10, 20, 20},
new[] {10f, 0, 20, 20},
new[] {20f, 20, 0, 10},
new[] {20f, 20, 10, 0}
},
Directed = true
}
}
};
var rewrittenModel = visitPositionRewriter.Rewrite(mappedModel, mockModelMapping);
var costs = rewrittenModel.TravelCosts[0].Costs;
for (var from = 0; from < 4; from++)
for (var to = 0; to < 4; to++)
{
var fromForward = (from % 2) == 1;
var toForward = (to % 2) == 1;
if (fromForward && toForward)
{
// there should be a non-infinite weight.
Assert.True(costs[from][to] < float.MaxValue, $"Costs at [{from}][{to}] don't match.");
}
else
{
// one of the two is forward, and left, so not allowed.
Assert.True(costs[from][to] >= float.MaxValue, $"Costs at [{from}][{to}] don't match.");
}
}
}
[Fact]
public void VisitPositionRewriter_N2_OneWayForward_AllLeft_ShouldNotRemoveLeftWeights()
{
var visitPositionRewriter = new VisitPositionRewriter(new VisitPositionRewriterSettings()
{
AngleFunc = p => 90
});
var mockModelMapping = new MockModelMapping();
var mappedModel = new MappedModel()
{
Visits = new[]
{
new Visit(),
new Visit()
},
TravelCosts = new[]
{
new TravelCostMatrix()
{
Costs = new[]
{
new[] {float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue},
new[] {float.MaxValue, 0, float.MaxValue, 20},
new[] {float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue},
new[] {float.MaxValue, 20, float.MaxValue, 0}
},
Directed = true
}
}
};
var rewrittenModel = visitPositionRewriter.Rewrite(mappedModel, mockModelMapping);
var costs = rewrittenModel.TravelCosts[0].Costs;
for (var from = 0; from < 4; from++)
for (var to = 0; to < 4; to++)
{
var fromForward = (from % 2) == 1;
var toForward = (to % 2) == 1;
if (fromForward && toForward)
{
// there should be a non-infinite weight.
// it should not have been overwritten.
Assert.True(costs[from][to] < float.MaxValue);
}
else
{
// one of the two is backward and that's impossible.
Assert.True(costs[from][to] >= float.MaxValue);
}
}
}
[Fact]
public void VisitPositionRewriter_N3_MixedDirections_MixedAngles_ShouldRemoveLeftWeights()
{
var visitPositionRewriter = new VisitPositionRewriter(new VisitPositionRewriterSettings()
{
AngleFunc = p =>
{
if (p.EdgeId == 0)
{
return 90;
}
else
{
return 270;
}
}
});
var mockModelMapping = new MockModelMapping();
var mappedModel = new MappedModel()
{
Visits = new[]
{
new Visit(),
new Visit(),
new Visit()
},
TravelCosts = new[]
{
new TravelCostMatrix()
{
Costs = new[]
{
new[] {float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue},
new[] {float.MaxValue, 0, float.MaxValue, 288, 254, 286},
new[] {float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue},
new[] {float.MaxValue, 352, float.MaxValue, 0, 128, 60},
new[] {float.MaxValue, 312, float.MaxValue, 49, 0, 48},
new[] {float.MaxValue, 380, float.MaxValue, 117, 89, 0},
},
Directed = true
}
}
};
var rewrittenModel = visitPositionRewriter.Rewrite(mappedModel, mockModelMapping);
var costs = rewrittenModel.TravelCosts[0].Costs;
var expectedCosts =new[]
{
new[] {float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue},
new[] {float.MaxValue, 0, float.MaxValue, 288, 254, float.MaxValue},
new[] {float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue},
new[] {float.MaxValue, 352, float.MaxValue, 0, 128, float.MaxValue},
new[] {float.MaxValue, 312, float.MaxValue, 49, 0, float.MaxValue},
new[] {float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue},
};
for (var from = 0; from < 6; from++)
for (var to = 0; to < 6; to++)
{
Assert.Equal(expectedCosts[from][to], costs[from][to]);
}
}
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId
{
public partial class SymbolKeyTest : SymbolKeyTestBase
{
#region "No change to symbol"
[Fact]
public void C2CTypeSymbolUnchanged01()
{
var src1 = @"using System;
public delegate void DFoo(int p1, string p2);
namespace N1.N2
{
public interface IFoo { }
namespace N3
{
public class CFoo
{
public struct SFoo
{
public enum EFoo { Zero, One }
}
}
}
}
";
var src2 = @"using System;
public delegate void DFoo(int p1, string p2);
namespace N1.N2
{
public interface IFoo
{
// Add member
N3.CFoo GetClass();
}
namespace N3
{
public class CFoo
{
public struct SFoo
{
// Update member
public enum EFoo { Zero, One, Two }
}
// Add member
public void M(int n) { Console.WriteLine(n); }
}
}
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, comp2, originalSymbols, comp1);
}
[Fact, WorkItem(530171)]
public void C2CErrorSymbolUnchanged01()
{
var src1 = @"public void Method() { }";
var src2 = @"
public void Method()
{
System.Console.WriteLine(12345);
}
";
var comp1 = CreateCompilationWithMscorlib(src1);
var comp2 = CreateCompilationWithMscorlib(src2);
var symbol01 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol;
var symbol02 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol;
Assert.NotNull(symbol01);
Assert.NotNull(symbol02);
Assert.NotEqual(symbol01.Kind, SymbolKind.ErrorType);
Assert.NotEqual(symbol02.Kind, SymbolKind.ErrorType);
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, comp2, originalSymbols, comp1);
}
[Fact]
[WorkItem(820263)]
public void PartialDefinitionAndImplementationResolveCorrectly()
{
var src = @"using System;
namespace NS
{
public partial class C1
{
partial void M() { }
partial void M();
}
}
";
var comp = CreateCompilationWithMscorlib(src, assemblyName: "Test");
var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var type = ns.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
var definition = type.GetMembers("M").First() as IMethodSymbol;
var implementation = definition.PartialImplementationPart;
// Assert that both the definition and implementation resolve back to themselves
Assert.Equal(definition, ResolveSymbol(definition, comp, comp, SymbolKeyComparison.None));
Assert.Equal(implementation, ResolveSymbol(implementation, comp, comp, SymbolKeyComparison.None));
}
[Fact]
[WorkItem(916341)]
public void ExplicitIndexerImplementationResolvesCorrectly()
{
var src = @"
interface I
{
object this[int index] { get; }
}
interface I<T>
{
T this[int index] { get; }
}
class C<T> : I<T>, I
{
object I.this[int index]
{
get
{
throw new System.NotImplementedException();
}
}
T I<T>.this[int index]
{
get
{
throw new System.NotImplementedException();
}
}
}
";
var compilation = CreateCompilationWithMscorlib(src, assemblyName: "Test");
var type = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single() as NamedTypeSymbol;
var indexer1 = type.GetMembers().Where(m => m.MetadataName == "I.Item").Single() as IPropertySymbol;
var indexer2 = type.GetMembers().Where(m => m.MetadataName == "I<T>.Item").Single() as IPropertySymbol;
AssertSymbolKeysEqual(indexer1, compilation, indexer2, compilation, SymbolKeyComparison.None, expectEqual: false);
Assert.Equal(indexer1, ResolveSymbol(indexer1, compilation, compilation, SymbolKeyComparison.None));
Assert.Equal(indexer2, ResolveSymbol(indexer2, compilation, compilation, SymbolKeyComparison.None));
}
#endregion
#region "Change to symbol"
[Fact]
public void C2CTypeSymbolChanged01()
{
var src1 = @"using System;
public delegate void DFoo(int p1);
namespace N1.N2
{
public interface IBase { }
public interface IFoo { }
namespace N3
{
public class CFoo
{
public struct SFoo
{
public enum EFoo { Zero, One }
}
}
}
}
";
var src2 = @"using System;
public delegate void DFoo(int p1, string p2); // add 1 more parameter
namespace N1.N2
{
public interface IBase { }
public interface IFoo : IBase // add base interface
{
}
namespace N3
{
public class CFoo : IFoo // impl interface
{
private struct SFoo // change modifier
{
internal enum EFoo : long { Zero, One } // change base class, and modifier
}
}
}
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType);
ResolveAndVerifySymbolList(newSymbols, comp2, originalSymbols, comp1);
}
[Fact]
public void C2CTypeSymbolChanged02()
{
var src1 = @"using System;
namespace NS
{
public class C1
{
public void M() {}
}
}
";
var src2 = @"
namespace NS
{
internal class C1 // add new C1
{
public string P { get; set; }
}
public class C2 // rename C1 to C2
{
public void M() {}
}
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var typeSym00 = namespace1.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var typeSym01 = namespace2.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
var typeSym02 = namespace2.GetTypeMembers("C2").Single() as NamedTypeSymbol;
// new C1 resolve to old C1
ResolveAndVerifySymbol(typeSym01, comp2, typeSym00, comp1);
// old C1 (new C2) NOT resolve to old C1
var symkey = SymbolKey.Create(typeSym02, comp1, CancellationToken.None);
var syminfo = symkey.Resolve(comp1);
Assert.Null(syminfo.Symbol);
}
[Fact]
public void C2CMemberSymbolChanged01()
{
var src1 = @"using System;
using System.Collections.Generic;
public class Test
{
private byte field = 123;
internal string P { get; set; }
public void M(ref int n) { }
event Action<string> myEvent;
}
";
var src2 = @"using System;
public class Test
{
internal protected byte field = 255; // change modifier and init-value
internal string P { get { return null; } } // remove 'set'
public int M(ref int n) { return 0; } // change ret type
event Action<string> myEvent // add add/remove
{
add { }
remove { }
}
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter)
.Where(s => !s.IsAccessor()).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.NonTypeMember | SymbolCategory.Parameter)
.Where(s => !s.IsAccessor()).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, comp2, originalSymbols, comp1);
}
[WorkItem(542700)]
[Fact]
public void C2CIndexerSymbolChanged01()
{
var src1 = @"using System;
using System.Collections.Generic;
public class Test
{
public string this[string p1] { set { } }
protected long this[long p1] { set { } }
}
";
var src2 = @"using System;
public class Test
{
internal string this[string p1] { set { } } // change modifier
protected long this[long p1] { get { return 0; } set { } } // add 'get'
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var typeSym1 = comp1.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol;
var originalSymbols = typeSym1.GetMembers(WellKnownMemberNames.Indexer);
var typeSym2 = comp2.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol;
var newSymbols = typeSym2.GetMembers(WellKnownMemberNames.Indexer);
ResolveAndVerifySymbol(newSymbols.First(), comp2, originalSymbols.First(), comp1, SymbolKeyComparison.CaseSensitive);
ResolveAndVerifySymbol(newSymbols.Last(), comp2, originalSymbols.Last(), comp1, SymbolKeyComparison.CaseSensitive);
}
[Fact]
public void C2CAssemblyChanged01()
{
var src = @"
namespace NS
{
public class C1
{
public void M() {}
}
}
";
var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly1");
var comp2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly2");
var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var typeSym01 = namespace1.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var typeSym02 = namespace2.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
// new C1 resolves to old C1 if we ignore assembly and module ids
ResolveAndVerifySymbol(typeSym02, comp2, typeSym01, comp1, SymbolKeyComparison.CaseSensitive | SymbolKeyComparison.IgnoreAssemblyIds);
// new C1 DOES NOT resolve to old C1 if we don't ignore assembly and module ids
Assert.Null(ResolveSymbol(typeSym02, comp2, comp1, SymbolKeyComparison.CaseSensitive));
}
[Fact(Skip = "530169"), WorkItem(530169)]
public void C2CAssemblyChanged02()
{
var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}";
// same identity
var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly");
var comp2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly");
Symbol sym1 = comp1.Assembly;
Symbol sym2 = comp2.Assembly;
// Not ignoreAssemblyAndModules
ResolveAndVerifySymbol(sym1, comp2, sym2, comp2);
AssertSymbolKeysEqual(sym1, comp1, sym2, comp2, SymbolKeyComparison.IgnoreAssemblyIds, true);
Assert.NotNull(ResolveSymbol(sym1, comp1, comp2, SymbolKeyComparison.IgnoreAssemblyIds));
// Module
sym1 = comp1.Assembly.Modules[0];
sym2 = comp2.Assembly.Modules[0];
ResolveAndVerifySymbol(sym1, comp1, sym2, comp2);
AssertSymbolKeysEqual(sym2, comp2, sym1, comp1, SymbolKeyComparison.IgnoreAssemblyIds, true);
Assert.NotNull(ResolveSymbol(sym2, comp2, comp1, SymbolKeyComparison.IgnoreAssemblyIds));
}
[Fact, WorkItem(530170)]
public void C2CAssemblyChanged03()
{
var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}";
// -------------------------------------------------------
// different name
var compilation1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly1");
var compilation2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly2");
ISymbol assembly1 = compilation1.Assembly;
ISymbol assembly2 = compilation2.Assembly;
// different
AssertSymbolKeysEqual(assembly2, compilation2, assembly1, compilation1, SymbolKeyComparison.CaseSensitive, expectEqual: false);
Assert.Null(ResolveSymbol(assembly2, compilation2, compilation1, SymbolKeyComparison.CaseSensitive));
// ignore means ALL assembly/module symbols have same ID
AssertSymbolKeysEqual(assembly2, compilation2, assembly1, compilation1, SymbolKeyComparison.IgnoreAssemblyIds, expectEqual: true);
// But can NOT be resolved
Assert.Null(ResolveSymbol(assembly2, compilation2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds));
// Module
var module1 = compilation1.Assembly.Modules[0];
var module2 = compilation2.Assembly.Modules[0];
// different
AssertSymbolKeysEqual(module1, compilation1, module2, compilation2, SymbolKeyComparison.CaseSensitive, expectEqual: false);
Assert.Null(ResolveSymbol(module1, compilation1, compilation2, SymbolKeyComparison.CaseSensitive));
AssertSymbolKeysEqual(module2, compilation2, module1, compilation1, SymbolKeyComparison.IgnoreAssemblyIds);
Assert.Null(ResolveSymbol(module2, compilation2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds));
}
[Fact, WorkItem(546254)]
public void C2CAssemblyChanged04()
{
var src = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")]
[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")]
public class C {}
";
var src2 = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.42"")]
[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")]
public class C {}
";
// different versions
var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Assembly");
Symbol sym1 = comp1.Assembly;
Symbol sym2 = comp2.Assembly;
// comment is changed to compare Name ONLY
AssertSymbolKeysEqual(sym1, comp1, sym2, comp2, SymbolKeyComparison.CaseSensitive, expectEqual: true);
var resolved = ResolveSymbol(sym2, comp2, comp1, SymbolKeyComparison.CaseSensitive);
Assert.Equal(sym1, resolved);
AssertSymbolKeysEqual(sym1, comp1, sym2, comp2, SymbolKeyComparison.IgnoreAssemblyIds);
Assert.Null(ResolveSymbol(sym2, comp2, comp1, SymbolKeyComparison.IgnoreAssemblyIds));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using CodeSmith.Engine;
using CslaGenerator.Metadata;
using DBSchemaInfo.Base;
namespace CslaGenerator.CodeGen
{
/// <summary>
/// Summary description for SprocTemplateHelper.
/// </summary>
public class SprocTemplateHelper : CodeTemplate
{
#region Private fields
private readonly ICatalog _catalog = GeneratorController.Catalog;
private CslaObjectInfo _info;
private Criteria _criteria = new Criteria();
private bool _criteriaDefined;
private CslaObjectInfo _topLevelObject;
private bool _topLevelCollectiontHasNoGetParams;
private readonly List<DuplicateTables> _correlationNames = new List<DuplicateTables>();
private int _innerJoins;
#endregion
#region Private struct
protected struct DuplicateTables
{
internal string PropertyName;
internal string TableName;
internal string ColumnName;
internal int Order;
}
#endregion
#region Public Properties
[Browsable(false)]
public ICatalog Catalog
{
get { return _catalog; }
}
public CslaObjectInfo Info
{
get { return _info; }
set { _info = value; }
}
/*public bool IncludeParentProperties
{
get { return _includeParentProperties; }
set { _includeParentProperties = value; }
}*/
protected bool CriteriaDefined
{
get { return _criteriaDefined; }
}
public Criteria Criteria
{
get { return _criteria; }
set
{
_criteria = value;
_criteriaDefined = true;
}
}
#endregion
public void Init(CslaObjectInfo info)
{
_topLevelObject = info;
if (IsCollectionType(_topLevelObject.ObjectType))
{
_topLevelCollectiontHasNoGetParams = true;
foreach (var crit in info.CriteriaObjects)
{
if ((crit.GetOptions.DataPortal || crit.GetOptions.Factory || crit.GetOptions.Procedure) &&
crit.Properties.Count > 0)
{
_topLevelCollectiontHasNoGetParams = false;
break;
}
}
}
}
#region Accessories
public string GetSchema(IResultObject table, bool fullSchema)
{
if (!Info.Parent.GenerationParams.GenerateQueriesWithSchema)
return "";
if (fullSchema)
return "[" + table.ObjectSchema + "].";
return table.ObjectSchema + ".";
}
private void StoreCorrelationNames(CslaObjectInfo info)
{
_correlationNames.Clear();
var writeCorr = new DuplicateTables();
var vpc = new ValuePropertyCollection();
/*if (IncludeParentProperties)
vpc.AddRange(info.GetParentValueProperties());*/
vpc.AddRange(info.GetAllValueProperties());
for (var vp = 0; vp < vpc.Count; vp++)
{
var count = 1;
for (var prop = 0; prop < vp; prop++)
{
var readCorr = _correlationNames[prop];
if (readCorr.PropertyName != vpc[vp].Name)
{
if (readCorr.TableName == vpc[vp].DbBindColumn.ObjectName &&
readCorr.ColumnName == vpc[vp].DbBindColumn.ColumnName)
{
if (readCorr.Order >= count)
count = readCorr.Order + 1;
}
}
}
writeCorr.PropertyName = vpc[vp].Name;
writeCorr.TableName = vpc[vp].DbBindColumn.ObjectName;
writeCorr.ColumnName = vpc[vp].DbBindColumn.ColumnName;
writeCorr.Order = count;
_correlationNames.Add(writeCorr);
}
}
private string GetCorrelationName(ValueProperty prop)
{
foreach (var correlationName in _correlationNames)
{
if (correlationName.PropertyName == prop.Name)
{
if (correlationName.Order > 1)
return correlationName.TableName + correlationName.Order;
return correlationName.TableName;
}
}
MessageBox.Show(@"Property " + prop.Name + @" not found.", @"Error!");
return "";
}
public string GetDataTypeString(CslaObjectInfo info, string propName)
{
var prop = GetValuePropertyByName(info,propName);
if (prop == null)
throw new Exception("Parameter '" + propName + "' does not have a corresponding ValueProperty. Make sure a ValueProperty with the same name exists");
if (prop.DbBindColumn == null)
throw new Exception("Property '" + propName + "' does not have it's DbBindColumn initialized.");
return GetDataTypeString(prop.DbBindColumn);
}
public string GetDataTypeString(CriteriaProperty col)
{
if (col.DbBindColumn.Column != null)
return GetDataTypeString(col.DbBindColumn);
var prop = Info.ValueProperties.Find(col.Name);
if (prop != null)
return GetDataTypeString(prop.DbBindColumn);
throw new ApplicationException("No column information for this criteria property: " + col.Name);
}
public string GetDataTypeString(DbBindColumn col)
{
var nativeType = col.NativeType.ToLower();
var sb = new StringBuilder();
if (nativeType == "varchar" ||
nativeType == "nvarchar" ||
nativeType == "char" ||
nativeType == "nchar" ||
nativeType == "binary" ||
nativeType == "varbinary")
{
sb.Append(col.NativeType);
sb.Append("(");
sb.Append(col.Column.ColumnLength >= 0 ? col.Column.ColumnLength.ToString() : "MAX");
sb.Append(")");
}
else if (nativeType == "decimal" ||
nativeType == "numeric")
{
sb.Append(col.NativeType);
sb.Append("(");
sb.Append(col.Column.ColumnLength.ToString());
sb.Append(", ");
sb.Append(col.Column.ColumnScale.ToString());
sb.Append(")");
}
else
sb.Append(col.NativeType);
return sb.ToString();
}
public string GetColumnString(CriteriaProperty param)
{
if (param.DbBindColumn.Column != null)
return GetColumnString(param.DbBindColumn);
var prop = Info.ValueProperties.Find(param.Name);
if (prop != null)
return GetColumnString(prop.DbBindColumn);
throw new ApplicationException("No column information for this criteria property: " + param.Name);
}
public string GetColumnString(DbBindColumn col)
{
return col.ColumnName;
}
public string GetTableString(CriteriaProperty param)
{
if (param.DbBindColumn.Column != null)
return GetTableString(param.DbBindColumn);
var prop = Info.ValueProperties.Find(param.Name);
if (prop != null)
return GetTableString(prop.DbBindColumn);
throw new ApplicationException("No table information for this criteria property: " + param.Name);
}
public string GetTableString(DbBindColumn col)
{
return col.ObjectName;
}
#endregion
#region SELECT core
public string GetSelect(CslaObjectInfo info, Criteria crit, bool includeParentObjects, bool isCollectionSearchWhereClause, int level, bool dontInnerJoinUp)
{
var collType = IsCollectionType(info.ObjectType);
if (collType)
info = FindChildInfo(info, info.ItemType);
var dataOrigin = "table";
// find out where the data come from
foreach (var prop in info.GetAllValueProperties())
{
if (prop.DbBindColumn.Column == null)
continue;
if (prop.DbBindColumn.ColumnOriginType == ColumnOriginType.View)
{
dataOrigin = "view";
break;
}
}
StoreCorrelationNames(info);
var sb = new StringBuilder();
sb.Append(Environment.NewLine);
sb.Append(Indent(2) + "/* Get " + info.ObjectName + " from " + dataOrigin + " */" + Environment.NewLine);
sb.Append(GetSelectFields(info, level));
if (dontInnerJoinUp)
sb.Append(GetFromClause(crit, info, false));
else
sb.Append(isCollectionSearchWhereClause
? GetFromClause(crit, info, true)
: GetFromClause(crit, info, includeParentObjects));
sb.Append(isCollectionSearchWhereClause
? GetSearchWhereClause(_topLevelObject, info, crit)
: GetWhereClause(info, crit, includeParentObjects));
return NormalizeNewLineAtEndOfFile(sb.ToString());
}
private static string NormalizeNewLineAtEndOfFile(string statement)
{
var uni = Environment.NewLine.ToCharArray();
statement = statement.TrimEnd(uni);
statement = statement.TrimEnd(uni);
statement = statement.TrimEnd(uni);
statement = statement.Replace(Environment.NewLine + Environment.NewLine + Environment.NewLine,
Environment.NewLine + Environment.NewLine);
return statement;
}
public string GetChildSelects(CslaObjectInfo info, Criteria crit, bool isCollectionSearchWhereClause, int level, bool dontInnerJoinUp)
{
level++;
if (IsCollectionType(info.ObjectType))
info = FindChildInfo(info, info.ItemType);
var sb = new StringBuilder();
var first = true;
foreach (var childProp in info.GetAllChildProperties())
{
var childInfo = FindChildInfo(info, childProp.TypeName);
if (childInfo != null && childProp.LoadingScheme == LoadingScheme.ParentLoad)
{
if (!first)
sb.Append(Environment.NewLine);
else
first = false;
if (level > 2)
sb.Append(Environment.NewLine);
sb.Append(GetSelect(childInfo, crit, true, isCollectionSearchWhereClause, level, dontInnerJoinUp));
sb.Append(GetChildSelects(childInfo, crit, isCollectionSearchWhereClause, level, dontInnerJoinUp));
}
}
return NormalizeNewLineAtEndOfFile(sb.ToString());
}
public string MissingForeignKeys(Criteria crit, CslaObjectInfo info, int level, bool dontInnerJoinUp)
{
var result = string.Empty;
level++;
if (IsCollectionType(info.ObjectType))
info = FindChildInfo(info, info.ItemType);
foreach (var childProp in info.GetAllChildProperties())
{
var childInfo = FindChildInfo(info, childProp.TypeName);
if (childInfo != null && childProp.LoadingScheme == LoadingScheme.ParentLoad)
{
var temp = MissingForeignKeys(crit, childInfo, level, dontInnerJoinUp);
if (temp != string.Empty)
{
if (result != string.Empty)
result += ", ";
result += temp;
}
}
}
if (level > 2)
{
var tables = GetTables(crit, info, true);
if (tables.Count > 1)
{
var problemTables = new List<IResultObject>();
var parentTables = GetTablesParent(crit, info);
foreach (var table in tables)
{
if (parentTables.Contains(table))
continue;
var fkFound = false;
var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(table);
SortKeys(fKeys, parentTables);
fKeys = FilterDuplicateConstraintTables(fKeys, info.GetDatabaseBoundValueProperties());
foreach (var key in fKeys)
{
if (tables.IndexOf(key.PKTable) >= 0)
{
fkFound = true;
break;
}
}
if (!fkFound)
{
problemTables.Add(table);
}
}
foreach (var table in tables)
{
if (parentTables.Contains(table))
continue;
var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(table);
SortKeys(fKeys, parentTables);
fKeys = FilterDuplicateConstraintTables(fKeys, info.GetDatabaseBoundValueProperties());
foreach (var key in fKeys)
{
for (var index = 0; index < problemTables.Count; index++)
{
var problemTable = problemTables[index];
if (table == problemTable)
continue;
if (key.PKTable.ObjectName == problemTable.ObjectName)
{
problemTables.Remove(problemTable);
if (problemTables.Count == 0)
break;
}
}
if (problemTables.Count == 0)
break;
}
if (problemTables.Count == 0)
break;
}
foreach (var problemTable in problemTables)
{
if (result != string.Empty)
result += ", ";
result += problemTable.ObjectName;
}
}
}
return result;
}
private string GetFromClause(Criteria crit, CslaObjectInfo info, bool includeParentObjects)
{
_innerJoins = 0;
var tables = GetTables(crit, info, includeParentObjects);
SortTables(tables);
CheckTableJoins(tables);
var sb = new StringBuilder();
sb.Append(Indent(2) + "FROM ");
if (tables.Count == 1)
{
sb.AppendFormat("{0}[{1}]", GetSchema(tables[0], true), tables[0].ObjectName);
sb.Append(Environment.NewLine);
return sb.ToString();
}
if (tables.Count > 1)
{
var usedTables = new List<IResultObject>();
var firstJoin = true;
var parentTables = GetTablesParent(crit, info);
foreach (var table in tables)
{
var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(table);
// sort key.PKTable so key.PKTable that reference the parent table come before other keys
// and
// Primary keys come before other constraint references to the parent object
SortKeys(fKeys, parentTables);
fKeys = FilterDuplicateConstraintTables(fKeys, info.GetDatabaseBoundValueProperties());
foreach (var key in fKeys)
{
// check if this key is needed in the join
if (tables.IndexOf(key.PKTable) >= 0)
{
if (key.PKTable != key.ConstraintTable)
{
if (firstJoin)
{
sb.AppendFormat("{0}[{1}]", GetSchema(key.ConstraintTable, true), key.ConstraintTable.ObjectName);
sb.Append(Environment.NewLine + Indent(3));
sb.Append("INNER JOIN ");
sb.AppendFormat("{0}[{1}]", GetSchema(key.PKTable, true), key.PKTable.ObjectName);
sb.Append(" ON ");
var firstKeyColl = true;
foreach (var kcPair in key.Columns)
{
if (firstKeyColl)
firstKeyColl = false;
else
{
sb.Append(" AND");
sb.Append(Environment.NewLine + Indent(6));
}
sb.Append(GetAliasedFieldString(key.ConstraintTable, kcPair.FKColumn));
sb.Append(" = ");
sb.Append(GetAliasedFieldString(key.PKTable, kcPair.PKColumn));
_innerJoins++;
}
usedTables.Add(key.PKTable);
usedTables.Add(key.ConstraintTable);
firstJoin = false;
}
else
{
if (usedTables.Contains(key.PKTable) &&
usedTables.Contains(key.ConstraintTable))
{
sb.Append(" AND");
sb.Append(Environment.NewLine + Indent(6));
}
else
{
sb.Append(Environment.NewLine + Indent(3));
sb.Append("INNER JOIN ");
sb.AppendFormat("{0}[{1}]", GetSchema(key.PKTable, true),
key.PKTable.ObjectName);
sb.Append(" ON ");
usedTables.Add(key.PKTable);
}
var firstKeyColl = true;
foreach (var kcPair in key.Columns)
{
if (firstKeyColl)
firstKeyColl = false;
else
{
sb.Append(" AND");
sb.Append(Environment.NewLine + Indent(6));
}
sb.Append(GetAliasedFieldString(key.ConstraintTable, kcPair.FKColumn));
sb.Append(" = ");
sb.Append(GetAliasedFieldString(key.PKTable, kcPair.PKColumn));
_innerJoins++;
}
}
}
}
}
}
sb.Append(Environment.NewLine);
return sb.ToString();
}
return String.Empty;
}
private string InjectParentPropertiesOnResultSet(CslaObjectInfo info, ref bool first, ref List<IColumnInfo> usedByParentProperties)
{
var tables = GetTables(new Criteria(info), info, false);
var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(tables[0]);
fKeys = FilterDuplicateConstraintTables(fKeys, info.GetDatabaseBoundValueProperties());
var sb = new StringBuilder();
var parentProperties = info.GetParentValueProperties();
foreach (var key in fKeys)
{
if (key.PKTable != key.ConstraintTable)
{
foreach (var prop in parentProperties)
{
if (prop.DbBindColumn.Column == null)
continue;
if (prop.DbBindColumn.ObjectName == key.PKTable.ObjectName)
{
foreach (var t in key.Columns)
{
if (prop.DbBindColumn.ColumnName == t.PKColumn.ColumnName)
{
usedByParentProperties.Add(t.FKColumn);
if (!first)
sb.Append("," + Environment.NewLine);
else
first = false;
sb.Append(Indent(3));
if (t.FKColumn.DbType == DbType.StringFixedLength)
{
sb.Append("RTRIM(");
sb.Append(GetAliasedFieldString(key.ConstraintTable, t.FKColumn) + ")");
}
else
{
sb.Append(GetAliasedFieldString(key.ConstraintTable, t.FKColumn));
}
}
}
}
}
}
}
return sb.ToString();
}
private string GetSelectFields(CslaObjectInfo info, int level)
{
var sb = new StringBuilder();
sb.Append(Indent(2) + "SELECT" + Environment.NewLine);
var first = true;
var usedByParentProperties = new List<IColumnInfo>();
if (level > 2 || (_topLevelCollectiontHasNoGetParams && level > 1))
sb.Append(InjectParentPropertiesOnResultSet(info, ref first, ref usedByParentProperties));
var vpc = new ValuePropertyCollection();
/*if (IncludeParentProperties)
vpc.AddRange(info.GetParentValueProperties());*/
//t.FKColumn
vpc.AddRange(info.GetAllValueProperties());
foreach (var prop in vpc)
{
if (prop.DbBindColumn.Column == null)
continue;
if (prop.DataAccess != ValueProperty.DataAccessBehaviour.WriteOnly)
{
var duplicatedColumn = false;
foreach (var parentProperty in usedByParentProperties)
{
if (parentProperty == prop.DbBindColumn.Column)
{
duplicatedColumn = true;
break;
}
}
if (duplicatedColumn)
continue;
if (!first)
sb.Append("," + Environment.NewLine);
else
first = false;
sb.Append(Indent(3));
if (prop.DbBindColumn.DataType.ToString() == "StringFixedLength")
{
sb.Append("RTRIM(");
sb.Append("[" + GetCorrelationName(prop) + "].[" + prop.DbBindColumn.ColumnName + "]" +
")");
sb.Append(String.Format(" AS [{0}]", prop.ParameterName));
}
else
{
sb.Append("[" + GetCorrelationName(prop) + "].[" + prop.DbBindColumn.ColumnName + "]");
if (prop.DbBindColumn.ColumnName != prop.ParameterName)
{
sb.Append(String.Format(" AS [{0}]", prop.ParameterName));
}
}
}
}
sb.Append(Environment.NewLine);
return sb.ToString();
}
private static string GetAliasedFieldString(DbBindColumn col)
{
return "[" + col.ObjectName + "].[" + col.ColumnName + "]";
}
public static string GetAliasedFieldString(IResultObject table, IColumnInfo col)
{
return "[" + table.ObjectName + "].[" + col.ColumnName + "]";
}
public static ValueProperty GetValuePropertyByName(CslaObjectInfo info, string propName)
{
var prop = info.ValueProperties.Find(propName);
if (prop == null)
prop = info.InheritedValueProperties.Find(propName);
// check itemType to see if this is collection
if (prop == null && info.ItemType != String.Empty)
{
var itemInfo = info.Parent.CslaObjects.Find(info.ItemType);
if (itemInfo != null)
prop = GetValuePropertyByName(itemInfo, propName);
}
return prop;
}
private string GetWhereClause(CslaObjectInfo info, Criteria crit, bool includeParentObjects)
{
var originalInfo = info;
var parentInfo = FindParent(info);
if (parentInfo != null)
{
var temp = parentInfo;
while (temp != null)
{
temp = FindParent(temp);
if (temp != null) { parentInfo = temp; }
}
info = parentInfo;
}
var chidParamDBC = new List<DbBindColumn>();
if (includeParentObjects)
{
var collType = info.Parent.CslaObjects.Find(originalInfo.ParentType);
foreach (var childCrit in collType.CriteriaObjects)
{
if (crit.GetOptions.Procedure && crit.GetOptions.ProcedureName != string.Empty)
{
foreach (var param in childCrit.Properties)
{
chidParamDBC.Add(param.DbBindColumn);
}
}
}
}
var sb = new StringBuilder();
var first = true;
var parmCounter = 0;
foreach (var parm in crit.Properties)
{
parmCounter++;
var dbc = parm.DbBindColumn;
if (dbc == null || dbc.Column == null)
{
var prop = GetValuePropertyByName(info, parm.Name);
if (prop != null)
dbc = prop.DbBindColumn;
}
if (dbc != null && dbc.Column != null)
{
if (first)
{
sb.Append(Indent(2) + "WHERE" + Environment.NewLine);
first = false;
}
else
sb.Append(" AND" + Environment.NewLine);
if (includeParentObjects && chidParamDBC.Count >= parmCounter)
sb.Append(Indent(3) + GetAliasedFieldString(chidParamDBC[parmCounter - 1]));
else
sb.Append(Indent(3) + GetAliasedFieldString(dbc));
sb.Append(" = @");
sb.Append(parm.ParameterName);
}
}
sb.Append(SoftDeleteWhereClause(originalInfo, crit, first));
return sb.ToString();
}
private string GetSearchWhereClause(CslaObjectInfo info, CslaObjectInfo originalInfo, Criteria crit)
{
var sb = new StringBuilder();
var first = true;
foreach (CriteriaProperty parm in crit.Properties)
{
var dbc = parm.DbBindColumn;
if (dbc == null)
{
var prop = GetValuePropertyByName(info, parm.Name);
dbc = prop.DbBindColumn;
}
if (dbc != null)
{
if (first)
{
sb.Append(Indent(2) + "WHERE" + Environment.NewLine);
first = false;
}
else
sb.Append(" AND" + Environment.NewLine);
sb.Append(Indent(3));
if (!parm.Nullable)
{
sb.Append(GetAliasedFieldString(dbc));
sb.Append(" = @");
sb.Append(parm.ParameterName);
}
else
{
if (IsStringType(dbc.DataType))
{
sb.Append("ISNULL(");
sb.Append(GetAliasedFieldString(dbc));
sb.Append(", '')");
if (dbc.DataType.ToString() == "StringFixedLength")
{
sb.Append(" LIKE RTRIM(@");
sb.Append(parm.ParameterName);
sb.Append(")");
}
else
{
sb.Append(" LIKE @");
sb.Append(parm.ParameterName);
}
}
else
{
sb.Append(GetAliasedFieldString(dbc));
sb.Append(" = ISNULL(@");
sb.Append(parm.ParameterName);
sb.Append(", ");
sb.Append(GetAliasedFieldString(dbc));
sb.Append(")");
}
}
}
}
sb.Append(SoftDeleteWhereClause(originalInfo, crit, first));
sb.Append(Environment.NewLine);
return sb.ToString();
}
#endregion
#region Tables
public List<IResultObject> GetTablesSelect(CslaObjectInfo info)
{
var tables = new List<IResultObject>();
var allValueProps = new ValuePropertyCollection();
if (!IsCollectionType(info.ObjectType))
allValueProps = info.GetAllValueProperties();
else
{
var item = info.Parent.CslaObjects.Find(info.ItemType);
allValueProps = item.GetAllValueProperties();
}
foreach (var prop in allValueProps)
{
if (prop.DbBindColumn.Column == null)
continue;
if ((prop.DataAccess != ValueProperty.DataAccessBehaviour.WriteOnly ||
prop.PrimaryKey != ValueProperty.UserDefinedKeyBehaviour.Default) &&
(prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table ||
prop.DbBindColumn.ColumnOriginType == ColumnOriginType.View))
{
var table = (IResultObject) prop.DbBindColumn.DatabaseObject;
if (!tables.Contains(table))
tables.Add(table);
}
}
return tables;
}
// patch for using SProcs as source of RO/NVL
public string GetSprocSchemaSelect(CslaObjectInfo info)
{
var result = string.Empty;
var tables = new List<IResultObject>();
var allValueProps = new ValuePropertyCollection();
if (!IsCollectionType(info.ObjectType))
allValueProps = info.GetAllValueProperties();
else
{
var item = info.Parent.CslaObjects.Find(info.ItemType);
allValueProps = item.GetAllValueProperties();
}
foreach (var prop in allValueProps)
{
if (prop.DbBindColumn.Column == null)
continue;
result = prop.DbBindColumn.SchemaName;
break;
}
return result;
}
public List<IResultObject> GetTablesInsert(CslaObjectInfo info)
{
var tables = new List<IResultObject>();
foreach (var prop in info.GetAllValueProperties())
{
if (prop.DbBindColumn.Column == null)
continue;
if (prop.DataAccess != ValueProperty.DataAccessBehaviour.ReadOnly &&
prop.DataAccess != ValueProperty.DataAccessBehaviour.UpdateOnly &&
prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table)
{
var table = (IResultObject)prop.DbBindColumn.DatabaseObject;
if (!tables.Contains(table))
{
tables.Add(table);
}
}
}
return tables;
}
public List<IResultObject> GetTablesUpdate(CslaObjectInfo info)
{
var tables = new List<IResultObject>();
foreach (var prop in info.GetAllValueProperties())
{
if (prop.DbBindColumn.Column == null)
continue;
if (prop.DataAccess != ValueProperty.DataAccessBehaviour.ReadOnly &&
prop.DataAccess != ValueProperty.DataAccessBehaviour.CreateOnly &&
prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table)
{
var table = (IResultObject)prop.DbBindColumn.DatabaseObject;
if (!tables.Contains(table))
tables.Add(table);
}
}
return tables;
}
public List<IResultObject> GetTablesDelete(CslaObjectInfo info)
{
var tablesCol = new List<IResultObject>();
foreach (var prop in info.GetAllValueProperties())
{
if (prop.DbBindColumn.Column == null)
continue;
if (prop.DataAccess != ValueProperty.DataAccessBehaviour.ReadOnly &&
prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table)
{
var table = (IResultObject)prop.DbBindColumn.DatabaseObject;
if (!tablesCol.Contains(table))
tablesCol.Add(table);
}
}
return tablesCol;
}
private static List<IResultObject> GetTables(Criteria crit)
{
var tablesCol = new List<IResultObject>();
foreach (var parm in crit.Properties)
{
if (parm.DbBindColumn.ColumnOriginType == ColumnOriginType.Table ||
parm.DbBindColumn.ColumnOriginType == ColumnOriginType.View)
{
var table = (IResultObject)parm.DbBindColumn.DatabaseObject;
if (table != null && !tablesCol.Contains(table))
tablesCol.Add(table);
}
}
return tablesCol;
}
public static List<IResultObject> GetTablesParent(Criteria crit, CslaObjectInfo info)
{
var tablesCol = new List<IResultObject>();
var parent = FindParent(info);
if (parent != null)
tablesCol.AddRange(GetTables(crit, parent, true));
return tablesCol;
}
public static List<IResultObject> GetTables(Criteria crit, CslaObjectInfo info, bool includeParentObjects)
{
return GetTables(crit, info, includeParentObjects, true);
}
public static List<IResultObject> GetTables(Criteria crit, CslaObjectInfo info, bool includeParentObjects, bool includeCriteria)
{
return GetTables(crit, info, includeParentObjects, includeCriteria, true);
}
public static List<IResultObject> GetTables(Criteria crit, CslaObjectInfo info, bool includeParentObjects, bool includeCriteria, bool includeAllValueProperties)
{
var tablesCol = new List<IResultObject>();
if (includeParentObjects)
{
var parent = FindParent(info);
if (parent != null)
tablesCol.AddRange(GetTables(crit, parent, true, includeCriteria, includeAllValueProperties));
}
foreach (var prop in info.GetAllValueProperties())
{
if (prop.DbBindColumn.Column == null)
continue;
if (includeAllValueProperties)
{
if (prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table ||
prop.DbBindColumn.ColumnOriginType == ColumnOriginType.View)
{
var table = (IResultObject) prop.DbBindColumn.DatabaseObject;
if (!tablesCol.Contains(table))
tablesCol.Add(table);
}
}
else
{
if (prop.PrimaryKey != ValueProperty.UserDefinedKeyBehaviour.Default)
{
var table = (IResultObject) prop.DbBindColumn.DatabaseObject;
if (!tablesCol.Contains(table))
tablesCol.Add(table);
}
}
}
if (includeCriteria)
{
foreach (var table in GetTables(crit))
{
if (!tablesCol.Contains(table))
tablesCol.Add(table);
}
}
return tablesCol;
}
public List<IResultObject> GetTablesParentProperties(Criteria crit, CslaObjectInfo childInfo, CslaObjectInfo topObjectInfo, bool parentFound)
{
return GetTablesParentProperties(crit, childInfo, topObjectInfo, parentFound, false);
}
public List<IResultObject> GetTablesParentProperties(Criteria crit, CslaObjectInfo childInfo, CslaObjectInfo topObjectInfo, bool parentFound, bool excludeCriteria)
{
var isRootOrRootItem = CslaTemplateHelperCS.IsRootOrRootItem(childInfo);
var parentInsertOnly = false;
if (CslaTemplateHelperCS.CanHaveParentProperties(childInfo))
parentInsertOnly = childInfo.ParentInsertOnly;
var tablesCol = new List<IResultObject>();
if (!parentFound)
{
var parentInfo = FindParent(childInfo);
if (parentInfo != null)
{
tablesCol.AddRange(GetTablesParentProperties(crit, parentInfo, topObjectInfo, parentInfo == topObjectInfo));
}
if (!isRootOrRootItem)
{
parentInfo = topObjectInfo.Parent.CslaObjects.Find(topObjectInfo.ParentType);
if (parentInfo != null)
isRootOrRootItem = CslaTemplateHelperCS.IsRootType(parentInfo);
}
}
foreach (var prop in childInfo.GetAllValueProperties())
{
if (prop.DbBindColumn.Column == null)
continue;
if (parentInsertOnly && prop.PrimaryKey == ValueProperty.UserDefinedKeyBehaviour.Default)
continue;
if (prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table ||
prop.DbBindColumn.ColumnOriginType == ColumnOriginType.View)
{
var table = (IResultObject) prop.DbBindColumn.DatabaseObject;
if (parentInsertOnly || isRootOrRootItem)
{
if (!tablesCol.Contains(table))
tablesCol.Add(table);
}
else
{
foreach (var parentProp in childInfo.GetParentValueProperties())
{
if (parentProp.DbBindColumn.Column == null)
continue;
if (prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table &&
parentProp.DbBindColumn.ColumnOriginType == ColumnOriginType.Table)
{
table = GetFKTableObjectForParentProperty(parentProp, table);
if (table != null)
if (!tablesCol.Contains(table))
tablesCol.Add(table);
}
}
}
}
}
if (!excludeCriteria)
{
foreach (var table in GetTables(crit))
{
if (!tablesCol.Contains(table))
tablesCol.Add(table);
}
}
return tablesCol;
}
public void SortTables(List<IResultObject> tables)
{
var tArray = tables.ToArray();
//Sort collection so that tables that reference others come after reference tables
for (var i = 0; i < tArray.Length - 1; i++)
{
var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(tArray[i]);
if (fKeys.Count > 0)
{
for (var j = i + 1; j < tArray.Length; j++)
{
var table = tArray[i];
if (!ReferencesTable(fKeys, tArray[j]))
{
tArray[i] = tArray[j];
tArray[j] = table;
}
}
}
}
tables.Clear();
tables.AddRange(tArray);
}
public static void SortKeys(List<IForeignKeyConstraint> fKeys, List<IResultObject> parentTables)
{
if (parentTables.Count == 0)
return;
var sorted = false;
var parentTable = parentTables[0].ObjectName;
var fkArray = fKeys.ToArray();
// sort collection so that keys that reference the parent table come before other keys
for (var i = 0; i < fkArray.Length; i++)
{
if (parentTable == fkArray[i].PKTable.ObjectName)
{
var fkey = fkArray[i];
for (var j = i; j > 0; j--)
{
fkArray[j] = fkArray[j- 1];
}
fkArray[0] = fkey;
sorted = true;
}
}
if (sorted)
{
fKeys.Clear();
fKeys.AddRange(fkArray);
}
// sort collection so that Primary Keys that reference the parent table come before other non-primary keys
sorted = false;
for (var i = 0; i < fkArray.Length; i++)
{
if (parentTable == fkArray[i].PKTable.ObjectName && fkArray[i].Columns[0].PKColumn.IsPrimaryKey)
{
var fkey = fkArray[i];
for (var j = i; j > 0; j--)
{
fkArray[j] = fkArray[j- 1];
}
fkArray[0] = fkey;
sorted = true;
}
}
if (sorted)
{
fKeys.Clear();
fKeys.AddRange(fkArray);
}
}
/*
// debugging only
private void ShowKeys(string header, List<IForeignKeyConstraint> fKeys1, List<IForeignKeyConstraint> fKeys2)
{
var msg = "Original\r\n";
foreach (var fKey in fKeys1)
{
msg += fKey.ConstraintName + ": ";
msg += fKey.ConstraintTable.ObjectName + " - ";
msg += fKey.Columns[0].FKColumn.ColumnName+ " / ";
msg += fKey.PKTable.ObjectName + " - ";
msg += fKey.Columns[0].PKColumn.ColumnName + Environment.NewLine;
}
msg += "\r\nRefactored\r\n";
foreach (var fKey in fKeys2)
{
msg += fKey.ConstraintName + ": ";
msg += fKey.ConstraintTable.ObjectName + " - ";
msg += fKey.Columns[0].FKColumn.ColumnName+ " / ";
msg += fKey.PKTable.ObjectName + " - ";
msg += fKey.Columns[0].PKColumn.ColumnName + Environment.NewLine;
}
MessageBox.Show(msg, header);
}
*/
public static List<IForeignKeyConstraint> FilterDuplicateConstraintTables(List<IForeignKeyConstraint> fKeys, ValuePropertyCollection vpc)
{
var filteredKeys = new List<IForeignKeyConstraint>();
if (fKeys.Count == 0)
return filteredKeys;
var fkArray = fKeys.ToArray();
// filter constraint table references not included by ValueProperty.FKConstraint
foreach (var key in fkArray)
{
var match = false;
foreach (var vp in vpc)
{
if (vp.FKConstraint == key.ConstraintName)
{
match = true;
break;
}
}
if (match)
filteredKeys.Add(key);
}
// filter duplicate references to the same constraint table
foreach (var t in fkArray)
{
var exists = false;
foreach (var key in filteredKeys)
{
if (t.ConstraintTable.ObjectName == key.ConstraintTable.ObjectName &&
t.PKTable.ObjectName == key.PKTable.ObjectName)
exists = true;
}
if (!exists)
filteredKeys.Add(t);
}
return filteredKeys;
}
private static bool ReferencesTable(List<IForeignKeyConstraint> constraints, IResultObject pkTable)
{
foreach (var fkc in constraints)
{
if (fkc.PKTable == pkTable)
return true;
}
return false;
}
public void CheckTableJoins(List<IResultObject> tables)
{
if (tables.Count < 2) { return; }
var tablesMissingJoins = new List<IResultObject>();
foreach (var t in tables)
{
if (!HasJoin(t, tables))
tablesMissingJoins.Add(t);
}
if (tablesMissingJoins.Count > 0)
AddJoinTables(tables, tablesMissingJoins);
}
private void AddJoinTables(List<IResultObject> tables, List<IResultObject> tablesMissingJoins)
{
var joinTables = FindJoinTables(tables, tablesMissingJoins);
foreach (var t in joinTables)
{
if (!tables.Contains(t))
tables.Add(t);
}
}
private List<IResultObject> FindJoinTables(List<IResultObject> tables, List<IResultObject> missingTables)
{
var joinTables = new List<IResultObject>();
foreach(var t in Catalog.Tables)
{
var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(t);
if (fKeys.Count > 1)
{
var tableCount = 0;
var missingTableCount = 0;
foreach(var key in fKeys)
{
if (missingTables.Contains(key.PKTable))
missingTableCount++;
else if (tables.Contains(key.PKTable))
tableCount++;
}
if (missingTableCount > 1 || (tableCount > 0 && missingTableCount > 0))
{
joinTables.Add(t);
}
}
}
return joinTables;
}
private bool HasJoin(IResultObject table, List<IResultObject> tables)
{
foreach (var key in Catalog.ForeignKeyConstraints.GetConstraintsFor(table))
{
if (tables.Contains(key.PKTable))
return true;
}
foreach (var t in tables)
{
if (t != table)
{
foreach (var key in Catalog.ForeignKeyConstraints.GetConstraintsFor(t))
{
if (key.PKTable == table)
return true;
}
}
}
return false;
}
#endregion
#region Helpers
public bool IsCollectionType(CslaObjectType cslaType)
{
if (cslaType == CslaObjectType.EditableRootCollection ||
cslaType == CslaObjectType.EditableChildCollection ||
cslaType == CslaObjectType.DynamicEditableRootCollection ||
cslaType == CslaObjectType.ReadOnlyCollection)
return true;
return false;
}
public CslaObjectInfo FindChildInfo(CslaObjectInfo info, string name)
{
return info.Parent.CslaObjects.Find(name);
}
private static CslaObjectInfo FindParent(CslaObjectInfo info)
{
CslaObjectInfo parentInfo = null;
if (string.IsNullOrEmpty(info.ParentType))
{
foreach (var cslaObject in info.Parent.CslaObjects)
{
foreach (var childProperty in cslaObject.GetAllChildProperties())
{
if (childProperty.TypeName == info.ObjectName)
parentInfo = cslaObject;
}
if (parentInfo != null)
break;
}
}
else
{
// no parent specified; find the object whose child is this object
parentInfo = info.Parent.CslaObjects.Find(info.ParentType);
}
if (parentInfo != null)
{
if (parentInfo.ItemType == info.ObjectName)
return FindParent(parentInfo);
if (parentInfo.GetAllChildProperties().FindType(info.ObjectName) != null)
return parentInfo;
/*if (parentInfo.GetCollectionChildProperties().FindType(info.ObjectName) != null)
return parentInfo;*/
}
return null;
}
/// <summary>
/// Gets all child objects of a CslaObjectInfo.
/// Gets all child properties: collection and non-collection, including inherited.
/// </summary>
/// <param name="info">The CslaOnjectInfo.</param>
/// <returns>A CslaObjectInfo array holding the objects for all child properties.</returns>
public CslaObjectInfo[] GetAllChildItems(CslaObjectInfo info)
{
var list = new List<CslaObjectInfo>();
foreach (var cp in info.GetAllChildProperties())
{
var childInfo = FindChildInfo(info, cp.TypeName);
if (IsCollectionType(childInfo.ObjectType))
{
var ci = FindChildInfo(info, cp.TypeName);
if (ci != null)
{
ci = FindChildInfo(info, ci.ItemType);
if (ci != null)
list.Add(ci);
}
}
else
{
list.Add(childInfo);
}
}
return list.ToArray();
}
/// <summary>
/// Gets the full hierarchy of all child object names of a CslaObjectInfo.
/// </summary>
/// <param name="info">The CslaOnjectInfo.</param>
/// <returns>A string array holding the objects for the hierarchy of all child properties.</returns>
public string[] GetAllChildItemsInHierarchy(CslaObjectInfo info)
{
var list = new List<string>();
foreach (var obj in GetAllChildItems(info))
{
list.Add(obj.ObjectName);
list.AddRange(GetAllChildItemsInHierarchy(obj));
}
return list.ToArray();
}
public bool IsStringType(DbType dbType)
{
if (dbType == DbType.String || dbType == DbType.StringFixedLength ||
dbType == DbType.AnsiString || dbType == DbType.AnsiStringFixedLength)
return true;
return false;
}
public static string Indent(int len)
{
return new string(' ', len * 4);
}
public string GetFKColumnForParentProperty(ValueProperty parentProp, IResultObject childTable)
{
if (parentProp.DbBindColumn.ColumnOriginType != ColumnOriginType.Table)
return parentProp.ParameterName;
var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(childTable);
foreach (var tks in fKeys)
{
if (tks.PKTable == parentProp.DbBindColumn.DatabaseObject)
{
foreach (var colPair in tks.Columns)
{
if (colPair.PKColumn == parentProp.DbBindColumn.Column)
return colPair.FKColumn.ColumnName;
}
}
}
return string.Empty;
}
public string GetFKTableForParentProperty(ValueProperty parentProp, IResultObject childTable)
{
if (parentProp.DbBindColumn.ColumnOriginType != ColumnOriginType.Table)
return parentProp.ParameterName;
var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(childTable);
foreach (var fKey in fKeys)
{
if (fKey.PKTable == parentProp.DbBindColumn.DatabaseObject)
{
foreach (var colPair in fKey.Columns)
{
if (colPair.PKColumn == parentProp.DbBindColumn.Column)
return colPair.FKColumn.FKConstraint.ConstraintTable.ObjectName;
}
}
}
return string.Empty;
}
public IResultObject GetFKTableObjectForParentProperty(ValueProperty parentProp, IResultObject childTable)
{
if (parentProp.DbBindColumn.ColumnOriginType != ColumnOriginType.Table)
return null;
var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(childTable);
foreach (var fKey in fKeys)
{
if (fKey.PKTable == parentProp.DbBindColumn.DatabaseObject)
{
foreach (var colPair in fKey.Columns)
{
if (colPair.PKColumn == parentProp.DbBindColumn.Column)
return colPair.FKColumn.FKConstraint.ConstraintTable;
}
}
}
return null;
}
public static bool IsChildSelfLoaded(CslaObjectInfo info)
{
var selfLoad = false;
var parent = info.Parent.CslaObjects.Find(info.ParentType);
if (parent != null)
{
foreach (var childProp in parent.GetAllChildProperties())
{
if (childProp.TypeName == info.ObjectName)
{
selfLoad = childProp.LoadingScheme == LoadingScheme.SelfLoad;
break;
}
}
}
return selfLoad;
}
#endregion
#region SoftDelete methods
private bool IgnoreFilterCriteria(Criteria crit)
{
foreach (var prop in crit.Properties)
{
if(prop.DbBindColumn.ColumnName == Info.Parent.Params.SpBoolSoftDeleteColumn &&
prop.DbBindColumn.Column.DbType == DbType.Boolean)
return true;
if(prop.DbBindColumn.ColumnName == Info.Parent.Params.SpIntSoftDeleteColumn &&
(prop.DbBindColumn.Column.DbType == DbType.Int16 ||
prop.DbBindColumn.Column.DbType == DbType.Int32 ||
prop.DbBindColumn.Column.DbType == DbType.Int64))
return true;
}
return false;
}
private string SoftDeleteWhereClause(CslaObjectInfo info, Criteria crit, bool first)
{
if (IgnoreFilterCriteria(crit))
return "";
var sb = new StringBuilder();
List<IResultObject> tablesCol;
if (CslaTemplateHelperCS.CanHaveParentProperties(info) && !info.ParentInsertOnly)
tablesCol = GetTablesParentProperties(crit, info, info, true, true);
else
tablesCol = GetTables(crit, info, false, false, false);
SortTables(tablesCol);
CheckTableJoins(tablesCol);
foreach (var table in tablesCol)
{
sb.Append(AppendSoftDeleteWhereClause(info, table, first));
first = false;
}
return sb.ToString();
}
private string AppendSoftDeleteWhereClause(CslaObjectInfo info, IResultObject table, bool first)
{
var sb = new StringBuilder();
if (UseBoolSoftDelete(table, IgnoreFilter(info)))
{
if (!first)
sb.Append(" AND" + Environment.NewLine);
else
{
sb.Append(Indent(2) + "WHERE" + Environment.NewLine);
}
sb.Append(Indent(3));
sb.Append("[" + table.ObjectName + "].[" + Info.Parent.Params.SpBoolSoftDeleteColumn + "] = 'true'");
}
return sb.ToString();
}
public bool IgnoreFilter(CslaObjectInfo info)
{
if (Info.Parent.Params.SpIgnoreFilterWhenSoftDeleteIsParam)
{
foreach (var prop in info.GetAllValueProperties())
{
if (prop.DbBindColumn.Column == null)
continue;
if (prop.Name == Info.Parent.Params.SpBoolSoftDeleteColumn)
return true;
}
}
return false;
}
/// <summary>
/// Uses the bool soft delete.
/// </summary>
/// <param name="tables">The tables to check.</param>
/// <param name="ignoreFilterEnabled">if set to <c>true</c> [ignore filter enabled].</param>
/// <returns></returns>
public bool UseBoolSoftDelete(List<IResultObject> tables, bool ignoreFilterEnabled)
{
if (!string.IsNullOrEmpty(Info.Parent.Params.SpBoolSoftDeleteColumn)
&& !ignoreFilterEnabled)
{
foreach (var table in tables)
{
if (!UseBoolSoftDelete(table, ignoreFilterEnabled))
return false;
}
return true;
}
return false;
}
private bool UseBoolSoftDelete(IResultObject table, bool ignoreFilterEnabled)
{
if (!string.IsNullOrEmpty(Info.Parent.Params.SpBoolSoftDeleteColumn)
&& !ignoreFilterEnabled)
{
for (var col = 0; col < table.Columns.Count; col++)
{
if (table.Columns[col].ColumnName == Info.Parent.Params.SpBoolSoftDeleteColumn &&
table.Columns[col].DbType == DbType.Boolean)
{
return true;
}
}
}
return false;
}
public bool UseIntSoftDelete(List<IResultObject> tables, bool ignoreFilterEnabled)
{
if (!string.IsNullOrEmpty(Info.Parent.Params.SpIntSoftDeleteColumn)
&& !ignoreFilterEnabled)
{
foreach (var table in tables)
{
if (!UseIntSoftDelete(table))
return false;
}
return true;
}
return false;
}
private bool UseIntSoftDelete(IResultObject table)
{
for (var col = 0; col < table.Columns.Count; col++)
{
if (table.Columns[col].ColumnName == Info.Parent.Params.SpIntSoftDeleteColumn &&
(table.Columns[col].DbType == DbType.Int16 ||
table.Columns[col].DbType == DbType.Int32 ||
table.Columns[col].DbType == DbType.Int64))
return true;
}
return false;
}
#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.Xml;
using System.Diagnostics;
using System.Collections;
using System.Globalization;
using System.Collections.Generic;
namespace System.Xml
{
internal sealed partial class XmlSubtreeReader : XmlWrappingReader, IXmlLineInfo, IXmlNamespaceResolver
{
//
// Private types
//
private class NodeData
{
internal XmlNodeType type;
internal string localName;
internal string prefix;
internal string name;
internal string namespaceUri;
internal string value;
internal NodeData()
{
}
internal void Set(XmlNodeType nodeType, string localName, string prefix, string name, string namespaceUri, string value)
{
this.type = nodeType;
this.localName = localName;
this.prefix = prefix;
this.name = name;
this.namespaceUri = namespaceUri;
this.value = value;
}
}
private enum State
{
Initial = ReadState.Initial,
Interactive = ReadState.Interactive,
Error = ReadState.Error,
EndOfFile = ReadState.EndOfFile,
Closed = ReadState.Closed,
PopNamespaceScope,
ClearNsAttributes,
ReadElementContentAsBase64,
ReadElementContentAsBinHex,
ReadContentAsBase64,
ReadContentAsBinHex,
}
private const int AttributeActiveStates = 0x62; // 00001100010 bin
private const int NamespaceActiveStates = 0x7E2; // 11111100010 bin
//
// Fields
//
private int _initialDepth;
private State _state;
// namespace management
private XmlNamespaceManager _nsManager;
private NodeData[] _nsAttributes;
private int _nsAttrCount;
private int _curNsAttr = -1;
private string _xmlns;
private string _xmlnsUri;
// incremental reading of added xmlns nodes (ReadValueChunk, ReadContentAsBase64, ReadContentAsBinHex)
private int _nsIncReadOffset;
private IncrementalReadDecoder _binDecoder;
// cached nodes
private bool _useCurNode;
private NodeData _curNode;
// node used for a text node of ReadAttributeValue or as Initial or EOF node
private NodeData _tmpNode;
//
// Constants
//
internal int InitialNamespaceAttributeCount = 4;
//
// Constructor
//
internal XmlSubtreeReader(XmlReader reader) : base(reader)
{
_initialDepth = reader.Depth;
_state = State.Initial;
_nsManager = new XmlNamespaceManager(reader.NameTable);
_xmlns = reader.NameTable.Add("xmlns");
_xmlnsUri = reader.NameTable.Add(XmlReservedNs.NsXmlNs);
_tmpNode = new NodeData();
_tmpNode.Set(XmlNodeType.None, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
SetCurrentNode(_tmpNode);
}
//
// XmlReader implementation
//
public override XmlNodeType NodeType
{
get
{
return (_useCurNode) ? _curNode.type : reader.NodeType;
}
}
public override string Name
{
get
{
return (_useCurNode) ? _curNode.name : reader.Name;
}
}
public override string LocalName
{
get
{
return (_useCurNode) ? _curNode.localName : reader.LocalName;
}
}
public override string NamespaceURI
{
get
{
return (_useCurNode) ? _curNode.namespaceUri : reader.NamespaceURI;
}
}
public override string Prefix
{
get
{
return (_useCurNode) ? _curNode.prefix : reader.Prefix;
}
}
public override string Value
{
get
{
return (_useCurNode) ? _curNode.value : reader.Value;
}
}
public override int Depth
{
get
{
int depth = reader.Depth - _initialDepth;
if (_curNsAttr != -1)
{
if (_curNode.type == XmlNodeType.Text)
{ // we are on namespace attribute value
depth += 2;
}
else
{
depth++;
}
}
return depth;
}
}
public override string BaseURI
{
get
{
return reader.BaseURI;
}
}
public override bool IsEmptyElement
{
get
{
return reader.IsEmptyElement;
}
}
public override bool EOF
{
get
{
return _state == State.EndOfFile || _state == State.Closed;
}
}
public override ReadState ReadState
{
get
{
if (reader.ReadState == ReadState.Error)
{
return ReadState.Error;
}
else
{
if ((int)_state <= (int)State.Closed)
{
return (ReadState)(int)_state;
}
else
{
return ReadState.Interactive;
}
}
}
}
public override XmlNameTable NameTable
{
get
{
return reader.NameTable;
}
}
public override int AttributeCount
{
get
{
return InAttributeActiveState ? reader.AttributeCount + _nsAttrCount : 0;
}
}
public override string GetAttribute(string name)
{
if (!InAttributeActiveState)
{
return null;
}
string attr = reader.GetAttribute(name);
if (attr != null)
{
return attr;
}
for (int i = 0; i < _nsAttrCount; i++)
{
if (name == _nsAttributes[i].name)
{
return _nsAttributes[i].value;
}
}
return null;
}
public override string GetAttribute(string name, string namespaceURI)
{
if (!InAttributeActiveState)
{
return null;
}
string attr = reader.GetAttribute(name, namespaceURI);
if (attr != null)
{
return attr;
}
for (int i = 0; i < _nsAttrCount; i++)
{
if (name == _nsAttributes[i].localName && namespaceURI == _xmlnsUri)
{
return _nsAttributes[i].value;
}
}
return null;
}
public override string GetAttribute(int i)
{
if (!InAttributeActiveState)
{
throw new ArgumentOutOfRangeException(nameof(i));
}
int n = reader.AttributeCount;
if (i < n)
{
return reader.GetAttribute(i);
}
else if (i - n < _nsAttrCount)
{
return _nsAttributes[i - n].value;
}
else
{
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool MoveToAttribute(string name)
{
if (!InAttributeActiveState)
{
return false;
}
if (reader.MoveToAttribute(name))
{
_curNsAttr = -1;
_useCurNode = false;
return true;
}
for (int i = 0; i < _nsAttrCount; i++)
{
if (name == _nsAttributes[i].name)
{
MoveToNsAttribute(i);
return true;
}
}
return false;
}
public override bool MoveToAttribute(string name, string ns)
{
if (!InAttributeActiveState)
{
return false;
}
if (reader.MoveToAttribute(name, ns))
{
_curNsAttr = -1;
_useCurNode = false;
return true;
}
for (int i = 0; i < _nsAttrCount; i++)
{
if (name == _nsAttributes[i].localName && ns == _xmlnsUri)
{
MoveToNsAttribute(i);
return true;
}
}
return false;
}
public override void MoveToAttribute(int i)
{
if (!InAttributeActiveState)
{
throw new ArgumentOutOfRangeException(nameof(i));
}
int n = reader.AttributeCount;
if (i < n)
{
reader.MoveToAttribute(i);
_curNsAttr = -1;
_useCurNode = false;
}
else if (i - n < _nsAttrCount)
{
MoveToNsAttribute(i - n);
}
else
{
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool MoveToFirstAttribute()
{
if (!InAttributeActiveState)
{
return false;
}
if (reader.MoveToFirstAttribute())
{
_useCurNode = false;
return true;
}
if (_nsAttrCount > 0)
{
MoveToNsAttribute(0);
return true;
}
return false;
}
public override bool MoveToNextAttribute()
{
if (!InAttributeActiveState)
{
return false;
}
if (_curNsAttr == -1 && reader.MoveToNextAttribute())
{
return true;
}
if (_curNsAttr + 1 < _nsAttrCount)
{
MoveToNsAttribute(_curNsAttr + 1);
return true;
}
return false;
}
public override bool MoveToElement()
{
if (!InAttributeActiveState)
{
return false;
}
_useCurNode = false;
//If on Namespace attribute, the base reader is already on Element node.
if (_curNsAttr >= 0)
{
_curNsAttr = -1;
Debug.Assert(reader.NodeType == XmlNodeType.Element);
return true;
}
else
{
return reader.MoveToElement();
}
}
public override bool ReadAttributeValue()
{
if (!InAttributeActiveState)
{
return false;
}
if (_curNsAttr == -1)
{
return reader.ReadAttributeValue();
}
else if (_curNode.type == XmlNodeType.Text)
{ // we are on namespace attribute value
return false;
}
else
{
Debug.Assert(_curNode.type == XmlNodeType.Attribute);
_tmpNode.type = XmlNodeType.Text;
_tmpNode.value = _curNode.value;
SetCurrentNode(_tmpNode);
return true;
}
}
public override bool Read()
{
switch (_state)
{
case State.Initial:
_useCurNode = false;
_state = State.Interactive;
ProcessNamespaces();
return true;
case State.Interactive:
_curNsAttr = -1;
_useCurNode = false;
reader.MoveToElement();
Debug.Assert(reader.Depth >= _initialDepth);
if (reader.Depth == _initialDepth)
{
if (reader.NodeType == XmlNodeType.EndElement ||
(reader.NodeType == XmlNodeType.Element && reader.IsEmptyElement))
{
_state = State.EndOfFile;
SetEmptyNode();
return false;
}
Debug.Assert(reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement);
}
if (reader.Read())
{
ProcessNamespaces();
return true;
}
else
{
SetEmptyNode();
return false;
}
case State.EndOfFile:
case State.Closed:
case State.Error:
return false;
case State.PopNamespaceScope:
_nsManager.PopScope();
goto case State.ClearNsAttributes;
case State.ClearNsAttributes:
_nsAttrCount = 0;
_state = State.Interactive;
goto case State.Interactive;
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
if (!FinishReadElementContentAsBinary())
{
return false;
}
return Read();
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
if (!FinishReadContentAsBinary())
{
return false;
}
return Read();
default:
Debug.Assert(false);
return false;
}
}
protected override void Dispose(bool disposing)
{
if (_state == State.Closed)
{
return;
}
try
{
// move the underlying reader to the next sibling
if (_state != State.EndOfFile)
{
reader.MoveToElement();
Debug.Assert(reader.Depth >= _initialDepth);
// move off the root of the subtree
if (reader.Depth == _initialDepth && reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement)
{
reader.Read();
}
// move to the end of the subtree, do nothing if on empty root element
while (reader.Depth > _initialDepth && reader.Read())
{
/* intentionally empty */
}
}
}
catch
{ // never fail...
}
finally
{
_curNsAttr = -1;
_useCurNode = false;
_state = State.Closed;
SetEmptyNode();
}
}
public override void Skip()
{
switch (_state)
{
case State.Initial:
Read();
return;
case State.Interactive:
_curNsAttr = -1;
_useCurNode = false;
reader.MoveToElement();
Debug.Assert(reader.Depth >= _initialDepth);
if (reader.Depth == _initialDepth)
{
if (reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement)
{
// we are on root of the subtree -> skip to the end element and set to Eof state
if (reader.Read())
{
while (reader.NodeType != XmlNodeType.EndElement && reader.Depth > _initialDepth)
{
reader.Skip();
}
}
}
Debug.Assert(reader.NodeType == XmlNodeType.EndElement ||
reader.NodeType == XmlNodeType.Element && reader.IsEmptyElement ||
reader.ReadState != ReadState.Interactive);
_state = State.EndOfFile;
SetEmptyNode();
return;
}
if (reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement)
{
_nsManager.PopScope();
}
reader.Skip();
ProcessNamespaces();
Debug.Assert(reader.Depth >= _initialDepth);
return;
case State.Closed:
case State.EndOfFile:
return;
case State.PopNamespaceScope:
_nsManager.PopScope();
goto case State.ClearNsAttributes;
case State.ClearNsAttributes:
_nsAttrCount = 0;
_state = State.Interactive;
goto case State.Interactive;
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
if (FinishReadElementContentAsBinary())
{
Skip();
}
break;
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
if (FinishReadContentAsBinary())
{
Skip();
}
break;
case State.Error:
return;
default:
Debug.Assert(false);
return;
}
}
public override object ReadContentAsObject()
{
try
{
InitReadContentAsType("ReadContentAsObject");
object value = reader.ReadContentAsObject();
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override bool ReadContentAsBoolean()
{
try
{
InitReadContentAsType("ReadContentAsBoolean");
bool value = reader.ReadContentAsBoolean();
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override double ReadContentAsDouble()
{
try
{
InitReadContentAsType("ReadContentAsDouble");
double value = reader.ReadContentAsDouble();
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override float ReadContentAsFloat()
{
try
{
InitReadContentAsType("ReadContentAsFloat");
float value = reader.ReadContentAsFloat();
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override decimal ReadContentAsDecimal()
{
try
{
InitReadContentAsType("ReadContentAsDecimal");
decimal value = reader.ReadContentAsDecimal();
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override int ReadContentAsInt()
{
try
{
InitReadContentAsType("ReadContentAsInt");
int value = reader.ReadContentAsInt();
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override long ReadContentAsLong()
{
try
{
InitReadContentAsType("ReadContentAsLong");
long value = reader.ReadContentAsLong();
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override string ReadContentAsString()
{
try
{
InitReadContentAsType("ReadContentAsString");
string value = reader.ReadContentAsString();
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver)
{
try
{
InitReadContentAsType("ReadContentAs");
object value = reader.ReadContentAs(returnType, namespaceResolver);
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override bool CanReadBinaryContent
{
get
{
return reader.CanReadBinaryContent;
}
}
public override int ReadContentAsBase64(byte[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.ClearNsAttributes:
case State.PopNamespaceScope:
switch (NodeType)
{
case XmlNodeType.Element:
throw CreateReadContentAsException("ReadContentAsBase64");
case XmlNodeType.EndElement:
return 0;
case XmlNodeType.Attribute:
if (_curNsAttr != -1 && reader.CanReadBinaryContent)
{
CheckBuffer(buffer, index, count);
if (count == 0)
{
return 0;
}
if (_nsIncReadOffset == 0)
{
// called first time on this ns attribute
if (_binDecoder != null && _binDecoder is Base64Decoder)
{
_binDecoder.Reset();
}
else
{
_binDecoder = new Base64Decoder();
}
}
if (_nsIncReadOffset == _curNode.value.Length)
{
return 0;
}
_binDecoder.SetNextOutputBuffer(buffer, index, count);
_nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
return _binDecoder.DecodedCount;
}
goto case XmlNodeType.Text;
case XmlNodeType.Text:
Debug.Assert(AttributeCount > 0);
return reader.ReadContentAsBase64(buffer, index, count);
default:
Debug.Assert(false);
return 0;
}
case State.Interactive:
_state = State.ReadContentAsBase64;
goto case State.ReadContentAsBase64;
case State.ReadContentAsBase64:
int read = reader.ReadContentAsBase64(buffer, index, count);
if (read == 0)
{
_state = State.Interactive;
ProcessNamespaces();
}
return read;
case State.ReadContentAsBinHex:
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Assert(false);
return 0;
}
}
public override int ReadElementContentAsBase64(byte[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.Interactive:
case State.PopNamespaceScope:
case State.ClearNsAttributes:
if (!InitReadElementContentAsBinary(State.ReadElementContentAsBase64))
{
return 0;
}
goto case State.ReadElementContentAsBase64;
case State.ReadElementContentAsBase64:
int read = reader.ReadContentAsBase64(buffer, index, count);
if (read > 0 || count == 0)
{
return read;
}
if (NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
}
// pop namespace scope
_state = State.Interactive;
ProcessNamespaces();
// set eof state or move off the end element
if (reader.Depth == _initialDepth)
{
_state = State.EndOfFile;
SetEmptyNode();
}
else
{
Read();
}
return 0;
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
case State.ReadElementContentAsBinHex:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Assert(false);
return 0;
}
}
public override int ReadContentAsBinHex(byte[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.ClearNsAttributes:
case State.PopNamespaceScope:
switch (NodeType)
{
case XmlNodeType.Element:
throw CreateReadContentAsException("ReadContentAsBinHex");
case XmlNodeType.EndElement:
return 0;
case XmlNodeType.Attribute:
if (_curNsAttr != -1 && reader.CanReadBinaryContent)
{
CheckBuffer(buffer, index, count);
if (count == 0)
{
return 0;
}
if (_nsIncReadOffset == 0)
{
// called first time on this ns attribute
if (_binDecoder != null && _binDecoder is BinHexDecoder)
{
_binDecoder.Reset();
}
else
{
_binDecoder = new BinHexDecoder();
}
}
if (_nsIncReadOffset == _curNode.value.Length)
{
return 0;
}
_binDecoder.SetNextOutputBuffer(buffer, index, count);
_nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
return _binDecoder.DecodedCount;
}
goto case XmlNodeType.Text;
case XmlNodeType.Text:
Debug.Assert(AttributeCount > 0);
return reader.ReadContentAsBinHex(buffer, index, count);
default:
Debug.Assert(false);
return 0;
}
case State.Interactive:
_state = State.ReadContentAsBinHex;
goto case State.ReadContentAsBinHex;
case State.ReadContentAsBinHex:
int read = reader.ReadContentAsBinHex(buffer, index, count);
if (read == 0)
{
_state = State.Interactive;
ProcessNamespaces();
}
return read;
case State.ReadContentAsBase64:
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Assert(false);
return 0;
}
}
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.Interactive:
case State.PopNamespaceScope:
case State.ClearNsAttributes:
if (!InitReadElementContentAsBinary(State.ReadElementContentAsBinHex))
{
return 0;
}
goto case State.ReadElementContentAsBinHex;
case State.ReadElementContentAsBinHex:
int read = reader.ReadContentAsBinHex(buffer, index, count);
if (read > 0 || count == 0)
{
return read;
}
if (NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
}
// pop namespace scope
_state = State.Interactive;
ProcessNamespaces();
// set eof state or move off the end element
if (reader.Depth == _initialDepth)
{
_state = State.EndOfFile;
SetEmptyNode();
}
else
{
Read();
}
return 0;
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
case State.ReadElementContentAsBase64:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
Debug.Assert(false);
return 0;
}
}
public override bool CanReadValueChunk
{
get
{
return reader.CanReadValueChunk;
}
}
public override int ReadValueChunk(char[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.ClearNsAttributes:
case State.PopNamespaceScope:
// ReadValueChunk implementation on added xmlns attributes
if (_curNsAttr != -1 && reader.CanReadValueChunk)
{
CheckBuffer(buffer, index, count);
int copyCount = _curNode.value.Length - _nsIncReadOffset;
if (copyCount > count)
{
copyCount = count;
}
if (copyCount > 0)
{
_curNode.value.CopyTo(_nsIncReadOffset, buffer, index, copyCount);
}
_nsIncReadOffset += copyCount;
return copyCount;
}
// Otherwise fall back to the case State.Interactive.
// No need to clean ns attributes or pop scope because the reader when ReadValueChunk is called
// - on Element errors
// - on EndElement errors
// - on Attribute does not move
// and that's all where State.ClearNsAttributes or State.PopnamespaceScope can be set
goto case State.Interactive;
case State.Interactive:
return reader.ReadValueChunk(buffer, index, count);
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
throw new InvalidOperationException(SR.Xml_MixingReadValueChunkWithBinary);
default:
Debug.Assert(false);
return 0;
}
}
public override string LookupNamespace(string prefix)
{
return ((IXmlNamespaceResolver)this).LookupNamespace(prefix);
}
//
// IXmlLineInfo implementation
//
int IXmlLineInfo.LineNumber
{
get
{
if (!_useCurNode)
{
IXmlLineInfo lineInfo = reader as IXmlLineInfo;
if (lineInfo != null)
{
return lineInfo.LineNumber;
}
}
return 0;
}
}
int IXmlLineInfo.LinePosition
{
get
{
if (!_useCurNode)
{
IXmlLineInfo lineInfo = reader as IXmlLineInfo;
if (lineInfo != null)
{
return lineInfo.LinePosition;
}
}
return 0;
}
}
bool IXmlLineInfo.HasLineInfo()
{
return reader is IXmlLineInfo;
}
//
// IXmlNamespaceResolver implementation
//
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
if (!InNamespaceActiveState)
{
return new Dictionary<string, string>();
}
return _nsManager.GetNamespacesInScope(scope);
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
if (!InNamespaceActiveState)
{
return null;
}
return _nsManager.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
if (!InNamespaceActiveState)
{
return null;
}
return _nsManager.LookupPrefix(namespaceName);
}
//
// Private methods
//
private void ProcessNamespaces()
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
_nsManager.PushScope();
string prefix = reader.Prefix;
string ns = reader.NamespaceURI;
if (_nsManager.LookupNamespace(prefix) != ns)
{
AddNamespace(prefix, ns);
}
if (reader.MoveToFirstAttribute())
{
do
{
prefix = reader.Prefix;
ns = reader.NamespaceURI;
if (Ref.Equal(ns, _xmlnsUri))
{
if (prefix.Length == 0)
{
_nsManager.AddNamespace(string.Empty, reader.Value);
RemoveNamespace(string.Empty, _xmlns);
}
else
{
prefix = reader.LocalName;
_nsManager.AddNamespace(prefix, reader.Value);
RemoveNamespace(_xmlns, prefix);
}
}
else if (prefix.Length != 0 && _nsManager.LookupNamespace(prefix) != ns)
{
AddNamespace(prefix, ns);
}
} while (reader.MoveToNextAttribute());
reader.MoveToElement();
}
if (reader.IsEmptyElement)
{
_state = State.PopNamespaceScope;
}
break;
case XmlNodeType.EndElement:
_state = State.PopNamespaceScope;
break;
}
}
private void AddNamespace(string prefix, string ns)
{
_nsManager.AddNamespace(prefix, ns);
int index = _nsAttrCount++;
if (_nsAttributes == null)
{
_nsAttributes = new NodeData[InitialNamespaceAttributeCount];
}
if (index == _nsAttributes.Length)
{
NodeData[] newNsAttrs = new NodeData[_nsAttributes.Length * 2];
Array.Copy(_nsAttributes, 0, newNsAttrs, 0, index);
_nsAttributes = newNsAttrs;
}
if (_nsAttributes[index] == null)
{
_nsAttributes[index] = new NodeData();
}
if (prefix.Length == 0)
{
_nsAttributes[index].Set(XmlNodeType.Attribute, _xmlns, string.Empty, _xmlns, _xmlnsUri, ns);
}
else
{
_nsAttributes[index].Set(XmlNodeType.Attribute, prefix, _xmlns, reader.NameTable.Add(string.Concat(_xmlns, ":", prefix)), _xmlnsUri, ns);
}
Debug.Assert(_state == State.ClearNsAttributes || _state == State.Interactive || _state == State.PopNamespaceScope);
_state = State.ClearNsAttributes;
_curNsAttr = -1;
}
private void RemoveNamespace(string prefix, string localName)
{
for (int i = 0; i < _nsAttrCount; i++)
{
if (Ref.Equal(prefix, _nsAttributes[i].prefix) &&
Ref.Equal(localName, _nsAttributes[i].localName))
{
if (i < _nsAttrCount - 1)
{
// swap
NodeData tmpNodeData = _nsAttributes[i];
_nsAttributes[i] = _nsAttributes[_nsAttrCount - 1];
_nsAttributes[_nsAttrCount - 1] = tmpNodeData;
}
_nsAttrCount--;
break;
}
}
}
private void MoveToNsAttribute(int index)
{
Debug.Assert(index >= 0 && index <= _nsAttrCount);
reader.MoveToElement();
_curNsAttr = index;
_nsIncReadOffset = 0;
SetCurrentNode(_nsAttributes[index]);
}
private bool InitReadElementContentAsBinary(State binaryState)
{
if (NodeType != XmlNodeType.Element)
{
throw reader.CreateReadElementContentAsException("ReadElementContentAsBase64");
}
bool isEmpty = IsEmptyElement;
// move to content or off the empty element
if (!Read() || isEmpty)
{
return false;
}
// special-case child element and end element
switch (NodeType)
{
case XmlNodeType.Element:
throw new XmlException(SR.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
case XmlNodeType.EndElement:
// pop scope & move off end element
ProcessNamespaces();
Read();
return false;
}
Debug.Assert(_state == State.Interactive);
_state = binaryState;
return true;
}
private bool FinishReadElementContentAsBinary()
{
Debug.Assert(_state == State.ReadElementContentAsBase64 || _state == State.ReadElementContentAsBinHex);
byte[] bytes = new byte[256];
if (_state == State.ReadElementContentAsBase64)
{
while (reader.ReadContentAsBase64(bytes, 0, 256) > 0) ;
}
else
{
while (reader.ReadContentAsBinHex(bytes, 0, 256) > 0) ;
}
if (NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
}
// pop namespace scope
_state = State.Interactive;
ProcessNamespaces();
// check eof
if (reader.Depth == _initialDepth)
{
_state = State.EndOfFile;
SetEmptyNode();
return false;
}
// move off end element
return Read();
}
private bool FinishReadContentAsBinary()
{
Debug.Assert(_state == State.ReadContentAsBase64 || _state == State.ReadContentAsBinHex);
byte[] bytes = new byte[256];
if (_state == State.ReadContentAsBase64)
{
while (reader.ReadContentAsBase64(bytes, 0, 256) > 0) ;
}
else
{
while (reader.ReadContentAsBinHex(bytes, 0, 256) > 0) ;
}
_state = State.Interactive;
ProcessNamespaces();
// check eof
if (reader.Depth == _initialDepth)
{
_state = State.EndOfFile;
SetEmptyNode();
return false;
}
return true;
}
private bool InAttributeActiveState
{
get
{
#if DEBUG
Debug.Assert(0 == (AttributeActiveStates & (1 << (int)State.Initial)));
Debug.Assert(0 != (AttributeActiveStates & (1 << (int)State.Interactive)));
Debug.Assert(0 == (AttributeActiveStates & (1 << (int)State.Error)));
Debug.Assert(0 == (AttributeActiveStates & (1 << (int)State.EndOfFile)));
Debug.Assert(0 == (AttributeActiveStates & (1 << (int)State.Closed)));
Debug.Assert(0 != (AttributeActiveStates & (1 << (int)State.PopNamespaceScope)));
Debug.Assert(0 != (AttributeActiveStates & (1 << (int)State.ClearNsAttributes)));
Debug.Assert(0 == (AttributeActiveStates & (1 << (int)State.ReadElementContentAsBase64)));
Debug.Assert(0 == (AttributeActiveStates & (1 << (int)State.ReadElementContentAsBinHex)));
Debug.Assert(0 == (AttributeActiveStates & (1 << (int)State.ReadContentAsBase64)));
Debug.Assert(0 == (AttributeActiveStates & (1 << (int)State.ReadContentAsBinHex)));
#endif
return 0 != (AttributeActiveStates & (1 << (int)_state));
}
}
private bool InNamespaceActiveState
{
get
{
#if DEBUG
Debug.Assert(0 == (NamespaceActiveStates & (1 << (int)State.Initial)));
Debug.Assert(0 != (NamespaceActiveStates & (1 << (int)State.Interactive)));
Debug.Assert(0 == (NamespaceActiveStates & (1 << (int)State.Error)));
Debug.Assert(0 == (NamespaceActiveStates & (1 << (int)State.EndOfFile)));
Debug.Assert(0 == (NamespaceActiveStates & (1 << (int)State.Closed)));
Debug.Assert(0 != (NamespaceActiveStates & (1 << (int)State.PopNamespaceScope)));
Debug.Assert(0 != (NamespaceActiveStates & (1 << (int)State.ClearNsAttributes)));
Debug.Assert(0 != (NamespaceActiveStates & (1 << (int)State.ReadElementContentAsBase64)));
Debug.Assert(0 != (NamespaceActiveStates & (1 << (int)State.ReadElementContentAsBinHex)));
Debug.Assert(0 != (NamespaceActiveStates & (1 << (int)State.ReadContentAsBase64)));
Debug.Assert(0 != (NamespaceActiveStates & (1 << (int)State.ReadContentAsBinHex)));
#endif
return 0 != (NamespaceActiveStates & (1 << (int)_state));
}
}
private void SetEmptyNode()
{
Debug.Assert(_tmpNode.localName == string.Empty && _tmpNode.prefix == string.Empty && _tmpNode.name == string.Empty && _tmpNode.namespaceUri == string.Empty);
_tmpNode.type = XmlNodeType.None;
_tmpNode.value = string.Empty;
_curNode = _tmpNode;
_useCurNode = true;
}
private void SetCurrentNode(NodeData node)
{
_curNode = node;
_useCurNode = true;
}
private void InitReadContentAsType(string methodName)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
throw new InvalidOperationException(SR.Xml_ClosedOrErrorReader);
case State.Interactive:
return;
case State.PopNamespaceScope:
case State.ClearNsAttributes:
// no need to clean ns attributes or pop scope because the reader when ReadContentAs is called
// - on Element errors
// - on Attribute does not move
// - on EndElement does not move
// and that's all where State.ClearNsAttributes or State.PopNamespacScope can be set
return;
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
throw new InvalidOperationException(SR.Xml_MixingReadValueChunkWithBinary);
default:
Debug.Assert(false);
break;
}
throw CreateReadContentAsException(methodName);
}
private void FinishReadContentAsType()
{
Debug.Assert(_state == State.Interactive ||
_state == State.PopNamespaceScope ||
_state == State.ClearNsAttributes);
switch (NodeType)
{
case XmlNodeType.Element:
// new element we moved to - process namespaces
ProcessNamespaces();
break;
case XmlNodeType.EndElement:
// end element we've stayed on or have been moved to
_state = State.PopNamespaceScope;
break;
case XmlNodeType.Attribute:
// stayed on attribute, do nothing
break;
}
}
private void CheckBuffer(Array buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (buffer.Length - index < count)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
}
}
}
| |
using EncompassRest.Loans.Enums;
using EncompassRest.Schema;
namespace EncompassRest.Loans
{
/// <summary>
/// LoanProgram
/// </summary>
[Entity(SerializeWholeListWhenDirty = true)]
public sealed partial class LoanProgram : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<StringEnumValue<YOrN>>? _acquisition;
private DirtyValue<string?>? _additionalArmInformation;
private DirtyValue<string?>? _allDateAndNumericalDisclosures;
private DirtyValue<decimal?>? _annualFeeNeeded;
private DirtyValue<string?>? _armTypeDescription;
private DirtyValue<string?>? _assumptionOnYourProperty;
private DirtyValue<int?>? _balloonLoanMaturityTermMonths;
private DirtyValue<int?>? _buydownChangeFrequencyMonths1;
private DirtyValue<int?>? _buydownChangeFrequencyMonths2;
private DirtyValue<int?>? _buydownChangeFrequencyMonths3;
private DirtyValue<int?>? _buydownChangeFrequencyMonths4;
private DirtyValue<int?>? _buydownChangeFrequencyMonths5;
private DirtyValue<int?>? _buydownChangeFrequencyMonths6;
private DirtyValue<decimal?>? _buydownIncreaseRatePercent1;
private DirtyValue<decimal?>? _buydownIncreaseRatePercent2;
private DirtyValue<decimal?>? _buydownIncreaseRatePercent3;
private DirtyValue<decimal?>? _buydownIncreaseRatePercent4;
private DirtyValue<decimal?>? _buydownIncreaseRatePercent5;
private DirtyValue<decimal?>? _buydownIncreaseRatePercent6;
private DirtyValue<string?>? _calculateBasedOnRemainingBalance;
private DirtyValue<string?>? _closingCostProgram;
private DirtyValue<string?>? _constructionDescription;
private DirtyValue<decimal?>? _constructionInterestReserveAmount;
private DirtyValue<string?>? _constructionLoanMethod;
private DirtyValue<int?>? _constructionPeriodMonths;
private DirtyValue<decimal?>? _constructionRate;
private DirtyValue<string?>? _convertible;
private DirtyValue<string?>? _creditDisability;
private DirtyValue<string?>? _creditLifeInsurance;
private DirtyValue<string?>? _demandFeature;
private DirtyValue<string?>? _description;
private DirtyValue<string?>? _disclosureType;
private DirtyValue<string?>? _discounted;
private DirtyValue<decimal?>? _discountedRate;
private DirtyValue<string?>? _drawRepayPeriodTableName;
private DirtyValue<decimal?>? _fhaUpfrontMiPremiumPercent;
private DirtyValue<string?>? _floodInsurance;
private DirtyValue<decimal?>? _floorPercent;
private DirtyValue<decimal?>? _fundingFeePaidInCash;
private DirtyValue<decimal?>? _gpmExtraPaymentForEarlyPayOff;
private DirtyValue<decimal?>? _gpmRate;
private DirtyValue<int?>? _gpmYears;
private DirtyValue<string?>? _id;
private DirtyValue<string?>? _ifYouPurchase;
private DirtyValue<string?>? _ifYouPurchaseType;
private DirtyValue<decimal?>? _indexCurrentValuePercent;
private DirtyValue<decimal?>? _indexMarginPercent;
private DirtyValue<decimal?>? _initialAdvanceAmount;
private DirtyValue<int?>? _interestOnlyMonths;
private DirtyValue<int?>? _lateChargeDays;
private DirtyValue<decimal?>? _lateChargePercent;
private DirtyValue<string?>? _lateChargeType;
private DirtyValue<string?>? _lenderInvestorCode;
private DirtyValue<string?>? _lienPriorityType;
private DirtyValue<int?>? _loanAmortizationTermMonths;
private DirtyValue<string?>? _loanAmortizationType;
private DirtyValue<string?>? _loanDocumentationType;
private DirtyValue<string?>? _loanFeaturesPaymentFrequencyType;
private DirtyValue<string?>? _loanProgramName;
private DirtyValue<StringEnumValue<YOrN>>? _lockField;
private DirtyValue<decimal?>? _maxBackRatio;
private DirtyValue<decimal?>? _maxCltv;
private DirtyValue<decimal?>? _maxFrontRatio;
private DirtyValue<decimal?>? _maximumBalance;
private DirtyValue<decimal?>? _maxLoanAmount;
private DirtyValue<decimal?>? _maxLtv;
private DirtyValue<string?>? _meansAnEstimate;
private DirtyValue<string?>? _miCalculationType;
private DirtyValue<string?>? _midpointCancellation;
private DirtyValue<string?>? _minCreditScore;
private DirtyValue<decimal?>? _minimumAdvanceAmount;
private DirtyValue<decimal?>? _minimumAllowableApr;
private DirtyValue<decimal?>? _minimumPaymentAmount;
private DirtyValue<decimal?>? _minimumPaymentPercent;
private DirtyValue<decimal?>? _mipPaidInCash;
private DirtyValue<StringEnumValue<YOrN>>? _mmi;
private DirtyValue<decimal?>? _mortgageInsuranceAdjustmentFactor1;
private DirtyValue<decimal?>? _mortgageInsuranceAdjustmentFactor2;
private DirtyValue<decimal?>? _mortgageInsuranceCancelPercent;
private DirtyValue<decimal?>? _mortgageInsuranceMonthlyPayment1;
private DirtyValue<decimal?>? _mortgageInsuranceMonthlyPayment2;
private DirtyValue<int?>? _mortgageInsuranceMonthsOfAdjustment1;
private DirtyValue<int?>? _mortgageInsuranceMonthsOfAdjustment2;
private DirtyValue<string?>? _mortgageType;
private DirtyValue<string?>? _otherAmortizationTypeDescription;
private DirtyValue<string?>? _otherLoanPurposeDescription;
private DirtyValue<string?>? _otherMortgageTypeDescription;
private DirtyValue<int?>? _paymentAdjustmentDurationMonths;
private DirtyValue<decimal?>? _paymentAdjustmentPeriodicCapPercent;
private DirtyValue<decimal?>? _paymentFactor;
private DirtyValue<decimal?>? _percentageOfRental;
private DirtyValue<string?>? _perDiemCalculationMethodType;
private DirtyValue<StringEnumValue<YOrN>>? _pmi;
private DirtyValue<string?>? _prepaymentPenaltyIndicator;
private DirtyValue<string?>? _programCode;
private DirtyValue<string?>? _propertyInsurance;
private DirtyValue<string?>? _propertyUsageType;
private DirtyValue<decimal?>? _qualifyingRatePercent;
private DirtyValue<int?>? _rateAdjustmentDurationMonths;
private DirtyValue<decimal?>? _rateAdjustmentLifetimeCapPercent;
private DirtyValue<decimal?>? _rateAdjustmentPercent;
private DirtyValue<decimal?>? _rateAdjustmentSubsequentCapPercent;
private DirtyValue<int?>? _rateAdjustmentSubsequentRateAdjustmentMonths;
private DirtyValue<int?>? _recastPaidMonths;
private DirtyValue<int?>? _recastStopMonths;
private DirtyValue<string?>? _refundPaymentIndicator;
private DirtyValue<decimal?>? _requestedInterestRatePercent;
private DirtyValue<string?>? _requiredDeposit;
private DirtyValue<decimal?>? _roundPercent;
private DirtyValue<string?>? _roundType;
private DirtyValue<string?>? _securityInterestInNameOf;
private DirtyValue<string?>? _securityType;
private DirtyValue<decimal?>? _subjectPropertyGrossRentalIncome;
private DirtyValue<decimal?>? _teaserRate;
private DirtyValue<decimal?>? _terminationFeeAmount;
private DirtyValue<int?>? _terminationPeriodMonthsCount;
private DirtyValue<decimal?>? _thirdPartyFeeFrom;
private DirtyValue<decimal?>? _thirdPartyFeeTo;
private DirtyValue<string?>? _type;
private DirtyValue<string?>? _useDaysInYears;
private DirtyValue<StringEnumValue<YOrN>>? _usePitiForRatio;
private DirtyValue<string?>? _variableRateFeature;
private DirtyValue<decimal?>? _yearlyTerm;
/// <summary>
/// LoanProgram Acquisition [LPNN113]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public StringEnumValue<YOrN> Acquisition { get => _acquisition; set => SetField(ref _acquisition, value); }
/// <summary>
/// LoanProgram AdditionalArmInformation [LPNN67]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? AdditionalArmInformation { get => _additionalArmInformation; set => SetField(ref _additionalArmInformation, value); }
/// <summary>
/// LoanProgram AllDateAndNumericalDisclosures [LPNN82]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? AllDateAndNumericalDisclosures { get => _allDateAndNumericalDisclosures; set => SetField(ref _allDateAndNumericalDisclosures, value); }
/// <summary>
/// LoanProgram AnnualFeeNeeded [LPNN115]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? AnnualFeeNeeded { get => _annualFeeNeeded; set => SetField(ref _annualFeeNeeded, value); }
/// <summary>
/// LoanProgram ArmTypeDescription [LPNN86]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? ArmTypeDescription { get => _armTypeDescription; set => SetField(ref _armTypeDescription, value); }
/// <summary>
/// LoanProgram AssumptionOnYourProperty [LPNN75]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? AssumptionOnYourProperty { get => _assumptionOnYourProperty; set => SetField(ref _assumptionOnYourProperty, value); }
/// <summary>
/// LoanProgram BalloonLoanMaturityTermMonths [LPNN11]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? BalloonLoanMaturityTermMonths { get => _balloonLoanMaturityTermMonths; set => SetField(ref _balloonLoanMaturityTermMonths, value); }
/// <summary>
/// LoanProgram BuydownChangeFrequencyMonths1 [LPNN13]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? BuydownChangeFrequencyMonths1 { get => _buydownChangeFrequencyMonths1; set => SetField(ref _buydownChangeFrequencyMonths1, value); }
/// <summary>
/// LoanProgram BuydownChangeFrequencyMonths2 [LPNN15]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? BuydownChangeFrequencyMonths2 { get => _buydownChangeFrequencyMonths2; set => SetField(ref _buydownChangeFrequencyMonths2, value); }
/// <summary>
/// LoanProgram BuydownChangeFrequencyMonths3 [LPNN17]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? BuydownChangeFrequencyMonths3 { get => _buydownChangeFrequencyMonths3; set => SetField(ref _buydownChangeFrequencyMonths3, value); }
/// <summary>
/// LoanProgram BuydownChangeFrequencyMonths4 [LPNN19]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? BuydownChangeFrequencyMonths4 { get => _buydownChangeFrequencyMonths4; set => SetField(ref _buydownChangeFrequencyMonths4, value); }
/// <summary>
/// LoanProgram BuydownChangeFrequencyMonths5 [LPNN21]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? BuydownChangeFrequencyMonths5 { get => _buydownChangeFrequencyMonths5; set => SetField(ref _buydownChangeFrequencyMonths5, value); }
/// <summary>
/// LoanProgram BuydownChangeFrequencyMonths6 [LPNN23]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? BuydownChangeFrequencyMonths6 { get => _buydownChangeFrequencyMonths6; set => SetField(ref _buydownChangeFrequencyMonths6, value); }
/// <summary>
/// LoanProgram BuydownIncreaseRatePercent1 [LPNN12]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? BuydownIncreaseRatePercent1 { get => _buydownIncreaseRatePercent1; set => SetField(ref _buydownIncreaseRatePercent1, value); }
/// <summary>
/// LoanProgram BuydownIncreaseRatePercent2 [LPNN14]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? BuydownIncreaseRatePercent2 { get => _buydownIncreaseRatePercent2; set => SetField(ref _buydownIncreaseRatePercent2, value); }
/// <summary>
/// LoanProgram BuydownIncreaseRatePercent3 [LPNN16]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? BuydownIncreaseRatePercent3 { get => _buydownIncreaseRatePercent3; set => SetField(ref _buydownIncreaseRatePercent3, value); }
/// <summary>
/// LoanProgram BuydownIncreaseRatePercent4 [LPNN18]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? BuydownIncreaseRatePercent4 { get => _buydownIncreaseRatePercent4; set => SetField(ref _buydownIncreaseRatePercent4, value); }
/// <summary>
/// LoanProgram BuydownIncreaseRatePercent5 [LPNN20]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? BuydownIncreaseRatePercent5 { get => _buydownIncreaseRatePercent5; set => SetField(ref _buydownIncreaseRatePercent5, value); }
/// <summary>
/// LoanProgram BuydownIncreaseRatePercent6 [LPNN22]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? BuydownIncreaseRatePercent6 { get => _buydownIncreaseRatePercent6; set => SetField(ref _buydownIncreaseRatePercent6, value); }
/// <summary>
/// LoanProgram CalculateBasedOnRemainingBalance [LPNN99]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? CalculateBasedOnRemainingBalance { get => _calculateBasedOnRemainingBalance; set => SetField(ref _calculateBasedOnRemainingBalance, value); }
/// <summary>
/// LoanProgram ClosingCostProgram [LPNN97]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? ClosingCostProgram { get => _closingCostProgram; set => SetField(ref _closingCostProgram, value); }
/// <summary>
/// LoanProgram ConstructionDescription [LPNN56]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? ConstructionDescription { get => _constructionDescription; set => SetField(ref _constructionDescription, value); }
/// <summary>
/// LoanProgram ConstructionInterestReserveAmount [LPNN55]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? ConstructionInterestReserveAmount { get => _constructionInterestReserveAmount; set => SetField(ref _constructionInterestReserveAmount, value); }
/// <summary>
/// LoanProgram ConstructionLoanMethod [LPNN112]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? ConstructionLoanMethod { get => _constructionLoanMethod; set => SetField(ref _constructionLoanMethod, value); }
/// <summary>
/// LoanProgram ConstructionPeriodMonths [LPNN53]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? ConstructionPeriodMonths { get => _constructionPeriodMonths; set => SetField(ref _constructionPeriodMonths, value); }
/// <summary>
/// LoanProgram ConstructionRate [LPNN54]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? ConstructionRate { get => _constructionRate; set => SetField(ref _constructionRate, value); }
/// <summary>
/// LoanProgram Convertible [LPNN79]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? Convertible { get => _convertible; set => SetField(ref _convertible, value); }
/// <summary>
/// LoanProgram CreditDisability [LPNN90]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? CreditDisability { get => _creditDisability; set => SetField(ref _creditDisability, value); }
/// <summary>
/// LoanProgram CreditLifeInsurance [LPNN89]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? CreditLifeInsurance { get => _creditLifeInsurance; set => SetField(ref _creditLifeInsurance, value); }
/// <summary>
/// LoanProgram DemandFeature [LPNN65]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? DemandFeature { get => _demandFeature; set => SetField(ref _demandFeature, value); }
/// <summary>
/// LoanProgram Description [LPNN88]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? Description { get => _description; set => SetField(ref _description, value); }
/// <summary>
/// LoanProgram DisclosureType [LPNN110]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? DisclosureType { get => _disclosureType; set => SetField(ref _disclosureType, value); }
/// <summary>
/// LoanProgram Discounted [LPNN123]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? Discounted { get => _discounted; set => SetField(ref _discounted, value); }
/// <summary>
/// LoanProgram DiscountedRate [LPNN124]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? DiscountedRate { get => _discountedRate; set => SetField(ref _discountedRate, value); }
/// <summary>
/// LoanProgram DrawRepayPeriodTableName [LPNN125]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? DrawRepayPeriodTableName { get => _drawRepayPeriodTableName; set => SetField(ref _drawRepayPeriodTableName, value); }
/// <summary>
/// LoanProgram FhaUpfrontMiPremiumPercent [LPNN101]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? FhaUpfrontMiPremiumPercent { get => _fhaUpfrontMiPremiumPercent; set => SetField(ref _fhaUpfrontMiPremiumPercent, value); }
/// <summary>
/// LoanProgram FloodInsurance [LPNN92]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? FloodInsurance { get => _floodInsurance; set => SetField(ref _floodInsurance, value); }
/// <summary>
/// LoanProgram FloorPercent [LPNN33]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? FloorPercent { get => _floorPercent; set => SetField(ref _floorPercent, value); }
/// <summary>
/// LoanProgram FundingFeePaidInCash [LPNN104]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? FundingFeePaidInCash { get => _fundingFeePaidInCash; set => SetField(ref _fundingFeePaidInCash, value); }
/// <summary>
/// LoanProgram GpmExtraPaymentForEarlyPayOff [LPNN43]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? GpmExtraPaymentForEarlyPayOff { get => _gpmExtraPaymentForEarlyPayOff; set => SetField(ref _gpmExtraPaymentForEarlyPayOff, value); }
/// <summary>
/// LoanProgram GpmRate [LPNN41]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? GpmRate { get => _gpmRate; set => SetField(ref _gpmRate, value); }
/// <summary>
/// LoanProgram GpmYears [LPNN42]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? GpmYears { get => _gpmYears; set => SetField(ref _gpmYears, value); }
/// <summary>
/// LoanProgram Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// LoanProgram IfYouPurchase [LPNN93]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? IfYouPurchase { get => _ifYouPurchase; set => SetField(ref _ifYouPurchase, value); }
/// <summary>
/// LoanProgram IfYouPurchaseType [LPNN94]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? IfYouPurchaseType { get => _ifYouPurchaseType; set => SetField(ref _ifYouPurchaseType, value); }
/// <summary>
/// LoanProgram IndexCurrentValuePercent [LPNN32]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? IndexCurrentValuePercent { get => _indexCurrentValuePercent; set => SetField(ref _indexCurrentValuePercent, value); }
/// <summary>
/// LoanProgram IndexMarginPercent [LPNN31]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? IndexMarginPercent { get => _indexMarginPercent; set => SetField(ref _indexMarginPercent, value); }
/// <summary>
/// LoanProgram InitialAdvanceAmount [LPNN114]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? InitialAdvanceAmount { get => _initialAdvanceAmount; set => SetField(ref _initialAdvanceAmount, value); }
/// <summary>
/// LoanProgram InterestOnlyMonths [LPNN25]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? InterestOnlyMonths { get => _interestOnlyMonths; set => SetField(ref _interestOnlyMonths, value); }
/// <summary>
/// LoanProgram LateChargeDays [LPNN72]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? LateChargeDays { get => _lateChargeDays; set => SetField(ref _lateChargeDays, value); }
/// <summary>
/// LoanProgram LateChargePercent [LPNN73]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? LateChargePercent { get => _lateChargePercent; set => SetField(ref _lateChargePercent, value); }
/// <summary>
/// LoanProgram LateChargeType [LPNN74]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? LateChargeType { get => _lateChargeType; set => SetField(ref _lateChargeType, value); }
/// <summary>
/// LoanProgram LenderInvestorCode [LPNN51]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? LenderInvestorCode { get => _lenderInvestorCode; set => SetField(ref _lenderInvestorCode, value); }
/// <summary>
/// LoanProgram LienPriorityType [LPNN03]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? LienPriorityType { get => _lienPriorityType; set => SetField(ref _lienPriorityType, value); }
/// <summary>
/// LoanProgram LoanAmortizationTermMonths [LPNN10]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? LoanAmortizationTermMonths { get => _loanAmortizationTermMonths; set => SetField(ref _loanAmortizationTermMonths, value); }
/// <summary>
/// LoanProgram LoanAmortizationType [LPNN07]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? LoanAmortizationType { get => _loanAmortizationType; set => SetField(ref _loanAmortizationType, value); }
/// <summary>
/// LoanProgram LoanDocumentationType [LPNN107]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? LoanDocumentationType { get => _loanDocumentationType; set => SetField(ref _loanDocumentationType, value); }
/// <summary>
/// LoanProgram LoanFeaturesPaymentFrequencyType [LPNN24]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? LoanFeaturesPaymentFrequencyType { get => _loanFeaturesPaymentFrequencyType; set => SetField(ref _loanFeaturesPaymentFrequencyType, value); }
/// <summary>
/// LoanProgram LoanProgramName [LPNN44]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? LoanProgramName { get => _loanProgramName; set => SetField(ref _loanProgramName, value); }
/// <summary>
/// LoanProgram LockField [LPNN102]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public StringEnumValue<YOrN> LockField { get => _lockField; set => SetField(ref _lockField, value); }
/// <summary>
/// LoanProgram MaxBackRatio [LPNN50]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? MaxBackRatio { get => _maxBackRatio; set => SetField(ref _maxBackRatio, value); }
/// <summary>
/// LoanProgram MaxCltv [LPNN47]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? MaxCltv { get => _maxCltv; set => SetField(ref _maxCltv, value); }
/// <summary>
/// LoanProgram MaxFrontRatio [LPNN49]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? MaxFrontRatio { get => _maxFrontRatio; set => SetField(ref _maxFrontRatio, value); }
/// <summary>
/// LoanProgram MaximumBalance [LPNN40]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? MaximumBalance { get => _maximumBalance; set => SetField(ref _maximumBalance, value); }
/// <summary>
/// LoanProgram MaxLoanAmount [LPNN45]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MaxLoanAmount { get => _maxLoanAmount; set => SetField(ref _maxLoanAmount, value); }
/// <summary>
/// LoanProgram MaxLtv [LPNN46]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? MaxLtv { get => _maxLtv; set => SetField(ref _maxLtv, value); }
/// <summary>
/// LoanProgram MeansAnEstimate [LPNN81]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? MeansAnEstimate { get => _meansAnEstimate; set => SetField(ref _meansAnEstimate, value); }
/// <summary>
/// LoanProgram MiCalculationType [LPNN100]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? MiCalculationType { get => _miCalculationType; set => SetField(ref _miCalculationType, value); }
/// <summary>
/// LoanProgram MidpointCancellation [LPNN98]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? MidpointCancellation { get => _midpointCancellation; set => SetField(ref _midpointCancellation, value); }
/// <summary>
/// LoanProgram MinCreditScore [LPNN48]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? MinCreditScore { get => _minCreditScore; set => SetField(ref _minCreditScore, value); }
/// <summary>
/// LoanProgram MinimumAdvanceAmount [LPNN119]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MinimumAdvanceAmount { get => _minimumAdvanceAmount; set => SetField(ref _minimumAdvanceAmount, value); }
/// <summary>
/// LoanProgram MinimumAllowableApr [LPNN120]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? MinimumAllowableApr { get => _minimumAllowableApr; set => SetField(ref _minimumAllowableApr, value); }
/// <summary>
/// LoanProgram MinimumPaymentAmount [LPNN122]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MinimumPaymentAmount { get => _minimumPaymentAmount; set => SetField(ref _minimumPaymentAmount, value); }
/// <summary>
/// LoanProgram MinimumPaymentPercent [LPNN121]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? MinimumPaymentPercent { get => _minimumPaymentPercent; set => SetField(ref _minimumPaymentPercent, value); }
/// <summary>
/// LoanProgram MipPaidInCash [LPNN103]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MipPaidInCash { get => _mipPaidInCash; set => SetField(ref _mipPaidInCash, value); }
/// <summary>
/// LoanProgram Mmi [LPNN108]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public StringEnumValue<YOrN> Mmi { get => _mmi; set => SetField(ref _mmi, value); }
/// <summary>
/// LoanProgram MortgageInsuranceAdjustmentFactor1 [LPNN57]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? MortgageInsuranceAdjustmentFactor1 { get => _mortgageInsuranceAdjustmentFactor1; set => SetField(ref _mortgageInsuranceAdjustmentFactor1, value); }
/// <summary>
/// LoanProgram MortgageInsuranceAdjustmentFactor2 [LPNN60]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? MortgageInsuranceAdjustmentFactor2 { get => _mortgageInsuranceAdjustmentFactor2; set => SetField(ref _mortgageInsuranceAdjustmentFactor2, value); }
/// <summary>
/// LoanProgram MortgageInsuranceCancelPercent [LPNN63]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? MortgageInsuranceCancelPercent { get => _mortgageInsuranceCancelPercent; set => SetField(ref _mortgageInsuranceCancelPercent, value); }
/// <summary>
/// LoanProgram MortgageInsuranceMonthlyPayment1 [LPNN59]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MortgageInsuranceMonthlyPayment1 { get => _mortgageInsuranceMonthlyPayment1; set => SetField(ref _mortgageInsuranceMonthlyPayment1, value); }
/// <summary>
/// LoanProgram MortgageInsuranceMonthlyPayment2 [LPNN62]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MortgageInsuranceMonthlyPayment2 { get => _mortgageInsuranceMonthlyPayment2; set => SetField(ref _mortgageInsuranceMonthlyPayment2, value); }
/// <summary>
/// LoanProgram MortgageInsuranceMonthsOfAdjustment1 [LPNN58]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? MortgageInsuranceMonthsOfAdjustment1 { get => _mortgageInsuranceMonthsOfAdjustment1; set => SetField(ref _mortgageInsuranceMonthsOfAdjustment1, value); }
/// <summary>
/// LoanProgram MortgageInsuranceMonthsOfAdjustment2 [LPNN61]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? MortgageInsuranceMonthsOfAdjustment2 { get => _mortgageInsuranceMonthsOfAdjustment2; set => SetField(ref _mortgageInsuranceMonthsOfAdjustment2, value); }
/// <summary>
/// LoanProgram MortgageType [LPNN01]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? MortgageType { get => _mortgageType; set => SetField(ref _mortgageType, value); }
/// <summary>
/// LoanProgram OtherAmortizationTypeDescription [LPNN87]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? OtherAmortizationTypeDescription { get => _otherAmortizationTypeDescription; set => SetField(ref _otherAmortizationTypeDescription, value); }
/// <summary>
/// LoanProgram OtherLoanPurposeDescription [LPNN96]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? OtherLoanPurposeDescription { get => _otherLoanPurposeDescription; set => SetField(ref _otherLoanPurposeDescription, value); }
/// <summary>
/// LoanProgram OtherMortgageTypeDescription [LPNN85]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? OtherMortgageTypeDescription { get => _otherMortgageTypeDescription; set => SetField(ref _otherMortgageTypeDescription, value); }
/// <summary>
/// LoanProgram PaymentAdjustmentDurationMonths [LPNN37]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? PaymentAdjustmentDurationMonths { get => _paymentAdjustmentDurationMonths; set => SetField(ref _paymentAdjustmentDurationMonths, value); }
/// <summary>
/// LoanProgram PaymentAdjustmentPeriodicCapPercent [LPNN36]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? PaymentAdjustmentPeriodicCapPercent { get => _paymentAdjustmentPeriodicCapPercent; set => SetField(ref _paymentAdjustmentPeriodicCapPercent, value); }
/// <summary>
/// LoanProgram PaymentFactor [LPNN52]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? PaymentFactor { get => _paymentFactor; set => SetField(ref _paymentFactor, value); }
/// <summary>
/// LoanProgram PercentageOfRental [LPNN84]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? PercentageOfRental { get => _percentageOfRental; set => SetField(ref _percentageOfRental, value); }
/// <summary>
/// LoanProgram PerDiemCalculationMethodType [LPNN111]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? PerDiemCalculationMethodType { get => _perDiemCalculationMethodType; set => SetField(ref _perDiemCalculationMethodType, value); }
/// <summary>
/// LoanProgram Pmi [LPNN109]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public StringEnumValue<YOrN> Pmi { get => _pmi; set => SetField(ref _pmi, value); }
/// <summary>
/// LoanProgram PrepaymentPenaltyIndicator [LPNN70]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? PrepaymentPenaltyIndicator { get => _prepaymentPenaltyIndicator; set => SetField(ref _prepaymentPenaltyIndicator, value); }
/// <summary>
/// LoanProgram ProgramCode [LPNN80]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? ProgramCode { get => _programCode; set => SetField(ref _programCode, value); }
/// <summary>
/// LoanProgram PropertyInsurance [LPNN91]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? PropertyInsurance { get => _propertyInsurance; set => SetField(ref _propertyInsurance, value); }
/// <summary>
/// LoanProgram PropertyUsageType [LPNN02]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? PropertyUsageType { get => _propertyUsageType; set => SetField(ref _propertyUsageType, value); }
/// <summary>
/// LoanProgram QualifyingRatePercent [LPNN09]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? QualifyingRatePercent { get => _qualifyingRatePercent; set => SetField(ref _qualifyingRatePercent, value); }
/// <summary>
/// LoanProgram RateAdjustmentDurationMonths [LPNN29]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? RateAdjustmentDurationMonths { get => _rateAdjustmentDurationMonths; set => SetField(ref _rateAdjustmentDurationMonths, value); }
/// <summary>
/// LoanProgram RateAdjustmentLifetimeCapPercent [LPNN30]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? RateAdjustmentLifetimeCapPercent { get => _rateAdjustmentLifetimeCapPercent; set => SetField(ref _rateAdjustmentLifetimeCapPercent, value); }
/// <summary>
/// LoanProgram RateAdjustmentPercent [LPNN26]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? RateAdjustmentPercent { get => _rateAdjustmentPercent; set => SetField(ref _rateAdjustmentPercent, value); }
/// <summary>
/// LoanProgram RateAdjustmentSubsequentCapPercent [LPNN28]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? RateAdjustmentSubsequentCapPercent { get => _rateAdjustmentSubsequentCapPercent; set => SetField(ref _rateAdjustmentSubsequentCapPercent, value); }
/// <summary>
/// LoanProgram RateAdjustmentSubsequentRateAdjustmentMonths [LPNN27]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? RateAdjustmentSubsequentRateAdjustmentMonths { get => _rateAdjustmentSubsequentRateAdjustmentMonths; set => SetField(ref _rateAdjustmentSubsequentRateAdjustmentMonths, value); }
/// <summary>
/// LoanProgram RecastPaidMonths [LPNN38]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? RecastPaidMonths { get => _recastPaidMonths; set => SetField(ref _recastPaidMonths, value); }
/// <summary>
/// LoanProgram RecastStopMonths [LPNN39]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? RecastStopMonths { get => _recastStopMonths; set => SetField(ref _recastStopMonths, value); }
/// <summary>
/// LoanProgram RefundPaymentIndicator [LPNN71]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? RefundPaymentIndicator { get => _refundPaymentIndicator; set => SetField(ref _refundPaymentIndicator, value); }
/// <summary>
/// LoanProgram RequestedInterestRatePercent [LPNN08]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? RequestedInterestRatePercent { get => _requestedInterestRatePercent; set => SetField(ref _requestedInterestRatePercent, value); }
/// <summary>
/// LoanProgram RequiredDeposit [LPNN64]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? RequiredDeposit { get => _requiredDeposit; set => SetField(ref _requiredDeposit, value); }
/// <summary>
/// LoanProgram RoundPercent [LPNN34]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? RoundPercent { get => _roundPercent; set => SetField(ref _roundPercent, value); }
/// <summary>
/// LoanProgram RoundType [LPNN35]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? RoundType { get => _roundType; set => SetField(ref _roundType, value); }
/// <summary>
/// LoanProgram SecurityInterestInNameOf [LPNN68]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? SecurityInterestInNameOf { get => _securityInterestInNameOf; set => SetField(ref _securityInterestInNameOf, value); }
/// <summary>
/// LoanProgram SecurityType [LPNN69]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? SecurityType { get => _securityType; set => SetField(ref _securityType, value); }
/// <summary>
/// LoanProgram SubjectPropertyGrossRentalIncome [LPNN83]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? SubjectPropertyGrossRentalIncome { get => _subjectPropertyGrossRentalIncome; set => SetField(ref _subjectPropertyGrossRentalIncome, value); }
/// <summary>
/// LoanProgram TeaserRate [LPNN116]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3, ReadOnly = true)]
public decimal? TeaserRate { get => _teaserRate; set => SetField(ref _teaserRate, value); }
/// <summary>
/// LoanProgram TerminationFeeAmount [LPNN126]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? TerminationFeeAmount { get => _terminationFeeAmount; set => SetField(ref _terminationFeeAmount, value); }
/// <summary>
/// LoanProgram TerminationPeriodMonthsCount [LPNN127]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? TerminationPeriodMonthsCount { get => _terminationPeriodMonthsCount; set => SetField(ref _terminationPeriodMonthsCount, value); }
/// <summary>
/// LoanProgram ThirdPartyFeeFrom [LPNN117]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? ThirdPartyFeeFrom { get => _thirdPartyFeeFrom; set => SetField(ref _thirdPartyFeeFrom, value); }
/// <summary>
/// LoanProgram ThirdPartyFeeTo [LPNN118]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? ThirdPartyFeeTo { get => _thirdPartyFeeTo; set => SetField(ref _thirdPartyFeeTo, value); }
/// <summary>
/// LoanProgram Type [LPNN05]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? Type { get => _type; set => SetField(ref _type, value); }
/// <summary>
/// LoanProgram UseDaysInYears [LPNN105]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? UseDaysInYears { get => _useDaysInYears; set => SetField(ref _useDaysInYears, value); }
/// <summary>
/// LoanProgram UsePitiForRatio [LPNN106]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public StringEnumValue<YOrN> UsePitiForRatio { get => _usePitiForRatio; set => SetField(ref _usePitiForRatio, value); }
/// <summary>
/// LoanProgram VariableRateFeature [LPNN66]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? VariableRateFeature { get => _variableRateFeature; set => SetField(ref _variableRateFeature, value); }
/// <summary>
/// LoanProgram YearlyTerm [LPNN95]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? YearlyTerm { get => _yearlyTerm; set => SetField(ref _yearlyTerm, value); }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms
{
public class AbsoluteLayout : Layout<View>
{
public static readonly BindableProperty LayoutFlagsProperty = BindableProperty.CreateAttached("LayoutFlags", typeof(AbsoluteLayoutFlags), typeof(AbsoluteLayout), AbsoluteLayoutFlags.None);
public static readonly BindableProperty LayoutBoundsProperty = BindableProperty.CreateAttached("LayoutBounds", typeof(Rectangle), typeof(AbsoluteLayout), new Rectangle(0, 0, AutoSize, AutoSize));
readonly AbsoluteElementCollection _children;
public AbsoluteLayout()
{
_children = new AbsoluteElementCollection(InternalChildren, this);
}
public static double AutoSize
{
get { return -1; }
}
public new IAbsoluteList<View> Children
{
get { return _children; }
}
[TypeConverter(typeof(BoundsTypeConverter))]
public static Rectangle GetLayoutBounds(BindableObject bindable)
{
return (Rectangle)bindable.GetValue(LayoutBoundsProperty);
}
public static AbsoluteLayoutFlags GetLayoutFlags(BindableObject bindable)
{
return (AbsoluteLayoutFlags)bindable.GetValue(LayoutFlagsProperty);
}
public static void SetLayoutBounds(BindableObject bindable, Rectangle bounds)
{
bindable.SetValue(LayoutBoundsProperty, bounds);
}
public static void SetLayoutFlags(BindableObject bindable, AbsoluteLayoutFlags flags)
{
bindable.SetValue(LayoutFlagsProperty, flags);
}
protected override void LayoutChildren(double x, double y, double width, double height)
{
foreach (View child in LogicalChildren)
{
Rectangle rect = ComputeLayoutForRegion(child, new Size(width, height));
rect.X += x;
rect.Y += y;
LayoutChildIntoBoundingRegion(child, rect);
}
}
protected override void OnChildAdded(Element child)
{
base.OnChildAdded(child);
child.PropertyChanged += ChildOnPropertyChanged;
}
protected override void OnChildRemoved(Element child)
{
child.PropertyChanged -= ChildOnPropertyChanged;
base.OnChildRemoved(child);
}
[Obsolete("Use OnMeasure")]
protected override SizeRequest OnSizeRequest(double widthConstraint, double heightConstraint)
{
var bestFitSize = new Size();
var minimum = new Size();
foreach (View child in LogicalChildren)
{
SizeRequest desiredSize = ComputeBoundingRegionDesiredSize(child);
bestFitSize.Width = Math.Max(bestFitSize.Width, desiredSize.Request.Width);
bestFitSize.Height = Math.Max(bestFitSize.Height, desiredSize.Request.Height);
minimum.Width = Math.Max(minimum.Width, desiredSize.Minimum.Width);
minimum.Height = Math.Max(minimum.Height, desiredSize.Minimum.Height);
}
return new SizeRequest(bestFitSize, minimum);
}
internal override void ComputeConstraintForView(View view)
{
AbsoluteLayoutFlags layoutFlags = GetLayoutFlags(view);
if ((layoutFlags & AbsoluteLayoutFlags.SizeProportional) == AbsoluteLayoutFlags.SizeProportional)
{
view.ComputedConstraint = Constraint;
return;
}
var result = LayoutConstraint.None;
Rectangle layoutBounds = GetLayoutBounds(view);
if ((layoutFlags & AbsoluteLayoutFlags.HeightProportional) != 0)
{
bool widthLocked = layoutBounds.Width != AutoSize;
result = Constraint & LayoutConstraint.VerticallyFixed;
if (widthLocked)
result |= LayoutConstraint.HorizontallyFixed;
}
else if ((layoutFlags & AbsoluteLayoutFlags.WidthProportional) != 0)
{
bool heightLocked = layoutBounds.Height != AutoSize;
result = Constraint & LayoutConstraint.HorizontallyFixed;
if (heightLocked)
result |= LayoutConstraint.VerticallyFixed;
}
else
{
if (layoutBounds.Width != AutoSize)
result |= LayoutConstraint.HorizontallyFixed;
if (layoutBounds.Height != AutoSize)
result |= LayoutConstraint.VerticallyFixed;
}
view.ComputedConstraint = result;
}
void ChildOnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == LayoutFlagsProperty.PropertyName || e.PropertyName == LayoutBoundsProperty.PropertyName)
{
InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
UpdateChildrenLayout();
}
}
static SizeRequest ComputeBoundingRegionDesiredSize(View view)
{
var width = 0.0;
var height = 0.0;
var sizeRequest = new Lazy<SizeRequest>(() => view.Measure(double.PositiveInfinity, double.PositiveInfinity, MeasureFlags.IncludeMargins));
Rectangle bounds = GetLayoutBounds(view);
AbsoluteLayoutFlags absFlags = GetLayoutFlags(view);
bool widthIsProportional = (absFlags & AbsoluteLayoutFlags.WidthProportional) != 0;
bool heightIsProportional = (absFlags & AbsoluteLayoutFlags.HeightProportional) != 0;
bool xIsProportional = (absFlags & AbsoluteLayoutFlags.XProportional) != 0;
bool yIsProportional = (absFlags & AbsoluteLayoutFlags.YProportional) != 0;
// add in required x values
if (!xIsProportional)
{
width += bounds.X;
}
if (!yIsProportional)
{
height += bounds.Y;
}
double minWidth = width;
double minHeight = height;
if (!widthIsProportional && bounds.Width != AutoSize)
{
// fixed size
width += bounds.Width;
minWidth += bounds.Width;
}
else if (!widthIsProportional)
{
// auto size
width += sizeRequest.Value.Request.Width;
minWidth += sizeRequest.Value.Minimum.Width;
}
else
{
// proportional size
width += sizeRequest.Value.Request.Width / Math.Max(0.25, bounds.Width);
//minWidth += 0;
}
if (!heightIsProportional && bounds.Height != AutoSize)
{
// fixed size
height += bounds.Height;
minHeight += bounds.Height;
}
else if (!heightIsProportional)
{
// auto size
height += sizeRequest.Value.Request.Height;
minHeight += sizeRequest.Value.Minimum.Height;
}
else
{
// proportional size
height += sizeRequest.Value.Request.Height / Math.Max(0.25, bounds.Height);
//minHeight += 0;
}
return new SizeRequest(new Size(width, height), new Size(minWidth, minHeight));
}
static Rectangle ComputeLayoutForRegion(View view, Size region)
{
var result = new Rectangle();
SizeRequest sizeRequest;
Rectangle bounds = GetLayoutBounds(view);
AbsoluteLayoutFlags absFlags = GetLayoutFlags(view);
bool widthIsProportional = (absFlags & AbsoluteLayoutFlags.WidthProportional) != 0;
bool heightIsProportional = (absFlags & AbsoluteLayoutFlags.HeightProportional) != 0;
bool xIsProportional = (absFlags & AbsoluteLayoutFlags.XProportional) != 0;
bool yIsProportional = (absFlags & AbsoluteLayoutFlags.YProportional) != 0;
if (widthIsProportional)
{
result.Width = Math.Round(region.Width * bounds.Width);
}
else if (bounds.Width != AutoSize)
{
result.Width = bounds.Width;
}
if (heightIsProportional)
{
result.Height = Math.Round(region.Height * bounds.Height);
}
else if (bounds.Height != AutoSize)
{
result.Height = bounds.Height;
}
if (!widthIsProportional && bounds.Width == AutoSize)
{
if (!heightIsProportional && bounds.Width == AutoSize)
{
// Width and Height are auto
sizeRequest = view.Measure(region.Width, region.Height, MeasureFlags.IncludeMargins);
result.Width = sizeRequest.Request.Width;
result.Height = sizeRequest.Request.Height;
}
else
{
// Only width is auto
sizeRequest = view.Measure(region.Width, result.Height, MeasureFlags.IncludeMargins);
result.Width = sizeRequest.Request.Width;
}
}
else if (!heightIsProportional && bounds.Height == AutoSize)
{
// Only height is auto
sizeRequest = view.Measure(result.Width, region.Height, MeasureFlags.IncludeMargins);
result.Height = sizeRequest.Request.Height;
}
if (xIsProportional)
{
result.X = Math.Round((region.Width - result.Width) * bounds.X);
}
else
{
result.X = bounds.X;
}
if (yIsProportional)
{
result.Y = Math.Round((region.Height - result.Height) * bounds.Y);
}
else
{
result.Y = bounds.Y;
}
return result;
}
public interface IAbsoluteList<T> : IList<T> where T : View
{
void Add(View view, Rectangle bounds, AbsoluteLayoutFlags flags = AbsoluteLayoutFlags.None);
void Add(View view, Point position);
}
class AbsoluteElementCollection : ElementCollection<View>, IAbsoluteList<View>
{
public AbsoluteElementCollection(ObservableCollection<Element> inner, AbsoluteLayout parent) : base(inner)
{
Parent = parent;
}
internal AbsoluteLayout Parent { get; set; }
public void Add(View view, Rectangle bounds, AbsoluteLayoutFlags flags = AbsoluteLayoutFlags.None)
{
SetLayoutBounds(view, bounds);
SetLayoutFlags(view, flags);
Add(view);
}
public void Add(View view, Point position)
{
SetLayoutBounds(view, new Rectangle(position.X, position.Y, AutoSize, AutoSize));
Add(view);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Reflection.Metadata
{
/// <summary>
/// Reads metadata as defined byte the ECMA 335 CLI specification.
/// </summary>
public sealed partial class MetadataReader
{
private readonly MetadataReaderOptions options;
internal readonly MetadataStringDecoder utf8Decoder;
internal readonly NamespaceCache namespaceCache;
private Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>> lazyNestedTypesMap;
internal readonly MemoryBlock Block;
// A row id of "mscorlib" AssemblyRef in a WinMD file (each WinMD file must have such a reference).
internal readonly uint WinMDMscorlibRef;
#region Constructors
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// </remarks>
public unsafe MetadataReader(byte* metadata, int length)
: this(metadata, length, MetadataReaderOptions.Default, null)
{
}
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions)"/> to obtain
/// metadata from a PE image.
/// </remarks>
public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options)
: this(metadata, length, options, null)
{
}
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions, MetadataStringDecoder)"/> to obtain
/// metadata from a PE image.
/// </remarks>
public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder utf8Decoder)
{
if (length <= 0)
{
throw new ArgumentOutOfRangeException("length");
}
if (metadata == null)
{
throw new ArgumentNullException("metadata");
}
if (utf8Decoder == null)
{
utf8Decoder = MetadataStringDecoder.DefaultUTF8;
}
if (!(utf8Decoder.Encoding is UTF8Encoding))
{
throw new ArgumentException(MetadataResources.MetadataStringDecoderEncodingMustBeUtf8, "utf8Decoder");
}
if (!BitConverter.IsLittleEndian)
{
throw new PlatformNotSupportedException(MetadataResources.LitteEndianArchitectureRequired);
}
this.Block = new MemoryBlock(metadata, length);
this.options = options;
this.utf8Decoder = utf8Decoder;
BlobReader memReader = new BlobReader(this.Block);
this.ReadMetadataHeader(ref memReader);
// storage header and stream headers:
MemoryBlock metadataTableStream;
var streamHeaders = this.ReadStreamHeaders(ref memReader);
this.InitializeStreamReaders(ref this.Block, streamHeaders, out metadataTableStream);
memReader = new BlobReader(metadataTableStream);
uint[] metadataTableRowCounts;
this.ReadMetadataTableHeader(ref memReader, out metadataTableRowCounts);
this.InitializeTableReaders(memReader.GetMemoryBlockAt(0, memReader.RemainingBytes), metadataTableRowCounts);
// This previously could occur in obfuscated assemblies but a check was added to prevent
// it getting to this point
Debug.Assert(this.AssemblyTable.NumberOfRows <= 1);
// Although the specification states that the module table will have exactly one row,
// the native metadata reader would successfully read files containing more than one row.
// Such files exist in the wild and may be produced by obfuscators.
if (this.ModuleTable.NumberOfRows < 1)
{
throw new BadImageFormatException(string.Format(MetadataResources.ModuleTableInvalidNumberOfRows, this.ModuleTable.NumberOfRows));
}
// read
this.namespaceCache = new NamespaceCache(this);
if (this.metadataKind != MetadataKind.Ecma335)
{
this.WinMDMscorlibRef = FindMscorlibAssemblyRefNoProjection();
}
}
#endregion
#region Metadata Headers
private MetadataHeader metadataHeader;
private MetadataKind metadataKind;
private MetadataStreamKind metadataStreamKind;
internal StringStreamReader StringStream;
internal BlobStreamReader BlobStream;
internal GuidStreamReader GuidStream;
internal UserStringStreamReader UserStringStream;
/// <summary>
/// True if the metadata stream has minimal delta format. Used for EnC.
/// </summary>
/// <remarks>
/// The metadata stream has minimal delta format if "#JTD" stream is present.
/// Minimal delta format uses large size (4B) when encoding table/heap references.
/// The heaps in minimal delta only contain data of the delta,
/// there is no padding at the beginning of the heaps that would align them
/// with the original full metadata heaps.
/// </remarks>
internal bool IsMinimalDelta;
/// <summary>
/// Looks like this function reads beginning of the header described in
/// Ecma-335 24.2.1 Metadata root
/// </summary>
private void ReadMetadataHeader(ref BlobReader memReader)
{
if (memReader.RemainingBytes < COR20Constants.MinimumSizeofMetadataHeader)
{
throw new BadImageFormatException(MetadataResources.MetadataHeaderTooSmall);
}
this.metadataHeader.Signature = memReader.ReadUInt32();
if (this.metadataHeader.Signature != COR20Constants.COR20MetadataSignature)
{
throw new BadImageFormatException(MetadataResources.MetadataSignature);
}
this.metadataHeader.MajorVersion = memReader.ReadUInt16();
this.metadataHeader.MinorVersion = memReader.ReadUInt16();
this.metadataHeader.ExtraData = memReader.ReadUInt32();
this.metadataHeader.VersionStringSize = memReader.ReadInt32();
if (memReader.RemainingBytes < this.metadataHeader.VersionStringSize)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForVersionString);
}
int numberOfBytesRead;
this.metadataHeader.VersionString = memReader.GetMemoryBlockAt(0, this.metadataHeader.VersionStringSize).PeekUtf8NullTerminated(0, null, utf8Decoder, out numberOfBytesRead, '\0');
memReader.SkipBytes(this.metadataHeader.VersionStringSize);
this.metadataKind = GetMetadataKind(metadataHeader.VersionString);
}
private MetadataKind GetMetadataKind(string versionString)
{
// Treat metadata as CLI raw metadata if the client doesn't want to see projections.
if ((options & MetadataReaderOptions.ApplyWindowsRuntimeProjections) == 0)
{
return MetadataKind.Ecma335;
}
if (!versionString.Contains("WindowsRuntime"))
{
return MetadataKind.Ecma335;
}
else if (versionString.Contains("CLR"))
{
return MetadataKind.ManagedWindowsMetadata;
}
else
{
return MetadataKind.WindowsMetadata;
}
}
/// <summary>
/// Reads stream headers described in Ecma-335 24.2.2 Stream header
/// </summary>
private StreamHeader[] ReadStreamHeaders(ref BlobReader memReader)
{
// storage header:
memReader.ReadUInt16();
int streamCount = memReader.ReadInt16();
var streamHeaders = new StreamHeader[streamCount];
for (int i = 0; i < streamHeaders.Length; i++)
{
if (memReader.RemainingBytes < COR20Constants.MinimumSizeofStreamHeader)
{
throw new BadImageFormatException(MetadataResources.StreamHeaderTooSmall);
}
streamHeaders[i].Offset = memReader.ReadUInt32();
streamHeaders[i].Size = memReader.ReadInt32();
streamHeaders[i].Name = memReader.ReadUtf8NullTerminated();
bool aligned = memReader.TryAlign(4);
if (!aligned || memReader.RemainingBytes == 0)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForStreamHeaderName);
}
}
return streamHeaders;
}
private void InitializeStreamReaders(ref MemoryBlock metadataRoot, StreamHeader[] streamHeaders, out MemoryBlock metadataTableStream)
{
metadataTableStream = default(MemoryBlock);
foreach (StreamHeader streamHeader in streamHeaders)
{
switch (streamHeader.Name)
{
case COR20Constants.StringStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForStringStream);
}
this.StringStream = new StringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), this.metadataKind);
break;
case COR20Constants.BlobStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForBlobStream);
}
this.BlobStream = new BlobStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), this.metadataKind);
break;
case COR20Constants.GUIDStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForGUIDStream);
}
this.GuidStream = new GuidStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size));
break;
case COR20Constants.UserStringStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForBlobStream);
}
this.UserStringStream = new UserStringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size));
break;
case COR20Constants.CompressedMetadataTableStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForMetadataStream);
}
this.metadataStreamKind = MetadataStreamKind.Compressed;
metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size);
break;
case COR20Constants.UncompressedMetadataTableStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForMetadataStream);
}
this.metadataStreamKind = MetadataStreamKind.Uncompressed;
metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size);
break;
case COR20Constants.MinimalDeltaMetadataTableStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(MetadataResources.NotEnoughSpaceForMetadataStream);
}
// the content of the stream is ignored
this.IsMinimalDelta = true;
break;
default:
// Skip unknown streams. Some obfuscators insert invalid streams.
continue;
}
}
if (IsMinimalDelta && metadataStreamKind != MetadataStreamKind.Uncompressed)
{
throw new BadImageFormatException(MetadataResources.InvalidMetadataStreamFormat);
}
}
#endregion
#region Tables and Heaps
private MetadataTableHeader MetadataTableHeader;
/// <summary>
/// A row count for each possible table. May be indexed by <see cref="TableIndex"/>.
/// </summary>
internal uint[] TableRowCounts;
internal ModuleTableReader ModuleTable;
internal TypeRefTableReader TypeRefTable;
internal TypeDefTableReader TypeDefTable;
internal FieldPtrTableReader FieldPtrTable;
internal FieldTableReader FieldTable;
internal MethodPtrTableReader MethodPtrTable;
internal MethodTableReader MethodDefTable;
internal ParamPtrTableReader ParamPtrTable;
internal ParamTableReader ParamTable;
internal InterfaceImplTableReader InterfaceImplTable;
internal MemberRefTableReader MemberRefTable;
internal ConstantTableReader ConstantTable;
internal CustomAttributeTableReader CustomAttributeTable;
internal FieldMarshalTableReader FieldMarshalTable;
internal DeclSecurityTableReader DeclSecurityTable;
internal ClassLayoutTableReader ClassLayoutTable;
internal FieldLayoutTableReader FieldLayoutTable;
internal StandAloneSigTableReader StandAloneSigTable;
internal EventMapTableReader EventMapTable;
internal EventPtrTableReader EventPtrTable;
internal EventTableReader EventTable;
internal PropertyMapTableReader PropertyMapTable;
internal PropertyPtrTableReader PropertyPtrTable;
internal PropertyTableReader PropertyTable;
internal MethodSemanticsTableReader MethodSemanticsTable;
internal MethodImplTableReader MethodImplTable;
internal ModuleRefTableReader ModuleRefTable;
internal TypeSpecTableReader TypeSpecTable;
internal ImplMapTableReader ImplMapTable;
internal FieldRVATableReader FieldRvaTable;
internal EnCLogTableReader EncLogTable;
internal EnCMapTableReader EncMapTable;
internal AssemblyTableReader AssemblyTable;
internal AssemblyProcessorTableReader AssemblyProcessorTable; // unused
internal AssemblyOSTableReader AssemblyOSTable; // unused
internal AssemblyRefTableReader AssemblyRefTable;
internal AssemblyRefProcessorTableReader AssemblyRefProcessorTable; // unused
internal AssemblyRefOSTableReader AssemblyRefOSTable; // unused
internal FileTableReader FileTable;
internal ExportedTypeTableReader ExportedTypeTable;
internal ManifestResourceTableReader ManifestResourceTable;
internal NestedClassTableReader NestedClassTable;
internal GenericParamTableReader GenericParamTable;
internal MethodSpecTableReader MethodSpecTable;
internal GenericParamConstraintTableReader GenericParamConstraintTable;
private void ReadMetadataTableHeader(ref BlobReader memReader, out uint[] metadataTableRowCounts)
{
if (memReader.RemainingBytes < MetadataStreamConstants.SizeOfMetadataTableHeader)
{
throw new BadImageFormatException(MetadataResources.MetadataTableHeaderTooSmall);
}
this.MetadataTableHeader.Reserved = memReader.ReadUInt32();
this.MetadataTableHeader.MajorVersion = memReader.ReadByte();
this.MetadataTableHeader.MinorVersion = memReader.ReadByte();
this.MetadataTableHeader.HeapSizeFlags = (HeapSizeFlag)memReader.ReadByte();
this.MetadataTableHeader.RowId = memReader.ReadByte();
this.MetadataTableHeader.ValidTables = (TableMask)memReader.ReadUInt64();
this.MetadataTableHeader.SortedTables = (TableMask)memReader.ReadUInt64();
ulong presentTables = (ulong)this.MetadataTableHeader.ValidTables;
// According to ECMA-335, MajorVersion and MinorVersion have fixed values and,
// based on recommendation in 24.1 Fixed fields: When writing these fields it
// is best that they be set to the value indicated, on reading they should be ignored.?
// we will not be checking version values. We will continue checking that the set of
// present tables is within the set we understand.
ulong validTables = (ulong)TableMask.V2_0_TablesMask;
if ((presentTables & ~validTables) != 0)
{
throw new BadImageFormatException(string.Format(MetadataResources.UnknownTables, presentTables));
}
if (this.metadataStreamKind == MetadataStreamKind.Compressed)
{
// In general Ptr tables and EnC tables are not allowed in a compressed stream.
// However when asked for a snapshot of the current metadata after an EnC change has been applied
// the CLR includes the EnCLog table into the snapshot. We need to be able to read the image,
// so we'll allow the table here but pretend it's empty later.
if ((presentTables & (ulong)(TableMask.PtrTables | TableMask.EnCMap)) != 0)
{
throw new BadImageFormatException(MetadataResources.IllegalTablesInCompressedMetadataStream);
}
}
int numberOfTables = this.MetadataTableHeader.GetNumberOfTablesPresent();
if (memReader.RemainingBytes < numberOfTables * sizeof(int))
{
throw new BadImageFormatException(MetadataResources.TableRowCountSpaceTooSmall);
}
var rowCounts = new uint[numberOfTables];
for (int i = 0; i < rowCounts.Length; i++)
{
rowCounts[i] = memReader.ReadUInt32();
}
metadataTableRowCounts = rowCounts;
}
private const int SmallIndexSize = 2;
private const int LargeIndexSize = 4;
private void InitializeTableReaders(MemoryBlock metadataTablesMemoryBlock, uint[] compressedRowCounts)
{
// Only sizes of tables present in metadata are recorded in rowCountCompressedArray.
// This array contains a slot for each possible table, not just those that are present in the metadata.
uint[] rowCounts = new uint[TableIndexExtensions.Count];
// Size of reference tags in each table.
int[] referenceSizes = new int[TableIndexExtensions.Count];
ulong validTables = (ulong)this.MetadataTableHeader.ValidTables;
int compressedRowCountIndex = 0;
for (int i = 0; i < TableIndexExtensions.Count; i++)
{
bool fitsSmall;
if ((validTables & 1UL) != 0)
{
uint rowCount = compressedRowCounts[compressedRowCountIndex++];
rowCounts[i] = rowCount;
fitsSmall = rowCount < MetadataStreamConstants.LargeTableRowCount;
}
else
{
fitsSmall = true;
}
referenceSizes[i] = (fitsSmall && !IsMinimalDelta) ? SmallIndexSize : LargeIndexSize;
validTables >>= 1;
}
this.TableRowCounts = rowCounts;
// Compute ref sizes for tables that can have pointer tables for it
int fieldRefSize = referenceSizes[(int)TableIndex.FieldPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Field];
int methodRefSize = referenceSizes[(int)TableIndex.MethodPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.MethodDef];
int paramRefSize = referenceSizes[(int)TableIndex.ParamPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Param];
int eventRefSize = referenceSizes[(int)TableIndex.EventPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Event];
int propertyRefSize = referenceSizes[(int)TableIndex.PropertyPtr] > SmallIndexSize ? LargeIndexSize : referenceSizes[(int)TableIndex.Property];
// Compute the coded token ref sizes
int typeDefOrRefRefSize = ComputeCodedTokenSize(TypeDefOrRefTag.LargeRowSize, rowCounts, TypeDefOrRefTag.TablesReferenced);
int hasConstantRefSize = ComputeCodedTokenSize(HasConstantTag.LargeRowSize, rowCounts, HasConstantTag.TablesReferenced);
int hasCustomAttributeRefSize = ComputeCodedTokenSize(HasCustomAttributeTag.LargeRowSize, rowCounts, HasCustomAttributeTag.TablesReferenced);
int hasFieldMarshalRefSize = ComputeCodedTokenSize(HasFieldMarshalTag.LargeRowSize, rowCounts, HasFieldMarshalTag.TablesReferenced);
int hasDeclSecurityRefSize = ComputeCodedTokenSize(HasDeclSecurityTag.LargeRowSize, rowCounts, HasDeclSecurityTag.TablesReferenced);
int memberRefParentRefSize = ComputeCodedTokenSize(MemberRefParentTag.LargeRowSize, rowCounts, MemberRefParentTag.TablesReferenced);
int hasSemanticsRefSize = ComputeCodedTokenSize(HasSemanticsTag.LargeRowSize, rowCounts, HasSemanticsTag.TablesReferenced);
int methodDefOrRefRefSize = ComputeCodedTokenSize(MethodDefOrRefTag.LargeRowSize, rowCounts, MethodDefOrRefTag.TablesReferenced);
int memberForwardedRefSize = ComputeCodedTokenSize(MemberForwardedTag.LargeRowSize, rowCounts, MemberForwardedTag.TablesReferenced);
int implementationRefSize = ComputeCodedTokenSize(ImplementationTag.LargeRowSize, rowCounts, ImplementationTag.TablesReferenced);
int customAttributeTypeRefSize = ComputeCodedTokenSize(CustomAttributeTypeTag.LargeRowSize, rowCounts, CustomAttributeTypeTag.TablesReferenced);
int resolutionScopeRefSize = ComputeCodedTokenSize(ResolutionScopeTag.LargeRowSize, rowCounts, ResolutionScopeTag.TablesReferenced);
int typeOrMethodDefRefSize = ComputeCodedTokenSize(TypeOrMethodDefTag.LargeRowSize, rowCounts, TypeOrMethodDefTag.TablesReferenced);
// Compute HeapRef Sizes
int stringHeapRefSize = (this.MetadataTableHeader.HeapSizeFlags & HeapSizeFlag.StringHeapLarge) == HeapSizeFlag.StringHeapLarge ? LargeIndexSize : SmallIndexSize;
int guidHeapRefSize = (this.MetadataTableHeader.HeapSizeFlags & HeapSizeFlag.GuidHeapLarge) == HeapSizeFlag.GuidHeapLarge ? LargeIndexSize : SmallIndexSize;
int blobHeapRefSize = (this.MetadataTableHeader.HeapSizeFlags & HeapSizeFlag.BlobHeapLarge) == HeapSizeFlag.BlobHeapLarge ? LargeIndexSize : SmallIndexSize;
// Populate the Table blocks
int totalRequiredSize = 0;
this.ModuleTable = new ModuleTableReader(rowCounts[(int)TableIndex.Module], stringHeapRefSize, guidHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ModuleTable.Block.Length;
this.TypeRefTable = new TypeRefTableReader(rowCounts[(int)TableIndex.TypeRef], resolutionScopeRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.TypeRefTable.Block.Length;
this.TypeDefTable = new TypeDefTableReader(rowCounts[(int)TableIndex.TypeDef], fieldRefSize, methodRefSize, typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.TypeDefTable.Block.Length;
this.FieldPtrTable = new FieldPtrTableReader(rowCounts[(int)TableIndex.FieldPtr], referenceSizes[(int)TableIndex.Field], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldPtrTable.Block.Length;
this.FieldTable = new FieldTableReader(rowCounts[(int)TableIndex.Field], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldTable.Block.Length;
this.MethodPtrTable = new MethodPtrTableReader(rowCounts[(int)TableIndex.MethodPtr], referenceSizes[(int)TableIndex.MethodDef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodPtrTable.Block.Length;
this.MethodDefTable = new MethodTableReader(rowCounts[(int)TableIndex.MethodDef], paramRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodDefTable.Block.Length;
this.ParamPtrTable = new ParamPtrTableReader(rowCounts[(int)TableIndex.ParamPtr], referenceSizes[(int)TableIndex.Param], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ParamPtrTable.Block.Length;
this.ParamTable = new ParamTableReader(rowCounts[(int)TableIndex.Param], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ParamTable.Block.Length;
this.InterfaceImplTable = new InterfaceImplTableReader(rowCounts[(int)TableIndex.InterfaceImpl], IsDeclaredSorted(TableMask.InterfaceImpl), referenceSizes[(int)TableIndex.TypeDef], typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.InterfaceImplTable.Block.Length;
this.MemberRefTable = new MemberRefTableReader(rowCounts[(int)TableIndex.MemberRef], memberRefParentRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MemberRefTable.Block.Length;
this.ConstantTable = new ConstantTableReader(rowCounts[(int)TableIndex.Constant], IsDeclaredSorted(TableMask.Constant), hasConstantRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ConstantTable.Block.Length;
this.CustomAttributeTable = new CustomAttributeTableReader(rowCounts[(int)TableIndex.CustomAttribute],
IsDeclaredSorted(TableMask.CustomAttribute),
hasCustomAttributeRefSize,
customAttributeTypeRefSize,
blobHeapRefSize,
metadataTablesMemoryBlock,
totalRequiredSize);
totalRequiredSize += this.CustomAttributeTable.Block.Length;
this.FieldMarshalTable = new FieldMarshalTableReader(rowCounts[(int)TableIndex.FieldMarshal], IsDeclaredSorted(TableMask.FieldMarshal), hasFieldMarshalRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldMarshalTable.Block.Length;
this.DeclSecurityTable = new DeclSecurityTableReader(rowCounts[(int)TableIndex.DeclSecurity], IsDeclaredSorted(TableMask.DeclSecurity), hasDeclSecurityRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.DeclSecurityTable.Block.Length;
this.ClassLayoutTable = new ClassLayoutTableReader(rowCounts[(int)TableIndex.ClassLayout], IsDeclaredSorted(TableMask.ClassLayout), referenceSizes[(int)TableIndex.TypeDef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ClassLayoutTable.Block.Length;
this.FieldLayoutTable = new FieldLayoutTableReader(rowCounts[(int)TableIndex.FieldLayout], IsDeclaredSorted(TableMask.FieldLayout), referenceSizes[(int)TableIndex.Field], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldLayoutTable.Block.Length;
this.StandAloneSigTable = new StandAloneSigTableReader(rowCounts[(int)TableIndex.StandAloneSig], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.StandAloneSigTable.Block.Length;
this.EventMapTable = new EventMapTableReader(rowCounts[(int)TableIndex.EventMap], referenceSizes[(int)TableIndex.TypeDef], eventRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EventMapTable.Block.Length;
this.EventPtrTable = new EventPtrTableReader(rowCounts[(int)TableIndex.EventPtr], referenceSizes[(int)TableIndex.Event], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EventPtrTable.Block.Length;
this.EventTable = new EventTableReader(rowCounts[(int)TableIndex.Event], typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EventTable.Block.Length;
this.PropertyMapTable = new PropertyMapTableReader(rowCounts[(int)TableIndex.PropertyMap], referenceSizes[(int)TableIndex.TypeDef], propertyRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.PropertyMapTable.Block.Length;
this.PropertyPtrTable = new PropertyPtrTableReader(rowCounts[(int)TableIndex.PropertyPtr], referenceSizes[(int)TableIndex.Property], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.PropertyPtrTable.Block.Length;
this.PropertyTable = new PropertyTableReader(rowCounts[(int)TableIndex.Property], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.PropertyTable.Block.Length;
this.MethodSemanticsTable = new MethodSemanticsTableReader(rowCounts[(int)TableIndex.MethodSemantics], IsDeclaredSorted(TableMask.MethodSemantics), referenceSizes[(int)TableIndex.MethodDef], hasSemanticsRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodSemanticsTable.Block.Length;
this.MethodImplTable = new MethodImplTableReader(rowCounts[(int)TableIndex.MethodImpl], IsDeclaredSorted(TableMask.MethodImpl), referenceSizes[(int)TableIndex.TypeDef], methodDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodImplTable.Block.Length;
this.ModuleRefTable = new ModuleRefTableReader(rowCounts[(int)TableIndex.ModuleRef], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ModuleRefTable.Block.Length;
this.TypeSpecTable = new TypeSpecTableReader(rowCounts[(int)TableIndex.TypeSpec], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.TypeSpecTable.Block.Length;
this.ImplMapTable = new ImplMapTableReader(rowCounts[(int)TableIndex.ImplMap], IsDeclaredSorted(TableMask.ImplMap), referenceSizes[(int)TableIndex.ModuleRef], memberForwardedRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ImplMapTable.Block.Length;
this.FieldRvaTable = new FieldRVATableReader(rowCounts[(int)TableIndex.FieldRva], IsDeclaredSorted(TableMask.FieldRva), referenceSizes[(int)TableIndex.Field], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldRvaTable.Block.Length;
this.EncLogTable = new EnCLogTableReader(rowCounts[(int)TableIndex.EncLog], metadataTablesMemoryBlock, totalRequiredSize, this.metadataStreamKind);
totalRequiredSize += this.EncLogTable.Block.Length;
this.EncMapTable = new EnCMapTableReader(rowCounts[(int)TableIndex.EncMap], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EncMapTable.Block.Length;
this.AssemblyTable = new AssemblyTableReader(rowCounts[(int)TableIndex.Assembly], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyTable.Block.Length;
this.AssemblyProcessorTable = new AssemblyProcessorTableReader(rowCounts[(int)TableIndex.AssemblyProcessor], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyProcessorTable.Block.Length;
this.AssemblyOSTable = new AssemblyOSTableReader(rowCounts[(int)TableIndex.AssemblyOS], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyOSTable.Block.Length;
this.AssemblyRefTable = new AssemblyRefTableReader((int)rowCounts[(int)TableIndex.AssemblyRef], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize, this.metadataKind);
totalRequiredSize += this.AssemblyRefTable.Block.Length;
this.AssemblyRefProcessorTable = new AssemblyRefProcessorTableReader(rowCounts[(int)TableIndex.AssemblyRefProcessor], referenceSizes[(int)TableIndex.AssemblyRef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyRefProcessorTable.Block.Length;
this.AssemblyRefOSTable = new AssemblyRefOSTableReader(rowCounts[(int)TableIndex.AssemblyRefOS], referenceSizes[(int)TableIndex.AssemblyRef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyRefOSTable.Block.Length;
this.FileTable = new FileTableReader(rowCounts[(int)TableIndex.File], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FileTable.Block.Length;
this.ExportedTypeTable = new ExportedTypeTableReader(rowCounts[(int)TableIndex.ExportedType], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ExportedTypeTable.Block.Length;
this.ManifestResourceTable = new ManifestResourceTableReader(rowCounts[(int)TableIndex.ManifestResource], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ManifestResourceTable.Block.Length;
this.NestedClassTable = new NestedClassTableReader(rowCounts[(int)TableIndex.NestedClass], IsDeclaredSorted(TableMask.NestedClass), referenceSizes[(int)TableIndex.TypeDef], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.NestedClassTable.Block.Length;
this.GenericParamTable = new GenericParamTableReader(rowCounts[(int)TableIndex.GenericParam], IsDeclaredSorted(TableMask.GenericParam), typeOrMethodDefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.GenericParamTable.Block.Length;
this.MethodSpecTable = new MethodSpecTableReader(rowCounts[(int)TableIndex.MethodSpec], methodDefOrRefRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodSpecTable.Block.Length;
this.GenericParamConstraintTable = new GenericParamConstraintTableReader(rowCounts[(int)TableIndex.GenericParamConstraint], IsDeclaredSorted(TableMask.GenericParamConstraint), referenceSizes[(int)TableIndex.GenericParam], typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.GenericParamConstraintTable.Block.Length;
if (totalRequiredSize > metadataTablesMemoryBlock.Length)
{
throw new BadImageFormatException(MetadataResources.MetadataTablesTooSmall);
}
}
private int ComputeCodedTokenSize(uint largeRowSize, uint[] rowCountArray, TableMask tablesReferenced)
{
if (IsMinimalDelta)
{
return LargeIndexSize;
}
bool isAllReferencedTablesSmall = true;
ulong tablesReferencedMask = (ulong)tablesReferenced;
for (int tableIndex = 0; tableIndex < TableIndexExtensions.Count; tableIndex++)
{
if ((tablesReferencedMask & 1UL) != 0)
{
isAllReferencedTablesSmall = isAllReferencedTablesSmall && (rowCountArray[tableIndex] < largeRowSize);
}
tablesReferencedMask >>= 1;
}
return isAllReferencedTablesSmall ? SmallIndexSize : LargeIndexSize;
}
private bool IsDeclaredSorted(TableMask index)
{
return (this.MetadataTableHeader.SortedTables & index) != 0;
}
#endregion
#region Helpers
// internal for testing
internal NamespaceCache NamespaceCache
{
get { return namespaceCache; }
}
internal bool UseFieldPtrTable
{
get { return this.FieldPtrTable.NumberOfRows > 0; }
}
internal bool UseMethodPtrTable
{
get { return this.MethodPtrTable.NumberOfRows > 0; }
}
internal bool UseParamPtrTable
{
get { return this.ParamPtrTable.NumberOfRows > 0; }
}
internal bool UseEventPtrTable
{
get { return this.EventPtrTable.NumberOfRows > 0; }
}
internal bool UsePropertyPtrTable
{
get { return this.PropertyPtrTable.NumberOfRows > 0; }
}
internal void GetFieldRange(TypeDefinitionHandle typeDef, out int firstFieldRowId, out int lastFieldRowId)
{
uint typeDefRowId = typeDef.RowId;
firstFieldRowId = (int)this.TypeDefTable.GetFieldStart(typeDefRowId);
if (firstFieldRowId == 0)
{
firstFieldRowId = 1;
lastFieldRowId = 0;
}
else if (typeDefRowId == this.TypeDefTable.NumberOfRows)
{
lastFieldRowId = (int)(this.UseFieldPtrTable ? this.FieldPtrTable.NumberOfRows : this.FieldTable.NumberOfRows);
}
else
{
lastFieldRowId = (int)this.TypeDefTable.GetFieldStart(typeDefRowId + 1) - 1;
}
}
internal void GetMethodRange(TypeDefinitionHandle typeDef, out int firstMethodRowId, out int lastMethodRowId)
{
uint typeDefRowId = typeDef.RowId;
firstMethodRowId = (int)this.TypeDefTable.GetMethodStart(typeDefRowId);
if (firstMethodRowId == 0)
{
firstMethodRowId = 1;
lastMethodRowId = 0;
}
else if (typeDefRowId == this.TypeDefTable.NumberOfRows)
{
lastMethodRowId = (int)(this.UseMethodPtrTable ? this.MethodPtrTable.NumberOfRows : this.MethodDefTable.NumberOfRows);
}
else
{
lastMethodRowId = (int)this.TypeDefTable.GetMethodStart(typeDefRowId + 1) - 1;
}
}
internal void GetEventRange(TypeDefinitionHandle typeDef, out int firstEventRowId, out int lastEventRowId)
{
uint eventMapRowId = this.EventMapTable.FindEventMapRowIdFor(typeDef);
if (eventMapRowId == 0)
{
firstEventRowId = 1;
lastEventRowId = 0;
return;
}
firstEventRowId = (int)this.EventMapTable.GetEventListStartFor(eventMapRowId);
if (eventMapRowId == this.EventMapTable.NumberOfRows)
{
lastEventRowId = (int)(this.UseEventPtrTable ? this.EventPtrTable.NumberOfRows : this.EventTable.NumberOfRows);
}
else
{
lastEventRowId = (int)this.EventMapTable.GetEventListStartFor(eventMapRowId + 1) - 1;
}
}
internal void GetPropertyRange(TypeDefinitionHandle typeDef, out int firstPropertyRowId, out int lastPropertyRowId)
{
uint propertyMapRowId = this.PropertyMapTable.FindPropertyMapRowIdFor(typeDef);
if (propertyMapRowId == 0)
{
firstPropertyRowId = 1;
lastPropertyRowId = 0;
return;
}
firstPropertyRowId = (int)this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId);
if (propertyMapRowId == this.PropertyMapTable.NumberOfRows)
{
lastPropertyRowId = (int)(this.UsePropertyPtrTable ? this.PropertyPtrTable.NumberOfRows : this.PropertyTable.NumberOfRows);
}
else
{
lastPropertyRowId = (int)this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId + 1) - 1;
}
}
internal void GetParameterRange(MethodDefinitionHandle methodDef, out int firstParamRowId, out int lastParamRowId)
{
uint rid = methodDef.RowId;
firstParamRowId = (int)this.MethodDefTable.GetParamStart(rid);
if (firstParamRowId == 0)
{
firstParamRowId = 1;
lastParamRowId = 0;
}
else if (rid == this.MethodDefTable.NumberOfRows)
{
lastParamRowId = (int)(this.UseParamPtrTable ? this.ParamPtrTable.NumberOfRows : this.ParamTable.NumberOfRows);
}
else
{
lastParamRowId = (int)this.MethodDefTable.GetParamStart(rid + 1) - 1;
}
}
// TODO: move throw helpers to common place.
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowValueArgumentNull()
{
throw new ArgumentNullException("value");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ThrowTableNotSorted(TableIndex tableIndex)
{
throw new BadImageFormatException(string.Format(MetadataResources.MetadataTableNotSorted, (int)tableIndex));
}
#endregion
#region Public APIs
public MetadataReaderOptions Options
{
get { return this.options; }
}
public string MetadataVersion
{
get { return metadataHeader.VersionString; }
}
public MetadataKind MetadataKind
{
get { return metadataKind; }
}
public MetadataStringComparer StringComparer
{
get { return new MetadataStringComparer(this); }
}
public bool IsAssembly
{
get { return this.AssemblyTable.NumberOfRows == 1; }
}
public AssemblyReferenceHandleCollection AssemblyReferences
{
get { return new AssemblyReferenceHandleCollection(this); }
}
public TypeDefinitionHandleCollection TypeDefinitions
{
get { return new TypeDefinitionHandleCollection((int)TypeDefTable.NumberOfRows); }
}
public TypeReferenceHandleCollection TypeReferences
{
get { return new TypeReferenceHandleCollection((int)TypeRefTable.NumberOfRows); }
}
public CustomAttributeHandleCollection CustomAttributes
{
get { return new CustomAttributeHandleCollection(this); }
}
public DeclarativeSecurityAttributeHandleCollection DeclarativeSecurityAttributes
{
get { return new DeclarativeSecurityAttributeHandleCollection(this); }
}
public MemberReferenceHandleCollection MemberReferences
{
get { return new MemberReferenceHandleCollection((int)MemberRefTable.NumberOfRows); }
}
public ManifestResourceHandleCollection ManifestResources
{
get { return new ManifestResourceHandleCollection((int)ManifestResourceTable.NumberOfRows); }
}
public AssemblyFileHandleCollection AssemblyFiles
{
get { return new AssemblyFileHandleCollection((int)FileTable.NumberOfRows); }
}
public ExportedTypeHandleCollection ExportedTypes
{
get { return new ExportedTypeHandleCollection((int)ExportedTypeTable.NumberOfRows); }
}
public MethodDefinitionHandleCollection MethodDefinitions
{
get { return new MethodDefinitionHandleCollection(this); }
}
public FieldDefinitionHandleCollection FieldDefinitions
{
get { return new FieldDefinitionHandleCollection(this); }
}
public EventDefinitionHandleCollection EventDefinitions
{
get { return new EventDefinitionHandleCollection(this); }
}
public PropertyDefinitionHandleCollection PropertyDefinitions
{
get { return new PropertyDefinitionHandleCollection(this); }
}
public AssemblyDefinition GetAssemblyDefinition()
{
if (!IsAssembly)
{
throw new InvalidOperationException(MetadataResources.MetadataImageDoesNotRepresentAnAssembly);
}
return new AssemblyDefinition(this);
}
public string GetString(StringHandle handle)
{
return StringStream.GetString(handle, utf8Decoder);
}
public string GetString(NamespaceDefinitionHandle handle)
{
if (handle.HasFullName)
{
return StringStream.GetString(handle.GetFullName(), utf8Decoder);
}
return namespaceCache.GetFullName(handle);
}
public byte[] GetBlobBytes(BlobHandle handle)
{
return BlobStream.GetBytes(handle);
}
public ImmutableArray<byte> GetBlobContent(BlobHandle handle)
{
// TODO: We can skip a copy for virtual blobs.
byte[] bytes = GetBlobBytes(handle);
return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes);
}
public BlobReader GetBlobReader(BlobHandle handle)
{
return BlobStream.GetBlobReader(handle);
}
public string GetUserString(UserStringHandle handle)
{
return UserStringStream.GetString(handle);
}
public Guid GetGuid(GuidHandle handle)
{
return GuidStream.GetGuid(handle);
}
public ModuleDefinition GetModuleDefinition()
{
return new ModuleDefinition(this);
}
public AssemblyReference GetAssemblyReference(AssemblyReferenceHandle handle)
{
return new AssemblyReference(this, handle.Token & TokenTypeIds.VirtualBitAndRowIdMask);
}
public TypeDefinition GetTypeDefinition(TypeDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new TypeDefinition(this, GetTypeDefTreatmentAndRowId(handle));
}
public NamespaceDefinition GetNamespaceDefinitionRoot()
{
NamespaceData data = namespaceCache.GetRootNamespace();
return new NamespaceDefinition(data);
}
public NamespaceDefinition GetNamespaceDefinition(NamespaceDefinitionHandle handle)
{
NamespaceData data = namespaceCache.GetNamespaceData(handle);
return new NamespaceDefinition(data);
}
private uint GetTypeDefTreatmentAndRowId(TypeDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateTypeDefTreatmentAndRowId(handle);
}
public TypeReference GetTypeReference(TypeReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new TypeReference(this, GetTypeRefTreatmentAndRowId(handle));
}
private uint GetTypeRefTreatmentAndRowId(TypeReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateTypeRefTreatmentAndRowId(handle);
}
public ExportedType GetExportedType(ExportedTypeHandle handle)
{
return new ExportedType(this, handle.RowId);
}
public CustomAttributeHandleCollection GetCustomAttributes(Handle handle)
{
Debug.Assert(!handle.IsNil);
return new CustomAttributeHandleCollection(this, handle);
}
public CustomAttribute GetCustomAttribute(CustomAttributeHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new CustomAttribute(this, GetCustomAttributeTreatmentAndRowId(handle));
}
private uint GetCustomAttributeTreatmentAndRowId(CustomAttributeHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return TreatmentAndRowId((byte)CustomAttributeTreatment.WinMD, handle.RowId);
}
public DeclarativeSecurityAttribute GetDeclarativeSecurityAttribute(DeclarativeSecurityAttributeHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new DeclarativeSecurityAttribute(this, handle.RowId);
}
public Constant GetConstant(ConstantHandle handle)
{
return new Constant(this, handle.RowId);
}
public MethodDefinition GetMethodDefinition(MethodDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new MethodDefinition(this, GetMethodDefTreatmentAndRowId(handle));
}
private uint GetMethodDefTreatmentAndRowId(MethodDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateMethodDefTreatmentAndRowId(handle);
}
public FieldDefinition GetFieldDefinition(FieldDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new FieldDefinition(this, GetFieldDefTreatmentAndRowId(handle));
}
private uint GetFieldDefTreatmentAndRowId(FieldDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateFieldDefTreatmentAndRowId(handle);
}
public PropertyDefinition GetPropertyDefinition(PropertyDefinitionHandle handle)
{
return new PropertyDefinition(this, handle);
}
public EventDefinition GetEventDefinition(EventDefinitionHandle handle)
{
return new EventDefinition(this, handle);
}
public MethodImplementation GetMethodImplementation(MethodImplementationHandle handle)
{
return new MethodImplementation(this, handle);
}
public MemberReference GetMemberReference(MemberReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new MemberReference(this, GetMemberRefTreatmentAndRowId(handle));
}
private uint GetMemberRefTreatmentAndRowId(MemberReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (this.metadataKind == MetadataKind.Ecma335)
{
return handle.RowId;
}
return CalculateMemberRefTreatmentAndRowId(handle);
}
public MethodSpecification GetMethodSpecification(MethodSpecificationHandle handle)
{
return new MethodSpecification(this, handle);
}
public Parameter GetParameter(ParameterHandle handle)
{
return new Parameter(this, handle);
}
public GenericParameter GetGenericParameter(GenericParameterHandle handle)
{
return new GenericParameter(this, handle);
}
public GenericParameterConstraint GetGenericParameterConstraint(GenericParameterConstraintHandle handle)
{
return new GenericParameterConstraint(this, handle);
}
public ManifestResource GetManifestResource(ManifestResourceHandle handle)
{
return new ManifestResource(this, handle);
}
public AssemblyFile GetAssemblyFile(AssemblyFileHandle handle)
{
return new AssemblyFile(this, handle);
}
public StandaloneSignature GetStandaloneSignature(StandaloneSignatureHandle handle)
{
return new StandaloneSignature(this, handle);
}
public TypeSpecification GetTypeSpecification(TypeSpecificationHandle handle)
{
return new TypeSpecification(this, handle);
}
public ModuleReference GetModuleReference(ModuleReferenceHandle handle)
{
return new ModuleReference(this, handle);
}
public InterfaceImplementation GetInterfaceImplementation(InterfaceImplementationHandle handle)
{
return new InterfaceImplementation(this, handle);
}
internal TypeDefinitionHandle GetDeclaringType(MethodDefinitionHandle methodDef)
{
uint methodRowId;
if (UseMethodPtrTable)
{
methodRowId = MethodPtrTable.GetRowIdForMethodDefRow(methodDef.RowId);
}
else
{
methodRowId = methodDef.RowId;
}
return TypeDefTable.FindTypeContainingMethod(methodRowId, (int)MethodDefTable.NumberOfRows);
}
internal TypeDefinitionHandle GetDeclaringType(FieldDefinitionHandle fieldDef)
{
uint fieldRowId;
if (UseFieldPtrTable)
{
fieldRowId = FieldPtrTable.GetRowIdForFieldDefRow(fieldDef.RowId);
}
else
{
fieldRowId = fieldDef.RowId;
}
return TypeDefTable.FindTypeContainingField(fieldRowId, (int)FieldTable.NumberOfRows);
}
#endregion
#region Nested Types
private void InitializeNestedTypesMap()
{
var groupedNestedTypes = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>.Builder>();
uint numberOfNestedTypes = NestedClassTable.NumberOfRows;
ImmutableArray<TypeDefinitionHandle>.Builder builder = null;
TypeDefinitionHandle previousEnclosingClass = default(TypeDefinitionHandle);
for (uint i = 1; i <= numberOfNestedTypes; i++)
{
TypeDefinitionHandle enclosingClass = NestedClassTable.GetEnclosingClass(i);
Debug.Assert(!enclosingClass.IsNil);
if (enclosingClass != previousEnclosingClass)
{
if (!groupedNestedTypes.TryGetValue(enclosingClass, out builder))
{
builder = ImmutableArray.CreateBuilder<TypeDefinitionHandle>();
groupedNestedTypes.Add(enclosingClass, builder);
}
previousEnclosingClass = enclosingClass;
}
else
{
Debug.Assert(builder == groupedNestedTypes[enclosingClass]);
}
builder.Add(NestedClassTable.GetNestedClass(i));
}
var nestedTypesMap = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>>();
foreach (var group in groupedNestedTypes)
{
nestedTypesMap.Add(group.Key, group.Value.ToImmutable());
}
this.lazyNestedTypesMap = nestedTypesMap;
}
/// <summary>
/// Returns an array of types nested in the specified type.
/// </summary>
internal ImmutableArray<TypeDefinitionHandle> GetNestedTypes(TypeDefinitionHandle typeDef)
{
if (this.lazyNestedTypesMap == null)
{
InitializeNestedTypesMap();
}
ImmutableArray<TypeDefinitionHandle> nestedTypes;
if (this.lazyNestedTypesMap.TryGetValue(typeDef, out nestedTypes))
{
return nestedTypes;
}
return ImmutableArray<TypeDefinitionHandle>.Empty;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 spa2.Areas.HelpPage.ModelDescriptions;
using spa2.Areas.HelpPage.Models;
namespace spa2.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;
}
if (complexTypeDescription != null)
{
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 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);
}
}
}
}
| |
//-----------------------------------------------------------------------------
// SavingImagesGame.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
namespace SavingEmbeddedImages
{
/// <summary>
/// SavingEmbeddedImages shows two ways of transferring content from a game project to
/// the Windows Phone 7 Media Library:
///
/// 1. Loading an image texture from the game's content project, converting the
/// image to a jpeg, and saving it to the media library.
///
/// 2. Obtaining an image stream from the game project files and saving the stream
/// to the media library
/// </summary>
public class SavingImagesGame : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont mainFont;
SpriteFont detailFont;
Texture2D backgroundImage;
// This image will be loaded from the game project
Texture2D gameProjectImage;
// This image will be loaded from the content project
Texture2D contentProjectImage;
// Bounding rectangles are used for image display and hit-testing.
// These coordinates were chosen to look nice, no other special reason.
Rectangle gameProjectImageBounds = new Rectangle(20, 20, 200, 333);
Rectangle contentProjectImageBounds = new Rectangle(260, 20, 200, 333);
// Simple flag to ignore UI input when system dialogs are animating.
bool imageSaveInProgress = false;
/// <summary>
/// Set up the game to run full screen and full resolution.
/// </summary>
public SavingImagesGame()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 480;
graphics.PreferredBackBufferHeight = 800;
graphics.IsFullScreen = true;
Content.RootDirectory = "Content";
// Frame rate is 30 fps by default for Windows Phone.
TargetElapsedTime = TimeSpan.FromTicks(333333);
}
/// <summary>
/// Perform pre-game initialization
/// </summary>
protected override void Initialize()
{
base.Initialize();
// enable tap gestures only for this sample
TouchPanel.EnabledGestures = GestureType.Tap;
}
/// <summary>
/// Load UI content and fonts. Also create a drawable texture from both image types.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Load the background image.
backgroundImage = Content.Load<Texture2D>("GameBackground");
// load the fonts
mainFont = Content.Load<SpriteFont>("mainFont");
detailFont = Content.Load<SpriteFont>("detailFont");
// Load the embedded image from the game project using TitleContainer
// and constructing a Texture2D from the resulting stream object.
// Note that the image properties are set to "Copy if newer" in the
// game project.
using (Stream gameProjectImageStream = TitleContainer.OpenStream("GameProjectImage.jpg"))
{
gameProjectImage = Texture2D.FromStream(GraphicsDevice, gameProjectImageStream);
}
// Load the embedded image from the content project using the content loader.
contentProjectImage = Content.Load<Texture2D>("ContentProjectImage");
}
/// <summary>
/// Check for the back button to exit the app, and see if a touch occurred
/// on one of the images.
/// </summary>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// check for touch input
while (TouchPanel.IsGestureAvailable)
{
GestureSample gesture = TouchPanel.ReadGesture();
// The text input dialog can allow input to occur between when it closes and when the
// callback occurs, so the game guards against processing input in this state with a
// simple flag.
if (gesture.GestureType == GestureType.Tap && !imageSaveInProgress)
{
Point tapLocation = new Point((int)gesture.Position.X, (int)gesture.Position.Y);
// An image touch triggersGuide.BeginShowKeyboardInput to receive
// a filename. A hit-test determines which image was touched, and
// the callback is different depending on the source of the image.
if (gameProjectImageBounds.Contains(tapLocation))
{
imageSaveInProgress = true;
Guide.BeginShowKeyboardInput(
0,
"Save Picture",
"Enter a filename for your image",
"gameProjectImage",
SaveGameProjectImageCallback,
null);
}
if (contentProjectImageBounds.Contains(tapLocation))
{
imageSaveInProgress = true;
Guide.BeginShowKeyboardInput(
0,
"Save Picture",
"Enter a filename for your image",
"contentProjectImage",
SaveContentProjectImageCallback,
null);
}
}
}
base.Update(gameTime);
}
/// <summary>
/// Render the UI.
/// </summary>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(backgroundImage, new Vector2(0, 0), Color.White);
spriteBatch.Draw(gameProjectImage, gameProjectImageBounds, null, Color.White);
spriteBatch.DrawString(
detailFont,
"game project image",
new Vector2(gameProjectImageBounds.X, gameProjectImageBounds.Y + gameProjectImageBounds.Height),
Color.White);
spriteBatch.Draw(contentProjectImage, contentProjectImageBounds, null, Color.White);
spriteBatch.DrawString(
detailFont,
"content project image",
new Vector2(contentProjectImageBounds.X, contentProjectImageBounds.Y + contentProjectImageBounds.Height),
Color.White);
spriteBatch.DrawString(mainFont, "Tap an image to save it\nto your media library.", new Vector2(40,500), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
/// <summary>
/// Utility function to save a stream to the media library. Media Library access won't
/// work if the Zune desktop software is running.
/// </summary>
protected void SaveStreamToMediaLibrary(string filename, Stream stream)
{
MediaLibrary library = new MediaLibrary();
string messageBoxTitle;
string messageBoxContent;
string[] buttons = { "OK" };
MessageBoxIcon messageBoxIcon;
try
{
library.SavePicture(filename, stream);
messageBoxTitle = "Image saved.";
messageBoxContent = filename + " successfully added to your Media Library.";
messageBoxIcon = MessageBoxIcon.None;
}
catch (InvalidOperationException)
{
// The most likely reason for failure is that the Zune desktop software is running.
// This prevents the phone from saving content to the device's media library.
messageBoxTitle = "Unable to save image.";
messageBoxContent = "The image could not be saved to the Media Library. One reason might be that the phone is tethered to a PC with the Zune software running.";
// the phone doesn't display an icon, but specifying MessageBoxIcon.Error causes a warning sound effect to be played
messageBoxIcon = MessageBoxIcon.Error;
}
IAsyncResult messageResult = Guide.BeginShowMessageBox(
messageBoxTitle, messageBoxContent,
buttons, 0, messageBoxIcon, null, null);
Guide.EndShowMessageBox(messageResult);
imageSaveInProgress = false;
}
/// <summary>
/// Called when the user has picked a filename for the GameProject image.
/// </summary>
protected void SaveGameProjectImageCallback(IAsyncResult result)
{
string filename = Guide.EndShowKeyboardInput(result);
if (!string.IsNullOrEmpty(filename))
{
// Both content images are loaded as textures for display, and could be
// saved with Texture2D.SaveAsJpeg(), but if you need to go from
// an image embedded in the .xap, an alternative approach is
// to open a TitleContainer stream, and save it to the media library.
using (Stream stream = TitleContainer.OpenStream("GameProjectImage.jpg"))
{
SaveStreamToMediaLibrary(filename, stream);
}
}
else
{
imageSaveInProgress = false;
}
}
/// <summary>
/// Called when the user has picked a filename for the ContentProject image.
/// </summary>
protected void SaveContentProjectImageCallback(IAsyncResult result)
{
string filename = Guide.EndShowKeyboardInput(result);
if (!string.IsNullOrEmpty(filename))
{
/// Write a Texture2D to a stream and then save the stream to the media library.
// The media library expects a Jpeg image, so make sure it gets the input type it wants.
using (MemoryStream stream = new MemoryStream())
{
contentProjectImage.SaveAsJpeg(stream, contentProjectImage.Width, contentProjectImage.Height);
// Reset the stream position after writing to it.
stream.Seek(0, 0);
SaveStreamToMediaLibrary(filename, stream);
}
}
else
{
imageSaveInProgress = false;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Project1.API.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Web.Routing;
using Orchard.ContentManagement;
using Orchard.Core.Settings.Models;
using Orchard.DisplayManagement;
using Orchard.Localization;
using Orchard.Mvc;
using Orchard.Security;
using Orchard.UI.Notify;
using Orchard.Users.Events;
using Orchard.Users.Models;
using Orchard.Users.Services;
using Orchard.Users.ViewModels;
using Orchard.Mvc.Extensions;
using System;
using Orchard.Settings;
using Orchard.UI.Navigation;
using Orchard.Utility.Extensions;
namespace Orchard.Users.Controllers {
[ValidateInput(false)]
public class AdminController : Controller, IUpdateModel {
private readonly IMembershipService _membershipService;
private readonly IUserService _userService;
private readonly IUserEventHandler _userEventHandlers;
private readonly ISiteService _siteService;
public AdminController(
IOrchardServices services,
IMembershipService membershipService,
IUserService userService,
IShapeFactory shapeFactory,
IUserEventHandler userEventHandlers,
ISiteService siteService) {
Services = services;
_membershipService = membershipService;
_userService = userService;
_userEventHandlers = userEventHandlers;
_siteService = siteService;
T = NullLocalizer.Instance;
Shape = shapeFactory;
}
dynamic Shape { get; set; }
public IOrchardServices Services { get; set; }
public Localizer T { get; set; }
public ActionResult Index(UserIndexOptions options, PagerParameters pagerParameters) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to list users")))
return new HttpUnauthorizedResult();
var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);
// default options
if (options == null)
options = new UserIndexOptions();
var users = Services.ContentManager
.Query<UserPart, UserPartRecord>();
switch (options.Filter) {
case UsersFilter.Approved:
users = users.Where(u => u.RegistrationStatus == UserStatus.Approved);
break;
case UsersFilter.Pending:
users = users.Where(u => u.RegistrationStatus == UserStatus.Pending);
break;
case UsersFilter.EmailPending:
users = users.Where(u => u.EmailStatus == UserStatus.Pending);
break;
}
if(!string.IsNullOrWhiteSpace(options.Search)) {
users = users.Where(u => u.UserName.Contains(options.Search) || u.Email.Contains(options.Search));
}
var pagerShape = Shape.Pager(pager).TotalItemCount(users.Count());
switch (options.Order) {
case UsersOrder.Name:
users = users.OrderBy(u => u.UserName);
break;
case UsersOrder.Email:
users = users.OrderBy(u => u.Email);
break;
case UsersOrder.CreatedUtc:
users = users.OrderBy(u => u.CreatedUtc);
break;
case UsersOrder.LastLoginUtc:
users = users.OrderBy(u => u.LastLoginUtc);
break;
}
var results = users
.Slice(pager.GetStartIndex(), pager.PageSize)
.ToList();
var model = new UsersIndexViewModel {
Users = results
.Select(x => new UserEntry { User = x.Record })
.ToList(),
Options = options,
Pager = pagerShape
};
// maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Filter", options.Filter);
routeData.Values.Add("Options.Search", options.Search);
routeData.Values.Add("Options.Order", options.Order);
pagerShape.RouteData(routeData);
return View(model);
}
[HttpPost]
[FormValueRequired("submit.BulkEdit")]
public ActionResult Index(FormCollection input) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var viewModel = new UsersIndexViewModel {Users = new List<UserEntry>(), Options = new UserIndexOptions()};
UpdateModel(viewModel);
var checkedEntries = viewModel.Users.Where(c => c.IsChecked);
switch (viewModel.Options.BulkAction) {
case UsersBulkAction.None:
break;
case UsersBulkAction.Approve:
foreach (var entry in checkedEntries) {
Approve(entry.User.Id);
}
break;
case UsersBulkAction.Disable:
foreach (var entry in checkedEntries) {
Moderate(entry.User.Id);
}
break;
case UsersBulkAction.ChallengeEmail:
foreach (var entry in checkedEntries) {
SendChallengeEmail(entry.User.Id);
}
break;
case UsersBulkAction.Delete:
foreach (var entry in checkedEntries) {
Delete(entry.User.Id);
}
break;
}
return RedirectToAction("Index", ControllerContext.RouteData.Values);
}
public ActionResult Create() {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.New<IUser>("User");
var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Create", Model: new UserCreateViewModel(), Prefix: null);
editor.Metadata.Position = "2";
var model = Services.ContentManager.BuildEditor(user);
model.Content.Add(editor);
return View(model);
}
[HttpPost, ActionName("Create")]
public ActionResult CreatePOST(UserCreateViewModel createModel) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
if (!string.IsNullOrEmpty(createModel.UserName)) {
if (!_userService.VerifyUserUnicity(createModel.UserName, createModel.Email)) {
AddModelError("NotUniqueUserName", T("User with that username and/or email already exists."));
}
}
if (!Regex.IsMatch(createModel.Email ?? "", UserPart.EmailPattern, RegexOptions.IgnoreCase)) {
// http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
ModelState.AddModelError("Email", T("You must specify a valid email address."));
}
if (createModel.Password != createModel.ConfirmPassword) {
AddModelError("ConfirmPassword", T("Password confirmation must match"));
}
var user = Services.ContentManager.New<IUser>("User");
if (ModelState.IsValid) {
user = _membershipService.CreateUser(new CreateUserParams(
createModel.UserName,
createModel.Password,
createModel.Email,
null, null, true));
}
var model = Services.ContentManager.UpdateEditor(user, this);
if (!ModelState.IsValid) {
Services.TransactionManager.Cancel();
var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Create", Model: createModel, Prefix: null);
editor.Metadata.Position = "2";
model.Content.Add(editor);
return View(model);
}
Services.Notifier.Success(T("User created"));
return RedirectToAction("Index");
}
public ActionResult Edit(int id) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.Get<UserPart>(id);
if (user == null)
return HttpNotFound();
var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Edit", Model: new UserEditViewModel {User = user}, Prefix: null);
editor.Metadata.Position = "2";
var model = Services.ContentManager.BuildEditor(user);
model.Content.Add(editor);
return View(model);
}
[HttpPost, ActionName("Edit")]
public ActionResult EditPOST(int id) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.Get<UserPart>(id, VersionOptions.DraftRequired);
if (user == null)
return HttpNotFound();
string previousName = user.UserName;
var model = Services.ContentManager.UpdateEditor(user, this);
var editModel = new UserEditViewModel { User = user };
if (TryUpdateModel(editModel)) {
if (!_userService.VerifyUserUnicity(id, editModel.UserName, editModel.Email)) {
AddModelError("NotUniqueUserName", T("User with that username and/or email already exists."));
}
else if (!Regex.IsMatch(editModel.Email ?? "", UserPart.EmailPattern, RegexOptions.IgnoreCase)) {
// http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
ModelState.AddModelError("Email", T("You must specify a valid email address."));
}
else {
// also update the Super user if this is the renamed account
if (string.Equals(Services.WorkContext.CurrentSite.SuperUser, previousName, StringComparison.Ordinal)) {
_siteService.GetSiteSettings().As<SiteSettingsPart>().SuperUser = editModel.UserName;
}
user.NormalizedUserName = editModel.UserName.ToLowerInvariant();
}
}
if (!ModelState.IsValid) {
Services.TransactionManager.Cancel();
var editor = Shape.EditorTemplate(TemplateName: "Parts/User.Edit", Model: editModel, Prefix: null);
editor.Metadata.Position = "2";
model.Content.Add(editor);
return View(model);
}
Services.ContentManager.Publish(user.ContentItem);
Services.Notifier.Success(T("User information updated"));
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Delete(int id) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.Get<IUser>(id);
if (user == null)
return HttpNotFound();
if (string.Equals(Services.WorkContext.CurrentSite.SuperUser, user.UserName, StringComparison.Ordinal)) {
Services.Notifier.Error(T("The Super user can't be removed. Please disable this account or specify another Super user account."));
}
else if (string.Equals(Services.WorkContext.CurrentUser.UserName, user.UserName, StringComparison.Ordinal)) {
Services.Notifier.Error(T("You can't remove your own account. Please log in with another account."));
}
else {
Services.ContentManager.Remove(user.ContentItem);
Services.Notifier.Success(T("User {0} deleted", user.UserName));
}
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult SendChallengeEmail(int id) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.Get<IUser>(id);
if (user == null)
return HttpNotFound();
var siteUrl = Services.WorkContext.CurrentSite.BaseUrl;
if (string.IsNullOrWhiteSpace(siteUrl)) {
siteUrl = HttpContext.Request.ToRootUrlString();
}
_userService.SendChallengeEmail(user.As<UserPart>(), nonce => Url.MakeAbsolute(Url.Action("ChallengeEmail", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl));
Services.Notifier.Success(T("Challenge email sent to {0}", user.UserName));
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Approve(int id) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.Get<IUser>(id);
if (user == null)
return HttpNotFound();
user.As<UserPart>().RegistrationStatus = UserStatus.Approved;
Services.Notifier.Success(T("User {0} approved", user.UserName));
_userEventHandlers.Approved(user);
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Moderate(int id) {
if (!Services.Authorizer.Authorize(Permissions.ManageUsers, T("Not authorized to manage users")))
return new HttpUnauthorizedResult();
var user = Services.ContentManager.Get<IUser>(id);
if (user == null)
return HttpNotFound();
if (string.Equals(Services.WorkContext.CurrentUser.UserName, user.UserName, StringComparison.Ordinal)) {
Services.Notifier.Error(T("You can't disable your own account. Please log in with another account"));
}
else {
user.As<UserPart>().RegistrationStatus = UserStatus.Pending;
Services.Notifier.Success(T("User {0} disabled", user.UserName));
}
return RedirectToAction("Index");
}
bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) {
return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
}
public void AddModelError(string key, LocalizedString errorMessage) {
ModelState.AddModelError(key, errorMessage.ToString());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Reflection.Emit
{
public static class __ILGenerator
{
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode,
(ILGeneratorValueLambda, opcodeLambda) => ILGeneratorValueLambda.Emit(opcodeLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Byte> arg)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, arg,
(ILGeneratorValueLambda, opcodeLambda, argLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, argLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.SByte> arg)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, arg,
(ILGeneratorValueLambda, opcodeLambda, argLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, argLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Int16> arg)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, arg,
(ILGeneratorValueLambda, opcodeLambda, argLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, argLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Int32> arg)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, arg,
(ILGeneratorValueLambda, opcodeLambda, argLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, argLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Reflection.MethodInfo> meth)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, meth,
(ILGeneratorValueLambda, opcodeLambda, methLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, methLambda));
}
public static IObservable<System.Reactive.Unit> EmitCalli(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode,
IObservable<System.Reflection.CallingConventions> callingConvention, IObservable<System.Type> returnType,
IObservable<System.Type[]> parameterTypes, IObservable<System.Type[]> optionalParameterTypes)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, callingConvention, returnType, parameterTypes,
optionalParameterTypes,
(ILGeneratorValueLambda, opcodeLambda, callingConventionLambda, returnTypeLambda, parameterTypesLambda,
optionalParameterTypesLambda) =>
ILGeneratorValueLambda.EmitCalli(opcodeLambda, callingConventionLambda, returnTypeLambda,
parameterTypesLambda, optionalParameterTypesLambda));
}
public static IObservable<System.Reactive.Unit> EmitCalli(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode,
IObservable<System.Runtime.InteropServices.CallingConvention> unmanagedCallConv,
IObservable<System.Type> returnType, IObservable<System.Type[]> parameterTypes)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, unmanagedCallConv, returnType, parameterTypes,
(ILGeneratorValueLambda, opcodeLambda, unmanagedCallConvLambda, returnTypeLambda, parameterTypesLambda)
=>
ILGeneratorValueLambda.EmitCalli(opcodeLambda, unmanagedCallConvLambda, returnTypeLambda,
parameterTypesLambda));
}
public static IObservable<System.Reactive.Unit> EmitCall(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Reflection.MethodInfo> methodInfo,
IObservable<System.Type[]> optionalParameterTypes)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, methodInfo, optionalParameterTypes,
(ILGeneratorValueLambda, opcodeLambda, methodInfoLambda, optionalParameterTypesLambda) =>
ILGeneratorValueLambda.EmitCall(opcodeLambda, methodInfoLambda, optionalParameterTypesLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode,
IObservable<System.Reflection.Emit.SignatureHelper> signature)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, signature,
(ILGeneratorValueLambda, opcodeLambda, signatureLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, signatureLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Reflection.ConstructorInfo> con)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, con,
(ILGeneratorValueLambda, opcodeLambda, conLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, conLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Type> cls)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, cls,
(ILGeneratorValueLambda, opcodeLambda, clsLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, clsLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Int64> arg)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, arg,
(ILGeneratorValueLambda, opcodeLambda, argLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, argLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Single> arg)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, arg,
(ILGeneratorValueLambda, opcodeLambda, argLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, argLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Double> arg)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, arg,
(ILGeneratorValueLambda, opcodeLambda, argLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, argLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Reflection.Emit.Label> label)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, label,
(ILGeneratorValueLambda, opcodeLambda, labelLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, labelLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Reflection.Emit.Label[]> labels)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, labels,
(ILGeneratorValueLambda, opcodeLambda, labelsLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, labelsLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Reflection.FieldInfo> field)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, field,
(ILGeneratorValueLambda, opcodeLambda, fieldLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, fieldLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.String> str)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, str,
(ILGeneratorValueLambda, opcodeLambda, strLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, strLambda));
}
public static IObservable<System.Reactive.Unit> Emit(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.OpCode> opcode, IObservable<System.Reflection.Emit.LocalBuilder> local)
{
return ObservableExt.ZipExecute(ILGeneratorValue, opcode, local,
(ILGeneratorValueLambda, opcodeLambda, localLambda) =>
ILGeneratorValueLambda.Emit(opcodeLambda, localLambda));
}
public static IObservable<System.Reflection.Emit.Label> BeginExceptionBlock(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue)
{
return Observable.Select(ILGeneratorValue,
(ILGeneratorValueLambda) => ILGeneratorValueLambda.BeginExceptionBlock());
}
public static IObservable<System.Reactive.Unit> EndExceptionBlock(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue)
{
return
Observable.Do(ILGeneratorValue, (ILGeneratorValueLambda) => ILGeneratorValueLambda.EndExceptionBlock())
.ToUnit();
}
public static IObservable<System.Reactive.Unit> BeginExceptFilterBlock(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue)
{
return
Observable.Do(ILGeneratorValue,
(ILGeneratorValueLambda) => ILGeneratorValueLambda.BeginExceptFilterBlock()).ToUnit();
}
public static IObservable<System.Reactive.Unit> BeginCatchBlock(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Type> exceptionType)
{
return ObservableExt.ZipExecute(ILGeneratorValue, exceptionType,
(ILGeneratorValueLambda, exceptionTypeLambda) =>
ILGeneratorValueLambda.BeginCatchBlock(exceptionTypeLambda));
}
public static IObservable<System.Reactive.Unit> BeginFaultBlock(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue)
{
return
Observable.Do(ILGeneratorValue, (ILGeneratorValueLambda) => ILGeneratorValueLambda.BeginFaultBlock())
.ToUnit();
}
public static IObservable<System.Reactive.Unit> BeginFinallyBlock(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue)
{
return
Observable.Do(ILGeneratorValue, (ILGeneratorValueLambda) => ILGeneratorValueLambda.BeginFinallyBlock())
.ToUnit();
}
public static IObservable<System.Reflection.Emit.Label> DefineLabel(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue)
{
return Observable.Select(ILGeneratorValue, (ILGeneratorValueLambda) => ILGeneratorValueLambda.DefineLabel());
}
public static IObservable<System.Reactive.Unit> MarkLabel(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.Label> loc)
{
return ObservableExt.ZipExecute(ILGeneratorValue, loc,
(ILGeneratorValueLambda, locLambda) => ILGeneratorValueLambda.MarkLabel(locLambda));
}
public static IObservable<System.Reactive.Unit> ThrowException(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue, IObservable<System.Type> excType)
{
return ObservableExt.ZipExecute(ILGeneratorValue, excType,
(ILGeneratorValueLambda, excTypeLambda) => ILGeneratorValueLambda.ThrowException(excTypeLambda));
}
public static IObservable<System.Reactive.Unit> EmitWriteLine(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue, IObservable<System.String> value)
{
return ObservableExt.ZipExecute(ILGeneratorValue, value,
(ILGeneratorValueLambda, valueLambda) => ILGeneratorValueLambda.EmitWriteLine(valueLambda));
}
public static IObservable<System.Reactive.Unit> EmitWriteLine(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.Emit.LocalBuilder> localBuilder)
{
return ObservableExt.ZipExecute(ILGeneratorValue, localBuilder,
(ILGeneratorValueLambda, localBuilderLambda) => ILGeneratorValueLambda.EmitWriteLine(localBuilderLambda));
}
public static IObservable<System.Reactive.Unit> EmitWriteLine(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Reflection.FieldInfo> fld)
{
return ObservableExt.ZipExecute(ILGeneratorValue, fld,
(ILGeneratorValueLambda, fldLambda) => ILGeneratorValueLambda.EmitWriteLine(fldLambda));
}
public static IObservable<System.Reflection.Emit.LocalBuilder> DeclareLocal(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue, IObservable<System.Type> localType)
{
return Observable.Zip(ILGeneratorValue, localType,
(ILGeneratorValueLambda, localTypeLambda) => ILGeneratorValueLambda.DeclareLocal(localTypeLambda));
}
public static IObservable<System.Reflection.Emit.LocalBuilder> DeclareLocal(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue, IObservable<System.Type> localType,
IObservable<System.Boolean> pinned)
{
return Observable.Zip(ILGeneratorValue, localType, pinned,
(ILGeneratorValueLambda, localTypeLambda, pinnedLambda) =>
ILGeneratorValueLambda.DeclareLocal(localTypeLambda, pinnedLambda));
}
public static IObservable<System.Reactive.Unit> UsingNamespace(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.String> usingNamespace)
{
return ObservableExt.ZipExecute(ILGeneratorValue, usingNamespace,
(ILGeneratorValueLambda, usingNamespaceLambda) =>
ILGeneratorValueLambda.UsingNamespace(usingNamespaceLambda));
}
public static IObservable<System.Reactive.Unit> MarkSequencePoint(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue,
IObservable<System.Diagnostics.SymbolStore.ISymbolDocumentWriter> document,
IObservable<System.Int32> startLine, IObservable<System.Int32> startColumn,
IObservable<System.Int32> endLine, IObservable<System.Int32> endColumn)
{
return ObservableExt.ZipExecute(ILGeneratorValue, document, startLine, startColumn, endLine, endColumn,
(ILGeneratorValueLambda, documentLambda, startLineLambda, startColumnLambda, endLineLambda,
endColumnLambda) =>
ILGeneratorValueLambda.MarkSequencePoint(documentLambda, startLineLambda, startColumnLambda,
endLineLambda, endColumnLambda));
}
public static IObservable<System.Reactive.Unit> BeginScope(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue)
{
return
Observable.Do(ILGeneratorValue, (ILGeneratorValueLambda) => ILGeneratorValueLambda.BeginScope())
.ToUnit();
}
public static IObservable<System.Reactive.Unit> EndScope(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue)
{
return
Observable.Do(ILGeneratorValue, (ILGeneratorValueLambda) => ILGeneratorValueLambda.EndScope()).ToUnit();
}
public static IObservable<System.Int32> get_ILOffset(
this IObservable<System.Reflection.Emit.ILGenerator> ILGeneratorValue)
{
return Observable.Select(ILGeneratorValue, (ILGeneratorValueLambda) => ILGeneratorValueLambda.ILOffset);
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////
// Open 3D Model Viewer (open3mod) (v2.0)
// [MeshDetailsDialog.cs]
// (c) 2012-2015, Open3Mod Contributors
//
// Licensed under the terms and conditions of the 3-clause BSD license. See
// the LICENSE file in the root folder of the repository for the details.
//
// HIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Windows.Forms;
using Assimp;
namespace open3mod
{
public partial class MeshDetailsDialog : Form, IHoverUpdateDialog
{
private const string XyzPosition = "XYZ Position";
private const string Normals = "Normals";
private const string Tangents = "Tangents";
private const string BoneWeights = "Bone Weights";
private const string VertexAnimation = "Vertex Animation";
private readonly MainWindow _host;
private readonly Scene _scene;
private NormalVectorGeneratorDialog _normalsDialog;
private Mesh _mesh;
private String _meshName;
public MeshDetailsDialog(MainWindow host, Scene scene)
{
Debug.Assert(host != null);
_host = host;
_scene = scene;
InitializeComponent();
// TODO(acgessler): Factor out preview generation and getting the checker pattern
// background into a separate utility.
pictureBoxMaterial.SizeMode = PictureBoxSizeMode.Zoom;
pictureBoxMaterial.BackgroundImage = MaterialThumbnailControl.GetBackgroundImage();
pictureBoxMaterial.BackgroundImageLayout = ImageLayout.Zoom;
StartUpdateMaterialPreviewLoop();
}
/// <summary>
/// Set current mesh for which detail information is displayed.
/// </summary>
/// <param name="mesh"></param>
/// <param name="meshName"></param>
public void SetMesh(Mesh mesh, string meshName)
{
Debug.Assert(mesh != null);
Debug.Assert(meshName != null);
if (mesh == _mesh)
{
return;
}
_mesh = mesh;
_meshName = meshName;
labelVertexCount.Text = mesh.VertexCount.ToString();
labelFaceCount.Text = mesh.FaceCount.ToString();
labelBoneCount.Text = mesh.BoneCount.ToString();
Text = string.Format("{0} - Mesh Editor", meshName);
UpdateFaceItems();
UpdateVertexItems();
// Immediate material update to avoid poll delay.
UpdateMaterialPreview();
}
private void UpdateFaceItems()
{
listBoxFaceData.Items.Clear();
if (_mesh.PrimitiveType.HasFlag(PrimitiveType.Triangle))
{
listBoxFaceData.Items.Add("Triangles");
}
if (_mesh.PrimitiveType.HasFlag(PrimitiveType.Line))
{
listBoxFaceData.Items.Add("Single Lines");
}
if (_mesh.PrimitiveType.HasFlag(PrimitiveType.Point))
{
listBoxFaceData.Items.Add("Single Points");
}
}
private void UpdateVertexItems()
{
object selectedItem = listBoxVertexData.SelectedItem;
listBoxVertexData.Items.Clear();
listBoxVertexData.Items.Add(XyzPosition);
if (_mesh.HasNormals)
{
listBoxVertexData.Items.Add(Normals);
}
if (_mesh.HasTangentBasis)
{
listBoxVertexData.Items.Add(Tangents);
}
for (var i = 0; i < _mesh.TextureCoordinateChannelCount; ++i)
{
listBoxVertexData.Items.Add(UVCoordinates(i));
}
for (var i = 0; i < _mesh.VertexColorChannelCount; ++i)
{
listBoxVertexData.Items.Add(VertexColors(i));
}
if (_mesh.HasBones)
{
listBoxVertexData.Items.Add(BoneWeights);
}
if (_mesh.HasMeshAnimationAttachments)
{
listBoxVertexData.Items.Add(VertexAnimation);
}
// Restore previous selected item.
foreach (var item in listBoxVertexData.Items)
{
if (item.Equals(selectedItem))
{
listBoxVertexData.SelectedItem = item;
}
}
}
private static string VertexColors(int i)
{
return string.Format("Vertex Color Set (#{0})", i);
}
private static string UVCoordinates(int i)
{
return string.Format("UV Coordinates (#{0})", i);
}
/// <summary>
/// Locate the tab within which the current mesh is.
/// </summary>
/// <returns></returns>
private Tab GetTabForCurrentMesh()
{
if (_mesh == null)
{
return null;
}
Debug.Assert(_host != null);
foreach (var tab in _host.UiState.TabsWithActiveScenes())
{
var scene = tab.ActiveScene;
Debug.Assert(scene != null);
for (var i = 0; i < scene.Raw.MeshCount; ++i)
{
var m = scene.Raw.Meshes[i];
if (m == _mesh)
{
return tab;
}
}
}
return null;
}
private void StartUpdateMaterialPreviewLoop()
{
// Unholy poll. This is the only case where material previews are
// needed other than the material panel itself.
MainWindow.DelayExecution(new TimeSpan(0, 0, 0, 0, 1000),
() =>
{
UpdateMaterialPreview();
StartUpdateMaterialPreviewLoop();
});
}
private void UpdateMaterialPreview()
{
var tab = GetTabForCurrentMesh();
if (tab == null)
{
pictureBoxMaterial.Image = null;
labelMaterialName.Text = "None";
return;
}
var scene = tab.ActiveScene;
var mat = scene.Raw.Materials[_mesh.MaterialIndex];
var ui = _host.UiForTab(tab);
Debug.Assert(ui != null);
var inspector = ui.GetInspector();
var thumb = inspector.Materials.GetMaterialControl(mat);
pictureBoxMaterial.Image = thumb.GetCurrentPreviewImage();
labelMaterialName.Text = mat.Name.Length > 0 ? mat.Name : "Unnamed Material";
}
private void OnJumpToMaterial(object sender, LinkLabelLinkClickedEventArgs e)
{
linkLabel1.LinkVisited = false;
var tab = GetTabForCurrentMesh();
if (tab == null)
{
return;
}
var scene = tab.ActiveScene;
var mat = scene.Raw.Materials[_mesh.MaterialIndex];
var ui = _host.UiForTab(tab);
Debug.Assert(ui != null);
var inspector = ui.GetInspector();
inspector.Materials.SelectEntry(mat);
var thumb = inspector.Materials.GetMaterialControl(mat);
inspector.OpenMaterialsTabAndScrollTo(thumb);
}
private void OnGenerateNormals(object sender, EventArgs e)
{
if (_normalsDialog != null)
{
_normalsDialog.Close();
_normalsDialog.Dispose();
_normalsDialog = null;
}
_normalsDialog = new NormalVectorGeneratorDialog(_scene, _mesh, _meshName);
_normalsDialog.Show(this);
// Disable this dialog for the duration of the NormalsVectorGeneratorDialog.
// The latter replaces the mesh being displayed with a temporary preview
// mesh, so changes made to the source mesh would not be visible. This is
// very confusing, so disallow it.
EnableDialogControls(false);
_normalsDialog.FormClosed +=
(o, args) =>
{
if (IsDisposed)
{
return;
}
_normalsDialog = null;
EnableDialogControls(true);
// Unless the user canceled the operation, Normals were added.
UpdateVertexItems();
};
}
private void EnableDialogControls(bool enabled)
{
// Only update children. If the form itself is disabled, it acts like a
// blocked dialog and can no longer be moved.
foreach (Control c in Controls)
{
c.Enabled = enabled;
}
}
private void OnDeleteSelectedVertexComponent(object sender, EventArgs e)
{
string item = (string) listBoxVertexData.SelectedItem;
if (item == null || item == XyzPosition)
{
return;
}
switch (item)
{
case Normals:
DeleteVertexComponent(Normals, m => m.Normals);
break;
case Tangents:
DeleteVertexComponent(Tangents, m => m.Tangents);
// TODO(acgessler): We should also delete bitangents.
break;
case VertexAnimation:
DeleteVertexComponent(VertexAnimation, m => m.MeshAnimationAttachments);
break;
case BoneWeights:
DeleteVertexComponent(BoneWeights, m => m.Bones);
break;
default:
for (var i = 0; i < _mesh.TextureCoordinateChannelCount; ++i)
{
if (item != UVCoordinates(i)) continue;
DeleteVertexComponent(UVCoordinates(i), m => m.TextureCoordinateChannels, i);
break;
}
for (var i = 0; i < _mesh.VertexColorChannelCount; ++i)
{
if (item != VertexColors(i)) continue;
DeleteVertexComponent(VertexColors(i), m => m.VertexColorChannels, i);
break;
}
break;
}
}
private void DeleteVertexComponent<T>(string name, Expression<Func<Mesh, T>> property) where T : new()
{
var expr = (MemberExpression)property.Body;
var prop = (PropertyInfo)expr.Member;
T oldValue = (T)prop.GetValue(_mesh, null);
var mesh = _mesh;
_scene.UndoStack.PushAndDo(String.Format("Mesh \"{0}\": delete {1}", _meshName, name),
() => prop.SetValue(mesh, new T(), null),
() => prop.SetValue(mesh, oldValue, null),
() =>
{
_scene.RequestRenderRefresh();
if (mesh == _mesh) // Only update UI if the dialog instance still displays the mesh.
{
UpdateVertexItems();
}
});
}
// Version for T[] (TextureCoordChannels, VertexColorChannels). Passing in an indexed expression
// directly yields a LINQ expression tree rooted at a BinaryExpression instead of MemberExpression.
// TODO(acgessler): Check for a way to express this with less duplication.
private void DeleteVertexComponent<T>(string name, Expression<Func<Mesh, T[]>> property, int index) where T : new()
{
var expr = (MemberExpression)property.Body;
var prop = (PropertyInfo)expr.Member;
var indexes = new object[] { index };
T oldValue = ((T[])prop.GetValue(_mesh, null))[index];
var mesh = _mesh;
_scene.UndoStack.PushAndDo(String.Format("Mesh \"{0}\": delete {1}", _meshName, name),
() => ((T[])prop.GetValue(_mesh, null))[index] = new T(),
() => ((T[])prop.GetValue(_mesh, null))[index] = oldValue,
() =>
{
_scene.RequestRenderRefresh();
if (mesh == _mesh)
{
UpdateVertexItems();
}
});
}
private void OnSelectedVertexComponentChanged(object sender, EventArgs e)
{
buttonDeleteVertexData.Enabled = !listBoxVertexData.SelectedItem.Equals(XyzPosition);
}
public bool HoverUpdateEnabled
{
// Disallow Hover Update while any child dialogs are open.
get { return _normalsDialog == null; }
}
}
}
/* vi: set shiftwidth=4 tabstop=4: */
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcsv = Google.Cloud.SecurityCenter.V1P1Beta1;
using sys = System;
namespace Google.Cloud.SecurityCenter.V1P1Beta1
{
/// <summary>Resource name for the <c>Source</c> resource.</summary>
public sealed partial class SourceName : gax::IResourceName, sys::IEquatable<SourceName>
{
/// <summary>The possible contents of <see cref="SourceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>organizations/{organization}/sources/{source}</c>.</summary>
OrganizationSource = 1,
/// <summary>A resource name with pattern <c>folders/{folder}/sources/{source}</c>.</summary>
FolderSource = 2,
/// <summary>A resource name with pattern <c>projects/{project}/sources/{source}</c>.</summary>
ProjectSource = 3,
}
private static gax::PathTemplate s_organizationSource = new gax::PathTemplate("organizations/{organization}/sources/{source}");
private static gax::PathTemplate s_folderSource = new gax::PathTemplate("folders/{folder}/sources/{source}");
private static gax::PathTemplate s_projectSource = new gax::PathTemplate("projects/{project}/sources/{source}");
/// <summary>Creates a <see cref="SourceName"/> 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="SourceName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static SourceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SourceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SourceName"/> with the pattern <c>organizations/{organization}/sources/{source}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SourceName"/> constructed from the provided ids.</returns>
public static SourceName FromOrganizationSource(string organizationId, string sourceId) =>
new SourceName(ResourceNameType.OrganizationSource, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>
/// Creates a <see cref="SourceName"/> with the pattern <c>folders/{folder}/sources/{source}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SourceName"/> constructed from the provided ids.</returns>
public static SourceName FromFolderSource(string folderId, string sourceId) =>
new SourceName(ResourceNameType.FolderSource, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>
/// Creates a <see cref="SourceName"/> with the pattern <c>projects/{project}/sources/{source}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SourceName"/> constructed from the provided ids.</returns>
public static SourceName FromProjectSource(string projectId, string sourceId) =>
new SourceName(ResourceNameType.ProjectSource, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SourceName"/> with pattern
/// <c>organizations/{organization}/sources/{source}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SourceName"/> with pattern
/// <c>organizations/{organization}/sources/{source}</c>.
/// </returns>
public static string Format(string organizationId, string sourceId) =>
FormatOrganizationSource(organizationId, sourceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SourceName"/> with pattern
/// <c>organizations/{organization}/sources/{source}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SourceName"/> with pattern
/// <c>organizations/{organization}/sources/{source}</c>.
/// </returns>
public static string FormatOrganizationSource(string organizationId, string sourceId) =>
s_organizationSource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SourceName"/> with pattern
/// <c>folders/{folder}/sources/{source}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SourceName"/> with pattern <c>folders/{folder}/sources/{source}</c>
/// .
/// </returns>
public static string FormatFolderSource(string folderId, string sourceId) =>
s_folderSource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SourceName"/> with pattern
/// <c>projects/{project}/sources/{source}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SourceName"/> with pattern
/// <c>projects/{project}/sources/{source}</c>.
/// </returns>
public static string FormatProjectSource(string projectId, string sourceId) =>
s_projectSource.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)));
/// <summary>Parses the given resource name string into a new <see cref="SourceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/sources/{source}</c></description></item>
/// <item><description><c>folders/{folder}/sources/{source}</c></description></item>
/// <item><description><c>projects/{project}/sources/{source}</c></description></item>
/// </list>
/// </remarks>
/// <param name="sourceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SourceName"/> if successful.</returns>
public static SourceName Parse(string sourceName) => Parse(sourceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SourceName"/> 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>organizations/{organization}/sources/{source}</c></description></item>
/// <item><description><c>folders/{folder}/sources/{source}</c></description></item>
/// <item><description><c>projects/{project}/sources/{source}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sourceName">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="SourceName"/> if successful.</returns>
public static SourceName Parse(string sourceName, bool allowUnparsed) =>
TryParse(sourceName, allowUnparsed, out SourceName 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="SourceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/sources/{source}</c></description></item>
/// <item><description><c>folders/{folder}/sources/{source}</c></description></item>
/// <item><description><c>projects/{project}/sources/{source}</c></description></item>
/// </list>
/// </remarks>
/// <param name="sourceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SourceName"/>, 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 sourceName, out SourceName result) => TryParse(sourceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SourceName"/> 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>organizations/{organization}/sources/{source}</c></description></item>
/// <item><description><c>folders/{folder}/sources/{source}</c></description></item>
/// <item><description><c>projects/{project}/sources/{source}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sourceName">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="SourceName"/>, 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 sourceName, bool allowUnparsed, out SourceName result)
{
gax::GaxPreconditions.CheckNotNull(sourceName, nameof(sourceName));
gax::TemplatedResourceName resourceName;
if (s_organizationSource.TryParseName(sourceName, out resourceName))
{
result = FromOrganizationSource(resourceName[0], resourceName[1]);
return true;
}
if (s_folderSource.TryParseName(sourceName, out resourceName))
{
result = FromFolderSource(resourceName[0], resourceName[1]);
return true;
}
if (s_projectSource.TryParseName(sourceName, out resourceName))
{
result = FromProjectSource(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(sourceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SourceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string folderId = null, string organizationId = null, string projectId = null, string sourceId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
FolderId = folderId;
OrganizationId = organizationId;
ProjectId = projectId;
SourceId = sourceId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SourceName"/> class from the component parts of pattern
/// <c>organizations/{organization}/sources/{source}</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
public SourceName(string organizationId, string sourceId) : this(ResourceNameType.OrganizationSource, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)))
{
}
/// <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>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Source</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string SourceId { 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.OrganizationSource: return s_organizationSource.Expand(OrganizationId, SourceId);
case ResourceNameType.FolderSource: return s_folderSource.Expand(FolderId, SourceId);
case ResourceNameType.ProjectSource: return s_projectSource.Expand(ProjectId, SourceId);
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 SourceName);
/// <inheritdoc/>
public bool Equals(SourceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SourceName a, SourceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SourceName a, SourceName b) => !(a == b);
}
public partial class Source
{
/// <summary>
/// <see cref="gcsv::SourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::SourceName SourceName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::SourceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Sse41.IsSupported)
{
using (TestTable<float> floatTable = new TestTable<float>(new float[4] { 1, -5, 100, 0 }, new float[4] { 22, -1, -50, 0 }, new float[4]))
{
var vf1 = Unsafe.Read<Vector128<float>>(floatTable.inArray1Ptr);
var vf2 = Unsafe.Read<Vector128<float>>(floatTable.inArray2Ptr);
var vf3 = Sse41.DotProduct(vf1, vf2, 255);
Unsafe.Write(floatTable.outArrayPtr, vf3);
if (!floatTable.CheckResult((x, y, z) => z.All(result => result == (x[0] * y[0]) + (x[1] * y[1]) +
(x[2] * y[2]) + (x[3] * y[3]))))
{
Console.WriteLine("SSE41 DotProduct failed on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf3 = Sse41.DotProduct(vf1, vf2, 127);
Unsafe.Write(floatTable.outArrayPtr, vf3);
if (!floatTable.CheckResult((x, y, z) => z.All(result => result == (x[0] * y[0]) + (x[1] * y[1]) +
(x[2] * y[2]))))
{
Console.WriteLine("SSE41 DotProduct failed on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf3 = Sse41.DotProduct(vf1, vf2, 63);
Unsafe.Write(floatTable.outArrayPtr, vf3);
if (!floatTable.CheckResult((x, y, z) => z.All(result => result == ((x[0] * y[0]) + (x[1] * y[1])))))
{
Console.WriteLine("3 SSE41 DotProduct failed on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf3 = Sse41.DotProduct(vf1, vf2, 85);
Unsafe.Write(floatTable.outArrayPtr, vf3);
if (!floatTable.CheckResult((x, y, z) => z[0] == ((x[0] * y[0]) + (x[2] * y[2])) &&
z[2] == ((x[0] * y[0]) + (x[2] * y[2])) &&
z[1] == 0 && z[3] == 0))
{
Console.WriteLine("SSE41 DotProduct failed on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf3 = (Vector128<float>)typeof(Sse41).GetMethod(nameof(Sse41.DotProduct), new Type[] { vf1.GetType(), vf2.GetType(), typeof(byte) }).Invoke(null, new object[] { vf1, vf2, (byte)(255) });
Unsafe.Write(floatTable.outArrayPtr, vf3);
if (!floatTable.CheckResult((x, y, z) => z.All(result => result == (x[0] * y[0]) + (x[1] * y[1]) +
(x[2] * y[2]) + (x[3] * y[3]))))
{
Console.WriteLine("SSE41 DotProduct failed on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<double> doubleTable = new TestTable<double>(new double[2] { 1, -5 }, new double[2] { 22, -1 }, new double[2]))
{
var vf1 = Unsafe.Read<Vector128<double>>(doubleTable.inArray1Ptr);
var vf2 = Unsafe.Read<Vector128<double>>(doubleTable.inArray2Ptr);
var vf3 = Sse41.DotProduct(vf1, vf2, 51);
Unsafe.Write(doubleTable.outArrayPtr, vf3);
if (!doubleTable.CheckResult((x, y, z) => z.All(result => result == (x[0] * y[0]) + (x[1] * y[1]))))
{
Console.WriteLine("SSE41 DotProduct failed on double:");
foreach (var item in doubleTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf3 = Sse41.DotProduct(vf1, vf2, 19);
Unsafe.Write(doubleTable.outArrayPtr, vf3);
if (!doubleTable.CheckResult((x, y, z) => z.All(result => result == (x[0] * y[0]))))
{
Console.WriteLine("SSE41 DotProduct failed on double:");
foreach (var item in doubleTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf3 = Sse41.DotProduct(vf1, vf2, 17);
Unsafe.Write(doubleTable.outArrayPtr, vf3);
if (!doubleTable.CheckResult((x, y, z) => z[0] == (x[0] * y[0]) &&
z[1] == 0))
{
Console.WriteLine("SSE41 DotProduct failed on double:");
foreach (var item in doubleTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf3 = Sse41.DotProduct(vf1, vf2, 33);
Unsafe.Write(doubleTable.outArrayPtr, vf3);
if (!doubleTable.CheckResult((x, y, z) => z[0] == (x[1] * y[1]) &&
z[1] == 0))
{
Console.WriteLine("SSE41 DotProduct failed on double:");
foreach (var item in doubleTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf3 = (Vector128<double>)typeof(Sse41).GetMethod(nameof(Sse41.DotProduct), new Type[] { vf1.GetType(), vf2.GetType(), typeof(byte) }).Invoke(null, new object[] { vf1, vf2, (byte)(51) });
Unsafe.Write(doubleTable.outArrayPtr, vf3);
if (!doubleTable.CheckResult((x, y, z) => z.All(result => result == (x[0] * y[0]) + (x[1] * y[1]))))
{
Console.WriteLine("SSE41 DotProduct failed on double:");
foreach (var item in doubleTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
}
return testResult;
}
public unsafe struct TestTable<T> : IDisposable where T : struct
{
public T[] inArray1;
public T[] inArray2;
public T[] outArray;
public void* inArray1Ptr => inHandle1.AddrOfPinnedObject().ToPointer();
public void* inArray2Ptr => inHandle2.AddrOfPinnedObject().ToPointer();
public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer();
GCHandle inHandle1;
GCHandle inHandle2;
GCHandle outHandle;
public TestTable(T[] a, T[] b, T[] c)
{
this.inArray1 = a;
this.inArray2 = b;
this.outArray = c;
inHandle1 = GCHandle.Alloc(inArray1, GCHandleType.Pinned);
inHandle2 = GCHandle.Alloc(inArray2, GCHandleType.Pinned);
outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned);
}
public bool CheckResult(Func<T[], T[], T[], bool> check)
{
return check(inArray1, inArray2, outArray);
}
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Redis;
using Microsoft.Azure.Management.Redis.Models;
namespace Microsoft.Azure.Management.Redis
{
/// <summary>
/// .Net client wrapper for the REST API for Azure Redis Cache Management
/// Service
/// </summary>
public static partial class RedisOperationsExtensions
{
/// <summary>
/// Create a redis cache, or replace (overwrite/recreate, with
/// potential downtime) an existing cache
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate redis operation.
/// </param>
/// <returns>
/// The response of CreateOrUpdate redis operation.
/// </returns>
public static RedisCreateOrUpdateResponse CreateOrUpdate(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).CreateOrUpdateAsync(resourceGroupName, name, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a redis cache, or replace (overwrite/recreate, with
/// potential downtime) an existing cache
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate redis operation.
/// </param>
/// <returns>
/// The response of CreateOrUpdate redis operation.
/// </returns>
public static Task<RedisCreateOrUpdateResponse> CreateOrUpdateAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, name, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes a redis cache. This operation takes a while to complete.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IRedisOperations operations, string resourceGroupName, string name)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).DeleteAsync(resourceGroupName, name);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a redis cache. This operation takes a while to complete.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IRedisOperations operations, string resourceGroupName, string name)
{
return operations.DeleteAsync(resourceGroupName, name, CancellationToken.None);
}
/// <summary>
/// Gets a redis cache (resource description).
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <returns>
/// The response of GET redis operation.
/// </returns>
public static RedisGetResponse Get(this IRedisOperations operations, string resourceGroupName, string name)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).GetAsync(resourceGroupName, name);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a redis cache (resource description).
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <returns>
/// The response of GET redis operation.
/// </returns>
public static Task<RedisGetResponse> GetAsync(this IRedisOperations operations, string resourceGroupName, string name)
{
return operations.GetAsync(resourceGroupName, name, CancellationToken.None);
}
/// <summary>
/// Gets all redis caches in a resource group (if provided) otherwise
/// all in subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Optional. The name of the resource group.
/// </param>
/// <returns>
/// The response of list redis operation.
/// </returns>
public static RedisListResponse List(this IRedisOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).ListAsync(resourceGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all redis caches in a resource group (if provided) otherwise
/// all in subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Optional. The name of the resource group.
/// </param>
/// <returns>
/// The response of list redis operation.
/// </returns>
public static Task<RedisListResponse> ListAsync(this IRedisOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName, CancellationToken.None);
}
/// <summary>
/// Retrieve a redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <returns>
/// The response of redis list keys operation.
/// </returns>
public static RedisListKeysResponse ListKeys(this IRedisOperations operations, string resourceGroupName, string name)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).ListKeysAsync(resourceGroupName, name);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <returns>
/// The response of redis list keys operation.
/// </returns>
public static Task<RedisListKeysResponse> ListKeysAsync(this IRedisOperations operations, string resourceGroupName, string name)
{
return operations.ListKeysAsync(resourceGroupName, name, CancellationToken.None);
}
/// <summary>
/// Gets all redis caches using next link.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// The response of list redis operation.
/// </returns>
public static RedisListResponse ListNext(this IRedisOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all redis caches using next link.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// The response of list redis operation.
/// </returns>
public static Task<RedisListResponse> ListNextAsync(this IRedisOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Regenerate redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Required. Specifies which key to reset.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse RegenerateKey(this IRedisOperations operations, string resourceGroupName, string name, RedisRegenerateKeyParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).RegenerateKeyAsync(resourceGroupName, name, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerate redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Required. Specifies which key to reset.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> RegenerateKeyAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisRegenerateKeyParameters parameters)
{
return operations.RegenerateKeyAsync(resourceGroupName, name, parameters, CancellationToken.None);
}
}
}
| |
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using GitMind.Common.ThemeHandling;
using GitMind.Features.Diffing;
using GitMind.Features.Tags;
using GitMind.GitModel;
using GitMind.Utils.Git;
using GitMind.Utils.UI;
using IBranchService = GitMind.Features.Branches.IBranchService;
using ICommitsService = GitMind.Features.Commits.ICommitsService;
namespace GitMind.RepositoryViews
{
internal class CommitViewModel : ViewModel
{
private readonly IBranchService branchService;
private readonly IDiffService diffService;
private readonly IThemeService themeService;
private readonly IRepositoryCommands repositoryCommands;
private readonly ICommitsService commitsService;
private readonly ITagService tagService;
private Commit commit;
private int windowWidth;
public CommitViewModel(
IBranchService branchService,
IDiffService diffService,
IThemeService themeService,
IRepositoryCommands repositoryCommands,
ICommitsService commitsService,
ITagService tagService)
{
this.branchService = branchService;
this.diffService = diffService;
this.themeService = themeService;
this.repositoryCommands = repositoryCommands;
this.commitsService = commitsService;
this.tagService = tagService;
}
public int ZIndex => 400;
public string Type => nameof(CommitViewModel);
public string CommitId => Commit.RealCommitSha.Sha;
public string ShortId => Commit.RealCommitSha.ShortSha;
public string Author => Commit.Author;
public string Date => Commit.AuthorDateText;
public string Subject { get; private set; }
//public string Tags { get; private set; }
//public string Tickets => Commit.Tickets;
public string BranchTips => Commit.BranchTips;
public string CommitBranchText => $"Hide branch: {Commit.Branch.Name}";
public string SwitchToBranchText => $"Switch to branch: {Commit.Branch.Name}";
public string MergeBranchCommitText => $"Merge from this commit to branch: {Commit.Repository.CurrentBranch.Name}";
public string PreviewMergeBranchCommitText => $"Preview merge from this commit to branch: {Commit.Repository.CurrentBranch.Name}";
public string CommitBranchName => Commit.Branch.Name;
public bool IsCurrent => Commit.IsCurrent;
public bool IsUncommitted => Commit.IsUncommitted;
public bool IsNotUncommitted => !Commit.IsUncommitted;
public bool CanUncommit => UncommitCommand.CanExecute();
public bool CanUndo => !Commit.IsUncommitted;
public bool IsShown => BranchTips == null;
public string BranchToolTip { get; set; }
public bool CanMerge => Commit.Branch.IsCanBeMergeToOther;
public int XPoint { get; set; }
public int YPoint => IsEndPoint ? 4 : IsMergePoint ? 2 : 4;
public int Size => IsEndPoint ? 8 : IsMergePoint ? 10 : 6;
public Rect Rect { get; set; }
public double Top => Rect.Top;
public double Left => Rect.Left;
public double Height => Rect.Height;
public Brush SubjectBrush { get; set; }
public Brush TagBrush { get; set; }
public Brush TagBackgroundBrush { get; set; }
public Brush TicketBrush { get; set; }
public Brush TicketBackgroundBrush { get; set; }
public Brush BranchTipBrush { get; set; }
public bool HasDeleteTags => DeleteTagItems.Any();
//public FontWeight SubjectWeight => Commit.CommitBranchName != null ? FontWeights.Bold : FontWeights.Normal;
public string ToolTip { get; set; }
public Brush Brush { get; set; }
public FontStyle SubjectStyle => Commit.IsVirtual ? FontStyles.Italic : FontStyles.Normal;
public Brush HoverBrush => themeService.Theme.HoverBrush;
public ObservableCollection<LinkItem> Tickets { get; private set; }
public ObservableCollection<LinkItem> Tags { get; private set; }
public ObservableCollection<DeleteTagItem> DeleteTagItems { get; private set; }
public double Width
{
get { return Get(); }
set { Set(value - 2); }
}
public int GraphWidth
{
get { return Get(); }
set { Set(value); }
}
public Brush BrushInner
{
get { return Get(); }
set { Set(value); }
}
public int WindowWidth
{
get { return windowWidth; }
set
{
if (windowWidth != value)
{
windowWidth = value;
Width = windowWidth - 35;
}
}
}
public Command CommitCommand => AsyncCommand(() => commitsService.CommitChangesAsync());
public Command ToggleDetailsCommand => Command(repositoryCommands.ToggleCommitDetails);
public Command ShowCommitDiffCommand => Command(
() => repositoryCommands.ShowDiff(
Commit.IsVirtual && !Commit.IsUncommitted ? Commit.FirstParent : Commit));
public Command SetCommitBranchCommand => Command(
() => commitsService.EditCommitBranchAsync(Commit));
public Command SwitchToCommitCommand => Command(
() => branchService.SwitchToBranchCommitAsync(Commit),
() => branchService.CanExecuteSwitchToBranchCommit(Commit));
public Command SwitchToBranchCommand => Command(
() => branchService.SwitchBranchAsync(Commit.Branch),
() => branchService.CanExecuteSwitchBranch(Commit.Branch));
public Command CreateBranchFromCommitCommand => Command(
() => branchService.CreateBranchFromCommitAsync(Commit));
public Command UndoUncommittedChangesCommand => AsyncCommand(
() => commitsService.UndoUncommittedChangesAsync());
public Command CleanWorkingFolderCommand => AsyncCommand(
commitsService.CleanWorkingFolderAsync);
public Command UncommitCommand => AsyncCommand(
() => commitsService.UnCommitAsync(Commit), () => commitsService.CanUnCommit(Commit));
public Command UndoCommitCommand => AsyncCommand(
() => commitsService.UndoCommitAsync(Commit), () => commitsService.CanUndoCommit(Commit));
public Command MergeBranchCommitCommand => AsyncCommand(() => branchService.MergeBranchCommitAsync(Commit));
public Command PreviewMergeCommitBranchCommand => AsyncCommand(
() => diffService.ShowPreviewMergeDiffAsync(
Commit.Repository.CurrentCommit.RealCommitSha, Commit.RealCommitSha));
public Command AddTagCommitCommand => AsyncCommand(() => tagService.AddTagAsync(Commit.RealCommitSha));
// Values used by other properties
public Commit Commit
{
get => commit;
set
{
commit = value;
SetCommitValues();
}
}
// If second parent is other branch (i.e. no a pull merge)
// If commit is first commit in a branch (first parent is other branch)
// If commit is tip commit, but not master
public bool IsMergePoint =>
(Commit.IsMergePoint && Commit.Branch != Commit.SecondParent.Branch)
|| (Commit.HasFirstParent && Commit.Branch != Commit.FirstParent.Branch)
|| (Commit == Commit.Branch.TipCommit && Commit.Branch.Name != BranchName.Master);
public bool IsEndPoint =>
(Commit.HasFirstParent && Commit.Branch != Commit.FirstParent.Branch)
|| (Commit == Commit.Branch.TipCommit && Commit.Branch.Name != BranchName.Master);
// Value used by merge and that determine if item is visible
public BranchViewModel BranchViewModel { get; set; }
public int RowIndex { get; set; }
public int X => BranchViewModel?.X ?? -20;
public int Y => Converters.ToY(RowIndex) + 10;
public void SetDim()
{
SubjectBrush = themeService.Theme.DimBrush;
TagBrush = themeService.Theme.DimBrush;
TicketBackgroundBrush = themeService.Theme.BackgroundBrush;
TicketBrush = themeService.Theme.DimBrush;
TicketBackgroundBrush = themeService.Theme.BackgroundBrush;
BranchTipBrush = themeService.Theme.DimBrush;
Notify(nameof(SubjectBrush), nameof(TicketBrush), nameof(TagBrush), nameof(BranchTipBrush));
}
public void SetNormal(Brush subjectBrush)
{
SubjectBrush = subjectBrush;
TagBrush = themeService.Theme.TagBrush;
TagBackgroundBrush = themeService.Theme.TagBackgroundBrush;
TicketBrush = themeService.Theme.TicketBrush;
TicketBackgroundBrush = themeService.Theme.TicketBackgroundBrush;
BranchTipBrush = themeService.Theme.BranchTipsBrush;
Notify(nameof(SubjectBrush), nameof(TicketBrush), nameof(TagBrush), nameof(BranchTipBrush));
}
private void SetCommitValues()
{
ObservableCollection<LinkItem> issueItems = new ObservableCollection<LinkItem>();
ObservableCollection<LinkItem> tagItems = new ObservableCollection<LinkItem>();
ObservableCollection<DeleteTagItem> deleteTagItems = new ObservableCollection<DeleteTagItem>();
Links subjectIssueLinks = commitsService.GetIssueLinks(Commit.Message);
if (!string.IsNullOrEmpty(Commit.Tags))
{
var tags = Commit.Tags.Split(":".ToCharArray()).Where(n => !string.IsNullOrEmpty(n)).ToList();
foreach (string tag in tags)
{
deleteTagItems.Add(new DeleteTagItem(tagService, tag));
Links tagIssueLinks = commitsService.GetIssueLinks(tag);
Links tagTagLinks = commitsService.GetTagLinks(tag);
if (tagIssueLinks.AllLinks.Any())
{
tagIssueLinks.AllLinks.ForEach(link => issueItems.Add(new LinkItem(this, $"[{link.Text}]", link.Uri, link.LinkType)));
}
else if (tagTagLinks.AllLinks.Any())
{
tagTagLinks.AllLinks.ForEach(link => tagItems.Add(new LinkItem(this, $"[{link.Text}]", link.Uri, link.LinkType)));
}
else
{
tagItems.Add(new LinkItem(this, $"[{tag}]", null, LinkType.tag));
}
}
}
DeleteTagItems = deleteTagItems;
Tags = tagItems;
Subject = GetTextWithoutStart(Commit.Subject, subjectIssueLinks.TotalText);
subjectIssueLinks.AllLinks.ForEach(link => issueItems.Add(new LinkItem(this, link.Text, link.Uri, link.LinkType)));
Tickets = issueItems;
}
public override string ToString() => $"{ShortId} {Subject} {Date}";
private static string GetTextWithoutStart(string text, string startText)
{
if ((text?.Length ?? 0) < (startText?.Length ?? 0))
{
return text;
}
if (text != null && startText != null && text.StartsWith(startText))
{
return text?.Substring(startText?.Length ?? 0);
}
return text;
}
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Orleans;
using Orleans.AzureUtils;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Tester;
using TestExtensions;
using UnitTests.MembershipTests;
using Xunit;
using Xunit.Abstractions;
namespace Tester.AzureUtils
{
/// <summary>
/// Tests for operation of Orleans SiloInstanceManager using AzureStore - Requires access to external Azure storage
/// </summary>
public class SiloInstanceTableManagerTests : IClassFixture<SiloInstanceTableManagerTests.Fixture>, IDisposable
{
public class Fixture
{
public Fixture()
{
LogManager.Initialize(new NodeConfiguration());
TestUtils.CheckForAzureStorage();
}
}
private string deploymentId;
private int generation;
private SiloAddress siloAddress;
private SiloInstanceTableEntry myEntry;
private OrleansSiloInstanceManager manager;
private readonly Logger logger;
private readonly ITestOutputHelper output;
public SiloInstanceTableManagerTests(ITestOutputHelper output)
{
this.output = output;
logger = LogManager.GetLogger("SiloInstanceTableManagerTests", LoggerType.Application);
deploymentId = "test-" + Guid.NewGuid();
generation = SiloAddress.AllocateNewGeneration();
siloAddress = SiloAddress.NewLocalAddress(generation);
logger.Info("DeploymentId={0} Generation={1}", deploymentId, generation);
logger.Info("Initializing SiloInstanceManager");
manager = OrleansSiloInstanceManager.GetManager(deploymentId, TestDefaultConfiguration.DataConnectionString)
.WaitForResultWithThrow(SiloInstanceTableTestConstants.Timeout);
}
// Use TestCleanup to run code after each test has run
public void Dispose()
{
if(manager != null && SiloInstanceTableTestConstants.DeleteEntriesAfterTest)
{
TimeSpan timeout = SiloInstanceTableTestConstants.Timeout;
logger.Info("TestCleanup Timeout={0}", timeout);
manager.DeleteTableEntries(deploymentId).WaitWithThrow(timeout);
logger.Info("TestCleanup - Finished");
manager = null;
}
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public void SiloInstanceTable_Op_RegisterSiloInstance()
{
RegisterSiloInstance();
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public void SiloInstanceTable_Op_ActivateSiloInstance()
{
RegisterSiloInstance();
manager.ActivateSiloInstance(myEntry);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public void SiloInstanceTable_Op_UnregisterSiloInstance()
{
RegisterSiloInstance();
manager.UnregisterSiloInstance(myEntry);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task SiloInstanceTable_Op_CreateSiloEntryConditionally()
{
bool didInsert = await manager.TryCreateTableVersionEntryAsync()
.WithTimeout(AzureTableDefaultPolicies.TableOperationTimeout);
Assert.True(didInsert, "Did insert");
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task SiloInstanceTable_Register_CheckData()
{
const string testName = "SiloInstanceTable_Register_CheckData";
logger.Info("Start {0}", testName);
RegisterSiloInstance();
var data = await FindSiloEntry(siloAddress);
SiloInstanceTableEntry siloEntry = data.Item1;
string eTag = data.Item2;
Assert.NotNull(eTag); // ETag should not be null
Assert.NotNull(siloEntry); // SiloInstanceTableEntry should not be null
Assert.Equal(SiloInstanceTableTestConstants.INSTANCE_STATUS_CREATED, siloEntry.Status);
CheckSiloInstanceTableEntry(myEntry, siloEntry);
logger.Info("End {0}", testName);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task SiloInstanceTable_Activate_CheckData()
{
RegisterSiloInstance();
manager.ActivateSiloInstance(myEntry);
var data = await FindSiloEntry(siloAddress);
Assert.NotNull(data); // Data returned should not be null
SiloInstanceTableEntry siloEntry = data.Item1;
string eTag = data.Item2;
Assert.NotNull(eTag); // ETag should not be null
Assert.NotNull(siloEntry); // SiloInstanceTableEntry should not be null
Assert.Equal(SiloInstanceTableTestConstants.INSTANCE_STATUS_ACTIVE, siloEntry.Status);
CheckSiloInstanceTableEntry(myEntry, siloEntry);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task SiloInstanceTable_Unregister_CheckData()
{
RegisterSiloInstance();
manager.UnregisterSiloInstance(myEntry);
var data = await FindSiloEntry(siloAddress);
SiloInstanceTableEntry siloEntry = data.Item1;
string eTag = data.Item2;
Assert.NotNull(eTag); // ETag should not be null
Assert.NotNull(siloEntry); // SiloInstanceTableEntry should not be null
Assert.Equal(SiloInstanceTableTestConstants.INSTANCE_STATUS_DEAD, siloEntry.Status);
CheckSiloInstanceTableEntry(myEntry, siloEntry);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public void SiloInstanceTable_FindAllGatewayProxyEndpoints()
{
RegisterSiloInstance();
var gateways = manager.FindAllGatewayProxyEndpoints().GetResult();
Assert.Equal(0, gateways.Count); // "Number of gateways before Silo.Activate"
manager.ActivateSiloInstance(myEntry);
gateways = manager.FindAllGatewayProxyEndpoints().GetResult();
Assert.Equal(1, gateways.Count); // "Number of gateways after Silo.Activate"
Uri myGateway = gateways.First();
Assert.Equal(myEntry.Address, myGateway.Host.ToString()); // "Gateway address"
Assert.Equal(myEntry.ProxyPort, myGateway.Port.ToString(CultureInfo.InvariantCulture)); // "Gateway port"
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public void SiloAddress_ToFrom_RowKey()
{
string ipAddress = "1.2.3.4";
int port = 5555;
int generation = 6666;
IPAddress address = IPAddress.Parse(ipAddress);
IPEndPoint endpoint = new IPEndPoint(address, port);
SiloAddress siloAddress = SiloAddress.New(endpoint, generation);
string MembershipRowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress);
output.WriteLine("SiloAddress = {0} Row Key string = {1}", siloAddress, MembershipRowKey);
SiloAddress fromRowKey = SiloInstanceTableEntry.UnpackRowKey(MembershipRowKey);
output.WriteLine("SiloAddress result = {0} From Row Key string = {1}", fromRowKey, MembershipRowKey);
Assert.Equal(siloAddress, fromRowKey);
Assert.Equal(SiloInstanceTableEntry.ConstructRowKey(siloAddress), SiloInstanceTableEntry.ConstructRowKey(fromRowKey));
}
private void RegisterSiloInstance()
{
string partitionKey = deploymentId;
string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress);
IPEndPoint myEndpoint = siloAddress.Endpoint;
myEntry = new SiloInstanceTableEntry
{
PartitionKey = partitionKey,
RowKey = rowKey,
DeploymentId = deploymentId,
Address = myEndpoint.Address.ToString(),
Port = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),
Generation = generation.ToString(CultureInfo.InvariantCulture),
HostName = myEndpoint.Address.ToString(),
ProxyPort = "30000",
RoleName = "MyRole",
SiloName = "MyInstance",
UpdateZone = "0",
FaultZone = "0",
StartTime = LogFormatter.PrintDate(DateTime.UtcNow),
};
logger.Info("MyEntry={0}", myEntry);
manager.RegisterSiloInstance(myEntry);
}
private async Task<Tuple<SiloInstanceTableEntry, string>> FindSiloEntry(SiloAddress siloAddr)
{
string partitionKey = deploymentId;
string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddr);
logger.Info("FindSiloEntry for SiloAddress={0} PartitionKey={1} RowKey={2}", siloAddr, partitionKey, rowKey);
Tuple<SiloInstanceTableEntry, string> data = await manager.ReadSingleTableEntryAsync(partitionKey, rowKey);
logger.Info("FindSiloEntry returning Data={0}", data);
return data;
}
private void CheckSiloInstanceTableEntry(SiloInstanceTableEntry referenceEntry, SiloInstanceTableEntry entry)
{
Assert.Equal(referenceEntry.DeploymentId, entry.DeploymentId);
Assert.Equal(referenceEntry.Address, entry.Address);
Assert.Equal(referenceEntry.Port, entry.Port);
Assert.Equal(referenceEntry.Generation, entry.Generation);
Assert.Equal(referenceEntry.HostName, entry.HostName);
//Assert.Equal(referenceEntry.Status, entry.Status);
Assert.Equal(referenceEntry.ProxyPort, entry.ProxyPort);
Assert.Equal(referenceEntry.RoleName, entry.RoleName);
Assert.Equal(referenceEntry.SiloName, entry.SiloName);
Assert.Equal(referenceEntry.UpdateZone, entry.UpdateZone);
Assert.Equal(referenceEntry.FaultZone, entry.FaultZone);
Assert.Equal(referenceEntry.StartTime, entry.StartTime);
Assert.Equal(referenceEntry.IAmAliveTime, entry.IAmAliveTime);
Assert.Equal(referenceEntry.MembershipVersion, entry.MembershipVersion);
Assert.Equal(referenceEntry.SuspectingTimes, entry.SuspectingTimes);
Assert.Equal(referenceEntry.SuspectingSilos, entry.SuspectingSilos);
}
}
}
| |
using Orleans.TestingHost;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Tester;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
using Xunit.Abstractions;
namespace AWSUtils.Tests.StorageTests
{
public abstract class Base_PersistenceGrainTests_AWSStore : OrleansTestingBase
{
private readonly ITestOutputHelper output;
protected TestCluster HostedCluster { get; private set; }
private readonly double timingFactor;
private const int LoopIterations_Grain = 1000;
private const int BatchSize = 100;
private const int MaxReadTime = 200;
private const int MaxWriteTime = 2000;
private readonly BaseTestClusterFixture fixture;
public Base_PersistenceGrainTests_AWSStore(ITestOutputHelper output, BaseTestClusterFixture fixture)
{
if (!AWSTestConstants.IsDynamoDbAvailable)
throw new SkipException("Unable to connect to DynamoDB simulator");
this.output = output;
this.fixture = fixture;
HostedCluster = fixture.HostedCluster;
timingFactor = TestUtils.CalibrateTimings();
}
protected async Task Grain_AWSStore_Delete()
{
Guid id = Guid.NewGuid();
IAWSStorageTestGrain grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id);
await grain.DoWrite(1);
await grain.DoDelete();
int val = await grain.GetValue(); // Should this throw instead?
Assert.Equal(0, val); // "Value after Delete"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Delete + New Write"
}
protected async Task Grain_AWSStore_Read()
{
Guid id = Guid.NewGuid();
IAWSStorageTestGrain grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
}
protected async Task Grain_GuidKey_AWSStore_Read_Write()
{
Guid id = Guid.NewGuid();
IAWSStorageTestGrain grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
await grain.DoWrite(1);
val = await grain.GetValue();
Assert.Equal(1, val); // "Value after Write-1"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(2, val); // "Value after Re-Read"
}
protected async Task Grain_LongKey_AWSStore_Read_Write()
{
long id = random.Next();
IAWSStorageTestGrain_LongKey grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain_LongKey>(id);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
await grain.DoWrite(1);
val = await grain.GetValue();
Assert.Equal(1, val); // "Value after Write-1"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(2, val); // "Value after Re-Read"
}
protected async Task Grain_LongKeyExtended_AWSStore_Read_Write()
{
long id = random.Next();
string extKey = random.Next().ToString(CultureInfo.InvariantCulture);
IAWSStorageTestGrain_LongExtendedKey
grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain_LongExtendedKey>(id, extKey, null);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
await grain.DoWrite(1);
val = await grain.GetValue();
Assert.Equal(1, val); // "Value after Write-1"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(2, val); // "Value after DoRead"
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Re-Read"
string extKeyValue = await grain.GetExtendedKeyValue();
Assert.Equal(extKey, extKeyValue); // "Extended Key"
}
protected async Task Grain_GuidKeyExtended_AWSStore_Read_Write()
{
var id = Guid.NewGuid();
string extKey = random.Next().ToString(CultureInfo.InvariantCulture);
IAWSStorageTestGrain_GuidExtendedKey
grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain_GuidExtendedKey>(id, extKey, null);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
await grain.DoWrite(1);
val = await grain.GetValue();
Assert.Equal(1, val); // "Value after Write-1"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(2, val); // "Value after DoRead"
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Re-Read"
string extKeyValue = await grain.GetExtendedKeyValue();
Assert.Equal(extKey, extKeyValue); // "Extended Key"
}
protected async Task Grain_Generic_AWSStore_Read_Write()
{
long id = random.Next();
IAWSStorageGenericGrain<int> grain = this.fixture.GrainFactory.GetGrain<IAWSStorageGenericGrain<int>>(id);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
await grain.DoWrite(1);
val = await grain.GetValue();
Assert.Equal(1, val); // "Value after Write-1"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(2, val); // "Value after Re-Read"
}
protected async Task Grain_Generic_AWSStore_DiffTypes()
{
long id1 = random.Next();
long id2 = id1;
long id3 = id1;
IAWSStorageGenericGrain<int> grain1 = this.fixture.GrainFactory.GetGrain<IAWSStorageGenericGrain<int>>(id1);
IAWSStorageGenericGrain<string> grain2 = this.fixture.GrainFactory.GetGrain<IAWSStorageGenericGrain<string>>(id2);
IAWSStorageGenericGrain<double> grain3 = this.fixture.GrainFactory.GetGrain<IAWSStorageGenericGrain<double>>(id3);
int val1 = await grain1.GetValue();
Assert.Equal(0, val1); // "Initial value - 1"
string val2 = await grain2.GetValue();
Assert.Null(val2); // "Initial value - 2"
double val3 = await grain3.GetValue();
Assert.Equal(0.0, val3); // "Initial value - 3"
int expected1 = 1;
await grain1.DoWrite(expected1);
val1 = await grain1.GetValue();
Assert.Equal(expected1, val1); // "Value after Write#1 - 1"
string expected2 = "Three";
await grain2.DoWrite(expected2);
val2 = await grain2.GetValue();
Assert.Equal(expected2, val2); // "Value after Write#1 - 2"
double expected3 = 5.1;
await grain3.DoWrite(expected3);
val3 = await grain3.GetValue();
Assert.Equal(expected3, val3); // "Value after Write#1 - 3"
val1 = await grain1.GetValue();
Assert.Equal(expected1, val1); // "Value before Write#2 - 1"
expected1 = 2;
await grain1.DoWrite(expected1);
val1 = await grain1.GetValue();
Assert.Equal(expected1, val1); // "Value after Write#2 - 1"
val1 = await grain1.DoRead();
Assert.Equal(expected1, val1); // "Value after Re-Read - 1"
val2 = await grain2.GetValue();
Assert.Equal(expected2, val2); // "Value before Write#2 - 2"
expected2 = "Four";
await grain2.DoWrite(expected2);
val2 = await grain2.GetValue();
Assert.Equal(expected2, val2); // "Value after Write#2 - 2"
val2 = await grain2.DoRead();
Assert.Equal(expected2, val2); // "Value after Re-Read - 2"
val3 = await grain3.GetValue();
Assert.Equal(expected3, val3); // "Value before Write#2 - 3"
expected3 = 6.2;
await grain3.DoWrite(expected3);
val3 = await grain3.GetValue();
Assert.Equal(expected3, val3); // "Value after Write#2 - 3"
val3 = await grain3.DoRead();
Assert.Equal(expected3, val3); // "Value after Re-Read - 3"
}
protected async Task Grain_AWSStore_SiloRestart()
{
var initialServiceId = this.HostedCluster.Options.ServiceId;
var initialDeploymentId = this.HostedCluster.Options.ClusterId;
var serviceId = await this.HostedCluster.Client.GetGrain<IServiceIdGrain>(Guid.Empty).GetServiceId();
output.WriteLine("ClusterId={0} ServiceId={1}", this.HostedCluster.Options.ClusterId, serviceId);
Guid id = Guid.NewGuid();
IAWSStorageTestGrain grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id);
int val = await grain.GetValue();
Assert.Equal(0, val); // "Initial value"
await grain.DoWrite(1);
output.WriteLine("About to reset Silos");
foreach (var silo in this.HostedCluster.GetActiveSilos().ToList())
{
await this.HostedCluster.RestartSiloAsync(silo);
}
await this.HostedCluster.StopClusterClientAsync();
await this.HostedCluster.InitializeClientAsync();
output.WriteLine("Silos restarted");
serviceId = await this.HostedCluster.Client.GetGrain<IServiceIdGrain>(Guid.Empty).GetServiceId();
output.WriteLine("ClusterId={0} ServiceId={1}", this.HostedCluster.Options.ClusterId, serviceId);
Assert.Equal(initialServiceId, serviceId); // "ServiceId same after restart."
Assert.Equal(initialDeploymentId, this.HostedCluster.Options.ClusterId); // "ClusterId same after restart."
val = await grain.GetValue();
Assert.Equal(1, val); // "Value after Write-1"
await grain.DoWrite(2);
val = await grain.GetValue();
Assert.Equal(2, val); // "Value after Write-2"
val = await grain.DoRead();
Assert.Equal(2, val); // "Value after Re-Read"
}
protected void Persistence_Perf_Activate()
{
const string testName = "Persistence_Perf_Activate";
int n = LoopIterations_Grain;
TimeSpan target = TimeSpan.FromMilliseconds(MaxReadTime * n);
// Timings for Activate
RunPerfTest(n, testName, target,
grainNoState => grainNoState.PingAsync(),
grainMemory => grainMemory.DoSomething(),
grainMemoryStore => grainMemoryStore.GetValue(),
grainAWSStore => grainAWSStore.GetValue());
}
protected void Persistence_Perf_Write()
{
const string testName = "Persistence_Perf_Write";
int n = LoopIterations_Grain;
TimeSpan target = TimeSpan.FromMilliseconds(MaxWriteTime * n);
// Timings for Write
RunPerfTest(n, testName, target,
grainNoState => grainNoState.EchoAsync(testName),
grainMemory => grainMemory.DoWrite(n),
grainMemoryStore => grainMemoryStore.DoWrite(n),
grainAWSStore => grainAWSStore.DoWrite(n));
}
protected void Persistence_Perf_Write_Reread()
{
const string testName = "Persistence_Perf_Write_Read";
int n = LoopIterations_Grain;
TimeSpan target = TimeSpan.FromMilliseconds(MaxWriteTime * n);
// Timings for Write
RunPerfTest(n, testName + "--Write", target,
grainNoState => grainNoState.EchoAsync(testName),
grainMemory => grainMemory.DoWrite(n),
grainMemoryStore => grainMemoryStore.DoWrite(n),
grainAWSStore => grainAWSStore.DoWrite(n));
// Timings for Activate
RunPerfTest(n, testName + "--ReRead", target,
grainNoState => grainNoState.GetLastEchoAsync(),
grainMemory => grainMemory.DoRead(),
grainMemoryStore => grainMemoryStore.DoRead(),
grainAWSStore => grainAWSStore.DoRead());
}
protected async Task Persistence_Silo_StorageProvider_AWS(Type providerType)
{
List<SiloHandle> silos = this.HostedCluster.GetActiveSilos().ToList();
foreach (var silo in silos)
{
string provider = providerType.FullName;
ICollection<string> providers = await this.HostedCluster.Client.GetTestHooks(silo).GetStorageProviderNames();
Assert.True(providers.Contains(provider), $"No storage provider found: {provider}");
}
}
// ---------- Utility functions ----------
protected void RunPerfTest(int n, string testName, TimeSpan target,
Func<IEchoTaskGrain, Task> actionNoState,
Func<IPersistenceTestGrain, Task> actionMemory,
Func<IMemoryStorageTestGrain, Task> actionMemoryStore,
Func<IAWSStorageTestGrain, Task> actionAWSTable)
{
IEchoTaskGrain[] noStateGrains = new IEchoTaskGrain[n];
IPersistenceTestGrain[] memoryGrains = new IPersistenceTestGrain[n];
IAWSStorageTestGrain[] awsStoreGrains = new IAWSStorageTestGrain[n];
IMemoryStorageTestGrain[] memoryStoreGrains = new IMemoryStorageTestGrain[n];
for (int i = 0; i < n; i++)
{
Guid id = Guid.NewGuid();
noStateGrains[i] = this.fixture.GrainFactory.GetGrain<IEchoTaskGrain>(id);
memoryGrains[i] = this.fixture.GrainFactory.GetGrain<IPersistenceTestGrain>(id);
awsStoreGrains[i] = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id);
memoryStoreGrains[i] = this.fixture.GrainFactory.GetGrain<IMemoryStorageTestGrain>(id);
}
TimeSpan baseline, elapsed;
elapsed = baseline = TestUtils.TimeRun(n, TimeSpan.Zero, testName + " (No state)",
() => RunIterations(testName, n, i => actionNoState(noStateGrains[i])));
elapsed = TestUtils.TimeRun(n, baseline, testName + " (Local Memory Store)",
() => RunIterations(testName, n, i => actionMemory(memoryGrains[i])));
elapsed = TestUtils.TimeRun(n, baseline, testName + " (Dev Store Grain Store)",
() => RunIterations(testName, n, i => actionMemoryStore(memoryStoreGrains[i])));
elapsed = TestUtils.TimeRun(n, baseline, testName + " (AWS Table Store)",
() => RunIterations(testName, n, i => actionAWSTable(awsStoreGrains[i])));
if (elapsed > target.Multiply(timingFactor))
{
string msg = string.Format("{0}: Elapsed time {1} exceeds target time {2}", testName, elapsed, target);
if (elapsed > target.Multiply(2.0 * timingFactor))
{
Assert.True(false, msg);
}
else
{
throw new SkipException(msg);
}
}
}
private void RunIterations(string testName, int n, Func<int, Task> action)
{
List<Task> promises = new List<Task>();
Stopwatch sw = Stopwatch.StartNew();
// Fire off requests in batches
for (int i = 0; i < n; i++)
{
var promise = action(i);
promises.Add(promise);
if ((i % BatchSize) == 0 && i > 0)
{
Task.WaitAll(promises.ToArray());
promises.Clear();
//output.WriteLine("{0} has done {1} iterations in {2} at {3} RPS",
// testName, i, sw.Elapsed, i / sw.Elapsed.TotalSeconds);
}
}
Task.WaitAll(promises.ToArray());
sw.Stop();
output.WriteLine("{0} completed. Did {1} iterations in {2} at {3} RPS",
testName, n, sw.Elapsed, n / sw.Elapsed.TotalSeconds);
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type GraphServiceWorkbooksCollectionRequest.
/// </summary>
public partial class GraphServiceWorkbooksCollectionRequest : BaseRequest, IGraphServiceWorkbooksCollectionRequest
{
/// <summary>
/// Constructs a new GraphServiceWorkbooksCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public GraphServiceWorkbooksCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified DriveItem to the collection via POST.
/// </summary>
/// <param name="driveItem">The DriveItem to add.</param>
/// <returns>The created DriveItem.</returns>
public System.Threading.Tasks.Task<DriveItem> AddAsync(DriveItem driveItem)
{
return this.AddAsync(driveItem, CancellationToken.None);
}
/// <summary>
/// Adds the specified DriveItem to the collection via POST.
/// </summary>
/// <param name="driveItem">The DriveItem to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created DriveItem.</returns>
public System.Threading.Tasks.Task<DriveItem> AddAsync(DriveItem driveItem, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<DriveItem>(driveItem, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IGraphServiceWorkbooksCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IGraphServiceWorkbooksCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<GraphServiceWorkbooksCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceWorkbooksCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceWorkbooksCollectionRequest Expand(Expression<Func<DriveItem, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceWorkbooksCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceWorkbooksCollectionRequest Select(Expression<Func<DriveItem, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceWorkbooksCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceWorkbooksCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceWorkbooksCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceWorkbooksCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Runtime;
using Orleans.Transactions.Abstractions;
using Orleans.Storage;
using Orleans.Configuration;
using Orleans.Timers.Internal;
namespace Orleans.Transactions.State
{
internal class TransactionQueue<TState>
where TState : class, new()
{
private readonly TransactionalStateOptions options;
private readonly ParticipantId resource;
private readonly Action deactivate;
private readonly ITransactionalStateStorage<TState> storage;
private readonly BatchWorker storageWorker;
protected readonly ILogger logger;
private readonly IActivationLifetime activationLifetime;
private readonly ConfirmationWorker<TState> confirmationWorker;
private CommitQueue<TState> commitQueue;
private Task readyTask;
protected StorageBatch<TState> storageBatch;
private int failCounter;
// collection tasks
private Dictionary<DateTime, PreparedMessages> unprocessedPreparedMessages;
private class PreparedMessages
{
public PreparedMessages(TransactionalStatus status)
{
this.Status = status;
}
public int Count;
public TransactionalStatus Status;
}
private TState stableState;
private long stableSequenceNumber;
public ReadWriteLock<TState> RWLock { get; }
public CausalClock Clock { get; }
public TransactionQueue(
IOptions<TransactionalStateOptions> options,
ParticipantId resource,
Action deactivate,
ITransactionalStateStorage<TState> storage,
IClock clock,
ILogger logger,
ITimerManager timerManager,
IActivationLifetime activationLifetime)
{
this.options = options.Value;
this.resource = resource;
this.deactivate = deactivate;
this.storage = storage;
this.Clock = new CausalClock(clock);
this.logger = logger;
this.activationLifetime = activationLifetime;
this.storageWorker = new BatchWorkerFromDelegate(StorageWork);
this.RWLock = new ReadWriteLock<TState>(options, this, this.storageWorker, logger, activationLifetime);
this.confirmationWorker = new ConfirmationWorker<TState>(options, this.resource, this.storageWorker, () => this.storageBatch, this.logger, timerManager, activationLifetime);
this.unprocessedPreparedMessages = new Dictionary<DateTime, PreparedMessages>();
this.commitQueue = new CommitQueue<TState>();
this.readyTask = Task.CompletedTask;
}
public async Task EnqueueCommit(TransactionRecord<TState> record)
{
try
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace($"start two-phase-commit {record.TransactionId} {record.Timestamp:o}");
commitQueue.Add(record);
// additional actions for each commit type
switch (record.Role)
{
case CommitRole.ReadOnly:
{
// no extra actions needed
break;
}
case CommitRole.LocalCommit:
{
// process prepared messages received ahead of time
if (unprocessedPreparedMessages.TryGetValue(record.Timestamp, out PreparedMessages info))
{
if (info.Status == TransactionalStatus.Ok)
{
record.WaitCount -= info.Count;
}
else
{
await AbortCommits(info.Status, commitQueue.Count - 1);
this.RWLock.Notify();
}
unprocessedPreparedMessages.Remove(record.Timestamp);
}
break;
}
case CommitRole.RemoteCommit:
{
// optimization: can immediately proceed if dependency is implied
bool behindRemoteEntryBySameTM = false;
/* disabled - jbragg - TODO - revisit
commitQueue.Count >= 2
&& commitQueue[commitQueue.Count - 2] is TransactionRecord<TState> rce
&& rce.Role == CommitRole.RemoteCommit
&& rce.TransactionManager.Equals(record.TransactionManager);
*/
if (record.NumberWrites > 0)
{
this.storageBatch.Prepare(record.SequenceNumber, record.TransactionId, record.Timestamp, record.TransactionManager, record.State);
}
else
{
this.storageBatch.Read(record.Timestamp);
}
this.storageBatch.FollowUpAction(() =>
{
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace("persisted {Record}", record);
}
record.PrepareIsPersisted = true;
if (behindRemoteEntryBySameTM)
{
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace("Sending immediate prepared {Record}", record);
}
// can send prepared message immediately after persisting prepare record
record.TransactionManager.Reference.AsReference<ITransactionManagerExtension>()
.Prepared(record.TransactionManager.Name, record.TransactionId, record.Timestamp, this.resource, TransactionalStatus.Ok)
.Ignore();
record.LastSent = DateTime.UtcNow;
}
});
break;
}
default:
{
logger.LogError(777, "internal error: impossible case {CommitRole}", record.Role);
throw new NotSupportedException($"{record.Role} is not a supported CommitRole.");
}
}
}
catch (Exception e)
{
logger.Error(666, $"transaction abort due to internal error in {nameof(EnqueueCommit)}: ", e);
await NotifyOfAbort(record, TransactionalStatus.UnknownException);
}
}
public async Task NotifyOfPrepared(Guid transactionId, DateTime timeStamp, TransactionalStatus status)
{
var pos = commitQueue.Find(transactionId, timeStamp);
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("NotifyOfPrepared - TransactionId:{TransactionId} Timestamp:{Timestamp}, TransactionalStatus{TransactionalStatus}", transactionId, timeStamp, status);
if (pos != -1)
{
var localEntry = commitQueue[pos];
if (localEntry.Role != CommitRole.LocalCommit)
{
logger.Error(666, $"transaction abort due to internal error in {nameof(NotifyOfPrepared)}: Wrong commit type");
throw new InvalidOperationException($"Wrong commit type: {localEntry.Role}");
}
if (status == TransactionalStatus.Ok)
{
localEntry.WaitCount--;
storageWorker.Notify();
}
else
{
await AbortCommits(status, pos);
this.RWLock.Notify();
}
}
else
{
// this message has arrived ahead of the commit request - we need to remember it
if (!this.unprocessedPreparedMessages.TryGetValue(timeStamp, out PreparedMessages info))
{
this.unprocessedPreparedMessages[timeStamp] = info = new PreparedMessages(status);
}
if (status == TransactionalStatus.Ok)
{
info.Count++;
}
else
{
info.Status = status;
}
// TODO fix memory leak if corresponding commit messages never arrive
}
}
public async Task NotifyOfPrepare(Guid transactionId, AccessCounter accessCount, DateTime timeStamp, ParticipantId transactionManager)
{
var locked = await this.RWLock.ValidateLock(transactionId, accessCount);
var status = locked.Item1;
var record = locked.Item2;
var valid = status == TransactionalStatus.Ok;
record.Timestamp = timeStamp;
record.Role = CommitRole.RemoteCommit; // we are not the TM
record.TransactionManager = transactionManager;
record.LastSent = null;
record.PrepareIsPersisted = false;
if (!valid)
{
await this.NotifyOfAbort(record, status);
}
else
{
this.Clock.Merge(record.Timestamp);
}
this.RWLock.Notify();
}
public async Task NotifyOfAbort(TransactionRecord<TState> entry, TransactionalStatus status)
{
switch (entry.Role)
{
case CommitRole.NotYetDetermined:
{
// cannot notify anyone. TA will detect broken lock during prepare.
break;
}
case CommitRole.RemoteCommit:
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("aborting status={Status} {Entry}", status, entry);
entry.ConfirmationResponsePromise?.TrySetException(new OrleansException($"Confirm failed: Status {status}"));
if (entry.LastSent.HasValue)
return; // cannot abort anymore if we already sent prepare-ok message
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("aborting via Prepared. Status={Status} Entry={Entry}", status, entry);
entry.TransactionManager.Reference.AsReference<ITransactionManagerExtension>()
.Prepared(entry.TransactionManager.Name, entry.TransactionId, entry.Timestamp, resource, status)
.Ignore();
break;
}
case CommitRole.LocalCommit:
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("aborting status={Status} {Entry}", status, entry);
try
{
// tell remote participants
await Task.WhenAll(entry.WriteParticipants
.Where(p => !p.Equals(resource))
.Select(p => p.Reference.AsReference<ITransactionalResourceExtension>()
.Cancel(p.Name, entry.TransactionId, entry.Timestamp, status)));
} catch(Exception ex)
{
this.logger.LogWarning(ex, "Failed to notify all transaction participants of cancellation. TransactionId: {TransactionId}, Timestamp: {Timestamp}, Status: {Status}", entry.TransactionId, entry.Timestamp, status);
}
// reply to transaction agent
entry.PromiseForTA.TrySetResult(status);
break;
}
case CommitRole.ReadOnly:
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("aborting status={Status} {Entry}", status, entry);
// reply to transaction agent
entry.PromiseForTA.TrySetResult(status);
break;
}
default:
{
logger.LogError(777, "internal error: impossible case {CommitRole}", entry.Role);
throw new NotSupportedException($"{entry.Role} is not a supported CommitRole.");
}
}
}
public async Task NotifyOfPing(Guid transactionId, DateTime timeStamp, ParticipantId resource)
{
if (this.commitQueue.Find(transactionId, timeStamp) != -1)
{
// no need to take special action now - the transaction is still
// in the commit queue and its status is not yet determined.
// confirmation or cancellation will be sent after committing or aborting.
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("received ping for {TransactionId}, irrelevant (still processing)", transactionId);
this.storageWorker.Notify(); // just in case the worker fell asleep or something
}
else
{
if (!this.confirmationWorker.IsConfirmed(transactionId))
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("received ping for {TransactionId}, unknown - presumed abort", transactionId);
// we never heard of this transaction - so it must have aborted
await resource.Reference.AsReference<ITransactionalResourceExtension>()
.Cancel(resource.Name, transactionId, timeStamp, TransactionalStatus.PresumedAbort);
}
}
}
public async Task NotifyOfConfirm(Guid transactionId, DateTime timeStamp)
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace($"NotifyOfConfirm: {transactionId} {timeStamp}");
// find in queue
var pos = commitQueue.Find(transactionId, timeStamp);
if (pos == -1)
return; // must have already been confirmed
var remoteEntry = commitQueue[pos];
if (remoteEntry.Role != CommitRole.RemoteCommit)
{
logger.Error(666, $"internal error in {nameof(NotifyOfConfirm)}: wrong commit type");
throw new InvalidOperationException($"Wrong commit type: {remoteEntry.Role}");
}
// setting this field makes this entry ready for batching
remoteEntry.ConfirmationResponsePromise = remoteEntry.ConfirmationResponsePromise ?? new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
storageWorker.Notify();
// now we wait for the batch to finish
await remoteEntry.ConfirmationResponsePromise.Task;
}
public async Task NotifyOfCancel(Guid transactionId, DateTime timeStamp, TransactionalStatus status)
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("{MethodName}. TransactionId: {TransactionId}, TimeStamp: {TimeStamp} Status: {TransactionalStatus}", nameof(NotifyOfCancel), transactionId, timeStamp, status);
// find in queue
var pos = commitQueue.Find(transactionId, timeStamp);
if (pos == -1)
return;
this.storageBatch.Cancel(commitQueue[pos].SequenceNumber);
await AbortCommits(status, pos);
storageWorker.Notify();
this.RWLock.Notify();
}
/// <summary>
/// called on activation, and when recovering from storage conflicts or other exceptions.
/// </summary>
public async Task NotifyOfRestore()
{
try
{
await Ready();
}
finally
{
this.readyTask = Restore();
}
await this.readyTask;
}
/// <summary>
/// Ensures queue is ready to process requests.
/// </summary>
/// <returns></returns>
public Task Ready()
{
return this.readyTask;
}
private async Task Restore()
{
TransactionalStorageLoadResponse<TState> loadresponse = await storage.Load();
this.storageBatch = new StorageBatch<TState>(loadresponse);
this.stableState = loadresponse.CommittedState;
this.stableSequenceNumber = loadresponse.CommittedSequenceId;
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug($"Load v{this.stableSequenceNumber} {loadresponse.PendingStates.Count}p {storageBatch.MetaData.CommitRecords.Count}c");
// ensure clock is consistent with loaded state
this.Clock.Merge(storageBatch.MetaData.TimeStamp);
// resume prepared transactions (not TM)
foreach (var pr in loadresponse.PendingStates.OrderBy(ps => ps.TimeStamp))
{
if (pr.SequenceId > loadresponse.CommittedSequenceId && pr.TransactionManager.Reference != null)
{
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug($"recover two-phase-commit {pr.TransactionId}");
ParticipantId tm = pr.TransactionManager;
commitQueue.Add(new TransactionRecord<TState>()
{
Role = CommitRole.RemoteCommit,
TransactionId = Guid.Parse(pr.TransactionId),
Timestamp = pr.TimeStamp,
State = pr.State,
SequenceNumber = pr.SequenceId,
TransactionManager = tm,
PrepareIsPersisted = true,
LastSent = default(DateTime),
ConfirmationResponsePromise = null,
NumberWrites = 1 // was a writing transaction
});
this.stableSequenceNumber = pr.SequenceId;
}
}
// resume committed transactions (on TM)
foreach (var kvp in storageBatch.MetaData.CommitRecords)
{
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug($"recover commit confirmation {kvp.Key}");
this.confirmationWorker.Add(kvp.Key, kvp.Value.Timestamp, kvp.Value.WriteParticipants);
}
// check for work
this.storageWorker.Notify();
this.RWLock.Notify();
}
public void GetMostRecentState(out TState state, out long sequenceNumber)
{
if (commitQueue.Count == 0)
{
state = this.stableState;
sequenceNumber = this.stableSequenceNumber;
}
else
{
var record = commitQueue.Last;
state = record.State;
sequenceNumber = record.SequenceNumber;
}
}
public int BatchableOperationsCount()
{
int count = 0;
int pos = commitQueue.Count - 1;
while (pos >= 0 && commitQueue[pos].Batchable)
{
pos--;
count++;
}
return count;
}
private async Task StorageWork()
{
// Stop if this activation is stopping/stopped.
if (this.activationLifetime.OnDeactivating.IsCancellationRequested) return;
using (this.activationLifetime.BlockDeactivation())
{
try
{
// count committable entries at the bottom of the commit queue
int committableEntries = 0;
while (committableEntries < commitQueue.Count && commitQueue[committableEntries].ReadyToCommit)
{
committableEntries++;
}
// process all committable entries, assembling a storage batch
if (committableEntries > 0)
{
// process all committable entries, adding storage events to the storage batch
CollectEventsForBatch(committableEntries);
if (logger.IsEnabled(LogLevel.Debug))
{
var r = commitQueue.Count > committableEntries ? commitQueue[committableEntries].ToString() : "";
logger.Debug($"batchcommit={committableEntries} leave={commitQueue.Count - committableEntries} {r}");
}
}
else
{
// send or re-send messages and detect timeouts
await CheckProgressOfCommitQueue();
}
// store the current storage batch, if it is not empty
StorageBatch<TState> batchBeingSentToStorage = null;
if (this.storageBatch.BatchSize > 0)
{
// get the next batch in place so it can be filled while we store the old one
batchBeingSentToStorage = this.storageBatch;
this.storageBatch = new StorageBatch<TState>(batchBeingSentToStorage);
try
{
if (await batchBeingSentToStorage.CheckStorePreConditions())
{
// perform the actual store, and record the e-tag
this.storageBatch.ETag = await batchBeingSentToStorage.Store(storage);
failCounter = 0;
}
else
{
logger.LogWarning("Store pre conditions not met.");
await AbortAndRestore(TransactionalStatus.CommitFailure);
return;
}
}
catch (InconsistentStateException e)
{
logger.LogWarning(888, e, "Reload from storage triggered by e-tag mismatch.");
await AbortAndRestore(TransactionalStatus.StorageConflict, true);
return;
}
catch (Exception e)
{
logger.Warn(888, $"Storage exception in storageWorker.", e);
await AbortAndRestore(TransactionalStatus.UnknownException);
return;
}
}
if (committableEntries > 0)
{
// update stable state
var lastCommittedEntry = commitQueue[committableEntries - 1];
this.stableState = lastCommittedEntry.State;
this.stableSequenceNumber = lastCommittedEntry.SequenceNumber;
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace($"Stable state version: {this.stableSequenceNumber}");
// remove committed entries from commit queue
commitQueue.RemoveFromFront(committableEntries);
storageWorker.Notify(); // we have to re-check for work
}
if (batchBeingSentToStorage != null)
{
batchBeingSentToStorage.RunFollowUpActions();
storageWorker.Notify(); // we have to re-check for work
}
}
catch (Exception e)
{
logger.LogWarning(888, e, "Exception in storageWorker. Retry {FailCounter}", failCounter);
await AbortAndRestore(TransactionalStatus.UnknownException);
}
}
}
private Task AbortAndRestore(TransactionalStatus status, bool force = false)
{
this.readyTask = Bail(status, force);
return this.readyTask;
}
private async Task Bail(TransactionalStatus status, bool force = false)
{
List<Task> pending = new List<Task>();
pending.Add(RWLock.AbortExecutingTransactions());
this.RWLock.AbortQueuedTransactions();
// abort all entries in the commit queue
foreach (var entry in commitQueue.Elements)
{
pending.Add(NotifyOfAbort(entry, status));
}
commitQueue.Clear();
await Task.WhenAll(pending);
if (++failCounter >= 10 || force)
{
logger.Debug("StorageWorker triggering grain Deactivation");
this.deactivate();
}
await this.Restore();
}
private async Task CheckProgressOfCommitQueue()
{
if (commitQueue.Count > 0)
{
var bottom = commitQueue[0];
var now = DateTime.UtcNow;
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("{CommitQueueSize} entries in queue waiting for bottom: {BottomEntry}", commitQueue.Count, bottom);
switch (bottom.Role)
{
case CommitRole.LocalCommit:
{
// check for timeout periodically
if (bottom.WaitingSince + this.options.PrepareTimeout <= now)
{
await AbortCommits(TransactionalStatus.PrepareTimeout);
this.RWLock.Notify();
}
else
{
storageWorker.Notify(bottom.WaitingSince + this.options.PrepareTimeout);
}
break;
}
case CommitRole.RemoteCommit:
{
if (bottom.PrepareIsPersisted && !bottom.LastSent.HasValue)
{
// send PreparedMessage to remote TM
bottom.TransactionManager.Reference.AsReference<ITransactionManagerExtension>()
.Prepared(bottom.TransactionManager.Name, bottom.TransactionId, bottom.Timestamp, resource, TransactionalStatus.Ok)
.Ignore();
bottom.LastSent = now;
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("sent prepared {BottomEntry}", bottom);
if (bottom.IsReadOnly)
{
storageWorker.Notify(); // we are ready to batch now
}
else
{
storageWorker.Notify(bottom.LastSent.Value + this.options.RemoteTransactionPingFrequency);
}
}
else if (!bottom.IsReadOnly && bottom.LastSent.HasValue)
{
// send ping messages periodically to reactivate crashed TMs
if (bottom.LastSent + this.options.RemoteTransactionPingFrequency <= now)
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace("sent ping {BottomEntry}", bottom);
bottom.TransactionManager.Reference.AsReference<ITransactionManagerExtension>()
.Ping(bottom.TransactionManager.Name, bottom.TransactionId, bottom.Timestamp, resource).Ignore();
bottom.LastSent = now;
}
storageWorker.Notify(bottom.LastSent.Value + this.options.RemoteTransactionPingFrequency);
}
break;
}
default:
{
logger.LogError(777, "internal error: impossible case {CommitRole}", bottom.Role);
throw new NotSupportedException($"{bottom.Role} is not a supported CommitRole.");
}
}
}
}
private void CollectEventsForBatch(int batchsize)
{
// collect events for batch
for (int i = 0; i < batchsize; i++)
{
TransactionRecord<TState> entry = commitQueue[i];
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Trace("committing {Entry}", entry);
}
switch (entry.Role)
{
case CommitRole.LocalCommit:
{
OnLocalCommit(entry);
break;
}
case CommitRole.RemoteCommit:
{
if (entry.ConfirmationResponsePromise == null)
{
// this is a read-only participant that has sent
// its prepared message.
// So we are really done and need not store or do anything.
}
else
{
// we must confirm in storage, and then respond to TM so it can collect
this.storageBatch.Confirm(entry.SequenceNumber);
this.storageBatch.FollowUpAction(() =>
{
entry.ConfirmationResponsePromise.TrySetResult(true);
if (this.logger.IsEnabled(LogLevel.Trace))
{
this.logger.Trace("Confirmed remote commit v{SequenceNumber}. TransactionId:{TransactionId} Timestamp:{Timestamp} TransactionManager:{TransactionManager}", entry.SequenceNumber, entry.TransactionId, entry.Timestamp, entry.TransactionManager);
}
});
}
break;
}
case CommitRole.ReadOnly:
{
// we are a participant of a read-only transaction. Must store timestamp and then respond.
this.storageBatch.Read(entry.Timestamp);
this.storageBatch.FollowUpAction(() =>
{
entry.PromiseForTA.TrySetResult(TransactionalStatus.Ok);
});
break;
}
default:
{
logger.LogError(777, "internal error: impossible case {CommitRole}", entry.Role);
throw new NotSupportedException($"{entry.Role} is not a supported CommitRole.");
}
}
}
}
protected virtual void OnLocalCommit(TransactionRecord<TState> entry)
{
this.storageBatch.Prepare(entry.SequenceNumber, entry.TransactionId, entry.Timestamp, entry.TransactionManager, entry.State);
this.storageBatch.Commit(entry.TransactionId, entry.Timestamp, entry.WriteParticipants);
this.storageBatch.Confirm(entry.SequenceNumber);
// after store, send response back to TA
this.storageBatch.FollowUpAction(() =>
{
if (this.logger.IsEnabled(LogLevel.Trace))
{
this.logger.Trace($"locally committed {entry.TransactionId} {entry.Timestamp:o}");
}
entry.PromiseForTA.TrySetResult(TransactionalStatus.Ok);
});
if (entry.WriteParticipants.Count > 1)
{
// after committing, we need to run a task to confirm and collect
this.storageBatch.FollowUpAction(() =>
{
if (this.logger.IsEnabled(LogLevel.Trace))
{
this.logger.Trace($"Adding confirmation to worker for {entry.TransactionId} {entry.Timestamp:o}");
}
this.confirmationWorker.Add(entry.TransactionId, entry.Timestamp, entry.WriteParticipants);
});
}
else
{
// there are no remote write participants to notify, so we can finish it all in one shot
this.storageBatch.Collect(entry.TransactionId);
}
}
private async Task AbortCommits(TransactionalStatus status, int from = 0)
{
List<Task> pending = new List<Task>();
// emtpy the back of the commit queue, starting at specified position
for (int i = from; i < commitQueue.Count; i++)
{
pending.Add(NotifyOfAbort(commitQueue[i], i == from ? status : TransactionalStatus.CascadingAbort));
}
commitQueue.RemoveFromBack(commitQueue.Count - from);
pending.Add(this.RWLock.AbortExecutingTransactions());
await Task.WhenAll(pending);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using Palaso.Data;
using Palaso.DictionaryServices.Lift;
using Palaso.DictionaryServices.Model;
using Palaso.Lift;
using Palaso.Lift.Options;
using NUnit.Framework;
using Palaso.Lift.Parsing;
namespace Palaso.DictionaryServices.Tests.Lift
{
[TestFixture]
public class LexEntryFromLiftBuilderTests: ILiftMergerTestSuite
{
private LexEntryFromLiftBuilder _builder;
private MemoryDataMapper<LexEntry> _dataMapper;
// private string _tempFile;
[SetUp]
public void Setup()
{
_dataMapper = new MemoryDataMapper<LexEntry>();
OptionsList pretendSemanticDomainList = new OptionsList();
pretendSemanticDomainList.Options.Add(new Option("4.2.7 Play, fun", new MultiText()));
_builder = new LexEntryFromLiftBuilder(_dataMapper, pretendSemanticDomainList);
}
[TearDown]
public void TearDown()
{
_builder.Dispose();
_dataMapper.Dispose();
}
/// <summary>
/// Test the form we get from FLEx 5.4 (it was changed in FLEx 6.0)
/// </summary>
[Test]
public void NewEntry_HasSemanticDomainWithTextualLabel_CorrectlyAddsSemanticDomain()
{
Extensible extensibleInfo = new Extensible();
LexEntry e = _builder.GetOrMakeEntry(extensibleInfo, 0);
LexSense s = _builder.GetOrMakeSense(e, new Extensible(), string.Empty);
var t = new Trait("semantic-domain-ddp4", //the name has migrated up to this already
"4.2.7");
_builder.MergeInTrait(s, t);
_builder.FinishEntry(e);
var property = e.Senses[0].GetProperty<OptionRefCollection>(LexSense.WellKnownProperties.SemanticDomainDdp4);
Assert.AreEqual("4.2.7 Play, fun", property.KeyAtIndex(0));
}
/// <summary>
/// Flex allows you to add domains. So make sure that doesn't break us.
/// </summary>
[Test]
public void NewEntry_HasSemanticDomainWeDontKnowAbout_AddedAnyways()
{
Extensible extensibleInfo = new Extensible();
LexEntry e = _builder.GetOrMakeEntry(extensibleInfo, 0);
LexSense s = _builder.GetOrMakeSense(e, new Extensible(), string.Empty);
var t = new Trait("semantic-domain-ddp4",
"9.9.9.9.9.9 Computer Gadgets" );
_builder.MergeInTrait(s, t);
_builder.FinishEntry(e);
var property = e.Senses[0].GetProperty<OptionRefCollection>(LexSense.WellKnownProperties.SemanticDomainDdp4);
Assert.AreEqual("9.9.9.9.9.9 Computer Gadgets", property.KeyAtIndex(0));
}
[Test]
public void NewEntryGetsId()
{
Extensible extensibleInfo = new Extensible();
extensibleInfo.Id = "foo";
LexEntry e = _builder.GetOrMakeEntry(extensibleInfo, 0);
Assert.AreEqual(extensibleInfo.Id, e.Id);
_builder.FinishEntry(e);
Assert.AreEqual(1, _dataMapper.CountAllItems());
}
[Test]
public void NewEntryGetsGuid()
{
Extensible extensibleInfo = new Extensible();
extensibleInfo.Guid = Guid.NewGuid();
LexEntry e = _builder.GetOrMakeEntry(extensibleInfo, 0);
Assert.AreEqual(extensibleInfo.Guid, e.Guid);
_builder.FinishEntry(e);
Assert.AreEqual(1, _dataMapper.CountAllItems());
}
[Test]
public void NewEntryGetsDates()
{
Extensible extensibleInfo = new Extensible();
extensibleInfo.CreationTime = DateTime.Parse("2/2/1969 12:15:12").ToUniversalTime();
extensibleInfo.ModificationTime =
DateTime.Parse("10/11/1968 12:15:12").ToUniversalTime();
LexEntry e = _builder.GetOrMakeEntry(extensibleInfo, 0);
Assert.AreEqual(extensibleInfo.CreationTime, e.CreationTime);
Assert.AreEqual(extensibleInfo.ModificationTime, e.ModificationTime);
_builder.FinishEntry(e);
Assert.AreEqual(1, _dataMapper.CountAllItems());
}
[Test, Ignore("TODO: move to wesay")]
public void NewEntry_NoDefYesGloss_GlossCopiedToDefintion()
{
// _builder.AfterEntryRead += _builder.ApplyWeSayPolicyToParsedEntry;
Extensible extensibleInfo = new Extensible();
LexEntry e = _builder.GetOrMakeEntry(extensibleInfo, 0);
LexSense s = _builder.GetOrMakeSense(e, new Extensible(), string.Empty);
_builder.MergeInGloss(s, new LiftMultiText("x","x meaning"));
_builder.FinishEntry(e);
Assert.AreEqual("x meaning",e.Senses[0].Gloss.GetExactAlternative("x"));
Assert.AreEqual("x meaning",e.Senses[0].Definition.GetExactAlternative("x"));
}
[Test, Ignore("TODO: move to wesay")]
public void NewEntry_OldLiteralMeaning_GetsMoved()
{
// _builder.AfterEntryRead += _builder.ApplyWeSayPolicyToParsedEntry;
Extensible extensibleInfo = new Extensible();
LexEntry e = _builder.GetOrMakeEntry(extensibleInfo, 0);
LexSense s = _builder.GetOrMakeSense(e, new Extensible(), string.Empty);
LiftMultiText t = new LiftMultiText("en", "test");
_builder.MergeInField(s, "LiteralMeaning", default(DateTime), default(DateTime), t, null);
_builder.FinishEntry(e);
Assert.IsNull(e.Senses[0].GetProperty<MultiText>("LiteralMeaning"));
Assert.IsNotNull(e.GetProperty<MultiText>(LexEntry.WellKnownProperties.LiteralMeaning));
Assert.AreEqual("test", e.GetProperty<MultiText>(LexEntry.WellKnownProperties.LiteralMeaning).GetExactAlternative("en"));
}
[Test, Ignore("TODO: move to wesay")]
public void NewEntry_HasDefGlossHasAnotherWSAlternative_CopiedToDefintion()
{
// _builder.AfterEntryRead += _builder.ApplyWeSayPolicyToParsedEntry;
Extensible extensibleInfo = new Extensible();
LexEntry e = _builder.GetOrMakeEntry(extensibleInfo, 0);
LexSense s = _builder.GetOrMakeSense(e, new Extensible(), string.Empty);
_builder.MergeInDefinition(s, new LiftMultiText("x", "x def"));
_builder.MergeInGloss(s, new LiftMultiText("x", "x meaning"));
_builder.MergeInGloss(s, new LiftMultiText("y", "y meaning"));
_builder.FinishEntry(e);
Assert.AreEqual("x meaning", e.Senses[0].Gloss.GetExactAlternative("x"));
Assert.AreEqual("x def", e.Senses[0].Definition.GetExactAlternative("x"));
Assert.AreEqual("y meaning", e.Senses[0].Definition.GetExactAlternative("y"));
}
[Test]
public void NewEntry_YesDefYesGloss_BothUnchanged()
{
Extensible extensibleInfo = new Extensible();
LexEntry e = _builder.GetOrMakeEntry(extensibleInfo, 0);
LexSense s = _builder.GetOrMakeSense(e, new Extensible(), string.Empty);
_builder.MergeInGloss(s, new LiftMultiText("x", "x gloss"));
_builder.MergeInDefinition(s, new LiftMultiText("x", "x def"));
_builder.FinishEntry(e);
Assert.AreEqual("x gloss", e.Senses[0].Gloss.GetExactAlternative("x"));
Assert.AreEqual("x def", e.Senses[0].Definition.GetExactAlternative("x"));
}
[Test]
public void NewEntry_NoGlossNoDef_GetNeitherInTheSense()
{
Extensible extensibleInfo = new Extensible();
LexEntry e = _builder.GetOrMakeEntry(extensibleInfo, 0);
LexSense s = _builder.GetOrMakeSense(e, new Extensible(), string.Empty);
_builder.FinishEntry(e);
Assert.AreEqual(0,e.Senses[0].Gloss.Count);
Assert.AreEqual(0, e.Senses[0].Definition.Count);
}
[Test]
public void NewEntryWithTextIdIgnoresIt()
{
Extensible extensibleInfo = new Extensible();
extensibleInfo.Id = "hello";
LexEntry e = _builder.GetOrMakeEntry(extensibleInfo, 0);
//no attempt is made to use that id
Assert.IsNotNull(e.Guid);
Assert.AreNotSame(Guid.Empty, e.Guid);
}
[Test]
public void NewEntryTakesGivenDates()
{
Extensible extensibleInfo = new Extensible();
extensibleInfo = AddDates(extensibleInfo);
LexEntry e = _builder.GetOrMakeEntry(extensibleInfo, 0);
Assert.AreEqual(extensibleInfo.CreationTime, e.CreationTime);
Assert.AreEqual(extensibleInfo.ModificationTime, e.ModificationTime);
}
[Test]
public void NewEntryNoDatesUsesNow()
{
LexEntry e = MakeSimpleEntry();
Assert.IsTrue(TimeSpan.FromTicks(DateTime.UtcNow.Ticks - e.CreationTime.Ticks).Seconds <
2);
Assert.IsTrue(
TimeSpan.FromTicks(DateTime.UtcNow.Ticks - e.ModificationTime.Ticks).Seconds < 2);
}
private LexEntry MakeSimpleEntry()
{
Extensible extensibleInfo = new Extensible();
return _builder.GetOrMakeEntry(extensibleInfo, 0);
}
[Test]
public void EntryGetsEmptyLexemeForm()
{
LexEntry e = MakeSimpleEntry();
_builder.MergeInLexemeForm(e, new LiftMultiText());
Assert.AreEqual(0, e.LexicalForm.Count);
}
[Test]
public void MergeInNote_NoteHasNoType_Added()
{
LexEntry e = MakeSimpleEntry();
_builder.MergeInNote(e, string.Empty, MakeBasicLiftMultiText(), string.Empty);
MultiText mt = e.GetProperty<MultiText>(PalasoDataObject.WellKnownProperties.Note);
Assert.AreEqual("uno", mt["ws-one"]);
Assert.AreEqual("dos", mt["ws-two"]);
}
[Test]
public void MergeInNote_NoteHasTypeOfGeneral_Added()
{
LexEntry e = MakeSimpleEntry();
_builder.MergeInNote(e, "general", MakeBasicLiftMultiText(), string.Empty);
MultiText mt = e.GetProperty<MultiText>(PalasoDataObject.WellKnownProperties.Note);
Assert.AreEqual("uno", mt["ws-one"]);
Assert.AreEqual("dos", mt["ws-two"]);
}
[Test]
public void MergeInNote_NoteHasTypeOtherThanGeneral_AllGoesToRoundTripResidue()
{
LexEntry e = MakeSimpleEntry();
_builder.MergeInNote(e, "red", MakeBasicLiftMultiText(), "<pretendXmlOfNote/>");
MultiText mt = e.GetProperty<MultiText>(PalasoDataObject.WellKnownProperties.Note);
Assert.IsNull(mt);
var residue =e.GetProperty<EmbeddedXmlCollection>(PalasoDataObject.GetEmbeddedXmlNameForProperty(PalasoDataObject.WellKnownProperties.Note));
Assert.AreEqual(1,residue.Values.Count);
Assert.AreEqual("<pretendXmlOfNote/>", residue.Values[0]);
}
[Test]
public void MergeInNote_NoType_AfterFirstTheyGoesToRoundTripResidue()
{
LexEntry e = MakeSimpleEntry();
_builder.MergeInNote(e, string.Empty, MakeBasicLiftMultiText("first"), "pretend xml one");
_builder.MergeInNote(e, string.Empty, MakeBasicLiftMultiText("second"), "<pretend xml two/>");
_builder.MergeInNote(e, string.Empty, MakeBasicLiftMultiText("third"), "<pretend xml three/>");
MultiText mt = e.GetProperty<MultiText>(PalasoDataObject.WellKnownProperties.Note);
Assert.AreEqual("first", mt["ws-one"]);
var residue = e.GetProperty<EmbeddedXmlCollection>(PalasoDataObject.GetEmbeddedXmlNameForProperty(PalasoDataObject.WellKnownProperties.Note));
Assert.AreEqual(2, residue.Values.Count);
Assert.AreEqual("<pretend xml two/>", residue.Values[0]);
Assert.AreEqual("<pretend xml three/>", residue.Values[1]);
}
[Test]
public void SenseGetsGrammi()
{
LexSense sense = new LexSense();
_builder.MergeInGrammaticalInfo(sense, "red", null);
OptionRef optionRef =
sense.GetProperty<OptionRef>(LexSense.WellKnownProperties.PartOfSpeech);
Assert.IsNotNull(optionRef);
Assert.AreEqual("red", optionRef.Value);
}
[Test]
public void GrammiGetsFlagTrait()
{
LexSense sense = new LexSense();
_builder.MergeInGrammaticalInfo(sense,
"red",
new List<Trait>(new Trait[] {new Trait("flag", "1")}));
OptionRef optionRef =
sense.GetProperty<OptionRef>(LexSense.WellKnownProperties.PartOfSpeech);
Assert.IsTrue(optionRef.IsStarred);
}
[Test]
public void SenseGetsExample()
{
LexSense sense = new LexSense();
Extensible x = new Extensible();
LexExampleSentence ex = _builder.GetOrMakeExample(sense, x);
Assert.IsNotNull(ex);
_builder.MergeInExampleForm(ex, MakeBasicLiftMultiText());
Assert.AreEqual(2, ex.Sentence.Forms.Length);
Assert.AreEqual("dos", ex.Sentence["ws-two"]);
}
[Test]
public void SenseGetsRelation()
{
LexSense sense = new LexSense();
_builder.MergeInRelation(sense, "synonym", "foo", null);
LexRelationCollection synonyms = sense.GetProperty<LexRelationCollection>("synonym");
LexRelation relation = synonyms.Relations[0];
Assert.AreEqual("synonym", relation.FieldId);
Assert.AreEqual("foo", relation.Key);
}
[Test]
public void MergeInRelation_RelationHasEmbeddedTraits_RelationGetsEmbeddedXmlForLaterRoundTrip()
{
LexEntry e = MakeSimpleEntry();
var xml = @"<relation type='component-lexeme' ref='bodzi_d333f64f-d388-431f-bb2b-7dd9b7f3fe3c'>
<trait name='complex-form-type' value='Composto'></trait>
<trait name='is-primary' value='true'/>
</relation>";
_builder.MergeInRelation(e, "component-lexeme", "someId", xml);
LexRelationCollection collection =
e.GetOrCreateProperty<LexRelationCollection>("component-lexeme");
Assert.AreEqual(2, collection.Relations[0].EmbeddedXmlElements.Count);
}
[Test]
public void ExampleSourcePreserved()
{
LexExampleSentence ex = new LexExampleSentence();
_builder.MergeInSource(ex, "fred");
Assert.AreEqual("fred",
ex.GetProperty<OptionRef>(LexExampleSentence.WellKnownProperties.Source)
.Value);
}
[Test]
public void SenseGetsDef()
{
LexSense sense = new LexSense();
_builder.MergeInDefinition(sense, MakeBasicLiftMultiText());
AssertPropertyHasExpectedMultiText(sense, LexSense.WellKnownProperties.Definition);
}
[Test]
public void SenseGetsNote()
{
LexSense sense = new LexSense();
_builder.MergeInNote(sense, null, MakeBasicLiftMultiText(), string.Empty);
AssertPropertyHasExpectedMultiText(sense, PalasoDataObject.WellKnownProperties.Note);
}
[Test]
public void SenseGetsId()
{
Extensible extensibleInfo = new Extensible();
extensibleInfo.Id = "foo";
LexSense s = _builder.GetOrMakeSense(new LexEntry(), extensibleInfo, string.Empty);
Assert.AreEqual(extensibleInfo.Id, s.Id);
}
// [Test]
// public void MergingIntoEmptyMultiTextWithFlags()
// {
// LiftMultiText lm = new LiftMultiText();
// lm.Add("one", "uno");
// lm.Add("two", "dos");
// lm.Traits.Add(new Trait("one", "flag", "1"));
//
// MultiText m = new MultiText();
// MultiText.Create(lm as System.Collections.Generic.Dictionary<string,string>, List<)
// LexSense sense = new LexSense();
// LiftMultiText text = MakeBasicLiftMultiText();
// text.Traits.Add(new Trait("ws-one", "flag", "1"));
// _builder.MergeInGloss(sense, text);
//
// Assert.IsTrue(sense.Gloss.GetAnnotationOfAlternativeIsStarred("ws-one"));
// }
[Test]
public void GlossGetsFlag()
{
LexSense sense = new LexSense();
LiftMultiText text = MakeBasicLiftMultiText();
AddAnnotationToLiftMultiText(text, "ws-one", "flag", "1");
_builder.MergeInGloss(sense, text);
Assert.IsTrue(sense.Gloss.GetAnnotationOfAlternativeIsStarred("ws-one"));
Assert.IsFalse(sense.Gloss.GetAnnotationOfAlternativeIsStarred("ws-two"));
text = MakeBasicLiftMultiText();
AddAnnotationToLiftMultiText(text, "ws-one", "flag", "0");
_builder.MergeInGloss(sense, text);
Assert.IsFalse(sense.Gloss.GetAnnotationOfAlternativeIsStarred("ws-one"));
}
[Test]
public void LexicalUnitGetsFlag()
{
LexEntry entry = MakeSimpleEntry();
LiftMultiText text = MakeBasicLiftMultiText();
AddAnnotationToLiftMultiText(text, "ws-one", "flag", "1");
_builder.MergeInLexemeForm(entry, text);
Assert.IsTrue(entry.LexicalForm.GetAnnotationOfAlternativeIsStarred("ws-one"));
Assert.IsFalse(entry.LexicalForm.GetAnnotationOfAlternativeIsStarred("ws-two"));
}
private static void AddAnnotationToLiftMultiText(LiftMultiText text,
string languageHint,
string name,
string value)
{
Annotation annotation = new Annotation(name, value, default(DateTime), null);
annotation.LanguageHint = languageHint;
text.Annotations.Add(annotation);
}
[Test]
public void MultipleGlossesCombined()
{
LexSense sense = new LexSense();
_builder.MergeInGloss(sense, MakeBasicLiftMultiText());
LiftMultiText secondGloss = new LiftMultiText();
secondGloss.Add("ws-one", "UNO");
secondGloss.Add("ws-three", "tres");
_builder.MergeInGloss(sense, secondGloss);
//MultiText mt = sense.GetProperty<MultiText>(LexSense.WellKnownProperties.Note);
Assert.AreEqual(3, sense.Gloss.Forms.Length);
Assert.AreEqual("uno; UNO", sense.Gloss["ws-one"]);
}
private static void AssertPropertyHasExpectedMultiText(PalasoDataObject dataObject,
string name)
{
//must match what is created by MakeBasicLiftMultiText()
MultiText mt = dataObject.GetProperty<MultiText>(name);
Assert.AreEqual(2, mt.Forms.Length);
Assert.AreEqual("dos", mt["ws-two"]);
}
private static LiftMultiText MakeBasicLiftMultiText(string text)
{
LiftMultiText forms = new LiftMultiText();
forms.Add("ws-one", text);
forms.Add("ws-two", text+"-in-two");
return forms;
}
private static LiftMultiText MakeBasicLiftMultiText()
{
LiftMultiText forms = new LiftMultiText();
forms.Add("ws-one", "uno");
forms.Add("ws-two", "dos");
return forms;
}
#region ILiftMergerTestSuite Members
[Test]
[Ignore("not yet")]
public void NewWritingSystemAlternativeHandled() {}
#endregion
[Test]
public void EntryGetsLexemeFormWithUnheardOfLanguage()
{
LexEntry e = MakeSimpleEntry();
LiftMultiText forms = new LiftMultiText();
forms.Add("x99", "hello");
_builder.MergeInLexemeForm(e, forms);
Assert.AreEqual("hello", e.LexicalForm["x99"]);
}
[Test]
public void NewEntryGetsLexemeForm()
{
LexEntry e = MakeSimpleEntry();
LiftMultiText forms = new LiftMultiText();
forms.Add("x", "hello");
forms.Add("y", "bye");
_builder.MergeInLexemeForm(e, forms);
Assert.AreEqual(2, e.LexicalForm.Count);
}
[Test]
public void EntryWithCitation()
{
LexEntry entry = MakeSimpleEntry();
LiftMultiText forms = new LiftMultiText();
forms.Add("x", "hello");
forms.Add("y", "bye");
_builder.MergeInCitationForm(entry, forms);
MultiText citation = entry.GetProperty<MultiText>(LexEntry.WellKnownProperties.Citation);
Assert.AreEqual(2, citation.Forms.Length);
Assert.AreEqual("hello", citation["x"]);
Assert.AreEqual("bye", citation["y"]);
}
[Test]
public void EntryWithChildren()
{
Extensible extensibleInfo = new Extensible();
LexEntry e = MakeSimpleEntry();
LexSense s = _builder.GetOrMakeSense(e, extensibleInfo, string.Empty);
LexExampleSentence ex = _builder.GetOrMakeExample(s, new Extensible());
ex.Sentence["foo"] = "this is a sentence";
ex.Translation["aa"] = "aaaa";
_builder.FinishEntry(e);
CheckCompleteEntry(e);
RepositoryId[] entries = _dataMapper.GetAllItems();
Assert.AreEqual(1, entries.Length);
//now check it again, from the list
CheckCompleteEntry(_dataMapper.GetItem(entries[0]));
}
[Test]
public void MergeInTranslationForm_TypeFree_GetContentsAndSavesType()
{
LexExampleSentence ex = new LexExampleSentence();
LiftMultiText translation = new LiftMultiText();
translation.Add("aa", "aaaa");
_builder.MergeInTranslationForm(ex, "Free translation", translation, "bogus raw xml");
Assert.AreEqual("aaaa", ex.Translation["aa"]);
Assert.AreEqual("Free translation", ex.TranslationType);
}
[Test]
public void MergeInTranslationForm_UnheardOfType_StillBecomesTranslation()
{
LexExampleSentence ex = new LexExampleSentence();
LiftMultiText translation = new LiftMultiText();
translation.Add("aa", "aaaa");
_builder.MergeInTranslationForm(ex, "madeUpType", translation, "bogus raw xml");
Assert.AreEqual("aaaa", ex.Translation["aa"]);
Assert.AreEqual("madeUpType",ex.TranslationType);
}
[Test]
public void MergeInTranslationForm_NoType_GetContents()
{
LexExampleSentence ex = new LexExampleSentence();
LiftMultiText translation = new LiftMultiText();
translation.Add("aa", "aaaa");
_builder.MergeInTranslationForm(ex, "", translation, "bogus raw xml");
Assert.AreEqual("aaaa", ex.Translation["aa"]);
Assert.IsTrue(string.IsNullOrEmpty(ex.TranslationType));
}
private static void CheckCompleteEntry(LexEntry entry)
{
Assert.AreEqual(1, entry.Senses.Count);
LexSense sense = entry.Senses[0];
Assert.AreEqual(1, sense.ExampleSentences.Count);
LexExampleSentence example = sense.ExampleSentences[0];
Assert.AreEqual("this is a sentence", example.Sentence["foo"]);
Assert.AreEqual("aaaa", example.Translation["aa"]);
Assert.AreEqual(entry, sense.Parent);
Assert.AreEqual(entry, example.Parent.Parent);
}
[Test]
[Ignore(
"Haven't implemented protecting modified dates of, e.g., the entry as you add/merge its children."
)]
public void ModifiedDatesRetained() {}
[Test]
public void ChangedEntryFound()
{
#if merging
Guid g = Guid.NewGuid();
Extensible extensibleInfo = CreateFullextensibleInfo(g);
LexEntry e = _repository.CreateItem();
LexSense sense1 = new LexSense();
LexSense sense2 = new LexSense();
e.Senses.Add(sense1);
e.Senses.Add(sense2);
e.CreationTime = extensibleInfo.CreationTime;
e.ModificationTime = new DateTime(e.CreationTime.Ticks + 100, DateTimeKind.Utc);
LexEntry found = _merger.GetOrMakeEntry(extensibleInfo, 0);
_merger.FinishEntry(found);
Assert.AreSame(found, e);
Assert.AreEqual(2, found.Senses.Count);
//this is a temp side track
Assert.AreEqual(1, _repository.CountAllItems());
Extensible xInfo = CreateFullextensibleInfo(Guid.NewGuid());
LexEntry x = _merger.GetOrMakeEntry(xInfo, 1);
_merger.FinishEntry(x);
Assert.AreEqual(2, _repository.CountAllItems());
#endif
}
[Test]
public void UnchangedEntryPruned()
{
#if merging
Guid g = Guid.NewGuid();
Extensible extensibleInfo = CreateFullextensibleInfo( g);
LexEntry e = _repository.CreateItem();
e.CreationTime = extensibleInfo.CreationTime;
e.ModificationTime = extensibleInfo.ModificationTime;
LexEntry found = _merger.GetOrMakeEntry(extensibleInfo, 0);
Assert.IsNull(found);
#endif
}
[Test]
[Ignore("This test is defective. found is always true CJP 2008-07-14")]
public void EntryWithIncomingUnspecifiedModTimeNotPruned()
{
Guid g = Guid.NewGuid();
Extensible eInfo = CreateFullextensibleInfo(g);
LexEntry item = _dataMapper.CreateItem();
item.Guid = eInfo.Guid;
item.Id = eInfo.Id;
item.ModificationTime = eInfo.ModificationTime;
item.CreationTime = eInfo.CreationTime;
_dataMapper.SaveItem(item);
//strip out the time
eInfo.ModificationTime = Extensible.ParseDateTimeCorrectly("2005-01-01");
Assert.AreEqual(DateTimeKind.Utc, eInfo.ModificationTime.Kind);
LexEntry found = _builder.GetOrMakeEntry(eInfo, 0);
Assert.IsNotNull(found);
}
[Test]
public void ParseDateTimeCorrectly()
{
Assert.AreEqual(DateTimeKind.Utc,
Extensible.ParseDateTimeCorrectly("2003-08-07T08:42:42Z").Kind);
Assert.AreEqual(DateTimeKind.Utc,
Extensible.ParseDateTimeCorrectly("2005-01-01T01:11:11+8:00").Kind);
Assert.AreEqual(DateTimeKind.Utc, Extensible.ParseDateTimeCorrectly("2005-01-01").Kind);
Assert.AreEqual("00:00:00",
Extensible.ParseDateTimeCorrectly("2005-01-01").TimeOfDay.ToString());
}
[Test]
[Ignore("Haven't implemented this.")]
public void MergingSameEntryLackingGuidId_TwiceFindMatch() {}
private static Extensible AddDates(Extensible extensibleInfo)
{
extensibleInfo.CreationTime = Extensible.ParseDateTimeCorrectly("2003-08-07T08:42:42Z");
extensibleInfo.ModificationTime =
Extensible.ParseDateTimeCorrectly("2005-01-01T01:11:11+8:00");
return extensibleInfo;
}
private static Extensible CreateFullextensibleInfo(Guid g)
{
Extensible extensibleInfo = new Extensible();
extensibleInfo.Guid = g;
extensibleInfo = AddDates(extensibleInfo);
return extensibleInfo;
}
[Test]
public void ExpectedAtomicTraitOnEntry()
{
_builder.ExpectedOptionTraits = new[]{"flub"};
LexEntry e = MakeSimpleEntry();
_builder.MergeInTrait(e, new Trait("flub", "dub"));
Assert.AreEqual(1, e.Properties.Count);
Assert.AreEqual("flub", e.Properties[0].Key);
OptionRef option = e.GetProperty<OptionRef>("flub");
Assert.AreEqual("dub", option.Value);
}
[Test]
public void UnexpectedAtomicTraitRetained()
{
LexEntry e = MakeSimpleEntry();
_builder.MergeInTrait(e, new Trait("flub", "dub"));
Assert.AreEqual(1, e.Properties.Count);
Assert.AreEqual("flub", e.Properties[0].Key);
OptionRefCollection option = e.GetProperty<OptionRefCollection>("flub");
Assert.IsTrue(option.Contains("dub"));
}
[Test]
public void ExpectedCollectionTrait()
{
_builder.ExpectedOptionCollectionTraits.Add("flub");
LexEntry e = MakeSimpleEntry();
_builder.MergeInTrait(e, new Trait("flub", "dub"));
_builder.MergeInTrait(e, new Trait("flub", "stub"));
Assert.AreEqual(1, e.Properties.Count);
Assert.AreEqual("flub", e.Properties[0].Key);
OptionRefCollection options = e.GetProperty<OptionRefCollection>("flub");
Assert.AreEqual(2, options.Count);
Assert.IsTrue(options.Contains("dub"));
Assert.IsTrue(options.Contains("stub"));
}
[Test]
public void UnexpectedAtomicCollectionRetained()
{
LexEntry e = MakeSimpleEntry();
_builder.MergeInTrait(e, new Trait("flub", "dub"));
_builder.MergeInTrait(e, new Trait("flub", "stub"));
Assert.AreEqual(1, e.Properties.Count);
Assert.AreEqual("flub", e.Properties[0].Key);
OptionRefCollection option = e.GetProperty<OptionRefCollection>("flub");
Assert.IsTrue(option.Contains("dub"));
Assert.IsTrue(option.Contains("stub"));
}
[Test]
public void ExpectedCustomField()
{
LexEntry e = MakeSimpleEntry();
LiftMultiText t = new LiftMultiText();
t["z"] = new LiftString("dub");
_builder.MergeInField(e, "flub", default(DateTime), default(DateTime), t, null);
Assert.AreEqual(1, e.Properties.Count);
Assert.AreEqual("flub", e.Properties[0].Key);
MultiText mt = e.GetProperty<MultiText>("flub");
Assert.AreEqual("dub", mt["z"]);
}
[Test]
public void UnexpectedCustomFieldRetained()
{
LexEntry e = MakeSimpleEntry();
LiftMultiText t = new LiftMultiText();
t["z"] = new LiftString("dub");
_builder.MergeInField(e, "flub", default(DateTime), default(DateTime), t, null);
Assert.AreEqual(1, e.Properties.Count);
Assert.AreEqual("flub", e.Properties[0].Key);
MultiText mt = e.GetProperty<MultiText>("flub");
Assert.AreEqual("dub", mt["z"]);
}
[Test]
public void EntryGetsFlag()
{
LexEntry e = MakeSimpleEntry();
_builder.MergeInTrait(e, new Trait(LexEntry.WellKnownProperties.FlagSkipBaseform, null));
Assert.IsTrue(e.GetHasFlag(LexEntry.WellKnownProperties.FlagSkipBaseform));
}
[Test]
public void SenseGetsPictureNoCaption()
{
Extensible extensibleInfo = new Extensible();
LexEntry e = MakeSimpleEntry();
LexSense s = _builder.GetOrMakeSense(e, extensibleInfo, string.Empty);
_builder.MergeInPicture(s, "testPicture.png", null);
PictureRef pict = s.GetProperty<PictureRef>("Picture");
Assert.AreEqual("testPicture.png", pict.Value);
Assert.IsNull(pict.Caption);
}
[Test]
public void SenseGetsPictureWithCaption()
{
Extensible extensibleInfo = new Extensible();
LexEntry e = MakeSimpleEntry();
LexSense s = _builder.GetOrMakeSense(e, extensibleInfo, string.Empty);
LiftMultiText caption = new LiftMultiText();
caption["aa"] = new LiftString("acaption");
_builder.MergeInPicture(s, "testPicture.png", caption);
PictureRef pict = s.GetProperty<PictureRef>("Picture");
Assert.AreEqual("testPicture.png", pict.Value);
Assert.AreEqual("acaption", pict.Caption["aa"]);
}
[Test]
public void GetOrMakeEntry_ReturnedLexEntryIsDirty()
{
Extensible extensibleInfo = new Extensible();
LexEntry entry = _builder.GetOrMakeEntry(extensibleInfo, 0);
Assert.IsTrue(entry.IsDirty);
}
}
}
| |
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Solenoid.Expressions.Support.Util;
namespace Solenoid.Expressions.Support.TypeConversion
{
/// <summary>
/// Utility methods that are used to convert objects from one type into another.
/// </summary>
/// <author>Aleksandar Seovic</author>
public static class TypeConversionUtils
{
/// <summary>
/// Convert the value to the required <see cref="System.Type"/> (if necessary from a string).
/// </summary>
/// <param name="newValue">The proposed change value.</param>
/// <param name="requiredType">
/// The <see cref="System.Type"/> we must convert to.
/// </param>
/// <param name="propertyName">Property name, used for error reporting purposes...</param>
/// <returns>The new value, possibly the result of type conversion.</returns>
public static object ConvertValueIfNecessary(Type requiredType, object newValue, string propertyName)
{
if (newValue != null)
{
// if it is assignable, return the value right away
if (IsAssignableFrom(newValue, requiredType))
{
return newValue;
}
// if required type is an array, convert all the elements
if (requiredType != null && requiredType.IsArray)
{
// convert individual elements to array elements
var componentType = requiredType.GetElementType();
if (newValue is ICollection)
{
var elements = (ICollection)newValue;
return ToArrayWithTypeConversion(componentType, elements, propertyName);
}
if (newValue is string)
{
if (requiredType == typeof(char[]))
{
return ((string)newValue).ToCharArray();
}
var elements = StringUtils.CommaDelimitedListToStringArray((string)newValue);
return ToArrayWithTypeConversion(componentType, elements, propertyName);
}
if (!newValue.GetType().IsArray)
{
// A plain value: convert it to an array with a single component.
var result = Array.CreateInstance(componentType, 1);
var val = ConvertValueIfNecessary(componentType, newValue, propertyName);
result.SetValue(val, 0);
return result;
}
}
// if required type is some IList<T>, convert all the elements
if (requiredType != null && requiredType.IsGenericType && TypeImplementsGenericInterface(requiredType, typeof(IList<>)))
{
// convert individual elements to array elements
var componentType = requiredType.GetGenericArguments()[0];
if (newValue is ICollection)
{
var elements = (ICollection)newValue;
return ToTypedCollectionWithTypeConversion(typeof(List<>), componentType, elements, propertyName);
}
}
// if required type is some IDictionary<K,V>, convert all the elements
if (requiredType != null && requiredType.IsGenericType && TypeImplementsGenericInterface(requiredType, typeof(IDictionary<,>)))
{
var typeParameters = requiredType.GetGenericArguments();
var keyType = typeParameters[0];
var valueType = typeParameters[1];
if (newValue is IDictionary)
{
var elements = (IDictionary)newValue;
var targetCollectionType = typeof(Dictionary<,>);
var collectionType = targetCollectionType.MakeGenericType(new[] { keyType, valueType });
var typedCollection = Activator.CreateInstance(collectionType);
var addMethod = collectionType.GetMethod("Add", new[] { keyType, valueType });
var i = 0;
foreach (DictionaryEntry entry in elements)
{
var propertyExpr = BuildIndexedPropertyName(propertyName, i);
var key = ConvertValueIfNecessary(keyType, entry.Key, propertyExpr + ".Key");
var value = ConvertValueIfNecessary(valueType, entry.Value, propertyExpr + ".Value");
addMethod.Invoke(typedCollection, new[] { key, value });
i++;
}
return typedCollection;
}
}
// if required type is some IEnumerable<T>, convert all the elements
if (requiredType != null &&
requiredType.IsGenericType &&
TypeImplementsGenericInterface(requiredType, typeof(IEnumerable<>)))
{
// convert individual elements to array elements
var componentType = requiredType.GetGenericArguments()[0];
if (newValue is ICollection)
{
var elements = (ICollection)newValue;
return ToTypedCollectionWithTypeConversion(typeof(List<>), componentType, elements, propertyName);
}
}
// try to convert using type converter
try
{
var typeConverter = TypeConverterRegistry.GetConverter(requiredType);
if (typeConverter != null && typeConverter.CanConvertFrom(newValue.GetType()))
{
try
{
newValue = typeConverter.ConvertFrom(newValue);
}
catch
{
if (newValue is string)
{
newValue = typeConverter.ConvertFromInvariantString((string)newValue);
}
}
}
else
{
typeConverter = TypeConverterRegistry.GetConverter(newValue.GetType());
if (typeConverter != null && typeConverter.CanConvertTo(requiredType))
{
newValue = typeConverter.ConvertTo(newValue, requiredType);
}
else
{
// look if it's an enum
if (requiredType != null &&
requiredType.IsEnum &&
(!(newValue is float) &&
(!(newValue is double))))
{
// convert numeric value into enum's underlying type
var numericType = Enum.GetUnderlyingType(requiredType);
newValue = Convert.ChangeType(newValue, numericType);
if (Enum.IsDefined(requiredType, newValue))
{
newValue = Enum.ToObject(requiredType, newValue);
}
else
{
throw new TypeMismatchException(
CreatePropertyChangeEventArgs(propertyName, null, newValue), requiredType);
}
}
else if (newValue is IConvertible)
{
// last resort - try ChangeType
newValue = Convert.ChangeType(newValue, requiredType);
}
else
{
throw new TypeMismatchException(
CreatePropertyChangeEventArgs(propertyName, null, newValue), requiredType);
}
}
}
}
catch (Exception ex)
{
throw new TypeMismatchException(
CreatePropertyChangeEventArgs(propertyName, null, newValue), requiredType, ex);
}
if (newValue == null && (requiredType == null || !Type.GetType("System.Nullable`1").Equals(requiredType.GetGenericTypeDefinition())))
{
throw new TypeMismatchException(
CreatePropertyChangeEventArgs(propertyName, null, newValue), requiredType);
}
}
return newValue;
}
private static object ToArrayWithTypeConversion(Type componentType, ICollection elements, string propertyName)
{
var destination = Array.CreateInstance(componentType, elements.Count);
var i = 0;
foreach (var element in elements)
{
var value = ConvertValueIfNecessary(componentType, element, BuildIndexedPropertyName(propertyName, i));
destination.SetValue(value, i);
i++;
}
return destination;
}
private static object ToTypedCollectionWithTypeConversion(Type targetCollectionType, Type componentType, ICollection elements, string propertyName)
{
if (!TypeImplementsGenericInterface(targetCollectionType, typeof(ICollection<>)))
{
throw new ArgumentException("argument must be a type that derives from ICollection<T>", "targetCollectionType");
}
var collectionType = targetCollectionType.MakeGenericType(new[] { componentType });
var typedCollection = Activator.CreateInstance(collectionType);
var i = 0;
foreach (var element in elements)
{
var value = ConvertValueIfNecessary(componentType, element,
BuildIndexedPropertyName(propertyName, i));
collectionType.GetMethod("Add").Invoke(typedCollection, new[] { value });
i++;
}
return typedCollection;
}
private static string BuildIndexedPropertyName(string propertyName, int index)
{
return (propertyName != null ?
propertyName + "[" + index + "]" :
null);
}
private static bool IsAssignableFrom(object newValue, Type requiredType)
{
if (newValue is MarshalByRefObject)
{
//TODO see what type of type checking can be done. May need to
//preserve information when proxy was created by SaoServiceExporter.
return true;
}
if (requiredType == null)
{
return false;
}
return requiredType.IsAssignableFrom(newValue.GetType());
}
/// <summary>
/// Utility method to create a property change event.
/// </summary>
/// <param name="fullPropertyName">
/// The full name of the property that has changed.
/// </param>
/// <param name="oldValue">The property old value</param>
/// <param name="newValue">The property new value</param>
/// <returns>
/// A new <see cref="PropertyChangeEventArgs"/>.
/// </returns>
private static PropertyChangeEventArgs CreatePropertyChangeEventArgs(string fullPropertyName, object oldValue,
object newValue)
{
return new PropertyChangeEventArgs(fullPropertyName, oldValue, newValue);
}
/// <summary>
/// Determines if a Type implements a specific generic interface.
/// </summary>
/// <param name="candidateType">Candidate <see lang="Type"/> to evaluate.</param>
/// <param name="matchingInterface">The <see lang="interface"/> to test for in the Candidate <see lang="Type"/>.</param>
/// <returns><see lang="true" /> if a match, else <see lang="false"/></returns>
private static bool TypeImplementsGenericInterface(Type candidateType, Type matchingInterface)
{
if (!matchingInterface.IsInterface)
{
throw new ArgumentException("matchingInterface Type must be an Interface Type", "matchingInterface");
}
if (candidateType.IsInterface && IsMatchingGenericInterface(candidateType, matchingInterface))
{
return true;
}
var match = false;
var implementedInterfaces = candidateType.GetInterfaces();
foreach (var interfaceType in implementedInterfaces)
{
if (IsMatchingGenericInterface(interfaceType, matchingInterface))
{
match = true;
break;
}
}
return match;
}
private static bool IsMatchingGenericInterface(Type candidateInterfaceType,
Type matchingGenericInterface)
{
return candidateInterfaceType.IsGenericType &&
candidateInterfaceType.GetGenericTypeDefinition() == matchingGenericInterface;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Data;
using BTCPayServer.Migrations;
using Microsoft.EntityFrameworkCore;
using NBitcoin;
using NBitcoin.DataEncoders;
namespace BTCPayServer.Services.Stores
{
public class StoreRepository
{
private readonly ApplicationDbContextFactory _ContextFactory;
public ApplicationDbContext CreateDbContext()
{
return _ContextFactory.CreateContext();
}
public StoreRepository(ApplicationDbContextFactory contextFactory)
{
_ContextFactory = contextFactory ?? throw new ArgumentNullException(nameof(contextFactory));
}
public async Task<StoreData> FindStore(string storeId)
{
if (storeId == null)
return null;
using var ctx = _ContextFactory.CreateContext();
var result = await ctx.FindAsync<StoreData>(storeId).ConfigureAwait(false);
return result;
}
public async Task<StoreData> FindStore(string storeId, string userId)
{
ArgumentNullException.ThrowIfNull(userId);
await using var ctx = _ContextFactory.CreateContext();
return (await ctx
.UserStore
.Where(us => us.ApplicationUserId == userId && us.StoreDataId == storeId)
.Include(store => store.StoreData.UserStores)
.Select(us => new
{
Store = us.StoreData,
Role = us.Role
}).ToArrayAsync())
.Select(us =>
{
us.Store.Role = us.Role;
return us.Store;
}).FirstOrDefault();
}
public class StoreUser
{
public string Id { get; set; }
public string Email { get; set; }
public string Role { get; set; }
}
public async Task<StoreUser[]> GetStoreUsers(string storeId)
{
ArgumentNullException.ThrowIfNull(storeId);
using var ctx = _ContextFactory.CreateContext();
return await ctx
.UserStore
.Where(u => u.StoreDataId == storeId)
.Select(u => new StoreUser()
{
Id = u.ApplicationUserId,
Email = u.ApplicationUser.Email,
Role = u.Role
}).ToArrayAsync();
}
public async Task<StoreData[]> GetStoresByUserId(string userId, IEnumerable<string> storeIds = null)
{
using var ctx = _ContextFactory.CreateContext();
return (await ctx.UserStore
.Where(u => u.ApplicationUserId == userId && (storeIds == null || storeIds.Contains(u.StoreDataId)))
.Select(u => new { u.StoreData, u.Role })
.ToArrayAsync())
.Select(u =>
{
u.StoreData.Role = u.Role;
return u.StoreData;
}).ToArray();
}
public async Task<StoreData> GetStoreByInvoiceId(string invoiceId)
{
await using var context = _ContextFactory.CreateContext();
var matched = await context.Invoices.Include(data => data.StoreData)
.SingleOrDefaultAsync(data => data.Id == invoiceId);
return matched?.StoreData;
}
public async Task<bool> AddStoreUser(string storeId, string userId, string role)
{
using var ctx = _ContextFactory.CreateContext();
var userStore = new UserStore() { StoreDataId = storeId, ApplicationUserId = userId, Role = role };
ctx.UserStore.Add(userStore);
try
{
await ctx.SaveChangesAsync();
return true;
}
catch (Microsoft.EntityFrameworkCore.DbUpdateException)
{
return false;
}
}
public async Task CleanUnreachableStores()
{
using var ctx = _ContextFactory.CreateContext();
if (!ctx.Database.SupportDropForeignKey())
return;
foreach (var store in await ctx.Stores.Where(s => !s.UserStores.Where(u => u.Role == StoreRoles.Owner).Any()).ToArrayAsync())
{
ctx.Stores.Remove(store);
}
await ctx.SaveChangesAsync();
}
public async Task<bool> RemoveStoreUser(string storeId, string userId)
{
await using var ctx = _ContextFactory.CreateContext();
if (!await ctx.UserStore.AnyAsync(store =>
store.StoreDataId == storeId && store.Role == StoreRoles.Owner &&
userId != store.ApplicationUserId)) return false;
var userStore = new UserStore() { StoreDataId = storeId, ApplicationUserId = userId };
ctx.UserStore.Add(userStore);
ctx.Entry(userStore).State = EntityState.Deleted;
await ctx.SaveChangesAsync();
return true;
}
private async Task DeleteStoreIfOrphan(string storeId)
{
using var ctx = _ContextFactory.CreateContext();
if (ctx.Database.SupportDropForeignKey())
{
if (!await ctx.UserStore.Where(u => u.StoreDataId == storeId && u.Role == StoreRoles.Owner).AnyAsync())
{
var store = await ctx.Stores.FindAsync(storeId);
if (store != null)
{
ctx.Stores.Remove(store);
await ctx.SaveChangesAsync();
}
}
}
}
public async Task CreateStore(string ownerId, StoreData storeData)
{
if (!string.IsNullOrEmpty(storeData.Id))
throw new ArgumentException("id should be empty", nameof(storeData.StoreName));
if (string.IsNullOrEmpty(storeData.StoreName))
throw new ArgumentException("name should not be empty", nameof(storeData.StoreName));
ArgumentNullException.ThrowIfNull(ownerId);
using var ctx = _ContextFactory.CreateContext();
storeData.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(32));
var userStore = new UserStore
{
StoreDataId = storeData.Id,
ApplicationUserId = ownerId,
Role = StoreRoles.Owner,
};
ctx.Add(storeData);
ctx.Add(userStore);
await ctx.SaveChangesAsync();
}
public async Task<StoreData> CreateStore(string ownerId, string name, string defaultCurrency, string preferredExchange)
{
var store = new StoreData { StoreName = name };
var blob = store.GetStoreBlob();
blob.DefaultCurrency = defaultCurrency;
blob.PreferredExchange = preferredExchange;
store.SetStoreBlob(blob);
await CreateStore(ownerId, store);
return store;
}
public async Task<WebhookData[]> GetWebhooks(string storeId)
{
using var ctx = _ContextFactory.CreateContext();
return await ctx.StoreWebhooks
.Where(s => s.StoreId == storeId)
.Select(s => s.Webhook).ToArrayAsync();
}
public async Task<WebhookDeliveryData> GetWebhookDelivery(string storeId, string webhookId, string deliveryId)
{
ArgumentNullException.ThrowIfNull(webhookId);
ArgumentNullException.ThrowIfNull(storeId);
using var ctx = _ContextFactory.CreateContext();
return await ctx.StoreWebhooks
.Where(d => d.StoreId == storeId && d.WebhookId == webhookId)
.SelectMany(d => d.Webhook.Deliveries)
.Where(d => d.Id == deliveryId)
.FirstOrDefaultAsync();
}
public async Task AddWebhookDelivery(WebhookDeliveryData delivery)
{
using var ctx = _ContextFactory.CreateContext();
ctx.WebhookDeliveries.Add(delivery);
var invoiceWebhookDelivery = delivery.GetBlob().ReadRequestAs<InvoiceWebhookDeliveryData>();
if (invoiceWebhookDelivery.InvoiceId != null)
{
ctx.InvoiceWebhookDeliveries.Add(new InvoiceWebhookDeliveryData()
{
InvoiceId = invoiceWebhookDelivery.InvoiceId,
DeliveryId = delivery.Id
});
}
await ctx.SaveChangesAsync();
}
public async Task<WebhookDeliveryData[]> GetWebhookDeliveries(string storeId, string webhookId, int? count)
{
ArgumentNullException.ThrowIfNull(webhookId);
ArgumentNullException.ThrowIfNull(storeId);
using var ctx = _ContextFactory.CreateContext();
IQueryable<WebhookDeliveryData> req = ctx.StoreWebhooks
.Where(s => s.StoreId == storeId && s.WebhookId == webhookId)
.SelectMany(s => s.Webhook.Deliveries)
.OrderByDescending(s => s.Timestamp);
if (count is int c)
req = req.Take(c);
return await req
.ToArrayAsync();
}
public async Task<string> CreateWebhook(string storeId, WebhookBlob blob)
{
ArgumentNullException.ThrowIfNull(storeId);
ArgumentNullException.ThrowIfNull(blob);
using var ctx = _ContextFactory.CreateContext();
WebhookData data = new WebhookData();
data.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16));
if (string.IsNullOrEmpty(blob.Secret))
blob.Secret = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16));
data.SetBlob(blob);
StoreWebhookData storeWebhook = new StoreWebhookData();
storeWebhook.StoreId = storeId;
storeWebhook.WebhookId = data.Id;
ctx.StoreWebhooks.Add(storeWebhook);
ctx.Webhooks.Add(data);
await ctx.SaveChangesAsync();
return data.Id;
}
public async Task<WebhookData> GetWebhook(string storeId, string webhookId)
{
ArgumentNullException.ThrowIfNull(webhookId);
ArgumentNullException.ThrowIfNull(storeId);
using var ctx = _ContextFactory.CreateContext();
return await ctx.StoreWebhooks
.Where(s => s.StoreId == storeId && s.WebhookId == webhookId)
.Select(s => s.Webhook)
.FirstOrDefaultAsync();
}
public async Task<WebhookData> GetWebhook(string webhookId)
{
ArgumentNullException.ThrowIfNull(webhookId);
using var ctx = _ContextFactory.CreateContext();
return await ctx.StoreWebhooks
.Where(s => s.WebhookId == webhookId)
.Select(s => s.Webhook)
.FirstOrDefaultAsync();
}
public async Task DeleteWebhook(string storeId, string webhookId)
{
ArgumentNullException.ThrowIfNull(webhookId);
ArgumentNullException.ThrowIfNull(storeId);
using var ctx = _ContextFactory.CreateContext();
var hook = await ctx.StoreWebhooks
.Where(s => s.StoreId == storeId && s.WebhookId == webhookId)
.Select(s => s.Webhook)
.FirstOrDefaultAsync();
if (hook is null)
return;
ctx.Webhooks.Remove(hook);
await ctx.SaveChangesAsync();
}
public async Task UpdateWebhook(string storeId, string webhookId, WebhookBlob webhookBlob)
{
ArgumentNullException.ThrowIfNull(webhookId);
ArgumentNullException.ThrowIfNull(storeId);
ArgumentNullException.ThrowIfNull(webhookBlob);
using var ctx = _ContextFactory.CreateContext();
var hook = await ctx.StoreWebhooks
.Where(s => s.StoreId == storeId && s.WebhookId == webhookId)
.Select(s => s.Webhook)
.FirstOrDefaultAsync();
if (hook is null)
return;
hook.SetBlob(webhookBlob);
await ctx.SaveChangesAsync();
}
public async Task RemoveStore(string storeId, string userId)
{
using (var ctx = _ContextFactory.CreateContext())
{
var storeUser = await ctx.UserStore.AsQueryable().FirstOrDefaultAsync(o => o.StoreDataId == storeId && o.ApplicationUserId == userId);
if (storeUser == null)
return;
ctx.UserStore.Remove(storeUser);
await ctx.SaveChangesAsync();
}
await DeleteStoreIfOrphan(storeId);
}
public async Task UpdateStore(StoreData store)
{
using var ctx = _ContextFactory.CreateContext();
var existing = await ctx.FindAsync<StoreData>(store.Id);
ctx.Entry(existing).CurrentValues.SetValues(store);
await ctx.SaveChangesAsync().ConfigureAwait(false);
}
public async Task<bool> DeleteStore(string storeId)
{
int retry = 0;
using var ctx = _ContextFactory.CreateContext();
if (!ctx.Database.SupportDropForeignKey())
return false;
var store = await ctx.Stores.FindAsync(storeId);
if (store == null)
return false;
var webhooks = await ctx.StoreWebhooks
.Where(o => o.StoreId == storeId)
.Select(o => o.Webhook)
.ToArrayAsync();
foreach (var w in webhooks)
ctx.Webhooks.Remove(w);
ctx.Stores.Remove(store);
retry:
try
{
await ctx.SaveChangesAsync();
}
catch (DbUpdateException ex) when (IsDeadlock(ex) && retry < 5)
{
await Task.Delay(100);
retry++;
goto retry;
}
return true;
}
private static bool IsDeadlock(DbUpdateException ex)
{
return ex.InnerException is Npgsql.PostgresException postgres && postgres.SqlState == "40P01";
}
public bool CanDeleteStores()
{
using var ctx = _ContextFactory.CreateContext();
return ctx.Database.SupportDropForeignKey();
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Tokens
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IdentityModel;
using System.IdentityModel.Selectors;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
public class SamlSerializer
{
DictionaryManager dictionaryManager;
public SamlSerializer()
{
}
// Interface to plug in external Dictionaries. The external
// dictionary should already be populated with all strings
// required by this assembly.
public void PopulateDictionary(IXmlDictionary dictionary)
{
if (dictionary == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dictionary");
this.dictionaryManager = new DictionaryManager(dictionary);
}
internal DictionaryManager DictionaryManager
{
get
{
if (this.dictionaryManager == null)
this.dictionaryManager = new DictionaryManager();
return this.dictionaryManager;
}
}
public virtual SamlSecurityToken ReadToken(XmlReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
{
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
XmlDictionaryReader dictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader);
WrappedReader wrappedReader = new WrappedReader(dictionaryReader);
SamlAssertion assertion = LoadAssertion(wrappedReader, keyInfoSerializer, outOfBandTokenResolver);
if (assertion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLUnableToLoadAssertion)));
//if (assertion.Signature == null)
// throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SamlTokenMissingSignature)));
return new SamlSecurityToken(assertion);
}
public virtual void WriteToken(SamlSecurityToken token, XmlWriter writer, SecurityTokenSerializer keyInfoSerializer)
{
if (token == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
#pragma warning suppress 56506 // token.Assertion is never null.
token.Assertion.WriteTo(writer, this, keyInfoSerializer);
}
public virtual SamlAssertion LoadAssertion(XmlDictionaryReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
{
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
SamlAssertion assertion = new SamlAssertion();
assertion.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver);
return assertion;
}
public virtual SamlCondition LoadCondition(XmlDictionaryReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
{
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
if (reader.IsStartElement(DictionaryManager.SamlDictionary.AudienceRestrictionCondition, DictionaryManager.SamlDictionary.Namespace))
{
SamlAudienceRestrictionCondition audienceRestriction = new SamlAudienceRestrictionCondition();
audienceRestriction.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver);
return audienceRestriction;
}
else if (reader.IsStartElement(DictionaryManager.SamlDictionary.DoNotCacheCondition, DictionaryManager.SamlDictionary.Namespace))
{
SamlDoNotCacheCondition doNotCacheCondition = new SamlDoNotCacheCondition();
doNotCacheCondition.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver);
return doNotCacheCondition;
}
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.SAMLUnableToLoadUnknownElement, reader.LocalName)));
}
public virtual SamlConditions LoadConditions(XmlDictionaryReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
{
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
SamlConditions conditions = new SamlConditions();
conditions.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver);
return conditions;
}
public virtual SamlAdvice LoadAdvice(XmlDictionaryReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
{
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
SamlAdvice advice = new SamlAdvice();
advice.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver);
return advice;
}
public virtual SamlStatement LoadStatement(XmlDictionaryReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
{
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
if (reader.IsStartElement(DictionaryManager.SamlDictionary.AuthenticationStatement, DictionaryManager.SamlDictionary.Namespace))
{
SamlAuthenticationStatement authStatement = new SamlAuthenticationStatement();
authStatement.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver);
return authStatement;
}
else if (reader.IsStartElement(DictionaryManager.SamlDictionary.AttributeStatement, DictionaryManager.SamlDictionary.Namespace))
{
SamlAttributeStatement attrStatement = new SamlAttributeStatement();
attrStatement.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver);
return attrStatement;
}
else if (reader.IsStartElement(DictionaryManager.SamlDictionary.AuthorizationDecisionStatement, DictionaryManager.SamlDictionary.Namespace))
{
SamlAuthorizationDecisionStatement authDecisionStatement = new SamlAuthorizationDecisionStatement();
authDecisionStatement.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver);
return authDecisionStatement;
}
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.SAMLUnableToLoadUnknownElement, reader.LocalName)));
}
public virtual SamlAttribute LoadAttribute(XmlDictionaryReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
{
// We will load all attributes as string values.
SamlAttribute attribute = new SamlAttribute();
attribute.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver);
return attribute;
}
// Helper metods to read and write SecurityKeyIdentifiers.
internal static SecurityKeyIdentifier ReadSecurityKeyIdentifier(XmlReader reader, SecurityTokenSerializer tokenSerializer)
{
if (tokenSerializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenSerializer", SR.GetString(SR.SamlSerializerRequiresExternalSerializers));
if (tokenSerializer.CanReadKeyIdentifier(reader))
{
return tokenSerializer.ReadKeyIdentifier(reader);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SamlSerializerUnableToReadSecurityKeyIdentifier)));
}
internal static void WriteSecurityKeyIdentifier(XmlWriter writer, SecurityKeyIdentifier ski, SecurityTokenSerializer tokenSerializer)
{
if (tokenSerializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenSerializer", SR.GetString(SR.SamlSerializerRequiresExternalSerializers));
bool keyWritten = false;
if (tokenSerializer.CanWriteKeyIdentifier(ski))
{
tokenSerializer.WriteKeyIdentifier(writer, ski);
keyWritten = true;
}
if (!keyWritten)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SamlSerializerUnableToWriteSecurityKeyIdentifier, ski.ToString())));
}
internal static SecurityKey ResolveSecurityKey(SecurityKeyIdentifier ski, SecurityTokenResolver tokenResolver)
{
if (ski == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ski");
if (tokenResolver != null)
{
for (int i = 0; i < ski.Count; ++i)
{
SecurityKey key = null;
if (tokenResolver.TryResolveSecurityKey(ski[i], out key))
return key;
}
}
if (ski.CanCreateKey)
return ski.CreateKey();
return null;
}
internal static SecurityToken ResolveSecurityToken(SecurityKeyIdentifier ski, SecurityTokenResolver tokenResolver)
{
SecurityToken token = null;
if (tokenResolver != null)
{
tokenResolver.TryResolveToken(ski, out token);
}
if (token == null)
{
// Check if this is a RSA key.
RsaKeyIdentifierClause rsaClause;
if (ski.TryFind<RsaKeyIdentifierClause>(out rsaClause))
token = new RsaSecurityToken(rsaClause.Rsa);
}
if (token == null)
{
// Check if this is a X509RawDataKeyIdentifier Clause.
X509RawDataKeyIdentifierClause rawDataKeyIdentifierClause;
if (ski.TryFind<X509RawDataKeyIdentifierClause>(out rawDataKeyIdentifierClause))
token = new X509SecurityToken(new X509Certificate2(rawDataKeyIdentifierClause.GetX509RawData()));
}
return token;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// String.Trim()
/// </summary>
public class StringTrim1
{
private int c_MINI_STRING_LENGTH = 8;
private int c_MAX_STRING_LENGTH = 256;
// U+200B stops being trimmable http://msdn2.microsoft.com/en-us/library/t97s7bs3.aspx
// U+FEFF has been deprecate as a trimmable space
private string[] spaceStrings = new string[]{"\u0009","\u000A","\u000B","\u000C","\u000D","\u0020",
"\u00A0","\u2000","\u2001","\u2002","\u2003","\u2004","\u2005",
"\u2006","\u2007","\u2008","\u2009","\u200A","\u3000"};
public static int Main()
{
StringTrim1 st1 = new StringTrim1();
TestLibrary.TestFramework.BeginTestCase("StringTrim1");
//while (st1.RunTests())
//{
// Console.WriteLine(")");
//}
//return 100;
if (st1.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;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
string strA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest1: empty string trim()");
try
{
strA = string.Empty;
ActualResult = strA.Trim();
if (ActualResult != string.Empty)
{
TestLibrary.TestFramework.LogError("001", "empty string trim() ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string strA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest2:normal string trim one");
try
{
strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
int i = this.GetInt32(0, spaceStrings.Length);
string strB = spaceStrings[i];
string strA1 = strB + "H" + strA + "D" + strB;
ActualResult = strA1.Trim();
if (ActualResult.ToString() != "H" + strA.ToString() + "D")
{
TestLibrary.TestFramework.LogError("003", "normal string trim one when space is (" + i + ":'" + strB.ToString() + "') ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string strA;
string ActualResult;
TestLibrary.TestFramework.BeginScenario("PosTest3:normal string trim two");
try
{
strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
int i = this.GetInt32(0, spaceStrings.Length);
string strB = spaceStrings[i];
string strA1 = strB + "H" + strB + strA + strB+ "D" + strB;
ActualResult = strA1.Trim();
if (ActualResult.ToString() != "H" + strB + strA.ToString() + strB + "D")
{
TestLibrary.TestFramework.LogError("005", "normal string trim one when space is ("+i+":'" + strB.ToString() + "') ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#region Help method for geting test data
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
private Char GetChar(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return Convert.ToChar(minValue);
}
if (minValue < maxValue)
{
return Convert.ToChar(Convert.ToInt32(TestLibrary.Generator.GetChar(-55)) % (maxValue - minValue) + minValue);
}
}
catch
{
throw;
}
return Convert.ToChar(minValue);
}
private string GetString(bool ValidPath, Int32 minValue, Int32 maxValue)
{
StringBuilder sVal = new StringBuilder();
string s;
if (0 == minValue && 0 == maxValue) return String.Empty;
if (minValue > maxValue) return null;
if (ValidPath)
{
return TestLibrary.Generator.GetString(-55, ValidPath, minValue, maxValue);
}
else
{
int length = this.GetInt32(minValue, maxValue);
for (int i = 0; length > i; i++)
{
char c = this.GetChar(minValue, maxValue);
sVal.Append(c);
}
s = sVal.ToString();
return s;
}
}
#endregion
}
| |
namespace UnityEngine.PostProcessing
{
using DebugMode = BuiltinDebugViewsModel.Mode;
public sealed class ColorGradingComponent : PostProcessingComponentRenderTexture<ColorGradingModel>
{
static class Uniforms
{
internal static readonly int _LutParams = Shader.PropertyToID("_LutParams");
internal static readonly int _NeutralTonemapperParams1 = Shader.PropertyToID("_NeutralTonemapperParams1");
internal static readonly int _NeutralTonemapperParams2 = Shader.PropertyToID("_NeutralTonemapperParams2");
internal static readonly int _HueShift = Shader.PropertyToID("_HueShift");
internal static readonly int _Saturation = Shader.PropertyToID("_Saturation");
internal static readonly int _Contrast = Shader.PropertyToID("_Contrast");
internal static readonly int _Balance = Shader.PropertyToID("_Balance");
internal static readonly int _Lift = Shader.PropertyToID("_Lift");
internal static readonly int _InvGamma = Shader.PropertyToID("_InvGamma");
internal static readonly int _Gain = Shader.PropertyToID("_Gain");
internal static readonly int _Slope = Shader.PropertyToID("_Slope");
internal static readonly int _Power = Shader.PropertyToID("_Power");
internal static readonly int _Offset = Shader.PropertyToID("_Offset");
internal static readonly int _ChannelMixerRed = Shader.PropertyToID("_ChannelMixerRed");
internal static readonly int _ChannelMixerGreen = Shader.PropertyToID("_ChannelMixerGreen");
internal static readonly int _ChannelMixerBlue = Shader.PropertyToID("_ChannelMixerBlue");
internal static readonly int _Curves = Shader.PropertyToID("_Curves");
internal static readonly int _LogLut = Shader.PropertyToID("_LogLut");
internal static readonly int _LogLut_Params = Shader.PropertyToID("_LogLut_Params");
internal static readonly int _ExposureEV = Shader.PropertyToID("_ExposureEV");
}
const int k_InternalLogLutSize = 32;
const int k_CurvePrecision = 128;
const float k_CurveStep = 1f / k_CurvePrecision;
Texture2D m_GradingCurves;
Color[] m_pixels = new Color[k_CurvePrecision * 2];
public override bool active
{
get
{
return model.enabled
&& !context.interrupted;
}
}
// An analytical model of chromaticity of the standard illuminant, by Judd et al.
// http://en.wikipedia.org/wiki/Standard_illuminant#Illuminant_series_D
// Slightly modifed to adjust it with the D65 white point (x=0.31271, y=0.32902).
float StandardIlluminantY(float x)
{
return 2.87f * x - 3f * x * x - 0.27509507f;
}
// CIE xy chromaticity to CAT02 LMS.
// http://en.wikipedia.org/wiki/LMS_color_space#CAT02
Vector3 CIExyToLMS(float x, float y)
{
float Y = 1f;
float X = Y * x / y;
float Z = Y * (1f - x - y) / y;
float L = 0.7328f * X + 0.4296f * Y - 0.1624f * Z;
float M = -0.7036f * X + 1.6975f * Y + 0.0061f * Z;
float S = 0.0030f * X + 0.0136f * Y + 0.9834f * Z;
return new Vector3(L, M, S);
}
Vector3 CalculateColorBalance(float temperature, float tint)
{
// Range ~[-1.8;1.8] ; using higher ranges is unsafe
float t1 = temperature / 55f;
float t2 = tint / 55f;
// Get the CIE xy chromaticity of the reference white point.
// Note: 0.31271 = x value on the D65 white point
float x = 0.31271f - t1 * (t1 < 0f ? 0.1f : 0.05f);
float y = StandardIlluminantY(x) + t2 * 0.05f;
// Calculate the coefficients in the LMS space.
var w1 = new Vector3(0.949237f, 1.03542f, 1.08728f); // D65 white point
var w2 = CIExyToLMS(x, y);
return new Vector3(w1.x / w2.x, w1.y / w2.y, w1.z / w2.z);
}
static Color NormalizeColor(Color c)
{
float sum = (c.r + c.g + c.b) / 3f;
if (Mathf.Approximately(sum, 0f))
return new Color(1f, 1f, 1f, c.a);
return new Color
{
r = c.r / sum,
g = c.g / sum,
b = c.b / sum,
a = c.a
};
}
static Vector3 ClampVector(Vector3 v, float min, float max)
{
return new Vector3(
Mathf.Clamp(v.x, min, max),
Mathf.Clamp(v.y, min, max),
Mathf.Clamp(v.z, min, max)
);
}
public static Vector3 GetLiftValue(Color lift)
{
const float kLiftScale = 0.1f;
var nLift = NormalizeColor(lift);
float avgLift = (nLift.r + nLift.g + nLift.b) / 3f;
// Getting some artifacts when going into the negatives using a very low offset (lift.a) with non ACES-tonemapping
float liftR = (nLift.r - avgLift) * kLiftScale + lift.a;
float liftG = (nLift.g - avgLift) * kLiftScale + lift.a;
float liftB = (nLift.b - avgLift) * kLiftScale + lift.a;
return ClampVector(new Vector3(liftR, liftG, liftB), -1f, 1f);
}
public static Vector3 GetGammaValue(Color gamma)
{
const float kGammaScale = 0.5f;
const float kMinGamma = 0.01f;
var nGamma = NormalizeColor(gamma);
float avgGamma = (nGamma.r + nGamma.g + nGamma.b) / 3f;
gamma.a *= gamma.a < 0f ? 0.8f : 5f;
float gammaR = Mathf.Pow(2f, (nGamma.r - avgGamma) * kGammaScale) + gamma.a;
float gammaG = Mathf.Pow(2f, (nGamma.g - avgGamma) * kGammaScale) + gamma.a;
float gammaB = Mathf.Pow(2f, (nGamma.b - avgGamma) * kGammaScale) + gamma.a;
float invGammaR = 1f / Mathf.Max(kMinGamma, gammaR);
float invGammaG = 1f / Mathf.Max(kMinGamma, gammaG);
float invGammaB = 1f / Mathf.Max(kMinGamma, gammaB);
return ClampVector(new Vector3(invGammaR, invGammaG, invGammaB), 0f, 5f);
}
public static Vector3 GetGainValue(Color gain)
{
const float kGainScale = 0.5f;
var nGain = NormalizeColor(gain);
float avgGain = (nGain.r + nGain.g + nGain.b) / 3f;
gain.a *= gain.a > 0f ? 3f : 1f;
float gainR = Mathf.Pow(2f, (nGain.r - avgGain) * kGainScale) + gain.a;
float gainG = Mathf.Pow(2f, (nGain.g - avgGain) * kGainScale) + gain.a;
float gainB = Mathf.Pow(2f, (nGain.b - avgGain) * kGainScale) + gain.a;
return ClampVector(new Vector3(gainR, gainG, gainB), 0f, 4f);
}
public static void CalculateLiftGammaGain(Color lift, Color gamma, Color gain, out Vector3 outLift, out Vector3 outGamma, out Vector3 outGain)
{
outLift = GetLiftValue(lift);
outGamma = GetGammaValue(gamma);
outGain = GetGainValue(gain);
}
public static Vector3 GetSlopeValue(Color slope)
{
const float kSlopeScale = 0.1f;
var nSlope = NormalizeColor(slope);
float avgSlope = (nSlope.r + nSlope.g + nSlope.b) / 3f;
slope.a *= 0.5f;
float slopeR = (nSlope.r - avgSlope) * kSlopeScale + slope.a + 1f;
float slopeG = (nSlope.g - avgSlope) * kSlopeScale + slope.a + 1f;
float slopeB = (nSlope.b - avgSlope) * kSlopeScale + slope.a + 1f;
return ClampVector(new Vector3(slopeR, slopeG, slopeB), 0f, 2f);
}
public static Vector3 GetPowerValue(Color power)
{
const float kPowerScale = 0.1f;
const float minPower = 0.01f;
var nPower = NormalizeColor(power);
float avgPower = (nPower.r + nPower.g + nPower.b) / 3f;
power.a *= 0.5f;
float powerR = (nPower.r - avgPower) * kPowerScale + power.a + 1f;
float powerG = (nPower.g - avgPower) * kPowerScale + power.a + 1f;
float powerB = (nPower.b - avgPower) * kPowerScale + power.a + 1f;
float invPowerR = 1f / Mathf.Max(minPower, powerR);
float invPowerG = 1f / Mathf.Max(minPower, powerG);
float invPowerB = 1f / Mathf.Max(minPower, powerB);
return ClampVector(new Vector3(invPowerR, invPowerG, invPowerB), 0.5f, 2.5f);
}
public static Vector3 GetOffsetValue(Color offset)
{
const float kOffsetScale = 0.05f;
var nOffset = NormalizeColor(offset);
float avgOffset = (nOffset.r + nOffset.g + nOffset.b) / 3f;
offset.a *= 0.5f;
float offsetR = (nOffset.r - avgOffset) * kOffsetScale + offset.a;
float offsetG = (nOffset.g - avgOffset) * kOffsetScale + offset.a;
float offsetB = (nOffset.b - avgOffset) * kOffsetScale + offset.a;
return ClampVector(new Vector3(offsetR, offsetG, offsetB), -0.8f, 0.8f);
}
public static void CalculateSlopePowerOffset(Color slope, Color power, Color offset, out Vector3 outSlope, out Vector3 outPower, out Vector3 outOffset)
{
outSlope = GetSlopeValue(slope);
outPower = GetPowerValue(power);
outOffset = GetOffsetValue(offset);
}
Texture2D GetCurveTexture()
{
if (m_GradingCurves == null)
{
m_GradingCurves = new Texture2D(k_CurvePrecision, 2, TextureFormat.RGBAHalf, false, true)
{
name = "Internal Curves Texture",
hideFlags = HideFlags.DontSave,
anisoLevel = 0,
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Bilinear
};
}
var curves = model.settings.curves;
curves.hueVShue.Cache();
curves.hueVSsat.Cache();
for (int i = 0; i < k_CurvePrecision; i++)
{
float t = i * k_CurveStep;
// HSL
float x = curves.hueVShue.Evaluate(t);
float y = curves.hueVSsat.Evaluate(t);
float z = curves.satVSsat.Evaluate(t);
float w = curves.lumVSsat.Evaluate(t);
m_pixels[i] = new Color(x, y, z, w);
// YRGB
float m = curves.master.Evaluate(t);
float r = curves.red.Evaluate(t);
float g = curves.green.Evaluate(t);
float b = curves.blue.Evaluate(t);
m_pixels[i + k_CurvePrecision] = new Color(r, g, b, m);
}
m_GradingCurves.SetPixels(m_pixels);
m_GradingCurves.Apply(false, false);
return m_GradingCurves;
}
bool IsLogLutValid(RenderTexture lut)
{
return lut != null && lut.IsCreated() && lut.height == k_InternalLogLutSize;
}
void GenerateLut()
{
var settings = model.settings;
if (!IsLogLutValid(model.bakedLut))
{
GraphicsUtils.Destroy(model.bakedLut);
model.bakedLut = new RenderTexture(k_InternalLogLutSize * k_InternalLogLutSize, k_InternalLogLutSize, 0, RenderTextureFormat.ARGBHalf)
{
name = "Color Grading Log LUT",
hideFlags = HideFlags.DontSave,
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp,
anisoLevel = 0
};
}
var lutMaterial = context.materialFactory.Get("Hidden/Post FX/Lut Generator");
lutMaterial.SetVector(Uniforms._LutParams, new Vector4(
k_InternalLogLutSize,
0.5f / (k_InternalLogLutSize * k_InternalLogLutSize),
0.5f / k_InternalLogLutSize,
k_InternalLogLutSize / (k_InternalLogLutSize - 1f))
);
// Tonemapping
lutMaterial.shaderKeywords = null;
var tonemapping = settings.tonemapping;
switch (tonemapping.tonemapper)
{
case ColorGradingModel.Tonemapper.Neutral:
{
lutMaterial.EnableKeyword("TONEMAPPING_NEUTRAL");
const float scaleFactor = 20f;
const float scaleFactorHalf = scaleFactor * 0.5f;
float inBlack = tonemapping.neutralBlackIn * scaleFactor + 1f;
float outBlack = tonemapping.neutralBlackOut * scaleFactorHalf + 1f;
float inWhite = tonemapping.neutralWhiteIn / scaleFactor;
float outWhite = 1f - tonemapping.neutralWhiteOut / scaleFactor;
float blackRatio = inBlack / outBlack;
float whiteRatio = inWhite / outWhite;
const float a = 0.2f;
float b = Mathf.Max(0f, Mathf.LerpUnclamped(0.57f, 0.37f, blackRatio));
float c = Mathf.LerpUnclamped(0.01f, 0.24f, whiteRatio);
float d = Mathf.Max(0f, Mathf.LerpUnclamped(0.02f, 0.20f, blackRatio));
const float e = 0.02f;
const float f = 0.30f;
lutMaterial.SetVector(Uniforms._NeutralTonemapperParams1, new Vector4(a, b, c, d));
lutMaterial.SetVector(Uniforms._NeutralTonemapperParams2, new Vector4(e, f, tonemapping.neutralWhiteLevel, tonemapping.neutralWhiteClip / scaleFactorHalf));
break;
}
case ColorGradingModel.Tonemapper.ACES:
{
lutMaterial.EnableKeyword("TONEMAPPING_FILMIC");
break;
}
}
// Color balance & basic grading settings
lutMaterial.SetFloat(Uniforms._HueShift, settings.basic.hueShift / 360f);
lutMaterial.SetFloat(Uniforms._Saturation, settings.basic.saturation);
lutMaterial.SetFloat(Uniforms._Contrast, settings.basic.contrast);
lutMaterial.SetVector(Uniforms._Balance, CalculateColorBalance(settings.basic.temperature, settings.basic.tint));
// Lift / Gamma / Gain
Vector3 lift, gamma, gain;
CalculateLiftGammaGain(
settings.colorWheels.linear.lift,
settings.colorWheels.linear.gamma,
settings.colorWheels.linear.gain,
out lift, out gamma, out gain
);
lutMaterial.SetVector(Uniforms._Lift, lift);
lutMaterial.SetVector(Uniforms._InvGamma, gamma);
lutMaterial.SetVector(Uniforms._Gain, gain);
// Slope / Power / Offset
Vector3 slope, power, offset;
CalculateSlopePowerOffset(
settings.colorWheels.log.slope,
settings.colorWheels.log.power,
settings.colorWheels.log.offset,
out slope, out power, out offset
);
lutMaterial.SetVector(Uniforms._Slope, slope);
lutMaterial.SetVector(Uniforms._Power, power);
lutMaterial.SetVector(Uniforms._Offset, offset);
// Channel mixer
lutMaterial.SetVector(Uniforms._ChannelMixerRed, settings.channelMixer.red);
lutMaterial.SetVector(Uniforms._ChannelMixerGreen, settings.channelMixer.green);
lutMaterial.SetVector(Uniforms._ChannelMixerBlue, settings.channelMixer.blue);
// Selective grading & YRGB curves
lutMaterial.SetTexture(Uniforms._Curves, GetCurveTexture());
// Generate the lut
Graphics.Blit(null, model.bakedLut, lutMaterial, 0);
}
public override void Prepare(Material uberMaterial)
{
if (model.isDirty || !IsLogLutValid(model.bakedLut))
{
GenerateLut();
model.isDirty = false;
}
uberMaterial.EnableKeyword(
context.profile.debugViews.IsModeActive(DebugMode.PreGradingLog)
? "COLOR_GRADING_LOG_VIEW"
: "COLOR_GRADING"
);
var bakedLut = model.bakedLut;
uberMaterial.SetTexture(Uniforms._LogLut, bakedLut);
uberMaterial.SetVector(Uniforms._LogLut_Params, new Vector3(1f / bakedLut.width, 1f / bakedLut.height, bakedLut.height - 1f));
float ev = Mathf.Exp(model.settings.basic.postExposure * 0.69314718055994530941723212145818f);
uberMaterial.SetFloat(Uniforms._ExposureEV, ev);
}
public void OnGUI()
{
var bakedLut = model.bakedLut;
var rect = new Rect(context.viewport.x * Screen.width + 8f, 8f, bakedLut.width, bakedLut.height);
GUI.DrawTexture(rect, bakedLut);
}
public override void OnDisable()
{
GraphicsUtils.Destroy(m_GradingCurves);
GraphicsUtils.Destroy(model.bakedLut);
m_GradingCurves = null;
model.bakedLut = null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// AsyncMethodBuilder.cs
//
//
// Compiler-targeted types that build tasks for use as the return types of asynchronous methods.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using Internal.Runtime.Augments;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using AsyncStatus = Internal.Runtime.Augments.AsyncStatus;
using CausalityRelation = Internal.Runtime.Augments.CausalityRelation;
using CausalitySource = Internal.Runtime.Augments.CausalitySource;
using CausalityTraceLevel = Internal.Runtime.Augments.CausalityTraceLevel;
using CausalitySynchronousWork = Internal.Runtime.Augments.CausalitySynchronousWork;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Provides a builder for asynchronous methods that return void.
/// This type is intended for compiler use only.
/// </summary>
public struct AsyncVoidMethodBuilder
{
/// <summary>Action to invoke the state machine's MoveNext.</summary>
private Action m_moveNextAction;
/// <summary>The synchronization context associated with this operation.</summary>
private SynchronizationContext m_synchronizationContext;
//WARNING: We allow diagnostic tools to directly inspect this member (m_task).
//See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
//Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
//Get in touch with the diagnostics team if you have questions.
/// <summary>Task used for debugging and logging purposes only. Lazily initialized.</summary>
private Task m_task;
/// <summary>Initializes a new <see cref="AsyncVoidMethodBuilder"/>.</summary>
/// <returns>The initialized <see cref="AsyncVoidMethodBuilder"/>.</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public static AsyncVoidMethodBuilder Create()
{
SynchronizationContext sc = SynchronizationContext.Current;
if (sc != null)
sc.OperationStarted();
// On ProjectN we will eagerly initalize the task and it's Id if the debugger is attached
AsyncVoidMethodBuilder avmb = new AsyncVoidMethodBuilder() { m_synchronizationContext = sc };
avmb.m_task = avmb.GetTaskIfDebuggingEnabled();
if (avmb.m_task != null)
{
int i = avmb.m_task.Id;
}
return avmb;
}
/// <summary>Initiates the builder's execution with the associated state machine.</summary>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception>
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
AsyncMethodBuilderCore.Start(ref stateMachine);
}
/// <summary>Associates the builder with the state machine it represents.</summary>
/// <param name="stateMachine">The heap-allocated state machine object.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception>
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
AsyncMethodBuilderCore.SetStateMachine(stateMachine, m_moveNextAction); // argument validation handled by AsyncMethodBuilderCore
}
/// <summary>
/// Schedules the specified state machine to be pushed forward when the specified awaiter completes.
/// </summary>
/// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
public void AwaitOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
AsyncMethodBuilderCore.CallOnCompleted(
AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()),
ref awaiter);
}
/// <summary>
/// Schedules the specified state machine to be pushed forward when the specified awaiter completes.
/// </summary>
/// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
AsyncMethodBuilderCore.CallUnsafeOnCompleted(
AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()),
ref awaiter);
}
/// <summary>Completes the method builder successfully.</summary>
public void SetResult()
{
Task taskIfDebuggingEnabled = this.GetTaskIfDebuggingEnabled();
if (taskIfDebuggingEnabled != null)
{
if (DebuggerSupport.LoggingOn)
DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, taskIfDebuggingEnabled, AsyncStatus.Completed);
DebuggerSupport.RemoveFromActiveTasks(taskIfDebuggingEnabled);
}
NotifySynchronizationContextOfCompletion();
}
/// <summary>Faults the method builder with an exception.</summary>
/// <param name="exception">The exception that is the cause of this fault.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public void SetException(Exception exception)
{
Task taskIfDebuggingEnabled = this.GetTaskIfDebuggingEnabled();
if (taskIfDebuggingEnabled != null)
{
if (DebuggerSupport.LoggingOn)
DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, taskIfDebuggingEnabled, AsyncStatus.Error);
}
AsyncMethodBuilderCore.ThrowAsync(exception, m_synchronizationContext);
NotifySynchronizationContextOfCompletion();
}
/// <summary>Notifies the current synchronization context that the operation completed.</summary>
[MethodImpl(MethodImplOptions.NoInlining)]
private void NotifySynchronizationContextOfCompletion()
{
if (m_synchronizationContext != null)
{
try
{
m_synchronizationContext.OperationCompleted();
}
catch (Exception exc)
{
// If the interaction with the SynchronizationContext goes awry,
// fall back to propagating on the ThreadPool.
AsyncMethodBuilderCore.ThrowAsync(exc, targetContext: null);
}
}
}
// This property lazily instantiates the Task in a non-thread-safe manner.
internal Task Task
{
get
{
if (m_task == null) m_task = new Task();
return m_task;
}
}
/// <summary>
/// Gets an object that may be used to uniquely identify this builder to the debugger.
/// </summary>
/// <remarks>
/// This property lazily instantiates the ID in a non-thread-safe manner.
/// It must only be used by the debugger and only in a single-threaded manner.
/// </remarks>
private object ObjectIdForDebugger
{
get
{
return this.Task;
}
}
}
/// <summary>
/// Provides a builder for asynchronous methods that return <see cref="System.Threading.Tasks.Task"/>.
/// This type is intended for compiler use only.
/// </summary>
/// <remarks>
/// AsyncTaskMethodBuilder is a value type, and thus it is copied by value.
/// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed,
/// or else the copies may end up building distinct Task instances.
/// </remarks>
public struct AsyncTaskMethodBuilder
{
/// <summary>A cached VoidTaskResult task used for builders that complete synchronously.</summary>
private readonly static Task<VoidTaskResult> s_cachedCompleted = AsyncTaskCache.CreateCacheableTask<VoidTaskResult>(default(VoidTaskResult));
private Action m_moveNextAction;
// WARNING: We allow diagnostic tools to directly inspect this member (m_task).
// See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
// Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
// Get in touch with the diagnostics team if you have questions.
private Task<VoidTaskResult> m_task;
/// <summary>Initializes a new <see cref="AsyncTaskMethodBuilder"/>.</summary>
/// <returns>The initialized <see cref="AsyncTaskMethodBuilder"/>.</returns>
public static AsyncTaskMethodBuilder Create()
{
AsyncTaskMethodBuilder atmb = default(AsyncTaskMethodBuilder);
// On ProjectN we will eagerly initalize the task and it's Id if the debugger is attached
atmb.m_task = (Task<VoidTaskResult>)atmb.GetTaskIfDebuggingEnabled();
if (atmb.m_task != null)
{
int i = atmb.m_task.Id;
}
return atmb;
}
/// <summary>Initiates the builder's execution with the associated state machine.</summary>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
AsyncMethodBuilderCore.Start(ref stateMachine);
}
/// <summary>Associates the builder with the state machine it represents.</summary>
/// <param name="stateMachine">The heap-allocated state machine object.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception>
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
AsyncMethodBuilderCore.SetStateMachine(stateMachine, m_moveNextAction); // argument validation handled by AsyncMethodBuilderCore
}
/// <summary>
/// Schedules the specified state machine to be pushed forward when the specified awaiter completes.
/// </summary>
/// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
public void AwaitOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
EnsureTaskCreated();
AsyncMethodBuilderCore.CallOnCompleted(
AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()),
ref awaiter);
}
/// <summary>
/// Schedules the specified state machine to be pushed forward when the specified awaiter completes.
/// </summary>
/// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
EnsureTaskCreated();
AsyncMethodBuilderCore.CallUnsafeOnCompleted(
AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()),
ref awaiter);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void EnsureTaskCreated()
{
if (m_task == null)
m_task = new Task<VoidTaskResult>();
}
/// <summary>Gets the <see cref="System.Threading.Tasks.Task"/> for this builder.</summary>
/// <returns>The <see cref="System.Threading.Tasks.Task"/> representing the builder's asynchronous operation.</returns>
/// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception>
public Task Task
{
get
{
return m_task ?? (m_task = new Task<VoidTaskResult>());
}
}
/// <summary>
/// Completes the <see cref="System.Threading.Tasks.Task"/> in the
/// <see cref="System.Threading.Tasks.TaskStatus">RanToCompletion</see> state.
/// </summary>
/// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception>
/// <exception cref="System.InvalidOperationException">The task has already completed.</exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public void SetResult()
{
var task = m_task;
if (task == null)
m_task = s_cachedCompleted;
else
{
if (DebuggerSupport.LoggingOn)
DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, task, AsyncStatus.Completed);
DebuggerSupport.RemoveFromActiveTasks(task);
if (!task.TrySetResult(default(VoidTaskResult)))
throw new InvalidOperationException(SR.TaskT_TransitionToFinal_AlreadyCompleted);
}
}
/// <summary>
/// Completes the <see cref="System.Threading.Tasks.Task"/> in the
/// <see cref="System.Threading.Tasks.TaskStatus">Faulted</see> state with the specified exception.
/// </summary>
/// <param name="exception">The <see cref="System.Exception"/> to use to fault the task.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception>
/// <exception cref="System.InvalidOperationException">The task has already completed.</exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public void SetException(Exception exception) { SetException(this.Task, exception); }
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void SetException(Task task, Exception exception)
{
if (exception == null) throw new ArgumentNullException("exception");
Contract.EndContractBlock();
// If the exception represents cancellation, cancel the task. Otherwise, fault the task.
var oce = exception as OperationCanceledException;
bool successfullySet = oce != null ?
task.TrySetCanceled(oce.CancellationToken, oce) :
task.TrySetException(exception);
// Unlike with TaskCompletionSource, we do not need to spin here until m_task is completed,
// since AsyncTaskMethodBuilder.SetException should not be immediately followed by any code
// that depends on the task having completely completed. Moreover, with correct usage,
// SetResult or SetException should only be called once, so the Try* methods should always
// return true, so no spinning would be necessary anyway (the spinning in TCS is only relevant
// if another thread won the race to complete the task).
if (!successfullySet)
{
throw new InvalidOperationException(SR.TaskT_TransitionToFinal_AlreadyCompleted);
}
}
/// <summary>
/// Called by the debugger to request notification when the first wait operation
/// (await, Wait, Result, etc.) on this builder's task completes.
/// </summary>
/// <param name="enabled">
/// true to enable notification; false to disable a previously set notification.
/// </param>
internal void SetNotificationForWaitCompletion(bool enabled)
{
// Get the task (forcing initialization if not already initialized), and set debug notification
Task.SetNotificationForWaitCompletion(enabled);
}
/// <summary>
/// Gets an object that may be used to uniquely identify this builder to the debugger.
/// </summary>
/// <remarks>
/// This property lazily instantiates the ID in a non-thread-safe manner.
/// It must only be used by the debugger, and only in a single-threaded manner
/// when no other threads are in the middle of accessing this property or this.Task.
/// </remarks>
private object ObjectIdForDebugger { get { return this.Task; } }
}
/// <summary>
/// Provides a builder for asynchronous methods that return <see cref="System.Threading.Tasks.Task{TResult}"/>.
/// This type is intended for compiler use only.
/// </summary>
/// <remarks>
/// AsyncTaskMethodBuilder{TResult} is a value type, and thus it is copied by value.
/// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed,
/// or else the copies may end up building distinct Task instances.
/// </remarks>
public struct AsyncTaskMethodBuilder<TResult>
{
#if false
/// <summary>A cached task for default(TResult).</summary>
internal readonly static Task<TResult> s_defaultResultTask = AsyncTaskCache.CreateCacheableTask(default(TResult));
#endif
private Action m_moveNextAction;
// WARNING: We allow diagnostic tools to directly inspect this member (m_task).
// See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
// Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
// Get in touch with the diagnostics team if you have questions.
// WARNING: For performance reasons, the m_task field is lazily initialized.
// For correct results, the struct AsyncTaskMethodBuilder<TResult> must
// always be used from the same location/copy, at least until m_task is
// initialized. If that guarantee is broken, the field could end up being
// initialized on the wrong copy.
/// <summary>The lazily-initialized built task.</summary>
private Task<TResult> m_task; // lazily-initialized: must not be readonly
/// <summary>Initializes a new <see cref="AsyncTaskMethodBuilder"/>.</summary>
/// <returns>The initialized <see cref="AsyncTaskMethodBuilder"/>.</returns>
public static AsyncTaskMethodBuilder<TResult> Create()
{
AsyncTaskMethodBuilder<TResult> atmb = new AsyncTaskMethodBuilder<TResult>();
// On ProjectN we will eagerly initalize the task and it's Id if the debugger is attached
atmb.m_task = (Task<TResult>)atmb.GetTaskIfDebuggingEnabled();
if (atmb.m_task != null)
{
int i = atmb.m_task.Id;
}
return atmb;
}
/// <summary>Initiates the builder's execution with the associated state machine.</summary>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
AsyncMethodBuilderCore.Start(ref stateMachine); // argument validation handled by AsyncMethodBuilderCore
}
/// <summary>Associates the builder with the state machine it represents.</summary>
/// <param name="stateMachine">The heap-allocated state machine object.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception>
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
AsyncMethodBuilderCore.SetStateMachine(stateMachine, m_moveNextAction); // argument validation handled by AsyncMethodBuilderCore
}
/// <summary>
/// Schedules the specified state machine to be pushed forward when the specified awaiter completes.
/// </summary>
/// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
public void AwaitOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
{
// If this is our first await, we're not boxed yet. Set up our Task now, so it will be
// visible to both the non-boxed and boxed builders.
EnsureTaskCreated();
AsyncMethodBuilderCore.CallOnCompleted(
AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()),
ref awaiter);
}
/// <summary>
/// Schedules the specified state machine to be pushed forward when the specified awaiter completes.
/// </summary>
/// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
{
// If this is our first await, we're not boxed yet. Set up our Task now, so it will be
// visible to both the non-boxed and boxed builders.
EnsureTaskCreated();
AsyncMethodBuilderCore.CallUnsafeOnCompleted(
AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()),
ref awaiter);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void EnsureTaskCreated()
{
if (m_task == null)
m_task = new Task<TResult>();
}
/// <summary>Gets the <see cref="System.Threading.Tasks.Task{TResult}"/> for this builder.</summary>
/// <returns>The <see cref="System.Threading.Tasks.Task{TResult}"/> representing the builder's asynchronous operation.</returns>
public Task<TResult> Task
{
get
{
// Get and return the task. If there isn't one, first create one and store it.
var task = m_task;
if (task == null) { m_task = task = new Task<TResult>(); }
return task;
}
}
/// <summary>
/// Completes the <see cref="System.Threading.Tasks.Task{TResult}"/> in the
/// <see cref="System.Threading.Tasks.TaskStatus">RanToCompletion</see> state with the specified result.
/// </summary>
/// <param name="result">The result to use to complete the task.</param>
/// <exception cref="System.InvalidOperationException">The task has already completed.</exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public void SetResult(TResult result)
{
// Get the currently stored task, which will be non-null if get_Task has already been accessed.
// If there isn't one, get a task and store it.
var task = m_task;
if (task == null)
{
m_task = GetTaskForResult(result);
Contract.Assert(m_task != null, "GetTaskForResult should never return null");
}
// Slow path: complete the existing task.
else
{
if (DebuggerSupport.LoggingOn)
DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, task, AsyncStatus.Completed);
DebuggerSupport.RemoveFromActiveTasks(task);
if (!task.TrySetResult(result))
{
throw new InvalidOperationException(SR.TaskT_TransitionToFinal_AlreadyCompleted);
}
}
}
/// <summary>
/// Completes the <see cref="System.Threading.Tasks.Task{TResult}"/> in the
/// <see cref="System.Threading.Tasks.TaskStatus">Faulted</see> state with the specified exception.
/// </summary>
/// <param name="exception">The <see cref="System.Exception"/> to use to fault the task.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The task has already completed.</exception>
[MethodImpl(MethodImplOptions.NoInlining)]
public void SetException(Exception exception)
{
AsyncTaskMethodBuilder.SetException(this.Task, exception);
}
/// <summary>
/// Called by the debugger to request notification when the first wait operation
/// (await, Wait, Result, etc.) on this builder's task completes.
/// </summary>
/// <param name="enabled">
/// true to enable notification; false to disable a previously set notification.
/// </param>
/// <remarks>
/// This should only be invoked from within an asynchronous method,
/// and only by the debugger.
/// </remarks>
internal void SetNotificationForWaitCompletion(bool enabled)
{
// Get the task (forcing initialization if not already initialized), and set debug notification
this.Task.SetNotificationForWaitCompletion(enabled);
}
/// <summary>
/// Gets an object that may be used to uniquely identify this builder to the debugger.
/// </summary>
/// <remarks>
/// This property lazily instantiates the ID in a non-thread-safe manner.
/// It must only be used by the debugger, and only in a single-threaded manner
/// when no other threads are in the middle of accessing this property or this.Task.
/// </remarks>
private object ObjectIdForDebugger { get { return this.Task; } }
/// <summary>
/// Gets a task for the specified result. This will either
/// be a cached or new task, never null.
/// </summary>
/// <param name="result">The result for which we need a task.</param>
/// <returns>The completed task containing the result.</returns>
private static Task<TResult> GetTaskForResult(TResult result)
{
// Currently NUTC does not perform the optimization needed by this method. The result is that
// every call to this method results in quite a lot of work, including many allocations, which
// is the opposite of the intent. For now, let's just return a new Task each time.
// Bug 719350 tracks re-optimizing this in ProjectN.
#if false
Contract.Ensures(
EqualityComparer<TResult>.Default.Equals(result, Contract.Result<Task<TResult>>().Result),
"The returned task's Result must return the same value as the specified result value.");
// The goal of this function is to be give back a cached task if possible,
// or to otherwise give back a new task. To give back a cached task,
// we need to be able to evaluate the incoming result value, and we need
// to avoid as much overhead as possible when doing so, as this function
// is invoked as part of the return path from every async method.
// Most tasks won't be cached, and thus we need the checks for those that are
// to be as close to free as possible. This requires some trickiness given the
// lack of generic specialization in .NET.
//
// Be very careful when modifying this code. It has been tuned
// to comply with patterns recognized by both 32-bit and 64-bit JITs.
// If changes are made here, be sure to look at the generated assembly, as
// small tweaks can have big consequences for what does and doesn't get optimized away.
//
// Note that this code only ever accesses a static field when it knows it'll
// find a cached value, since static fields (even if readonly and integral types)
// require special access helpers in this NGEN'd and domain-neutral.
if (null != (object)default(TResult)) // help the JIT avoid the value type branches for ref types
{
// Special case simple value types:
// - Boolean
// - Byte, SByte
// - Char
// - Decimal
// - Int32, UInt32
// - Int64, UInt64
// - Int16, UInt16
// - IntPtr, UIntPtr
// As of .NET 4.5, the (Type)(object)result pattern used below
// is recognized and optimized by both 32-bit and 64-bit JITs.
// For Boolean, we cache all possible values.
if (typeof(TResult) == typeof(Boolean)) // only the relevant branches are kept for each value-type generic instantiation
{
Boolean value = (Boolean)(object)result;
Task<Boolean> task = value ? AsyncTaskCache.TrueTask : AsyncTaskCache.FalseTask;
return (Task<TResult>)(Task)(task);// JitHelpers.UnsafeCast<Task<TResult>>(task); // UnsafeCast avoids type check we know will succeed
}
// For Int32, we cache a range of common values, e.g. [-1,4).
else if (typeof(TResult) == typeof(Int32))
{
// Compare to constants to avoid static field access if outside of cached range.
// We compare to the upper bound first, as we're more likely to cache miss on the upper side than on the
// lower side, due to positive values being more common than negative as return values.
Int32 value = (Int32)(object)result;
if (value < AsyncTaskCache.EXCLUSIVE_INT32_MAX &&
value >= AsyncTaskCache.INCLUSIVE_INT32_MIN)
{
Task<Int32> task = AsyncTaskCache.Int32Tasks[value - AsyncTaskCache.INCLUSIVE_INT32_MIN];
return (Task<TResult>)(Task)(task);// JitHelpers.UnsafeCast<Task<TResult>>(task); // UnsafeCast avoids a type check we know will succeed
}
}
// For other known value types, we only special-case 0 / default(TResult).
else if (
(typeof(TResult) == typeof(UInt32) && default(UInt32) == (UInt32)(object)result) ||
(typeof(TResult) == typeof(Byte) && default(Byte) == (Byte)(object)result) ||
(typeof(TResult) == typeof(SByte) && default(SByte) == (SByte)(object)result) ||
(typeof(TResult) == typeof(Char) && default(Char) == (Char)(object)result) ||
(typeof(TResult) == typeof(Decimal) && default(Decimal) == (Decimal)(object)result) ||
(typeof(TResult) == typeof(Int64) && default(Int64) == (Int64)(object)result) ||
(typeof(TResult) == typeof(UInt64) && default(UInt64) == (UInt64)(object)result) ||
(typeof(TResult) == typeof(Int16) && default(Int16) == (Int16)(object)result) ||
(typeof(TResult) == typeof(UInt16) && default(UInt16) == (UInt16)(object)result) ||
(typeof(TResult) == typeof(IntPtr) && default(IntPtr) == (IntPtr)(object)result) ||
(typeof(TResult) == typeof(UIntPtr) && default(UIntPtr) == (UIntPtr)(object)result))
{
return s_defaultResultTask;
}
}
else if (result == null) // optimized away for value types
{
return s_defaultResultTask;
}
#endif
// No cached task is available. Manufacture a new one for this result.
return new Task<TResult>(result);
}
}
/// <summary>Provides a cache of closed generic tasks for async methods.</summary>
internal static class AsyncTaskCache
{
// All static members are initialized inline to ensure type is beforefieldinit
#if false
/// <summary>A cached Task{Boolean}.Result == true.</summary>
internal readonly static Task<Boolean> TrueTask = CreateCacheableTask(true);
/// <summary>A cached Task{Boolean}.Result == false.</summary>
internal readonly static Task<Boolean> FalseTask = CreateCacheableTask(false);
/// <summary>The cache of Task{Int32}.</summary>
internal readonly static Task<Int32>[] Int32Tasks = CreateInt32Tasks();
/// <summary>The minimum value, inclusive, for which we want a cached task.</summary>
internal const Int32 INCLUSIVE_INT32_MIN = -1;
/// <summary>The maximum value, exclusive, for which we want a cached task.</summary>
internal const Int32 EXCLUSIVE_INT32_MAX = 9;
/// <summary>Creates an array of cached tasks for the values in the range [INCLUSIVE_MIN,EXCLUSIVE_MAX).</summary>
private static Task<Int32>[] CreateInt32Tasks()
{
Contract.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min");
var tasks = new Task<Int32>[EXCLUSIVE_INT32_MAX - INCLUSIVE_INT32_MIN];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = CreateCacheableTask(i + INCLUSIVE_INT32_MIN);
}
return tasks;
}
#endif
/// <summary>Creates a non-disposable task.</summary>
/// <typeparam name="TResult">Specifies the result type.</typeparam>
/// <param name="result">The result for the task.</param>
/// <returns>The cacheable task.</returns>
internal static Task<TResult> CreateCacheableTask<TResult>(TResult result)
{
return new Task<TResult>(false, result, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default(CancellationToken));
}
}
internal static class AsyncMethodBuilderCore
{
/// <summary>Initiates the builder's execution with the associated state machine.</summary>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument is null (Nothing in Visual Basic).</exception>
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IAsyncStateMachine
{
// Async state machines are required not to throw, so no need for try/finally here.
ExecutionContextSwitcher ecs = default(ExecutionContextSwitcher);
ExecutionContext.EstablishCopyOnWriteScope(ref ecs);
stateMachine.MoveNext();
ecs.Undo();
}
//
// We are going to do something odd here, which may require some explaining. GetCompletionAction does quite a bit
// of work, and is generic, parameterized over the type of the state machine. Since every async method has its own
// state machine type, and they are basically all value types, we end up generating separate copies of this method
// for every state machine. This adds up to a *lot* of code for an app that has many async methods.
//
// So, to save code size, we delegate all of the work to a non-generic helper. In the non-generic method, we have
// to coerce our "ref TStateMachine" arg into both a "ref byte" and a "ref IAsyncResult."
//
// Note that this is only safe because:
//
// a) We are coercing byrefs only. These are just interior pointers; the runtime doesn't care *what* they point to.
// b) We only read from one of those pointers after we're sure it's of the right type. This prevents us from,
// say, ending up with a "heap reference" that's really a pointer to the stack.
//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Action GetCompletionAction<TStateMachine>(ref Action cachedMoveNextAction, ref TStateMachine stateMachine, Task taskIfDebuggingEnabled)
where TStateMachine : IAsyncStateMachine
{
return GetCompletionActionHelper(
ref cachedMoveNextAction,
ref Unsafe.As<TStateMachine, byte>(ref stateMachine),
EETypePtr.EETypePtrOf<TStateMachine>(),
taskIfDebuggingEnabled);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe Action GetCompletionActionHelper(
ref Action cachedMoveNextAction,
ref byte stateMachineAddress,
EETypePtr stateMachineType,
Task taskIfDebuggingEnabled)
{
// Alert a listening debugger that we can't make forward progress unless it slips threads.
// If we don't do this, and a method that uses "await foo;" is invoked through funceval,
// we could end up hooking up a callback to push forward the async method's state machine,
// the debugger would then abort the funceval after it takes too long, and then continuing
// execution could result in another callback being hooked up. At that point we have
// multiple callbacks registered to push the state machine, which could result in bad behavior.
//Debugger.NotifyOfCrossThreadDependency();
MoveNextRunner runner;
if (cachedMoveNextAction != null)
{
Debug.Assert(cachedMoveNextAction.Target is MoveNextRunner);
runner = (MoveNextRunner)cachedMoveNextAction.Target;
runner.m_executionContext = ExecutionContext.Capture();
return cachedMoveNextAction;
}
runner = new MoveNextRunner();
runner.m_executionContext = ExecutionContext.Capture();
cachedMoveNextAction = runner.CallMoveNext;
if (taskIfDebuggingEnabled != null)
{
runner.m_task = taskIfDebuggingEnabled;
if (DebuggerSupport.LoggingOn)
{
IntPtr eeType = stateMachineType.RawValue;
DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, taskIfDebuggingEnabled, "Async: " + eeType.ToString("x"), 0);
}
DebuggerSupport.AddToActiveTasks(taskIfDebuggingEnabled);
}
//
// If the state machine is a value type, we need to box it now.
//
IAsyncStateMachine boxedStateMachine;
if (stateMachineType.IsValueType)
{
object boxed = RuntimeImports.RhBox(stateMachineType, ref stateMachineAddress);
Debug.Assert(boxed is IAsyncStateMachine);
boxedStateMachine = Unsafe.As<IAsyncStateMachine>(boxed);
}
else
{
boxedStateMachine = Unsafe.As<byte, IAsyncStateMachine>(ref stateMachineAddress);
}
runner.m_stateMachine = boxedStateMachine;
#if DEBUG
//
// In debug builds, we'll go ahead and call SetStateMachine, even though all of our initialization is done.
// This way we'll keep forcing state machine implementations to keep the behavior needed by the CLR.
//
boxedStateMachine.SetStateMachine(boxedStateMachine);
#endif
// All done!
return cachedMoveNextAction;
}
private class MoveNextRunner
{
internal IAsyncStateMachine m_stateMachine;
internal ExecutionContext m_executionContext;
internal Task m_task;
internal void CallMoveNext()
{
Task task = m_task;
if (task != null)
DebuggerSupport.TraceSynchronousWorkStart(CausalityTraceLevel.Required, task, CausalitySynchronousWork.Execution);
ExecutionContext.Run(
m_executionContext,
state => Unsafe.As<IAsyncStateMachine>(state).MoveNext(),
m_stateMachine);
if (task != null)
DebuggerSupport.TraceSynchronousWorkCompletion(CausalityTraceLevel.Required, CausalitySynchronousWork.Execution);
}
}
/// <summary>Associates the builder with the state machine it represents.</summary>
/// <param name="stateMachine">The heap-allocated state machine object.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception>
internal static void SetStateMachine(IAsyncStateMachine stateMachine, Action cachedMoveNextAction)
{
//
// Unlike the CLR, we do all of our initialization of the boxed state machine in GetCompletionAction. All we
// need to do here is validate that everything's been set up correctly. Note that we don't call
// IAsyncStateMachine.SetStateMachine in retail builds of the Framework, so we don't really expect a lot of calls
// to this method.
//
if (stateMachine == null)
throw new ArgumentNullException("stateMachine");
Contract.EndContractBlock();
if (cachedMoveNextAction == null)
throw new InvalidOperationException(SR.AsyncMethodBuilder_InstanceNotInitialized);
Action unwrappedMoveNextAction = TryGetStateMachineForDebugger(cachedMoveNextAction);
if (unwrappedMoveNextAction.Target != stateMachine)
throw new InvalidOperationException(SR.AsyncMethodBuilder_InstanceNotInitialized);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void CallOnCompleted<TAwaiter>(Action continuation, ref TAwaiter awaiter)
where TAwaiter : INotifyCompletion
{
try
{
awaiter.OnCompleted(continuation);
}
catch (Exception e)
{
RuntimeAugments.ReportUnhandledException(e);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void CallUnsafeOnCompleted<TAwaiter>(Action continuation, ref TAwaiter awaiter)
where TAwaiter : ICriticalNotifyCompletion
{
try
{
awaiter.UnsafeOnCompleted(continuation);
}
catch (Exception e)
{
RuntimeAugments.ReportUnhandledException(e);
}
}
/// <summary>Throws the exception on the ThreadPool.</summary>
/// <param name="exception">The exception to propagate.</param>
/// <param name="targetContext">The target context on which to propagate the exception. Null to use the ThreadPool.</param>
internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
{
if (exception == null) throw new ArgumentNullException("exception");
Contract.EndContractBlock();
// If the user supplied a SynchronizationContext...
if (targetContext != null)
{
try
{
// Capture the exception into an ExceptionDispatchInfo so that its
// stack trace and Watson bucket info will be preserved
var edi = ExceptionDispatchInfo.Capture(exception);
// Post the throwing of the exception to that context, and return.
targetContext.Post(state => ((ExceptionDispatchInfo)state).Throw(), edi);
return;
}
catch (Exception postException)
{
// If something goes horribly wrong in the Post, we'll treat this a *both* exceptions
// going unhandled.
RuntimeAugments.ReportUnhandledException(new AggregateException(exception, postException));
}
}
RuntimeAugments.ReportUnhandledException(exception);
}
//
// This helper routine is targeted by the debugger. Its purpose is to remove any delegate wrappers introduced by the framework
// that the debugger doesn't want to see.
//
[DependencyReductionRoot]
internal static Action TryGetStateMachineForDebugger(Action action)
{
Object target = action.Target;
MoveNextRunner runner = target as MoveNextRunner;
if (runner != null)
return runner.m_stateMachine.MoveNext;
return action;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
using u16 = System.UInt16;
using u32 = System.UInt32;
using sqlite3_int64 = System.Int64;
namespace Community.CsharpSqlite
{
using sqlite3_stmt = Sqlite3.Vdbe;
public partial class Sqlite3
{
/*
** 2005 May 25
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the implementation of the sqlite3_prepare()
** interface, and routines that contribute to loading the database schema
** from disk.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** Fill the InitData structure with an error message that indicates
** that the database is corrupt.
*/
static void corruptSchema(
InitData pData, /* Initialization context */
string zObj, /* Object being parsed at the point of error */
string zExtra /* Error information */
)
{
sqlite3 db = pData.db;
if ( /* 0 == db.mallocFailed && */ ( db.flags & SQLITE_RecoveryMode ) == 0 )
{
{
if ( zObj == null )
{
zObj = "?";
#if SQLITE_OMIT_UTF16
if (ENC(db) != SQLITE_UTF8)
zObj =encnames[(ENC(db))].zName;
#endif
}
sqlite3SetString( ref pData.pzErrMsg, db,
"malformed database schema (%s)", zObj );
if ( !String.IsNullOrEmpty( zExtra ) )
{
pData.pzErrMsg = sqlite3MAppendf( db, pData.pzErrMsg
, "%s - %s", pData.pzErrMsg, zExtra );
}
}
pData.rc = //db.mallocFailed != 0 ? SQLITE_NOMEM :
SQLITE_CORRUPT_BKPT();
}
}
/*
** This is the callback routine for the code that initializes the
** database. See sqlite3Init() below for additional information.
** This routine is also called from the OP_ParseSchema opcode of the VDBE.
**
** Each callback contains the following information:
**
** argv[0] = name of thing being created
** argv[1] = root page number for table or index. 0 for trigger or view.
** argv[2] = SQL text for the CREATE statement.
**
*/
static int sqlite3InitCallback( object pInit, sqlite3_int64 argc, object p2, object NotUsed )
{
string[] argv = (string[])p2;
InitData pData = (InitData)pInit;
sqlite3 db = pData.db;
int iDb = pData.iDb;
Debug.Assert( argc == 3 );
UNUSED_PARAMETER2( NotUsed, argc );
Debug.Assert( sqlite3_mutex_held( db.mutex ) );
DbClearProperty( db, iDb, DB_Empty );
//if ( db.mallocFailed != 0 )
//{
// corruptSchema( pData, argv[0], "" );
// return 1;
//}
Debug.Assert( iDb >= 0 && iDb < db.nDb );
if ( argv == null )
return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
if ( argv[1] == null )
{
corruptSchema( pData, argv[0], "" );
}
else if ( !String.IsNullOrEmpty( argv[2] ) )
{
/* Call the parser to process a CREATE TABLE, INDEX or VIEW.
** But because db.init.busy is set to 1, no VDBE code is generated
** or executed. All the parser does is build the internal data
** structures that describe the table, index, or view.
*/
int rc;
sqlite3_stmt pStmt = null;
#if !NDEBUG || SQLITE_COVERAGE_TEST
//TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
int rcp;
#endif
Debug.Assert( db.init.busy != 0 );
db.init.iDb = iDb;
db.init.newTnum = sqlite3Atoi( argv[1] );
db.init.orphanTrigger = 0;
//TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
#if !NDEBUG || SQLITE_COVERAGE_TEST
rcp = sqlite3_prepare( db, argv[2], -1, ref pStmt, 0 );
#else
sqlite3_prepare(db, argv[2], -1, ref pStmt, 0);
#endif
rc = db.errCode;
#if !NDEBUG || SQLITE_COVERAGE_TEST
Debug.Assert( ( rc & 0xFF ) == ( rcp & 0xFF ) );
#endif
db.init.iDb = 0;
if ( SQLITE_OK != rc )
{
if ( db.init.orphanTrigger != 0 )
{
Debug.Assert( iDb == 1 );
}
else
{
pData.rc = rc;
//if ( rc == SQLITE_NOMEM )
//{
// // db.mallocFailed = 1;
//}
//else
if ( rc != SQLITE_INTERRUPT && ( rc & 0xFF ) != SQLITE_LOCKED )
{
corruptSchema( pData, argv[0], sqlite3_errmsg( db ) );
}
}
}
sqlite3_finalize( pStmt );
}
else if ( argv[0] == null || argv[0] == "" )
{
corruptSchema( pData, null, null );
}
else
{
/* If the SQL column is blank it means this is an index that
** was created to be the PRIMARY KEY or to fulfill a UNIQUE
** constraint for a CREATE TABLE. The index should have already
** been created when we processed the CREATE TABLE. All we have
** to do here is record the root page number for that index.
*/
Index pIndex;
pIndex = sqlite3FindIndex( db, argv[0], db.aDb[iDb].zName );
if ( pIndex == null )
{
/* This can occur if there exists an index on a TEMP table which
** has the same name as another index on a permanent index. Since
** the permanent table is hidden by the TEMP table, we can also
** safely ignore the index on the permanent table.
*/
/* Do Nothing */
;
}
else if ( sqlite3GetInt32( argv[1], ref pIndex.tnum ) == false )
{
corruptSchema( pData, argv[0], "invalid rootpage" );
}
}
return 0;
}
/*
** Attempt to read the database schema and initialize internal
** data structures for a single database file. The index of the
** database file is given by iDb. iDb==0 is used for the main
** database. iDb==1 should never be used. iDb>=2 is used for
** auxiliary databases. Return one of the SQLITE_ error codes to
** indicate success or failure.
*/
static int sqlite3InitOne( sqlite3 db, int iDb, ref string pzErrMsg )
{
int rc;
int i;
int size;
Table pTab;
Db pDb;
string[] azArg = new string[4];
u32[] meta = new u32[5];
InitData initData = new InitData();
string zMasterSchema;
string zMasterName;
int openedTransaction = 0;
/*
** The master database table has a structure like this
*/
string master_schema =
"CREATE TABLE sqlite_master(\n" +
" type text,\n" +
" name text,\n" +
" tbl_name text,\n" +
" rootpage integer,\n" +
" sql text\n" +
")"
;
#if !SQLITE_OMIT_TEMPDB
string temp_master_schema =
"CREATE TEMP TABLE sqlite_temp_master(\n" +
" type text,\n" +
" name text,\n" +
" tbl_name text,\n" +
" rootpage integer,\n" +
" sql text\n" +
")"
;
#else
//#define temp_master_schema 0
#endif
Debug.Assert( iDb >= 0 && iDb < db.nDb );
Debug.Assert( db.aDb[iDb].pSchema != null );
Debug.Assert( sqlite3_mutex_held( db.mutex ) );
Debug.Assert( iDb == 1 || sqlite3BtreeHoldsMutex( db.aDb[iDb].pBt ) );
/* zMasterSchema and zInitScript are set to point at the master schema
** and initialisation script appropriate for the database being
** initialised. zMasterName is the name of the master table.
*/
if ( OMIT_TEMPDB == 0 && iDb == 1 )
{
zMasterSchema = temp_master_schema;
}
else
{
zMasterSchema = master_schema;
}
zMasterName = SCHEMA_TABLE( iDb );
/* Construct the schema tables. */
azArg[0] = zMasterName;
azArg[1] = "1";
azArg[2] = zMasterSchema;
azArg[3] = "";
initData.db = db;
initData.iDb = iDb;
initData.rc = SQLITE_OK;
initData.pzErrMsg = pzErrMsg;
sqlite3InitCallback( initData, 3, azArg, null );
if ( initData.rc != 0 )
{
rc = initData.rc;
goto error_out;
}
pTab = sqlite3FindTable( db, zMasterName, db.aDb[iDb].zName );
if ( ALWAYS( pTab ) )
{
pTab.tabFlags |= TF_Readonly;
}
/* Create a cursor to hold the database open
*/
pDb = db.aDb[iDb];
if ( pDb.pBt == null )
{
if ( OMIT_TEMPDB == 0 && ALWAYS( iDb == 1 ) )
{
DbSetProperty( db, 1, DB_SchemaLoaded );
}
return SQLITE_OK;
}
/* If there is not already a read-only (or read-write) transaction opened
** on the b-tree database, open one now. If a transaction is opened, it
** will be closed before this function returns. */
sqlite3BtreeEnter( pDb.pBt );
if ( !sqlite3BtreeIsInReadTrans( pDb.pBt ) )
{
rc = sqlite3BtreeBeginTrans( pDb.pBt, 0 );
if ( rc != SQLITE_OK )
{
#if SQLITE_OMIT_WAL
if (pDb.pBt.pBt.pSchema.file_format == 2)
sqlite3SetString( ref pzErrMsg, db, "%s (wal format detected)", sqlite3ErrStr( rc ) );
else
sqlite3SetString( ref pzErrMsg, db, "%s", sqlite3ErrStr( rc ) );
#else
sqlite3SetString( ref pzErrMsg, db, "%s", sqlite3ErrStr( rc ) );
#endif
goto initone_error_out;
}
openedTransaction = 1;
}
/* Get the database meta information.
**
** Meta values are as follows:
** meta[0] Schema cookie. Changes with each schema change.
** meta[1] File format of schema layer.
** meta[2] Size of the page cache.
** meta[3] Largest rootpage (auto/incr_vacuum mode)
** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
** meta[5] User version
** meta[6] Incremental vacuum mode
** meta[7] unused
** meta[8] unused
** meta[9] unused
**
** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
** the possible values of meta[BTREE_TEXT_ENCODING-1].
*/
for ( i = 0; i < ArraySize( meta ); i++ )
{
sqlite3BtreeGetMeta( pDb.pBt, i + 1, ref meta[i] );
}
pDb.pSchema.schema_cookie = (int)meta[BTREE_SCHEMA_VERSION - 1];
/* If opening a non-empty database, check the text encoding. For the
** main database, set sqlite3.enc to the encoding of the main database.
** For an attached db, it is an error if the encoding is not the same
** as sqlite3.enc.
*/
if ( meta[BTREE_TEXT_ENCODING - 1] != 0 )
{ /* text encoding */
if ( iDb == 0 )
{
u8 encoding;
/* If opening the main database, set ENC(db). */
encoding = (u8)( meta[BTREE_TEXT_ENCODING - 1] & 3 );
if ( encoding == 0 )
encoding = SQLITE_UTF8;
db.aDb[0].pSchema.enc = encoding; //ENC( db ) = encoding;
db.pDfltColl = sqlite3FindCollSeq( db, SQLITE_UTF8, "BINARY", 0 );
}
else
{
/* If opening an attached database, the encoding much match ENC(db) */
if ( meta[BTREE_TEXT_ENCODING - 1] != ENC( db ) )
{
sqlite3SetString( ref pzErrMsg, db, "attached databases must use the same" +
" text encoding as main database" );
rc = SQLITE_ERROR;
goto initone_error_out;
}
}
}
else
{
DbSetProperty( db, iDb, DB_Empty );
}
pDb.pSchema.enc = ENC( db );
if ( pDb.pSchema.cache_size == 0 )
{
size = sqlite3AbsInt32((int)meta[BTREE_DEFAULT_CACHE_SIZE - 1]);
if ( size == 0 )
{
size = SQLITE_DEFAULT_CACHE_SIZE;
}
pDb.pSchema.cache_size = size;
sqlite3BtreeSetCacheSize( pDb.pBt, pDb.pSchema.cache_size );
}
/*
** file_format==1 Version 3.0.0.
** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
*/
pDb.pSchema.file_format = (u8)meta[BTREE_FILE_FORMAT - 1];
if ( pDb.pSchema.file_format == 0 )
{
pDb.pSchema.file_format = 1;
}
if ( pDb.pSchema.file_format > SQLITE_MAX_FILE_FORMAT )
{
sqlite3SetString( ref pzErrMsg, db, "unsupported file format" );
rc = SQLITE_ERROR;
goto initone_error_out;
}
/* Ticket #2804: When we open a database in the newer file format,
** clear the legacy_file_format pragma flag so that a VACUUM will
** not downgrade the database and thus invalidate any descending
** indices that the user might have created.
*/
if ( iDb == 0 && meta[BTREE_FILE_FORMAT - 1] >= 4 )
{
db.flags &= ~SQLITE_LegacyFileFmt;
}
/* Read the schema information out of the schema tables
*/
Debug.Assert( db.init.busy != 0 );
{
string zSql;
zSql = sqlite3MPrintf( db,
"SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
db.aDb[iDb].zName, zMasterName );
#if NO_SQLITE_OMIT_AUTHORIZATION //#if !SQLITE_OMIT_AUTHORIZATION
{
int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
xAuth = db.xAuth;
db.xAuth = 0;
#endif
rc = sqlite3_exec( db, zSql, (dxCallback)sqlite3InitCallback, initData, 0 );
pzErrMsg = initData.pzErrMsg;
#if NO_SQLITE_OMIT_AUTHORIZATION //#if !SQLITE_OMIT_AUTHORIZATION
db.xAuth = xAuth;
}
#endif
if ( rc == SQLITE_OK )
rc = initData.rc;
sqlite3DbFree( db, ref zSql );
#if !SQLITE_OMIT_ANALYZE
if ( rc == SQLITE_OK )
{
sqlite3AnalysisLoad( db, iDb );
}
#endif
}
//if ( db.mallocFailed != 0 )
//{
// rc = SQLITE_NOMEM;
// sqlite3ResetInternalSchema( db, -1 );
//}
if ( rc == SQLITE_OK || ( db.flags & SQLITE_RecoveryMode ) != 0 )
{
/* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
** the schema loaded, even if errors occurred. In this situation the
** current sqlite3_prepare() operation will fail, but the following one
** will attempt to compile the supplied statement against whatever subset
** of the schema was loaded before the error occurred. The primary
** purpose of this is to allow access to the sqlite_master table
** even when its contents have been corrupted.
*/
DbSetProperty( db, iDb, DB_SchemaLoaded );
rc = SQLITE_OK;
}
/* Jump here for an error that occurs after successfully allocating
** curMain and calling sqlite3BtreeEnter(). For an error that occurs
** before that point, jump to error_out.
*/
initone_error_out:
if ( openedTransaction != 0 )
{
sqlite3BtreeCommit( pDb.pBt );
}
sqlite3BtreeLeave( pDb.pBt );
error_out:
if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM )
{
// db.mallocFailed = 1;
}
return rc;
}
/*
** Initialize all database files - the main database file, the file
** used to store temporary tables, and any additional database files
** created using ATTACH statements. Return a success code. If an
** error occurs, write an error message into pzErrMsg.
**
** After a database is initialized, the DB_SchemaLoaded bit is set
** bit is set in the flags field of the Db structure. If the database
** file was of zero-length, then the DB_Empty flag is also set.
*/
static int sqlite3Init( sqlite3 db, ref string pzErrMsg )
{
int i, rc;
bool commit_internal = !( ( db.flags & SQLITE_InternChanges ) != 0 );
Debug.Assert( sqlite3_mutex_held( db.mutex ) );
rc = SQLITE_OK;
db.init.busy = 1;
for ( i = 0; rc == SQLITE_OK && i < db.nDb; i++ )
{
if ( DbHasProperty( db, i, DB_SchemaLoaded ) || i == 1 )
continue;
rc = sqlite3InitOne( db, i, ref pzErrMsg );
if ( rc != 0 )
{
sqlite3ResetInternalSchema( db, i );
}
}
/* Once all the other databases have been initialised, load the schema
** for the TEMP database. This is loaded last, as the TEMP database
** schema may contain references to objects in other databases.
*/
#if !SQLITE_OMIT_TEMPDB
if ( rc == SQLITE_OK && ALWAYS( db.nDb > 1 )
&& !DbHasProperty( db, 1, DB_SchemaLoaded ) )
{
rc = sqlite3InitOne( db, 1, ref pzErrMsg );
if ( rc != 0 )
{
sqlite3ResetInternalSchema( db, 1 );
}
}
#endif
db.init.busy = 0;
if ( rc == SQLITE_OK && commit_internal )
{
sqlite3CommitInternalChanges( db );
}
return rc;
}
/*
** This routine is a no-op if the database schema is already initialised.
** Otherwise, the schema is loaded. An error code is returned.
*/
static int sqlite3ReadSchema( Parse pParse )
{
int rc = SQLITE_OK;
sqlite3 db = pParse.db;
Debug.Assert( sqlite3_mutex_held( db.mutex ) );
if ( 0 == db.init.busy )
{
rc = sqlite3Init( db, ref pParse.zErrMsg );
}
if ( rc != SQLITE_OK )
{
pParse.rc = rc;
pParse.nErr++;
}
return rc;
}
/*
** Check schema cookies in all databases. If any cookie is out
** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
** make no changes to pParse->rc.
*/
static void schemaIsValid( Parse pParse )
{
sqlite3 db = pParse.db;
int iDb;
int rc;
u32 cookie = 0;
Debug.Assert( pParse.checkSchema != 0 );
Debug.Assert( sqlite3_mutex_held( db.mutex ) );
for ( iDb = 0; iDb < db.nDb; iDb++ )
{
int openedTransaction = 0; /* True if a transaction is opened */
Btree pBt = db.aDb[iDb].pBt; /* Btree database to read cookie from */
if ( pBt == null )
continue;
/* If there is not already a read-only (or read-write) transaction opened
** on the b-tree database, open one now. If a transaction is opened, it
** will be closed immediately after reading the meta-value. */
if ( !sqlite3BtreeIsInReadTrans( pBt ) )
{
rc = sqlite3BtreeBeginTrans( pBt, 0 );
//if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM )
//{
// db.mallocFailed = 1;
//}
if ( rc != SQLITE_OK )
return;
openedTransaction = 1;
}
/* Read the schema cookie from the database. If it does not match the
** value stored as part of the in-memory schema representation,
** set Parse.rc to SQLITE_SCHEMA. */
sqlite3BtreeGetMeta( pBt, BTREE_SCHEMA_VERSION, ref cookie );
Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
if ( cookie != db.aDb[iDb].pSchema.schema_cookie )
{
sqlite3ResetInternalSchema( db, iDb );
pParse.rc = SQLITE_SCHEMA;
}
/* Close the transaction, if one was opened. */
if ( openedTransaction != 0 )
{
sqlite3BtreeCommit( pBt );
}
}
}
/*
** Convert a schema pointer into the iDb index that indicates
** which database file in db.aDb[] the schema refers to.
**
** If the same database is attached more than once, the first
** attached database is returned.
*/
static int sqlite3SchemaToIndex( sqlite3 db, Schema pSchema )
{
int i = -1000000;
/* If pSchema is NULL, then return -1000000. This happens when code in
** expr.c is trying to resolve a reference to a transient table (i.e. one
** created by a sub-select). In this case the return value of this
** function should never be used.
**
** We return -1000000 instead of the more usual -1 simply because using
** -1000000 as the incorrect index into db->aDb[] is much
** more likely to cause a segfault than -1 (of course there are assert()
** statements too, but it never hurts to play the odds).
*/
Debug.Assert( sqlite3_mutex_held( db.mutex ) );
if ( pSchema != null )
{
for ( i = 0; ALWAYS( i < db.nDb ); i++ )
{
if ( db.aDb[i].pSchema == pSchema )
{
break;
}
}
Debug.Assert( i >= 0 && i < db.nDb );
}
return i;
}
/*
** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
*/
static int sqlite3Prepare(
sqlite3 db, /* Database handle. */
string zSql, /* UTF-8 encoded SQL statement. */
int nBytes, /* Length of zSql in bytes. */
int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
Vdbe pReprepare, /* VM being reprepared */
ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */
ref string pzTail /* OUT: End of parsed string */
)
{
Parse pParse; /* Parsing context */
string zErrMsg = ""; /* Error message */
int rc = SQLITE_OK; /* Result code */
int i; /* Loop counter */
ppStmt = null;
pzTail = null;
/* Allocate the parsing context */
pParse = new Parse();//sqlite3StackAllocZero(db, sizeof(*pParse));
//if ( pParse == null )
//{
// rc = SQLITE_NOMEM;
// goto end_prepare;
//}
pParse.pReprepare = pReprepare;
pParse.sLastToken.z = "";
// assert( ppStmt && *ppStmt==0 );
//Debug.Assert( 0 == db.mallocFailed );
Debug.Assert( sqlite3_mutex_held( db.mutex ) );
/* Check to verify that it is possible to get a read lock on all
** database schemas. The inability to get a read lock indicates that
** some other database connection is holding a write-lock, which in
** turn means that the other connection has made uncommitted changes
** to the schema.
**
** Were we to proceed and prepare the statement against the uncommitted
** schema changes and if those schema changes are subsequently rolled
** back and different changes are made in their place, then when this
** prepared statement goes to run the schema cookie would fail to detect
** the schema change. Disaster would follow.
**
** This thread is currently holding mutexes on all Btrees (because
** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
** is not possible for another thread to start a new schema change
** while this routine is running. Hence, we do not need to hold
** locks on the schema, we just need to make sure nobody else is
** holding them.
**
** Note that setting READ_UNCOMMITTED overrides most lock detection,
** but it does *not* override schema lock detection, so this all still
** works even if READ_UNCOMMITTED is set.
*/
for ( i = 0; i < db.nDb; i++ )
{
Btree pBt = db.aDb[i].pBt;
if ( pBt != null )
{
Debug.Assert( sqlite3BtreeHoldsMutex( pBt ) );
rc = sqlite3BtreeSchemaLocked( pBt );
if ( rc != 0 )
{
string zDb = db.aDb[i].zName;
sqlite3Error( db, rc, "database schema is locked: %s", zDb );
testcase( db.flags & SQLITE_ReadUncommitted );
goto end_prepare;
}
}
}
sqlite3VtabUnlockList( db );
pParse.db = db;
pParse.nQueryLoop = (double)1;
if ( nBytes >= 0 && ( nBytes == 0 || zSql[nBytes - 1] != 0 ) )
{
string zSqlCopy;
int mxLen = db.aLimit[SQLITE_LIMIT_SQL_LENGTH];
testcase( nBytes == mxLen );
testcase( nBytes == mxLen + 1 );
if ( nBytes > mxLen )
{
sqlite3Error( db, SQLITE_TOOBIG, "statement too long" );
rc = sqlite3ApiExit( db, SQLITE_TOOBIG );
goto end_prepare;
}
zSqlCopy = zSql.Substring( 0, nBytes );// sqlite3DbStrNDup(db, zSql, nBytes);
if ( zSqlCopy != null )
{
sqlite3RunParser( pParse, zSqlCopy, ref zErrMsg );
sqlite3DbFree( db, ref zSqlCopy );
//pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
}
else
{
//pParse->zTail = &zSql[nBytes];
}
}
else
{
sqlite3RunParser( pParse, zSql, ref zErrMsg );
}
Debug.Assert( 1 == (int)pParse.nQueryLoop );
//if ( db.mallocFailed != 0 )
//{
// pParse.rc = SQLITE_NOMEM;
//}
if ( pParse.rc == SQLITE_DONE )
pParse.rc = SQLITE_OK;
if ( pParse.checkSchema != 0 )
{
schemaIsValid( pParse );
}
//if ( db.mallocFailed != 0 )
//{
// pParse.rc = SQLITE_NOMEM;
//}
//if (pzTail != null)
{
pzTail = pParse.zTail == null ? "" : pParse.zTail.ToString();
}
rc = pParse.rc;
#if !SQLITE_OMIT_EXPLAIN
if ( rc == SQLITE_OK && pParse.pVdbe != null && pParse.explain != 0 )
{
string[] azColName = new string[] {
"addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
"selectid", "order", "from", "detail"
};
int iFirst, mx;
if ( pParse.explain == 2 )
{
sqlite3VdbeSetNumCols( pParse.pVdbe, 4 );
iFirst = 8;
mx = 12;
}
else
{
sqlite3VdbeSetNumCols( pParse.pVdbe, 8 );
iFirst = 0;
mx = 8;
}
for ( i = iFirst; i < mx; i++ )
{
sqlite3VdbeSetColName( pParse.pVdbe, i - iFirst, COLNAME_NAME,
azColName[i], SQLITE_STATIC );
}
}
#endif
Debug.Assert( db.init.busy == 0 || saveSqlFlag == 0 );
if ( db.init.busy == 0 )
{
Vdbe pVdbe = pParse.pVdbe;
sqlite3VdbeSetSql( pVdbe, zSql, (int)( zSql.Length - ( pParse.zTail == null ? 0 : pParse.zTail.Length ) ), saveSqlFlag );
}
if ( pParse.pVdbe != null && ( rc != SQLITE_OK /*|| db.mallocFailed != 0 */ ) )
{
sqlite3VdbeFinalize( ref pParse.pVdbe );
//Debug.Assert( ppStmt == null );
}
else
{
ppStmt = pParse.pVdbe;
}
if ( zErrMsg != "" )
{
sqlite3Error( db, rc, "%s", zErrMsg );
sqlite3DbFree( db, ref zErrMsg );
}
else
{
sqlite3Error( db, rc, 0 );
}
/* Delete any TriggerPrg structures allocated while parsing this statement. */
while ( pParse.pTriggerPrg != null )
{
TriggerPrg pT = pParse.pTriggerPrg;
pParse.pTriggerPrg = pT.pNext;
sqlite3DbFree( db, ref pT );
}
end_prepare:
//sqlite3StackFree( db, pParse );
rc = sqlite3ApiExit( db, rc );
Debug.Assert( ( rc & db.errMask ) == rc );
return rc;
}
//C# Version w/o End of Parsed String
static int sqlite3LockAndPrepare(
sqlite3 db, /* Database handle. */
string zSql, /* UTF-8 encoded SQL statement. */
int nBytes, /* Length of zSql in bytes. */
int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
Vdbe pOld, /* VM being reprepared */
ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */
int dummy /* OUT: End of parsed string */
)
{
string sOut = null;
return sqlite3LockAndPrepare( db, zSql, nBytes, saveSqlFlag, pOld, ref ppStmt, ref sOut );
}
static int sqlite3LockAndPrepare(
sqlite3 db, /* Database handle. */
string zSql, /* UTF-8 encoded SQL statement. */
int nBytes, /* Length of zSql in bytes. */
int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
Vdbe pOld, /* VM being reprepared */
ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */
ref string pzTail /* OUT: End of parsed string */
)
{
int rc;
// assert( ppStmt!=0 );
if ( !sqlite3SafetyCheckOk( db ) )
{
ppStmt = null;
pzTail = null;
return SQLITE_MISUSE_BKPT();
}
sqlite3_mutex_enter( db.mutex );
sqlite3BtreeEnterAll( db );
rc = sqlite3Prepare( db, zSql, nBytes, saveSqlFlag, pOld, ref ppStmt, ref pzTail );
if ( rc == SQLITE_SCHEMA )
{
sqlite3_finalize( ppStmt );
rc = sqlite3Prepare( db, zSql, nBytes, saveSqlFlag, pOld, ref ppStmt, ref pzTail );
}
sqlite3BtreeLeaveAll( db );
sqlite3_mutex_leave( db.mutex );
return rc;
}
/*
** Rerun the compilation of a statement after a schema change.
**
** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
** if the statement cannot be recompiled because another connection has
** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
** occurs, return SQLITE_SCHEMA.
*/
static int sqlite3Reprepare( Vdbe p )
{
int rc;
sqlite3_stmt pNew = new sqlite3_stmt();
string zSql;
sqlite3 db;
Debug.Assert( sqlite3_mutex_held( sqlite3VdbeDb( p ).mutex ) );
zSql = sqlite3_sql( (sqlite3_stmt)p );
Debug.Assert( zSql != null ); /* Reprepare only called for prepare_v2() statements */
db = sqlite3VdbeDb( p );
Debug.Assert( sqlite3_mutex_held( db.mutex ) );
rc = sqlite3LockAndPrepare( db, zSql, -1, 0, p, ref pNew, 0 );
if ( rc != 0 )
{
if ( rc == SQLITE_NOMEM )
{
// db.mallocFailed = 1;
}
Debug.Assert( pNew == null );
return rc;
}
else
{
Debug.Assert( pNew != null );
}
sqlite3VdbeSwap( (Vdbe)pNew, p );
sqlite3TransferBindings( pNew, (sqlite3_stmt)p );
sqlite3VdbeResetStepResult( (Vdbe)pNew );
sqlite3VdbeFinalize( ref pNew );
return SQLITE_OK;
}
//C# Overload for ignore error out
static public int sqlite3_prepare(
sqlite3 db, /* Database handle. */
string zSql, /* UTF-8 encoded SQL statement. */
int nBytes, /* Length of zSql in bytes. */
ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */
int dummy /* OUT: End of parsed string */
)
{
string sOut = null;
return sqlite3_prepare( db, zSql, nBytes, ref ppStmt, ref sOut );
}
/*
** Two versions of the official API. Legacy and new use. In the legacy
** version, the original SQL text is not saved in the prepared statement
** and so if a schema change occurs, SQLITE_SCHEMA is returned by
** sqlite3_step(). In the new version, the original SQL text is retained
** and the statement is automatically recompiled if an schema change
** occurs.
*/
static public int sqlite3_prepare(
sqlite3 db, /* Database handle. */
string zSql, /* UTF-8 encoded SQL statement. */
int nBytes, /* Length of zSql in bytes. */
ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */
ref string pzTail /* OUT: End of parsed string */
)
{
int rc;
rc = sqlite3LockAndPrepare( db, zSql, nBytes, 0, null, ref ppStmt, ref pzTail );
Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */
return rc;
}
public static int sqlite3_prepare_v2(
sqlite3 db, /* Database handle. */
string zSql, /* UTF-8 encoded SQL statement. */
int nBytes, /* Length of zSql in bytes. */
ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */
int dummy /* ( No string passed) */
)
{
string pzTail = null;
int rc;
rc = sqlite3LockAndPrepare( db, zSql, nBytes, 1, null, ref ppStmt, ref pzTail );
Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */
return rc;
}
public static int sqlite3_prepare_v2(
sqlite3 db, /* Database handle. */
string zSql, /* UTF-8 encoded SQL statement. */
int nBytes, /* Length of zSql in bytes. */
ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */
ref string pzTail /* OUT: End of parsed string */
)
{
int rc;
rc = sqlite3LockAndPrepare( db, zSql, nBytes, 1, null, ref ppStmt, ref pzTail );
Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */
return rc;
}
#if NO_SQLITE_OMIT_UTF16 //#if !SQLITE_OMIT_UTF16
/*
** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
*/
static int sqlite3Prepare16(
sqlite3 db, /* Database handle. */
string zSql, /* UTF-15 encoded SQL statement. */
int nBytes, /* Length of zSql in bytes. */
bool saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
out sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */
out string pzTail /* OUT: End of parsed string */
){
/* This function currently works by first transforming the UTF-16
** encoded string to UTF-8, then invoking sqlite3_prepare(). The
** tricky bit is figuring out the pointer to return in pzTail.
*/
string zSql8;
string zTail8 = "";
int rc = SQLITE_OK;
assert( ppStmt );
*ppStmt = 0;
if( !sqlite3SafetyCheckOk(db) ){
return SQLITE_MISUSE_BKPT;
}
sqlite3_mutex_enter(db.mutex);
zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
if( zSql8 !=""){
rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, null, ref ppStmt, ref zTail8);
}
if( zTail8 !="" && pzTail !=""){
/* If sqlite3_prepare returns a tail pointer, we calculate the
** equivalent pointer into the UTF-16 string by counting the unicode
** characters between zSql8 and zTail8, and then returning a pointer
** the same number of characters into the UTF-16 string.
*/
Debugger.Break (); // TODO --
// int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
// pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
}
sqlite3DbFree(db,ref zSql8);
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db.mutex);
return rc;
}
/*
** Two versions of the official API. Legacy and new use. In the legacy
** version, the original SQL text is not saved in the prepared statement
** and so if a schema change occurs, SQLITE_SCHEMA is returned by
** sqlite3_step(). In the new version, the original SQL text is retained
** and the statement is automatically recompiled if an schema change
** occurs.
*/
public static int sqlite3_prepare16(
sqlite3 db, /* Database handle. */
string zSql, /* UTF-16 encoded SQL statement. */
int nBytes, /* Length of zSql in bytes. */
out sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */
out string pzTail /* OUT: End of parsed string */
){
int rc;
rc = sqlite3Prepare16(db,zSql,nBytes,false,ref ppStmt,ref pzTail);
Debug.Assert( rc==SQLITE_OK || ppStmt==null || ppStmt==null ); /* VERIFY: F13021 */
return rc;
}
public static int sqlite3_prepare16_v2(
sqlite3 db, /* Database handle. */
string zSql, /* UTF-16 encoded SQL statement. */
int nBytes, /* Length of zSql in bytes. */
out sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */
out string pzTail /* OUT: End of parsed string */
)
{
int rc;
rc = sqlite3Prepare16(db,zSql,nBytes,true,ref ppStmt,ref pzTail);
Debug.Assert( rc==SQLITE_OK || ppStmt==null || ppStmt==null ); /* VERIFY: F13021 */
return rc;
}
#endif // * SQLITE_OMIT_UTF16 */
}
}
| |
using System;
using System.Collections.Generic;
#if NETFX_CORE
using System.Collections.Concurrent;
#endif
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using NServiceKit.Common.Support;
using NServiceKit.Logging;
using NServiceKit.Net30.Collections.Concurrent;
using NServiceKit.ServiceHost;
using NServiceKit.Text;
namespace NServiceKit.Common.Utils
{
/// <summary>Encapsulates the result of a custom http.</summary>
[DataContract(Namespace = "http://schemas.NServiceKit.net/types")]
public class CustomHttpResult { }
/// <summary>A reflection utilities.</summary>
public class ReflectionUtils
{
/// <summary>The log.</summary>
public static readonly ILog Log = LogManager.GetLogger(typeof(ReflectionUtils));
/// <summary>
/// Populate an object with Example data.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static object PopulateObject(object obj)
{
if (obj == null) return null;
var httpResult = obj as IHttpResult;
if (httpResult != null)
{
obj = new CustomHttpResult();
}
var type = obj.GetType();
if (type.IsArray() || type.IsValueType() || type.IsGeneric())
{
var value = CreateDefaultValue(type, new Dictionary<Type, int>(20));
return value;
}
return PopulateObjectInternal(obj, new Dictionary<Type, int>(20));
}
/// <summary>
/// Populates the object with example data.
/// </summary>
/// <param name="obj"></param>
/// <param name="recursionInfo">Tracks how deeply nested we are</param>
/// <returns></returns>
private static object PopulateObjectInternal(object obj, Dictionary<Type, int> recursionInfo)
{
if (obj == null) return null;
if (obj is string) return obj; // prevents it from dropping into the char[] Chars property. Sheesh
var type = obj.GetType();
var members = type.GetPublicMembers();
foreach (var info in members)
{
var fieldInfo = info as FieldInfo;
var propertyInfo = info as PropertyInfo;
if (fieldInfo != null || propertyInfo != null)
{
var memberType = fieldInfo != null ? fieldInfo.FieldType : propertyInfo.PropertyType;
var value = CreateDefaultValue(memberType, recursionInfo);
SetValue(fieldInfo, propertyInfo, obj, value);
}
}
return obj;
}
private static readonly Dictionary<Type, object> DefaultValueTypes
= new Dictionary<Type, object>();
/// <summary>Gets default value.</summary>
///
/// <param name="type">The type.</param>
///
/// <returns>The default value.</returns>
public static object GetDefaultValue(Type type)
{
if (!type.IsValueType()) return null;
object defaultValue;
lock (DefaultValueTypes)
{
if (!DefaultValueTypes.TryGetValue(type, out defaultValue))
{
defaultValue = Activator.CreateInstance(type);
DefaultValueTypes[type] = defaultValue;
}
}
return defaultValue;
}
private static readonly ConcurrentDictionary<string, AssignmentDefinition> AssignmentDefinitionCache
= new ConcurrentDictionary<string, AssignmentDefinition>();
/// <summary>Gets assignment definition.</summary>
///
/// <param name="toType"> Type of to.</param>
/// <param name="fromType">Type of from.</param>
///
/// <returns>The assignment definition.</returns>
public static AssignmentDefinition GetAssignmentDefinition(Type toType, Type fromType)
{
var cacheKey = toType.FullName + "<" + fromType.FullName;
return AssignmentDefinitionCache.GetOrAdd(cacheKey, delegate {
var definition = new AssignmentDefinition {
ToType = toType,
FromType = fromType,
};
var readMap = GetMembers(fromType, isReadable: true);
var writeMap = GetMembers(toType, isReadable: false);
foreach (var assignmentMember in readMap)
{
AssignmentMember writeMember;
if (writeMap.TryGetValue(assignmentMember.Key, out writeMember))
{
definition.AddMatch(assignmentMember.Key, assignmentMember.Value, writeMember);
}
}
return definition;
});
}
private static Dictionary<string, AssignmentMember> GetMembers(Type type, bool isReadable)
{
var map = new Dictionary<string, AssignmentMember>();
var members = type.GetAllPublicMembers();
foreach (var info in members)
{
if (info.DeclaringType == typeof(object)) continue;
var propertyInfo = info as PropertyInfo;
if (propertyInfo != null)
{
if (isReadable)
{
if (propertyInfo.CanRead)
{
map[info.Name] = new AssignmentMember(propertyInfo.PropertyType, propertyInfo);
continue;
}
}
else
{
if (propertyInfo.CanWrite && propertyInfo.GetSetMethod() != null)
{
map[info.Name] = new AssignmentMember(propertyInfo.PropertyType, propertyInfo);
continue;
}
}
}
var fieldInfo = info as FieldInfo;
if (fieldInfo != null)
{
map[info.Name] = new AssignmentMember(fieldInfo.FieldType, fieldInfo);
continue;
}
var methodInfo = info as MethodInfo;
if (methodInfo != null)
{
var parameterInfos = methodInfo.GetParameters();
if (isReadable)
{
if (parameterInfos.Length == 0)
{
var name = info.Name.StartsWith("get_") ? info.Name.Substring(4) : info.Name;
if (!map.ContainsKey(name))
{
map[name] = new AssignmentMember(methodInfo.ReturnType, methodInfo);
continue;
}
}
}
else
{
if (parameterInfos.Length == 1 && methodInfo.ReturnType == typeof(void))
{
var name = info.Name.StartsWith("set_") ? info.Name.Substring(4) : info.Name;
if (!map.ContainsKey(name))
{
map[name] = new AssignmentMember(parameterInfos[0].ParameterType, methodInfo);
continue;
}
}
}
}
}
return map;
}
/// <summary>Populate object.</summary>
///
/// <typeparam name="To"> Type of to.</typeparam>
/// <typeparam name="From">Type of from.</typeparam>
/// <param name="to"> to.</param>
/// <param name="from">Source for the.</param>
///
/// <returns>To.</returns>
public static To PopulateObject<To, From>(To to, From from)
{
if (Equals(to, default(To)) || Equals(from, default(From))) return default(To);
var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType());
assignmentDefinition.Populate(to, from);
return to;
}
/// <summary>Populate with non default values.</summary>
///
/// <typeparam name="To"> Type of to.</typeparam>
/// <typeparam name="From">Type of from.</typeparam>
/// <param name="to"> to.</param>
/// <param name="from">Source for the.</param>
///
/// <returns>To.</returns>
public static To PopulateWithNonDefaultValues<To, From>(To to, From from)
{
if (Equals(to, default(To)) || Equals(from, default(From))) return default(To);
var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType());
assignmentDefinition.PopulateWithNonDefaultValues(to, from);
return to;
}
/// <summary>Populate from properties with attribute.</summary>
///
/// <typeparam name="To"> Type of to.</typeparam>
/// <typeparam name="From">Type of from.</typeparam>
/// <param name="to"> to.</param>
/// <param name="from"> Source for the.</param>
/// <param name="attributeType">Type of the attribute.</param>
///
/// <returns>To.</returns>
public static To PopulateFromPropertiesWithAttribute<To, From>(To to, From from,
Type attributeType)
{
if (Equals(to, default(To)) || Equals(from, default(From))) return default(To);
var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType());
assignmentDefinition.PopulateFromPropertiesWithAttribute(to, from, attributeType);
return to;
}
/// <summary>Sets a property.</summary>
///
/// <param name="obj"> .</param>
/// <param name="propertyInfo">Information describing the property.</param>
/// <param name="value"> The value.</param>
public static void SetProperty(object obj, PropertyInfo propertyInfo, object value)
{
if (!propertyInfo.CanWrite)
{
Log.WarnFormat("Attempted to set read only property '{0}'", propertyInfo.Name);
return;
}
var propertySetMetodInfo = propertyInfo.SetMethod();
if (propertySetMetodInfo != null)
{
propertySetMetodInfo.Invoke(obj, new[] { value });
}
}
/// <summary>Gets a property.</summary>
///
/// <param name="obj"> .</param>
/// <param name="propertyInfo">Information describing the property.</param>
///
/// <returns>The property.</returns>
public static object GetProperty(object obj, PropertyInfo propertyInfo)
{
if (propertyInfo == null || !propertyInfo.CanRead)
return null;
var getMethod = propertyInfo.GetMethodInfo();
return getMethod != null ? getMethod.Invoke(obj, new object[0]) : null;
}
/// <summary>Sets a value.</summary>
///
/// <param name="fieldInfo"> Information describing the field.</param>
/// <param name="propertyInfo">Information describing the property.</param>
/// <param name="obj"> .</param>
/// <param name="value"> The value.</param>
public static void SetValue(FieldInfo fieldInfo, PropertyInfo propertyInfo, object obj, object value)
{
try
{
if (IsUnsettableValue(fieldInfo, propertyInfo)) return;
if (fieldInfo != null && !fieldInfo.IsLiteral)
{
fieldInfo.SetValue(obj, value);
}
else
{
SetProperty(obj, propertyInfo, value);
}
}
catch (Exception ex)
{
var name = (fieldInfo != null) ? fieldInfo.Name : propertyInfo.Name;
Log.DebugFormat("Could not set member: {0}. Error: {1}", name, ex.Message);
}
}
/// <summary>Query if 'fieldInfo' is unsettable value.</summary>
///
/// <param name="fieldInfo"> Information describing the field.</param>
/// <param name="propertyInfo">Information describing the property.</param>
///
/// <returns>true if unsettable value, false if not.</returns>
public static bool IsUnsettableValue(FieldInfo fieldInfo, PropertyInfo propertyInfo)
{
#if NETFX_CORE
if (propertyInfo != null)
{
// Properties on non-user defined classes should not be set
// Currently we define those properties as properties declared on
// types defined in mscorlib
if (propertyInfo.DeclaringType.AssemblyQualifiedName.Equals(typeof(object).AssemblyQualifiedName))
{
return true;
}
}
#else
if (propertyInfo != null && propertyInfo.ReflectedType != null)
{
// Properties on non-user defined classes should not be set
// Currently we define those properties as properties declared on
// types defined in mscorlib
if (propertyInfo.DeclaringType.Assembly == typeof(object).Assembly)
{
return true;
}
}
#endif
return false;
}
/// <summary>Creates default values.</summary>
///
/// <param name="types"> The types.</param>
/// <param name="recursionInfo">Tracks how deeply nested we are.</param>
///
/// <returns>A new array of object.</returns>
public static object[] CreateDefaultValues(IEnumerable<Type> types, Dictionary<Type, int> recursionInfo)
{
var values = new List<object>();
foreach (var type in types)
{
values.Add(CreateDefaultValue(type, recursionInfo));
}
return values.ToArray();
}
private const int MaxRecursionLevelForDefaultValues = 2; // do not nest a single type more than this deep.
/// <summary>Creates default value.</summary>
///
/// <param name="type"> The type.</param>
/// <param name="recursionInfo">Tracks how deeply nested we are.</param>
///
/// <returns>The new default value.</returns>
public static object CreateDefaultValue(Type type, Dictionary<Type, int> recursionInfo)
{
if (type == typeof(string))
{
return type.Name;
}
if (type.IsEnum())
{
#if SILVERLIGHT4 || WINDOWS_PHONE
return Enum.ToObject(type, 0);
#else
return Enum.GetValues(type).GetValue(0);
#endif
}
// If we have hit our recursion limit for this type, then return null
int recurseLevel; // will get set to 0 if TryGetValue() fails
recursionInfo.TryGetValue(type, out recurseLevel);
if (recurseLevel > MaxRecursionLevelForDefaultValues) return null;
recursionInfo[type] = recurseLevel + 1; // increase recursion level for this type
try // use a try/finally block to make sure we decrease the recursion level for this type no matter which code path we take,
{
//when using KeyValuePair<TKey, TValue>, TKey must be non-default to stuff in a Dictionary
if (type.IsGeneric() && type.GenericTypeDefinition() == typeof(KeyValuePair<,>))
{
var genericTypes = type.GenericTypeArguments();
var valueType = Activator.CreateInstance(type, CreateDefaultValue(genericTypes[0], recursionInfo), CreateDefaultValue(genericTypes[1], recursionInfo));
return PopulateObjectInternal(valueType, recursionInfo);
}
if (type.IsValueType())
{
return type.CreateInstance();
}
if (type.IsArray)
{
return PopulateArray(type, recursionInfo);
}
var constructorInfo = type.GetEmptyConstructor();
var hasEmptyConstructor = constructorInfo != null;
if (hasEmptyConstructor)
{
var value = constructorInfo.Invoke(new object[0]);
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
var genericCollectionType = GetGenericCollectionType(type);
if (genericCollectionType != null)
{
SetGenericCollection(genericCollectionType, value, recursionInfo);
}
#endif
//when the object might have nested properties such as enums with non-0 values, etc
return PopulateObjectInternal(value, recursionInfo);
}
return null;
}
finally
{
recursionInfo[type] = recurseLevel;
}
}
private static Type GetGenericCollectionType(Type type)
{
#if NETFX_CORE
var genericCollectionType =
type.GetTypeInfo().ImplementedInterfaces
.FirstOrDefault(t => t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == typeof (ICollection<>));
#elif WINDOWS_PHONE || SILVERLIGHT
var genericCollectionType =
type.GetInterfaces()
.FirstOrDefault(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof (ICollection<>));
#else
var genericCollectionType = type.FindInterfaces((t, critera) =>
t.IsGenericType
&& t.GetGenericTypeDefinition() == typeof(ICollection<>), null).FirstOrDefault();
#endif
return genericCollectionType;
}
/// <summary>Sets generic collection.</summary>
///
/// <param name="realisedListType">Type of the realised list.</param>
/// <param name="genericObj"> The generic object.</param>
/// <param name="recursionInfo"> Tracks how deeply nested we are.</param>
public static void SetGenericCollection(Type realisedListType, object genericObj, Dictionary<Type, int> recursionInfo)
{
var args = realisedListType.GenericTypeArguments();
if (args.Length != 1)
{
Log.ErrorFormat("Found a generic list that does not take one generic argument: {0}", realisedListType);
return;
}
var methodInfo = realisedListType.GetMethodInfo("Add");
if (methodInfo != null)
{
var argValues = CreateDefaultValues(args, recursionInfo);
methodInfo.Invoke(genericObj, argValues);
}
}
/// <summary>Populate array.</summary>
///
/// <param name="type"> The type.</param>
/// <param name="recursionInfo">Tracks how deeply nested we are.</param>
///
/// <returns>An Array.</returns>
public static Array PopulateArray(Type type, Dictionary<Type, int> recursionInfo)
{
var elementType = type.GetElementType();
var objArray = Array.CreateInstance(elementType, 1);
var objElementType = CreateDefaultValue(elementType, recursionInfo);
objArray.SetValue(objElementType, 0);
return objArray;
}
/// <summary>TODO: replace with InAssignableFrom.</summary>
///
/// <param name="toType"> Type of to.</param>
/// <param name="fromType">Type of from.</param>
///
/// <returns>true if we can cast, false if not.</returns>
public static bool CanCast(Type toType, Type fromType)
{
if (toType.IsInterface())
{
var interfaceList = fromType.Interfaces().ToList();
if (interfaceList.Contains(toType)) return true;
}
else
{
Type baseType = fromType;
bool areSameTypes;
do
{
areSameTypes = baseType == toType;
}
while (!areSameTypes && (baseType = fromType.BaseType()) != null);
if (areSameTypes) return true;
}
return false;
}
/// <summary>Gets the property attributes in this collection.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="fromType">Type of from.</param>
///
/// <returns>An enumerator that allows foreach to be used to process the property attributes in this collection.</returns>
public static IEnumerable<KeyValuePair<PropertyInfo, T>> GetPropertyAttributes<T>(Type fromType) where T : Attribute
{
var attributeType = typeof(T);
var baseType = fromType;
do
{
var propertyInfos = baseType.AllProperties();
foreach (var propertyInfo in propertyInfos)
{
var attributes = propertyInfo.GetCustomAttributes(attributeType, true);
foreach (T attribute in attributes)
{
yield return new KeyValuePair<PropertyInfo, T>(propertyInfo, attribute);
}
}
}
while ((baseType = baseType.BaseType()) != null);
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
namespace AnimatGuiCtrls.Controls
{
// namespace OutlookBar
// {
internal class BandTagInfo
{
public OutlookBar outlookBar;
public int index;
public BandTagInfo(OutlookBar ob, int index)
{
outlookBar=ob;
this.index=index;
}
}
public class OutlookBar : Panel
{
private int buttonHeight;
private int selectedBand;
private int selectedBandHeight;
public int ButtonHeight
{
get
{
return buttonHeight;
}
set
{
buttonHeight=value;
// do recalc layout for entire bar
}
}
public int SelectedBand
{
get
{
return selectedBand;
}
set
{
SelectBand(value);
}
}
public OutlookBar()
{
buttonHeight=25;
selectedBand=0;
selectedBandHeight=0;
AllowDrop = true;
}
public void Initialize()
{
// parent must exist!
this.SizeChanged+=new EventHandler(SizeChangedEvent);
}
public void AddBand(string caption, ContentPanel content)
{
content.outlookBar=this;
int index=Controls.Count;
BandTagInfo bti=new BandTagInfo(this, index);
BandPanel bandPanel=new BandPanel(caption, content, bti);
Controls.Add(bandPanel);
UpdateBarInfo();
RecalcLayout(bandPanel, index);
}
public void SelectBand(int index)
{
selectedBand=index;
RedrawBands();
}
// public override void Refresh()
// {
// RecalcLayout();
// base.Refresh ();
// }
protected override void OnResize(EventArgs e)
{
try
{
RedrawBands();
base.OnResize (e);
}
catch(System.Exception ex)
{string strMsg = ex.Message;}
}
private void RedrawBands()
{
UpdateBarInfo();
for (int i=0; i<Controls.Count; i++)
{
BandPanel bp=Controls[i] as BandPanel;
RecalcLayout(bp, i);
}
}
private void UpdateBarInfo()
{
selectedBandHeight=ClientRectangle.Height-(Controls.Count * buttonHeight);
}
private void RecalcLayout(BandPanel bandPanel, int index)
{
int vPos=(index <= selectedBand) ? buttonHeight*index : buttonHeight*index+selectedBandHeight;
int height=selectedBand==index ? selectedBandHeight+buttonHeight : buttonHeight;
// the band dimensions
bandPanel.Location=new Point(0, vPos);
bandPanel.Size=new Size(ClientRectangle.Width, height);
// the contained button dimensions
bandPanel.Controls[0].Location=new Point(0, 0);
bandPanel.Controls[0].Size=new Size(ClientRectangle.Width, buttonHeight);
// the contained content panel dimensions
bandPanel.Controls[1].Location=new Point(0, buttonHeight);
bandPanel.Controls[1].Size=new Size(ClientRectangle.Width-2, height-25);
foreach(System.Windows.Forms.Control ctrlIcon in bandPanel.Content.Controls)
{
int iX = bandPanel.Content.Size.Width/2 - ctrlIcon.Width/2;
ctrlIcon.Location = new Point(iX, ctrlIcon.Location.Y);
}
}
private void SizeChangedEvent(object sender, EventArgs e)
{
try
{
//Size=new Size(Size.Width, ((Control)sender).ClientRectangle.Size.Height);
UpdateBarInfo();
RedrawBands();
}
catch(System.Exception ex)
{string strMsg = ex.Message;}
}
}
internal class BandPanel : Panel
{
private ContentPanel m_Content;
public BandPanel(string caption, ContentPanel content, BandTagInfo bti)
{
BandButton bandButton=new BandButton(caption, bti);
Controls.Add(bandButton);
Controls.Add(content);
m_Content = content;
}
public ContentPanel Content
{
get
{
return m_Content;
}
}
}
internal class BandButton : Button
{
private BandTagInfo bti;
public BandButton(string caption, BandTagInfo bti)
{
Text=caption;
FlatStyle=FlatStyle.Standard;
Visible=true;
this.bti=bti;
Click+=new EventHandler(SelectBand);
}
private void SelectBand(object sender, EventArgs e)
{
bti.outlookBar.SelectBand(bti.index);
}
}
public abstract class ContentPanel : Panel
{
public OutlookBar outlookBar;
public ContentPanel()
{
// initial state
Visible=true;
}
}
public class IconPanel : ContentPanel
{
protected int iconHeight;
protected int iconSpacing;
protected int margin;
public int IconSpacing
{
get
{
return iconSpacing;
}
}
public int PanelMargin
{
get
{
return margin;
}
}
public int IconHeight
{
get
{
return iconHeight;
}
set
{
if(value > 0)
iconHeight = value;
iconSpacing=iconHeight+15+margin; // icon height + text height + margin
}
}
public IconPanel()
{
margin=10;
iconHeight=35;
iconSpacing=iconHeight+15+margin; // icon height + text height + margin
BackColor=Color.LightBlue;
AutoScroll=true;
AllowDrop = true;
}
public PanelIcon AddIcon(string caption, Image imgPanel, Image imgDrag, Object IconData)
{
return AddIcon(caption, imgPanel, imgDrag, IconData, null, null);
}
public PanelIcon AddIcon(string caption, Image imgPanel, Image imgDrag, Object IconData, EventHandler onClickEvent)
{
return AddIcon(caption, imgPanel, imgDrag, IconData, onClickEvent, null);
}
public PanelIcon AddIcon(string caption, Image imgPanel, Image imgDrag, Object IconData, EventHandler onClickEvent, PanelIcon.DoubleClickIconEvent onDoubleClickEvent)
{
int index=Controls.Count/2; // two entries per icon
if(imgPanel == null)
throw new System.Exception("The image associated with the icon '" + caption + "' is not defined.");
if(imgDrag == null)
throw new System.Exception("The drag image associated with the icon '" + caption + "' is not defined.");
if(IconData == null)
throw new System.Exception("The IconData associated with the icon '" + caption + "' is not defined.");
PanelIcon panelIcon=new PanelIcon(this, imgPanel, imgDrag, index, IconData, onClickEvent, onDoubleClickEvent);
Controls.Add(panelIcon);
Label label=new Label();
label.Text=caption;
label.Visible=true;
label.Location=new Point(0, margin+imgPanel.Size.Height+index*iconSpacing);
label.Size=new Size(Size.Width, 15);
label.TextAlign=ContentAlignment.TopCenter;
label.Click+=onClickEvent;
label.Tag=panelIcon;
Controls.Add(label);
return panelIcon;
}
}
public class PanelIcon : PictureBox
{
public int index;
public IconPanel iconPanel;
protected ImageList m_imageList;
protected ImageListDrag m_imageDrag;
protected bool m_bDraggingIcon;
protected System.Drawing.Image m_imgDrag;
public delegate void DoubleClickIconEvent(PanelIcon Icon);
public event DoubleClickIconEvent DoubleClickIcon;
private Color bckgColor;
//private bool mouseEnter;
private Object m_oIconData;
public int Index
{
get
{
return index;
}
}
public Object Data
{
get
{
return m_oIconData;
}
set
{
m_oIconData = value;
}
}
public bool DraggingIcon
{
get
{
return m_bDraggingIcon;
}
set
{
m_bDraggingIcon = value;
}
}
public System.Drawing.Image DragImage
{
get
{
return m_imgDrag;
}
set
{
m_imgDrag = value;
}
}
public PanelIcon(IconPanel parent, Image imgPanel, Image imgDrag, int index, Object IconData)
{
Initialize(parent, imgPanel, imgDrag, index, IconData, null, null);
}
public PanelIcon(IconPanel parent, Image imgPanel, Image imgDrag, int index, Object IconData, EventHandler onClickEvent)
{
Initialize(parent, imgPanel, imgDrag, index, IconData, onClickEvent, null);
}
public PanelIcon(IconPanel parent, Image imgPanel, Image imgDrag, int index, Object IconData, EventHandler onClickEvent, DoubleClickIconEvent onDoubleClickEvent)
{
Initialize(parent, imgPanel, imgDrag, index, IconData, onClickEvent, onDoubleClickEvent);
}
private void Initialize(IconPanel parent, Image imgPanel, Image imgDrag, int index, Object IconData, EventHandler onClickEvent, DoubleClickIconEvent onDoubleClickEvent)
{
this.index=index;
this.iconPanel=parent;
this.m_oIconData = IconData;
m_imgDrag = imgDrag;
if(IconData == null)
throw new Exception("IconData is not set for this panel icon.");
Image=imgPanel;
Visible=true;
Location=new Point(iconPanel.outlookBar.Size.Width/2-imgPanel.Size.Width/2,
iconPanel.PanelMargin + index*iconPanel.IconSpacing);
Size=imgPanel.Size;
if(onClickEvent != null)
Click+=onClickEvent;
if(onDoubleClickEvent != null)
DoubleClickIcon+=onDoubleClickEvent;
Tag=this;
MouseEnter+=new EventHandler(OnMouseEnter);
MouseLeave+=new EventHandler(OnMouseLeave);
MouseMove+=new MouseEventHandler(OnMouseMove);
MouseDown+=new MouseEventHandler(OnMouseDown);
GiveFeedback+=new GiveFeedbackEventHandler(OnGiveFeedback);
m_imageDrag = new ImageListDrag();
m_imageList = new ImageList();
m_imageList.ImageSize = new Size(imgDrag.Width, imgDrag.Height);
m_imageDrag.Imagelist = m_imageList;
m_imageList.Images.Add(imgDrag, System.Drawing.Color.Transparent);
m_bDraggingIcon = false;
bckgColor=iconPanel.BackColor;
//mouseEnter=false;
AllowDrop = true;
}
private void OnMouseMove(object sender, MouseEventArgs args)
{
try
{
if(args.Button == MouseButtons.Left)
{
//if they are moving the mouse while the left mouse button is down then
//they are attempting to drag the item.
m_bDraggingIcon = true;
m_imageDrag.StartDrag(0, (int) (m_imgDrag.Width/2), (int) (m_imgDrag.Height/2));
this.DoDragDrop(this, DragDropEffects.Copy);
m_imageDrag.CompleteDrag();
}
}
catch(System.Exception ex)
{string strMsg = ex.Message;}
}
private void OnMouseEnter(object sender, EventArgs e)
{
}
private void OnMouseLeave(object sender, EventArgs e)
{
// if (mouseEnter)
// {
// BackColor=bckgColor;
// BorderStyle=BorderStyle.None;
// Location=Location+new Size(1, 1);
// mouseEnter=false;
// }
}
private void OnMouseDown(object sender, MouseEventArgs args)
{
// m_bDraggingIcon = true;
//
// m_imageDrag.StartDrag(0, (int) (m_imgDrag.Width/2), (int) (m_imgDrag.Height/2));
//
// this.DoDragDrop(this, DragDropEffects.Copy);
//
// m_imageDrag.CompleteDrag();
}
protected override void OnDoubleClick(EventArgs e)
{
try
{
base.OnDoubleClick (e);
DoubleClickIcon(this);
}
catch(System.Exception ex)
{string strMsg = ex.Message;}
}
protected override void OnDragEnter(DragEventArgs drgevent)
{
try
{
base.OnDragEnter (drgevent);
drgevent.Effect = DragDropEffects.Copy;
}
catch(System.Exception ex)
{string strMsg = ex.Message;}
}
private void OnGiveFeedback(object sender, System.Windows.Forms.GiveFeedbackEventArgs args)
{
try
{
args.UseDefaultCursors = false;
// Draw the drag image:
// Debug.WriteLine("OnGiveFeedback: DraggingIcon: " + m_bDraggingIcon);
if(m_bDraggingIcon)
m_imageDrag.DragDrop();
}
catch(System.Exception ex)
{string strMsg = ex.Message;}
}
}
// }
}
| |
// 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.
#if NET5_0
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.Text;
using osu.Framework.Extensions;
using osu.Framework.Lists;
using osu.Framework.Logging;
namespace osu.Framework.Testing
{
internal class RoslynTypeReferenceBuilder : ITypeReferenceBuilder
{
// The "Attribute" suffix disappears when used via a nuget package, so it is trimmed here.
private static readonly string exclude_attribute_name = nameof(ExcludeFromDynamicCompileAttribute).Replace(nameof(Attribute), string.Empty);
private const string jetbrains_annotations_namespace = "JetBrains.Annotations";
private readonly Logger logger;
private readonly ConcurrentDictionary<TypeReference, IReadOnlyCollection<TypeReference>> referenceMap = new ConcurrentDictionary<TypeReference, IReadOnlyCollection<TypeReference>>();
private readonly ConcurrentDictionary<Project, Compilation> compilationCache = new ConcurrentDictionary<Project, Compilation>();
private readonly ConcurrentDictionary<string, SemanticModel> semanticModelCache = new ConcurrentDictionary<string, SemanticModel>();
private readonly ConcurrentDictionary<TypeReference, bool> typeInheritsFromGameCache = new ConcurrentDictionary<TypeReference, bool>();
private readonly ConcurrentDictionary<string, bool> syntaxExclusionMap = new ConcurrentDictionary<string, bool>();
private readonly ConcurrentDictionary<string, byte> assembliesContainingReferencedInternalMembers = new ConcurrentDictionary<string, byte>();
private Solution solution;
public RoslynTypeReferenceBuilder()
{
logger = Logger.GetLogger("dynamic-compilation");
logger.OutputToListeners = false;
}
public async Task Initialise(string solutionFile)
{
MSBuildLocator.RegisterDefaults();
solution = await MSBuildWorkspace.Create().OpenSolutionAsync(solutionFile).ConfigureAwait(false);
}
public async Task<IReadOnlyCollection<string>> GetReferencedFiles(Type testType, string changedFile)
{
clearCaches();
updateFile(changedFile);
await buildReferenceMapAsync(testType, changedFile).ConfigureAwait(false);
var sources = getTypesFromFile(changedFile).ToArray();
if (sources.Length == 0)
throw new NoLinkBetweenTypesException(testType, changedFile);
return getReferencedFiles(sources, getDirectedGraph());
}
public async Task<IReadOnlyCollection<AssemblyReference>> GetReferencedAssemblies(Type testType, string changedFile) => await Task.Run(() =>
{
// Todo: This is temporary, and is potentially missing assemblies.
var assemblies = new HashSet<AssemblyReference>();
foreach (var asm in compilationCache.Values.SelectMany(c => c.ReferencedAssemblyNames))
addReference(Assembly.Load(asm.Name), false);
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic))
addReference(asm, false);
addReference(typeof(JetBrains.Annotations.NotNullAttribute).Assembly, true);
return assemblies;
void addReference(Assembly assembly, bool force)
{
if (string.IsNullOrEmpty(assembly.Location))
return;
Type[] loadedTypes = assembly.GetLoadableTypes();
// JetBrains.Annotations is a special namespace that some libraries define to take advantage of R# annotations.
// Since internals are exposed to the compiler, these libraries would cause type conflicts and are thus excluded.
if (!force && loadedTypes.Any(t => t.Namespace == jetbrains_annotations_namespace))
return;
bool containsReferencedInternalMember = assembliesContainingReferencedInternalMembers.Any(i => assembly.FullName?.Contains(i.Key) == true);
assemblies.Add(new AssemblyReference(assembly, containsReferencedInternalMember));
}
}).ConfigureAwait(false);
public void Reset()
{
clearCaches();
referenceMap.Clear();
}
/// <summary>
/// Builds the reference map, connecting all types to their immediate references. Results are placed inside <see cref="referenceMap"/>.
/// </summary>
/// <param name="testType">The test target - the top-most level.</param>
/// <param name="changedFile">The file that was changed.</param>
/// <exception cref="InvalidOperationException">If <paramref name="testType"/> could not be retrieved from the solution.</exception>
private async Task buildReferenceMapAsync(Type testType, string changedFile)
{
// We want to find a graph of types from the testType symbol (P) to all the types which it references recursively.
//
// P
// / \
// / \
// / \
// C1 C2 ---
// / \ | /
// C3 C4 C5 /
// \ / /
// C6 ---
//
// The reference map is a key-value pairing of all types to their immediate references. A directed graph can be built by traversing through types.
//
// P -> { C1, C2 }
// C1 -> { C3, C4 }
// C2 -> { C5, C6 }
// C3 -> { }
// C4 -> { C6 }
// C5 -> { C6 }
// C6 -> { C2 }
logger.Add("Building reference map...");
var compiledTestProject = await compileProjectAsync(findTestProject()).ConfigureAwait(false);
var compiledTestType = compiledTestProject.GetTypeByMetadataName(testType.FullName);
if (compiledTestType == null)
throw new InvalidOperationException("Failed to retrieve test type from the solution.");
if (referenceMap.Count > 0)
{
logger.Add("Attempting to use cache...");
// We already have some references, so we can do a partial re-process of the map for only the changed file.
var oldTypes = getTypesFromFile(changedFile).ToArray();
foreach (var t in oldTypes)
{
referenceMap.TryRemove(t, out _);
typeInheritsFromGameCache.TryRemove(t, out _);
}
foreach (var t in oldTypes)
{
string typePath = t.Symbol.Locations.First().SourceTree?.FilePath;
// The type we have is on an old compilation, we need to re-retrieve it on the new one.
var project = getProjectFromFile(typePath);
if (project == null)
{
logger.Add("File has been renamed. Rebuilding reference map from scratch...");
Reset();
break;
}
var compilation = await compileProjectAsync(project).ConfigureAwait(false);
var syntaxTree = compilation.SyntaxTrees.Single(tree => tree.FilePath == typePath);
var semanticModel = await getSemanticModelAsync(syntaxTree).ConfigureAwait(false);
var referencedTypes = await getReferencedTypesAsync(semanticModel).ConfigureAwait(false);
referenceMap[TypeReference.FromSymbol(t.Symbol)] = referencedTypes.ToHashSet();
foreach (var referenced in referencedTypes)
await buildReferenceMapRecursiveAsync(referenced).ConfigureAwait(false);
}
}
if (referenceMap.Count == 0)
{
// We have no cache available, so we must rebuild the whole map.
await buildReferenceMapRecursiveAsync(TypeReference.FromSymbol(compiledTestType)).ConfigureAwait(false);
}
}
/// <summary>
/// Builds the reference map starting from a root type reference, connecting all types to their immediate references. Results are placed inside <see cref="referenceMap"/>.
/// </summary>
/// <remarks>
/// This should not be used by itself. Use <see cref="buildReferenceMapAsync"/> instead.
/// </remarks>
/// <param name="rootReference">The root, where the map should start being build from.</param>
private async Task buildReferenceMapRecursiveAsync(TypeReference rootReference)
{
var searchQueue = new ConcurrentBag<TypeReference> { rootReference };
while (searchQueue.Count > 0)
{
var toProcess = searchQueue.ToArray();
searchQueue.Clear();
await Task.WhenAll(toProcess.Select(async toCheck =>
{
var referencedTypes = await getReferencedTypesAsync(toCheck).ConfigureAwait(false);
referenceMap[toCheck] = referencedTypes;
foreach (var referenced in referencedTypes)
{
// We don't want to cycle over types that have already been explored.
if (referenceMap.TryAdd(referenced, null))
searchQueue.Add(referenced);
}
})).ConfigureAwait(false);
}
}
/// <summary>
/// Retrieves all <see cref="TypeReference"/>s referenced by a given <see cref="TypeReference"/>, across all symbol sources.
/// </summary>
/// <param name="typeReference">The target <see cref="TypeReference"/>.</param>
/// <returns>All <see cref="TypeReference"/>s referenced to across all symbol sources by <paramref name="typeReference"/>.</returns>
private async Task<HashSet<TypeReference>> getReferencedTypesAsync(TypeReference typeReference)
{
var result = new HashSet<TypeReference>();
foreach (var reference in typeReference.Symbol.DeclaringSyntaxReferences)
{
var semanticModel = await getSemanticModelAsync(reference.SyntaxTree).ConfigureAwait(false);
var referencedTypes = await getReferencedTypesAsync(semanticModel).ConfigureAwait(false);
foreach (var type in referencedTypes)
result.Add(type);
}
return result;
}
/// <summary>
/// Retrieves all <see cref="TypeReference"/>s referenced by a given <see cref="SemanticModel"/>.
/// </summary>
/// <param name="semanticModel">The target <see cref="SemanticModel"/>.</param>
/// <returns>All <see cref="TypeReference"/>s referenced by <paramref name="semanticModel"/>.</returns>
private async Task<ICollection<TypeReference>> getReferencedTypesAsync(SemanticModel semanticModel)
{
var result = new ConcurrentDictionary<TypeReference, byte>();
var root = await semanticModel.SyntaxTree.GetRootAsync().ConfigureAwait(false);
var descendantNodes = root.DescendantNodes(n =>
{
var kind = n.Kind();
// Ignored:
// - Entire using lines.
// - Namespace names (not entire namespaces).
// - Entire static classes.
// - Variable declarators (names of variables).
// - The single IdentifierName child of an assignment expression (variable name), below.
// - The single IdentifierName child of an argument syntax (variable name), below.
// - The name of namespace declarations.
// - Name-colon syntaxes.
// - The expression of invocation expressions. Static classes are explicitly disallowed so the target type of an invocation must be available elsewhere in the syntax tree.
// - The single IdentifierName child of a foreach expression (source variable name), below.
// - The single 'var' IdentifierName child of a variable declaration, below.
// - Element access expressions.
return kind != SyntaxKind.UsingDirective
&& kind != SyntaxKind.NamespaceKeyword
&& (kind != SyntaxKind.ClassDeclaration || ((ClassDeclarationSyntax)n).Modifiers.All(m => m.Kind() != SyntaxKind.StaticKeyword))
&& (kind != SyntaxKind.QualifiedName || !(n.Parent is NamespaceDeclarationSyntax))
&& kind != SyntaxKind.NameColon
&& (kind != SyntaxKind.QualifiedName || n.Parent?.Kind() != SyntaxKind.NamespaceDeclaration)
&& kind != SyntaxKind.NameColon
&& kind != SyntaxKind.ElementAccessExpression
&& (n.Parent?.Kind() != SyntaxKind.InvocationExpression || n != ((InvocationExpressionSyntax)n.Parent).Expression);
});
// This hashset is used to prevent re-exploring syntaxes with the same name.
// Todo: This can be used across all files, but care needs to be taken for redefined types (via using X = y), using the same-named type from a different namespace, or via type hiding.
var seenTypes = new ConcurrentDictionary<string, byte>();
await Task.WhenAll(descendantNodes.Select(node => Task.Run(() =>
{
if (node.Kind() == SyntaxKind.IdentifierName && node.Parent != null)
{
// Ignore the variable name of assignment expressions.
if (node.Parent is AssignmentExpressionSyntax)
return;
switch (node.Parent.Kind())
{
case SyntaxKind.VariableDeclarator: // Ignore the variable name of variable declarators.
case SyntaxKind.Argument: // Ignore the variable name of arguments.
case SyntaxKind.InvocationExpression: // Ignore a single identifier name expression of an invocation expression (e.g. IdentifierName()).
case SyntaxKind.ForEachStatement: // Ignore a single identifier of a foreach statement (the source).
case SyntaxKind.VariableDeclaration when node.ToString() == "var": // Ignore the single 'var' identifier of a variable declaration.
return;
}
}
switch (node.Kind())
{
case SyntaxKind.GenericName:
case SyntaxKind.IdentifierName:
{
string syntaxName = node.ToString();
if (seenTypes.ContainsKey(syntaxName))
return;
if (!tryNode(node, out var symbol))
return;
// The node has been processed so we want to avoid re-processing the same node again if possible, as this is a costly operation.
// Note that the syntax name may differ from the finalised symbol name (e.g. member access).
// We can only prevent future reprocessing if the symbol name and syntax name exactly match because we can't determine that the type won't be accessed later, such as:
//
// A.X = 5; // Syntax name = A, Symbol name = B
// B.X = 5; // Syntax name = B, Symbol name = A
// public A B;
// public B A;
//
if (symbol.Name == syntaxName)
seenTypes.TryAdd(symbol.Name, 0);
break;
}
}
}))).ConfigureAwait(false);
return result.Keys;
bool tryNode(SyntaxNode node, out INamedTypeSymbol symbol)
{
if (semanticModel.GetSymbolInfo(node).Symbol is INamedTypeSymbol sType)
{
addTypeSymbol(sType);
symbol = sType;
return true;
}
if (semanticModel.GetTypeInfo(node).Type is INamedTypeSymbol tType)
{
addTypeSymbol(tType);
symbol = tType;
return true;
}
// Todo: Reduce the number of cases that fall through here.
symbol = null;
return false;
}
void addTypeSymbol(INamedTypeSymbol typeSymbol)
{
var reference = TypeReference.FromSymbol(typeSymbol);
if (typeInheritsFromGame(reference))
{
logger.Add($"Type {typeSymbol.Name} inherits from game and is marked for exclusion.");
return;
}
// Exclude types marked with the [ExcludeFromDynamicCompile] attribute
// When multiple types exist in one file, the exclusion attribute may be omitted from some types, causing references to those types to indirectly compile explicitly excluded types.
// If this type hasn't been seen before, do a manual pass over all its syntaxes to determine if an exclusion attribute is present anywhere in the file.
if (!referenceMap.ContainsKey(reference))
{
foreach (var syntax in typeSymbol.DeclaringSyntaxReferences)
{
if (!syntaxExclusionMap.TryGetValue(syntax.SyntaxTree.FilePath, out bool containsExclusion))
containsExclusion = syntaxExclusionMap[syntax.SyntaxTree.FilePath] = syntax.SyntaxTree.ToString().Contains(exclude_attribute_name);
if (containsExclusion)
{
logger.Add($"Type {typeSymbol.Name} referenced but marked for exclusion.");
return;
}
}
}
if (typeSymbol.DeclaredAccessibility == Accessibility.Internal)
assembliesContainingReferencedInternalMembers.TryAdd(typeSymbol.ContainingAssembly.Name, 0);
result.TryAdd(reference, 0);
}
}
/// <summary>
/// Traverses <see cref="referenceMap"/> to build a directed graph of <see cref="DirectedTypeNode"/> joined by their parents.
/// </summary>
/// <returns>A dictionary containing the directed graph from each <see cref="TypeReference"/> in <see cref="referenceMap"/>.</returns>
private Dictionary<TypeReference, DirectedTypeNode> getDirectedGraph()
{
// Given the reference map (from above):
//
// P -> { C1, C2 }
// C1 -> { C3, C4 }
// C2 -> { C5, C6 }
// C3 -> { }
// C4 -> { C6 }
// C5 -> { C6 }
// C6 -> { C2 }
//
// The respective directed graph is built by traversing upwards and finding all incoming references at each type, such that:
//
// P -> { }
// C1 -> { P }
// C2 -> { C6, P, C5, C4, C2, C1 }
// C3 -> { C1, P }
// C4 -> { C1, P }
// C5 -> { C2, P }
// C6 -> { C5, C4, C2, C1, C6, P }
//
// The directed graph may contain cycles where multiple paths lead to the same node (e.g. C2, C6).
logger.Add("Retrieving reference graph...");
var result = new Dictionary<TypeReference, DirectedTypeNode>();
// Traverse through the reference map and assign parents to all children referenced types.
foreach (var kvp in referenceMap)
{
var parentNode = getNode(kvp.Key);
foreach (var typeRef in kvp.Value)
getNode(typeRef).Parents.Add(parentNode);
}
return result;
DirectedTypeNode getNode(TypeReference typeSymbol)
{
if (!result.TryGetValue(typeSymbol, out var existing))
result[typeSymbol] = existing = new DirectedTypeNode(typeSymbol);
return existing;
}
}
/// <summary>
/// Traverses a directed graph to find all direct and indirect references to a set of <see cref="TypeReference"/>s. References are returned as file names.
/// </summary>
/// <param name="sources">The <see cref="TypeReference"/>s to search from.</param>
/// <param name="directedGraph">The directed graph generated through <see cref="getDirectedGraph"/>.</param>
/// <returns>All files containing direct or indirect references to the given <paramref name="sources"/>.</returns>
private HashSet<string> getReferencedFiles(IEnumerable<TypeReference> sources, IReadOnlyDictionary<TypeReference, DirectedTypeNode> directedGraph)
{
logger.Add("Retrieving referenced files...");
// Iterate through the graph and find the "expansion factor" at each node. The expansion factor is a count of how many nodes it or any of its parents have opened up.
// As a node opens up more nodes, a successful re-compilation becomes increasingly improbable as integral parts of the game may start getting touched,
// so the maximal expansion factor must be constrained to increase the probability of a successful re-compilation.
foreach (var s in sources)
computeExpansionFactors(directedGraph[s]);
// Invert the expansion factors such the changed file and the test will have the lowest values, and the centre of the graph will have the greatest values.
ulong maxExpansionFactor = sources.Select(s => directedGraph[s].ExpansionFactor).Max();
foreach (var (_, node) in directedGraph)
node.ExpansionFactor = Math.Min(node.ExpansionFactor, maxExpansionFactor - node.ExpansionFactor);
var result = new HashSet<string>();
foreach (var s in sources)
getReferencedFilesRecursive(directedGraph[s], result);
return result;
}
private bool computeExpansionFactors(DirectedTypeNode node, HashSet<DirectedTypeNode> seenTypes = null)
{
seenTypes ??= new HashSet<DirectedTypeNode>();
if (seenTypes.Contains(node))
return false;
seenTypes.Add(node);
node.ExpansionFactor = (ulong)node.Parents.Count;
foreach (var p in node.Parents)
{
if (computeExpansionFactors(p, seenTypes))
node.ExpansionFactor += p.ExpansionFactor;
}
return true;
}
private void getReferencedFilesRecursive(DirectedTypeNode node, HashSet<string> result, HashSet<DirectedTypeNode> seenTypes = null, int level = 0, SortedList<ulong> childExpansions = null)
{
// Don't go through duplicate nodes (multiple references from different types).
seenTypes ??= new HashSet<DirectedTypeNode>();
if (seenTypes.Contains(node))
return;
seenTypes.Add(node);
// Concatenate the expansion factors from ourselves and the child.
var expansions = new SortedList<ulong>();
if (childExpansions != null)
expansions.AddRange(childExpansions);
expansions.AddRange(node.Parents.Where(p => p != node).Select(p => p.ExpansionFactor));
// Compute the "right bound" after which far outlier parents that expand too many nodes shouldn't be traversed.
// This is calculated as 3x the inter-quartile range (see: https://en.wikipedia.org/wiki/Outlier#Tukey's_fences).
double rightBound = double.PositiveInfinity;
if (expansions.Count > 1)
{
var q1 = getMedian(expansions.Take(expansions.Count / 2).ToList(), out var q1Centre);
var q3 = getMedian(expansions.Skip((int)Math.Ceiling(expansions.Count / 2f)).ToList(), out _);
rightBound = q3 + 3 * (q3 - q1);
// Finally, remove all left-bound elements as they would skew the results as parents are traversed.
expansions.RemoveRange(0, q1Centre);
}
// Output the current iteration to the log. A '.' is prepended since the logger trims lines.
logger.Add($"{(level > 0 ? $".{new string(' ', level * 2 - 1)}| " : string.Empty)} {node.ExpansionFactor} (rb: {rightBound}): {node}");
// Add all the current type's locations to the resulting set.
foreach (var location in node.Reference.Symbol.Locations)
{
var syntaxTree = location.SourceTree;
if (syntaxTree != null)
result.Add(syntaxTree.FilePath);
}
// Follow through the process for all parents.
foreach (var p in node.Parents)
{
int nextLevel = level + 1;
// Right-bound outlier test - exclude parents greater than 3x IQR. Always expand left-bound parents as they are unlikely to cause compilation errors.
if (p.ExpansionFactor > rightBound)
{
logger.Add($"{(nextLevel > 0 ? $".{new string(' ', nextLevel * 2 - 1)}| " : string.Empty)} {node.ExpansionFactor} (rb: {rightBound}): {node} (!! EXCLUDED !!)");
continue;
}
getReferencedFilesRecursive(p, result, seenTypes, nextLevel, expansions);
}
}
private ulong getMedian(List<ulong> range, out int centre)
{
centre = range.Count / 2;
// If count is odd - return the middle element.
if (range.Count % 2 == 1)
return range[centre];
// If count is even, return the average of the two nearest elements (centre is essentially the upper index).
return (range[centre - 1] + range[centre]) / 2;
}
private bool typeInheritsFromGame(TypeReference reference)
{
if (typeInheritsFromGameCache.TryGetValue(reference, out var existing))
return existing;
// When used via a nuget package, the local type name seems to always be more qualified than the symbol's type name.
// E.g. Type name: osu.Framework.Game, symbol name: Framework.Game.
if (typeof(Game).FullName?.Contains(reference.ToString()) == true)
return typeInheritsFromGameCache[reference] = true;
if (reference.Symbol.BaseType == null)
return typeInheritsFromGameCache[reference] = false;
return typeInheritsFromGameCache[reference] = typeInheritsFromGame(TypeReference.FromSymbol(reference.Symbol.BaseType));
}
/// <summary>
/// Finds all the <see cref="TypeReference"/>s which list a given filename as any of their sources.
/// </summary>
/// <param name="fileName">The target filename.</param>
/// <returns>All <see cref="TypeReference"/>s with <paramref name="fileName"/> listed as one of their symbol locations.</returns>
private IEnumerable<TypeReference> getTypesFromFile(string fileName) => referenceMap
.Select(kvp => kvp.Key)
.Where(t => t.Symbol.Locations.Any(l => l.SourceTree?.FilePath == fileName));
/// <summary>
/// Compiles a <see cref="Project"/>.
/// </summary>
/// <param name="project">The <see cref="Project"/> to compile.</param>
/// <returns>The resulting <see cref="Compilation"/>.</returns>
private async Task<Compilation> compileProjectAsync(Project project)
{
if (compilationCache.TryGetValue(project, out var existing))
return existing;
logger.Add($"Compiling project {project.Name}...");
return compilationCache[project] = await project.GetCompilationAsync().ConfigureAwait(false);
}
/// <summary>
/// Retrieves a <see cref="SemanticModel"/> from a given <see cref="SyntaxTree"/>.
/// </summary>
/// <param name="syntaxTree">The target <see cref="SyntaxTree"/>.</param>
/// <returns>The corresponding <see cref="SemanticModel"/>.</returns>
private async Task<SemanticModel> getSemanticModelAsync(SyntaxTree syntaxTree)
{
string filePath = syntaxTree.FilePath;
if (semanticModelCache.TryGetValue(filePath, out var existing))
return existing;
var compilation = await compileProjectAsync(getProjectFromFile(filePath)).ConfigureAwait(false);
// Syntax trees are identified with the compilation they're in, so they must be re-retrieved on the new compilation.
syntaxTree = compilation.SyntaxTrees.Single(t => t.FilePath == filePath);
return semanticModelCache[filePath] = compilation.GetSemanticModel(syntaxTree, true);
}
/// <summary>
/// Retrieves the <see cref="Project"/> which contains a given filename as a document.
/// </summary>
/// <param name="fileName">The target filename.</param>
/// <returns>The <see cref="Project"/> that contains <paramref name="fileName"/>.</returns>
private Project getProjectFromFile(string fileName) => solution.Projects.FirstOrDefault(p => p.Documents.Any(d => d.FilePath == fileName));
/// <summary>
/// Retrieves the project which contains the currently-executing test.
/// </summary>
/// <returns>The <see cref="Project"/> containing the currently-executing test.</returns>
private Project findTestProject()
{
var executingAssembly = Assembly.GetEntryAssembly()?.GetName().Name;
return solution.Projects.FirstOrDefault(p => p.AssemblyName == executingAssembly);
}
private void clearCaches()
{
compilationCache.Clear();
semanticModelCache.Clear();
syntaxExclusionMap.Clear();
}
/// <summary>
/// Updates a file in the solution with its new on-disk contents.
/// </summary>
/// <param name="fileName">The file to update.</param>
private void updateFile(string fileName)
{
logger.Add($"Updating file {fileName} in solution...");
var changedDoc = solution.GetDocumentIdsWithFilePath(fileName)[0];
solution = solution.WithDocumentText(changedDoc, SourceText.From(File.ReadAllText(fileName)));
}
/// <summary>
/// Wraps a <see cref="INamedTypeSymbol"/> for stable inter-<see cref="Compilation"/> hashcode and equality comparisons.
/// </summary>
private readonly struct TypeReference : IEquatable<TypeReference>
{
public readonly INamedTypeSymbol Symbol;
public readonly string ContainingNamespace;
public readonly string SymbolName;
public TypeReference(INamedTypeSymbol symbol)
{
Symbol = symbol;
ContainingNamespace = symbol.ContainingNamespace.ToString();
SymbolName = symbol.ToString();
}
public bool Equals(TypeReference other)
=> ContainingNamespace == other.ContainingNamespace
&& SymbolName == other.SymbolName;
public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(SymbolName, StringComparer.Ordinal);
return hash.ToHashCode();
}
public override string ToString() => SymbolName;
public static TypeReference FromSymbol(INamedTypeSymbol symbol) => new TypeReference(symbol);
}
/// <summary>
/// A single node in the directed graph of <see cref="TypeReference"/>s, linked upwards by its parenting <see cref="DirectedTypeNode"/>.
/// </summary>
private class DirectedTypeNode : IEquatable<DirectedTypeNode>
{
public readonly TypeReference Reference;
public readonly List<DirectedTypeNode> Parents = new List<DirectedTypeNode>();
/// <summary>
/// The number of nodes expanded by this <see cref="DirectedTypeNode"/> and all parents recursively.
/// </summary>
public ulong ExpansionFactor;
public DirectedTypeNode(TypeReference reference)
{
Reference = reference;
}
public bool Equals(DirectedTypeNode other)
=> other != null
&& Reference.Equals(other.Reference);
public override int GetHashCode() => Reference.GetHashCode();
public override string ToString() => Reference.ToString();
}
}
}
#endif
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript {
using Microsoft.JScript.Vsa;
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Globalization;
public sealed class FunctionDeclaration : AST{
internal FunctionObject func;
private Member declaringObject = null;
private TypeExpression ifaceId = null;
private String name;
internal bool isMethod;
private bool inFastScope = false;
private JSVariableField field = null;
internal JSProperty enclosingProperty = null;
private Completion completion = new Completion();
internal FunctionDeclaration(Context context, AST ifaceId, IdentifierLiteral id, ParameterDeclaration[] formal_parameters, TypeExpression return_type,
Block body, FunctionScope own_scope, FieldAttributes attributes,
bool isMethod, bool isGetter, bool isSetter, bool isAbstract, bool isFinal, CustomAttributeList customAttributes)
: base(context) {
MethodAttributes methodAttributes = (MethodAttributes)0;
if ((attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public)
methodAttributes = MethodAttributes.Public;
else if ((attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private)
methodAttributes = MethodAttributes.Private;
else if ((attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly)
methodAttributes = MethodAttributes.Assembly;
else if ((attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family)
methodAttributes = MethodAttributes.Family;
else if ((attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem)
methodAttributes = MethodAttributes.FamORAssem;
else
methodAttributes = MethodAttributes.Public;
if ((attributes & FieldAttributes.Static) != 0 || !isMethod)
methodAttributes |= MethodAttributes.Static;
else
methodAttributes |= MethodAttributes.Virtual | MethodAttributes.NewSlot;
if (isAbstract)
methodAttributes |= MethodAttributes.Abstract;
if (isFinal)
methodAttributes |= MethodAttributes.Final;
this.name = id.ToString();
this.isMethod = isMethod;
if (ifaceId != null){
if (isMethod){
this.ifaceId = new TypeExpression(ifaceId);
methodAttributes &= ~MethodAttributes.MemberAccessMask;
methodAttributes |= MethodAttributes.Private|MethodAttributes.Final;
}else{
this.declaringObject = new Member(ifaceId.context, ifaceId, id);
this.name = this.declaringObject.ToString();
}
}
ScriptObject enclosingScope = Globals.ScopeStack.Peek();
if (attributes == 0 && !isAbstract && !isFinal){
if (enclosingScope is ClassScope)
attributes |= FieldAttributes.Public;
}else{
if (!(enclosingScope is ClassScope)){
this.context.HandleError(JSError.NotInsideClass);
attributes = (FieldAttributes)0;
methodAttributes = MethodAttributes.Public;
}
}
if (enclosingScope is ActivationObject){
this.inFastScope = ((ActivationObject)enclosingScope).fast;
// if later on originalName != this.name this is a property getter/setter
String originalName = this.name;
// mangle the name
if (isGetter){
methodAttributes |= MethodAttributes.SpecialName;
this.name = "get_" + this.name;
if (return_type == null)
return_type = new TypeExpression(new ConstantWrapper(Typeob.Object, context));
}else if (isSetter){
methodAttributes |= MethodAttributes.SpecialName;
this.name = "set_" + this.name;
return_type = new TypeExpression(new ConstantWrapper(Typeob.Void, context));
}
attributes &= FieldAttributes.FieldAccessMask;
MethodAttributes access = methodAttributes & MethodAttributes.MemberAccessMask;
if ((methodAttributes & MethodAttributes.Virtual) != (MethodAttributes)0 &&
(methodAttributes & MethodAttributes.Final) == (MethodAttributes)0 &&
(access == MethodAttributes.Private || access == MethodAttributes.Assembly || access == MethodAttributes.FamANDAssem))
methodAttributes |= MethodAttributes.CheckAccessOnOverride;
// create the function object
this.func = new FunctionObject(this.name, formal_parameters, return_type, body, own_scope, enclosingScope, this.context,
methodAttributes, customAttributes, this.isMethod);
if (this.declaringObject != null) return;
// check whether the function name (possibly mangled) is in use already
String fieldName = this.name;
if (this.ifaceId != null) fieldName = ifaceId.ToString()+"."+fieldName;
JSVariableField localField = (JSVariableField)((ActivationObject)enclosingScope).name_table[fieldName];
if (localField != null && (!(localField is JSMemberField) || !(((JSMemberField)localField).value is FunctionObject) || this.func.isExpandoMethod)){
if (originalName != this.name)
localField.originalContext.HandleError(JSError.ClashWithProperty);
else{
id.context.HandleError(JSError.DuplicateName, this.func.isExpandoMethod);
if (localField.value is FunctionObject)
((FunctionObject)localField.value).suppressIL = true;
}
}
// create or update the proper field
if (this.isMethod){
if (!(localField is JSMemberField) || !(((JSMemberField)localField).value is FunctionObject) || originalName != this.name){
this.field = ((ActivationObject)enclosingScope).AddNewField(fieldName, this.func, attributes|FieldAttributes.Literal);
if (originalName == this.name) // if it is a property do not assign the type
((JSVariableField)this.field).type = new TypeExpression(new ConstantWrapper(Typeob.FunctionWrapper, this.context));
}else
this.field = ((JSMemberField)localField).AddOverload(this.func, attributes|FieldAttributes.Literal);
}else if (enclosingScope is FunctionScope){
if (this.inFastScope) attributes |= FieldAttributes.Literal;
this.field = ((FunctionScope)enclosingScope).AddNewField(this.name, attributes, this.func);
if (this.field is JSLocalField){
JSLocalField locField = (JSLocalField)this.field;
if (this.inFastScope){
locField.type = new TypeExpression(new ConstantWrapper(Typeob.ScriptFunction, this.context));
locField.attributeFlags |= FieldAttributes.Literal;
}
locField.debugOn = this.context.document.debugOn;
locField.isDefined = true;
}
}else if (this.inFastScope){
this.field = ((ActivationObject)enclosingScope).AddNewField(this.name, this.func, attributes|FieldAttributes.Literal);
((JSVariableField)this.field).type = new TypeExpression(new ConstantWrapper(Typeob.ScriptFunction, this.context));
//Do not use typeof(Closure) for the field, since that has the arguments and callee properties, which are not
//accessible in fast mode
}else //enclosingScope is GlobalObject
this.field = ((ActivationObject)enclosingScope).AddNewField(this.name, this.func, attributes|FieldAttributes.Static);
((JSVariableField)this.field).originalContext = context;
// if it is a property create/update the PropertyInfo and assign the getter/setter
if (originalName != this.name){
String propertyFieldName = originalName;
if (this.ifaceId != null) propertyFieldName = ifaceId.ToString()+"."+originalName;
FieldInfo prop = (FieldInfo)((ClassScope)enclosingScope).name_table[propertyFieldName];
if (prop != null){
// check whether a property was defined already
if (prop.IsLiteral){
Object val = ((JSVariableField)prop).value;
if (val is JSProperty)
this.enclosingProperty = (JSProperty)val;
}
if (this.enclosingProperty == null)
id.context.HandleError(JSError.DuplicateName, true); // the matching name was not a property
}
if (this.enclosingProperty == null){
this.enclosingProperty = new JSProperty(originalName);
prop = ((ActivationObject)enclosingScope).AddNewField(propertyFieldName, this.enclosingProperty, attributes|FieldAttributes.Literal);
((JSMemberField)prop).originalContext = this.context;
}else{
if ((isGetter && this.enclosingProperty.getter != null) || (isSetter && this.enclosingProperty.setter != null))
id.context.HandleError(JSError.DuplicateName, true); // duplicated setter or getter
}
if (isGetter)
this.enclosingProperty.getter = new JSFieldMethod(this.field, enclosingScope);
else
this.enclosingProperty.setter = new JSFieldMethod(this.field, enclosingScope);
}
}else{ //Might get here if function declaration is inside of an eval.
this.inFastScope = false;
this.func = new FunctionObject(this.name, formal_parameters, return_type, body, own_scope, enclosingScope, this.context, MethodAttributes.Public, null, false);
this.field = ((StackFrame)enclosingScope).AddNewField(this.name, new Closure(this.func), attributes|FieldAttributes.Static);
}
}
internal override Object Evaluate(){
if (this.declaringObject != null)
this.declaringObject.SetValue(this.func);
return this.completion;
}
public static Closure JScriptFunctionDeclaration(RuntimeTypeHandle handle, String name, String method_name, String[] formal_parameters,
JSLocalField[] fields, bool must_save_stack_locals, bool hasArgumentsObject, String text, Object declaringObject, VsaEngine engine){
Type t = Type.GetTypeFromHandle(handle);
FunctionObject func = new FunctionObject(t, name, method_name, formal_parameters, fields, must_save_stack_locals, hasArgumentsObject, text, engine);
return new Closure(func, declaringObject);
}
internal override Context GetFirstExecutableContext(){
return null;
}
internal override AST PartiallyEvaluate(){
if (this.ifaceId != null){
this.ifaceId.PartiallyEvaluate();
this.func.implementedIface = this.ifaceId.ToIReflect();
Type t = this.func.implementedIface as Type;
ClassScope csc = this.func.implementedIface as ClassScope;
if (t != null && !t.IsInterface || csc != null && !csc.owner.isInterface){
this.ifaceId.context.HandleError(JSError.NeedInterface);
this.func.implementedIface = null;
}
if ((this.func.attributes & MethodAttributes.Abstract) != 0)
this.func.funcContext.HandleError(JSError.AbstractCannotBePrivate);
}else if (this.declaringObject != null)
this.declaringObject.PartiallyEvaluateAsCallable();
this.func.PartiallyEvaluate();
if (this.inFastScope && this.func.isExpandoMethod && this.field != null && this.field.type != null)
this.field.type.expression = new ConstantWrapper(Typeob.ScriptFunction, null);
if ((this.func.attributes & MethodAttributes.Abstract) != 0 &&
!((ClassScope)this.func.enclosing_scope).owner.isAbstract){
((ClassScope)this.func.enclosing_scope).owner.attributes |= TypeAttributes.Abstract;
((ClassScope)this.func.enclosing_scope).owner.context.HandleError(JSError.CannotBeAbstract, this.name);
}
if (this.enclosingProperty != null)
if (!this.enclosingProperty.GetterAndSetterAreConsistent())
this.context.HandleError(JSError.GetAndSetAreInconsistent);
return this;
}
private void TranslateToILClosure(ILGenerator il){
if (!this.func.isStatic)
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldtoken, this.func.classwriter != null ? this.func.classwriter : compilerGlobals.classwriter);
il.Emit(OpCodes.Ldstr, this.name);
il.Emit(OpCodes.Ldstr, this.func.GetName());
int n = this.func.formal_parameters.Length;
ConstantWrapper.TranslateToILInt(il, n);
il.Emit(OpCodes.Newarr, Typeob.String);
for (int i = 0; i < n; i++){
il.Emit(OpCodes.Dup);
ConstantWrapper.TranslateToILInt(il, i);
il.Emit(OpCodes.Ldstr, this.func.formal_parameters[i]);
il.Emit(OpCodes.Stelem_Ref);
}
n = this.func.fields.Length;
ConstantWrapper.TranslateToILInt(il, n);
il.Emit(OpCodes.Newarr, Typeob.JSLocalField);
for (int i = 0; i < n; i++){
JSLocalField field = this.func.fields[i];
il.Emit(OpCodes.Dup);
ConstantWrapper.TranslateToILInt(il, i);
il.Emit(OpCodes.Ldstr, field.Name);
il.Emit(OpCodes.Ldtoken, field.FieldType);
ConstantWrapper.TranslateToILInt(il, field.slotNumber);
il.Emit(OpCodes.Newobj, CompilerGlobals.jsLocalFieldConstructor);
il.Emit(OpCodes.Stelem_Ref);
}
if (this.func.must_save_stack_locals)
il.Emit(OpCodes.Ldc_I4_1);
else
il.Emit(OpCodes.Ldc_I4_0);
if (this.func.hasArgumentsObject)
il.Emit(OpCodes.Ldc_I4_1);
else
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ldstr, this.func.ToString());
if (!this.func.isStatic)
il.Emit(OpCodes.Ldarg_0);
else
il.Emit(OpCodes.Ldnull);
this.EmitILToLoadEngine(il);
il.Emit(OpCodes.Call, CompilerGlobals.jScriptFunctionDeclarationMethod);
}
internal override void TranslateToIL(ILGenerator il, Type rtype){
Debug.PreCondition(rtype == Typeob.Void);
return;
}
internal override void TranslateToILInitializer(ILGenerator il){
if (this.func.suppressIL) return;
this.func.TranslateToIL(compilerGlobals);
if (this.declaringObject != null){
this.declaringObject.TranslateToILInitializer(il);
this.declaringObject.TranslateToILPreSet(il);
this.TranslateToILClosure(il);
this.declaringObject.TranslateToILSet(il);
return;
}
Object tok = ((JSVariableField)this.field).metaData;
if (this.func.isMethod){
if (tok is FunctionDeclaration){
((JSVariableField)this.field).metaData = null;
return;
}
this.TranslateToILSourceTextProvider();
return;
}
if (tok == null) return;
this.TranslateToILClosure(il);
if (tok is LocalBuilder)
il.Emit(OpCodes.Stloc, (LocalBuilder)tok);
else if (this.func.isStatic)
il.Emit(OpCodes.Stsfld, (FieldInfo)tok);
else
il.Emit(OpCodes.Stfld, (FieldInfo)tok);
}
private void TranslateToILSourceTextProvider(){
if (this.Engine.doFast) return;
// If the field name doesn't match this name, then don't emit the stub for source
// text provider. The function is a private method impl and there is no way to get
// a handle to the function. i.e. name="Bar", field.name="InterfaceA.Bar"
if (0 != String.Compare(this.name, this.field.Name, StringComparison.Ordinal))
return;
StringBuilder sb = new StringBuilder(this.func.ToString());
JSMemberField mf = ((JSMemberField)this.field).nextOverload;
while (mf != null){
mf.metaData = this;
sb.Append('\n');
sb.Append(mf.value.ToString());
mf = mf.nextOverload;
}
MethodAttributes attr = MethodAttributes.Public|MethodAttributes.Static;
MethodBuilder mb = ((ClassScope)(this.func.enclosing_scope)).GetTypeBuilder().DefineMethod(this.name+" source", attr, Typeob.String, new Type[0]);
ILGenerator il = mb.GetILGenerator();
il.Emit(OpCodes.Ldstr, sb.ToString());
il.Emit(OpCodes.Ret);
}
}
}
| |
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Xunit;
#if AVALONIA_SKIA
namespace Avalonia.Skia.RenderTests
#else
namespace Avalonia.Direct2D1.RenderTests.Controls
#endif
{
public class BorderTests : TestBase
{
public BorderTests()
: base(@"Controls\Border")
{
}
[Fact]
public async Task Border_1px_Border()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(1),
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_2px_Border()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Uniform_CornerRadius()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
CornerRadius = new CornerRadius(16),
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_NonUniform_CornerRadius()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
CornerRadius = new CornerRadius(16, 4, 7, 10),
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Fill()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
Background = Brushes.Red,
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Brush_Offsets_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new Border
{
Background = Brushes.Red,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Padding_Offsets_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Padding = new Thickness(2),
Child = new Border
{
Background = Brushes.Red,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Margin_Offsets_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new Border
{
Background = Brushes.Red,
Margin = new Thickness(2),
}
}
};
await RenderToFile(target);
CompareImages();
}
[Win32Fact("Has text")]
public async Task Border_Centers_Content_Horizontally()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = new FontFamily("Segoe UI"),
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Center,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Win32Fact("Has text")]
public async Task Border_Centers_Content_Vertically()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = new FontFamily("Segoe UI"),
FontSize = 12,
VerticalAlignment = VerticalAlignment.Center,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Stretches_Content_Horizontally()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = new FontFamily("Segoe UI"),
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Stretch,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Stretches_Content_Vertically()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = new FontFamily("Segoe UI"),
FontSize = 12,
VerticalAlignment = VerticalAlignment.Stretch,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Win32Fact("Has text")]
public async Task Border_Left_Aligns_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = new FontFamily("Segoe UI"),
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Left,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Win32Fact("Has text")]
public async Task Border_Right_Aligns_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = new FontFamily("Segoe UI"),
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Right,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Win32Fact("Has text")]
public async Task Border_Top_Aligns_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = new FontFamily("Segoe UI"),
FontSize = 12,
VerticalAlignment = VerticalAlignment.Top,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Win32Fact("Has text")]
public async Task Border_Bottom_Aligns_Content()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = new TextBlock
{
Text = "Foo",
Background = Brushes.Red,
FontFamily = new FontFamily("Segoe UI"),
FontSize = 12,
VerticalAlignment = VerticalAlignment.Bottom,
}
}
};
await RenderToFile(target);
CompareImages();
}
[Fact]
public async Task Border_Nested_Rotate()
{
Decorator target = new Decorator
{
Padding = new Thickness(8),
Width = 200,
Height = 200,
Child = new Border
{
Background = Brushes.Coral,
Width = 100,
Height = 100,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Child = new Border
{
Margin = new Thickness(25),
Background = Brushes.Chocolate,
},
RenderTransform = new RotateTransform(45),
}
};
await RenderToFile(target);
CompareImages();
}
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse;
using OpenMetaverse.Packets;
using NUnit.Framework;
namespace OpenMetaverse.Tests
{
[TestFixture]
public class PacketTests : Assert
{
[Test]
public void HeaderFlags()
{
TestMessagePacket packet = new TestMessagePacket();
packet.Header.AppendedAcks = false;
packet.Header.Reliable = false;
packet.Header.Resent = false;
packet.Header.Zerocoded = false;
Assert.IsFalse(packet.Header.AppendedAcks, "AppendedAcks: Failed to initially set the flag to false");
Assert.IsFalse(packet.Header.Reliable, "Reliable: Failed to initially set the flag to false");
Assert.IsFalse(packet.Header.Resent, "Resent: Failed to initially set the flag to false");
Assert.IsFalse(packet.Header.Zerocoded, "Zerocoded: Failed to initially set the flag to false");
packet.Header.AppendedAcks = false;
packet.Header.Reliable = false;
packet.Header.Resent = false;
packet.Header.Zerocoded = false;
Assert.IsFalse(packet.Header.AppendedAcks, "AppendedAcks: Failed to set the flag to false a second time");
Assert.IsFalse(packet.Header.Reliable, "Reliable: Failed to set the flag to false a second time");
Assert.IsFalse(packet.Header.Resent, "Resent: Failed to set the flag to false a second time");
Assert.IsFalse(packet.Header.Zerocoded, "Zerocoded: Failed to set the flag to false a second time");
packet.Header.AppendedAcks = true;
packet.Header.Reliable = true;
packet.Header.Resent = true;
packet.Header.Zerocoded = true;
Assert.IsTrue(packet.Header.AppendedAcks, "AppendedAcks: Failed to set the flag to true");
Assert.IsTrue(packet.Header.Reliable, "Reliable: Failed to set the flag to true");
Assert.IsTrue(packet.Header.Resent, "Resent: Failed to set the flag to true");
Assert.IsTrue(packet.Header.Zerocoded, "Zerocoded: Failed to set the flag to true");
packet.Header.AppendedAcks = true;
packet.Header.Reliable = true;
packet.Header.Resent = true;
packet.Header.Zerocoded = true;
Assert.IsTrue(packet.Header.AppendedAcks, "AppendedAcks: Failed to set the flag to true a second time");
Assert.IsTrue(packet.Header.Reliable, "Reliable: Failed to set the flag to true a second time");
Assert.IsTrue(packet.Header.Resent, "Resent: Failed to set the flag to true a second time");
Assert.IsTrue(packet.Header.Zerocoded, "Zerocoded: Failed to set the flag to true a second time");
packet.Header.AppendedAcks = false;
packet.Header.Reliable = false;
packet.Header.Resent = false;
packet.Header.Zerocoded = false;
Assert.IsFalse(packet.Header.AppendedAcks, "AppendedAcks: Failed to set the flag back to false");
Assert.IsFalse(packet.Header.Reliable, "Reliable: Failed to set the flag back to false");
Assert.IsFalse(packet.Header.Resent, "Resent: Failed to set the flag back to false");
Assert.IsFalse(packet.Header.Zerocoded, "Zerocoded: Failed to set the flag back to false");
}
[Test]
public void ToBytesMultiple()
{
UUID testID = UUID.Random();
DirPlacesReplyPacket bigPacket = new DirPlacesReplyPacket();
bigPacket.Header.Zerocoded = false;
bigPacket.Header.Sequence = 42;
bigPacket.Header.AppendedAcks = true;
bigPacket.Header.AckList = new uint[50];
for (int i = 0; i < bigPacket.Header.AckList.Length; i++) { bigPacket.Header.AckList[i] = (uint)i; }
bigPacket.AgentData.AgentID = testID;
bigPacket.QueryData = new DirPlacesReplyPacket.QueryDataBlock[100];
for (int i = 0; i < bigPacket.QueryData.Length; i++)
{
bigPacket.QueryData[i] = new DirPlacesReplyPacket.QueryDataBlock();
bigPacket.QueryData[i].QueryID = testID;
}
bigPacket.QueryReplies = new DirPlacesReplyPacket.QueryRepliesBlock[100];
for (int i = 0; i < bigPacket.QueryReplies.Length; i++)
{
bigPacket.QueryReplies[i] = new DirPlacesReplyPacket.QueryRepliesBlock();
bigPacket.QueryReplies[i].Auction = (i & 1) == 0;
bigPacket.QueryReplies[i].Dwell = (float)i;
bigPacket.QueryReplies[i].ForSale = (i & 1) == 0;
bigPacket.QueryReplies[i].Name = Utils.StringToBytes("DirPlacesReply Test String");
bigPacket.QueryReplies[i].ParcelID = testID;
}
bigPacket.StatusData = new DirPlacesReplyPacket.StatusDataBlock[100];
for (int i = 0; i < bigPacket.StatusData.Length; i++)
{
bigPacket.StatusData[i] = new DirPlacesReplyPacket.StatusDataBlock();
bigPacket.StatusData[i].Status = (uint)i;
}
byte[][] splitPackets = bigPacket.ToBytesMultiple();
int queryDataCount = 0;
int queryRepliesCount = 0;
int statusDataCount = 0;
for (int i = 0; i < splitPackets.Length; i++)
{
byte[] packetData = splitPackets[i];
int len = packetData.Length - 1;
DirPlacesReplyPacket packet = (DirPlacesReplyPacket)Packet.BuildPacket(packetData, ref len, packetData);
Assert.IsTrue(packet.AgentData.AgentID == bigPacket.AgentData.AgentID);
for (int j = 0; j < packet.QueryReplies.Length; j++)
{
Assert.IsTrue(packet.QueryReplies[j].Dwell == (float)(queryRepliesCount + j),
"Expected Dwell of " + (float)(queryRepliesCount + j) + " but got " + packet.QueryReplies[j].Dwell);
Assert.IsTrue(packet.QueryReplies[j].ParcelID == testID);
}
queryDataCount += packet.QueryData.Length;
queryRepliesCount += packet.QueryReplies.Length;
statusDataCount += packet.StatusData.Length;
}
Assert.IsTrue(queryDataCount == bigPacket.QueryData.Length);
Assert.IsTrue(queryRepliesCount == bigPacket.QueryData.Length);
Assert.IsTrue(statusDataCount == bigPacket.StatusData.Length);
ScriptDialogPacket scriptDialogPacket = new ScriptDialogPacket();
scriptDialogPacket.Data.ChatChannel = 0;
scriptDialogPacket.Data.FirstName = Utils.EmptyBytes;
scriptDialogPacket.Data.ImageID = UUID.Zero;
scriptDialogPacket.Data.LastName = Utils.EmptyBytes;
scriptDialogPacket.Data.Message = Utils.EmptyBytes;
scriptDialogPacket.Data.ObjectID = UUID.Zero;
scriptDialogPacket.Data.ObjectName = Utils.EmptyBytes;
scriptDialogPacket.Buttons = new ScriptDialogPacket.ButtonsBlock[0];
byte[][] splitPacket = scriptDialogPacket.ToBytesMultiple();
Assert.IsNotNull(splitPacket);
Assert.IsTrue(splitPacket.Length == 1, "Expected ScriptDialog packet to split into 1 packet but got " + splitPacket.Length);
ParcelReturnObjectsPacket proPacket = new ParcelReturnObjectsPacket();
proPacket.AgentData.AgentID = UUID.Zero;
proPacket.AgentData.SessionID = UUID.Zero;
proPacket.ParcelData.LocalID = 0;
proPacket.ParcelData.ReturnType = 0;
proPacket.TaskIDs = new ParcelReturnObjectsPacket.TaskIDsBlock[0];
proPacket.OwnerIDs = new ParcelReturnObjectsPacket.OwnerIDsBlock[1];
proPacket.OwnerIDs[0] = new ParcelReturnObjectsPacket.OwnerIDsBlock();
proPacket.OwnerIDs[0].OwnerID = UUID.Zero;
splitPacket = proPacket.ToBytesMultiple();
Assert.IsNotNull(splitPacket);
Assert.IsTrue(splitPacket.Length == 1, "Expected ParcelReturnObjectsPacket packet to split into 1 packet but got " + splitPacket.Length);
InventoryDescendentsPacket invPacket = new InventoryDescendentsPacket();
invPacket.FolderData = new InventoryDescendentsPacket.FolderDataBlock[1];
invPacket.FolderData[0] = new InventoryDescendentsPacket.FolderDataBlock();
invPacket.FolderData[0].Name = Utils.EmptyBytes;
invPacket.ItemData = new InventoryDescendentsPacket.ItemDataBlock[5];
for (int i = 0; i < 5; i++)
{
invPacket.ItemData[i] = new InventoryDescendentsPacket.ItemDataBlock();
invPacket.ItemData[i].Description = Utils.StringToBytes("Unit Test Item Description");
invPacket.ItemData[i].Name = Utils.StringToBytes("Unit Test Item Name");
}
splitPacket = invPacket.ToBytesMultiple();
Assert.IsNotNull(splitPacket);
Assert.IsTrue(splitPacket.Length == 1, "Split InventoryDescendents packet into " + splitPacket.Length + " instead of 1 packet");
int x = 0;
int y = splitPacket[0].Length - 1;
invPacket.FromBytes(splitPacket[0], ref x, ref y, null);
Assert.IsTrue(invPacket.FolderData.Length == 1, "InventoryDescendents packet came back with " + invPacket.FolderData.Length + " FolderData blocks");
Assert.IsTrue(invPacket.ItemData.Length == 5, "InventoryDescendents packet came back with " + invPacket.ItemData.Length + " ItemData blocks");
}
[Test]
public void TickCountResolution()
{
float minResolution = Single.MaxValue;
float maxResolution = Single.MinValue;
// Measure the resolution of Environment.TickCount
float tickCountResolution = 0f;
for (int i = 0; i < 10; i++)
{
int start = Environment.TickCount;
int now = start;
while (now == start)
now = Environment.TickCount;
float resolution = (float)(now - start);
tickCountResolution += tickCountResolution * 0.1f;
minResolution = Math.Min(minResolution, resolution);
maxResolution = Math.Max(maxResolution, resolution);
}
Console.WriteLine("Average Environment.TickCount resolution: " + tickCountResolution + "ms");
Assert.Less(maxResolution - minResolution, 10f, "Environment.TickCount resolution fluctuated between " +
minResolution + "ms and " + maxResolution + "ms");
}
}
}
| |
namespace KabMan.Client
{
partial class NewSwitch
{
/// <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 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.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.LookUpLcUrmStartNo = new DevExpress.XtraEditors.LookUpEdit();
this.txtCountLcUrm = new DevExpress.XtraEditors.TextEdit();
this.CBoxLcUrmMeter = new DevExpress.XtraEditors.ComboBoxEdit();
this.txtIPNO4 = new DevExpress.XtraEditors.TextEdit();
this.txtIPNO3 = new DevExpress.XtraEditors.TextEdit();
this.LookUpBlechType = new DevExpress.XtraEditors.LookUpEdit();
this.BtnCreateVTPort = new DevExpress.XtraEditors.SimpleButton();
this.LookUpVTPort = new DevExpress.XtraEditors.LookUpEdit();
this.BtnCancel = new DevExpress.XtraEditors.SimpleButton();
this.txtIPNO2 = new DevExpress.XtraEditors.TextEdit();
this.txtIpNo = new DevExpress.XtraEditors.TextEdit();
this.BtnCreateBlech = new DevExpress.XtraEditors.SimpleButton();
this.LookUpBlech = new DevExpress.XtraEditors.LookUpEdit();
this.LookUpRoom = new DevExpress.XtraEditors.LookUpEdit();
this.LookUpSwitchModel = new DevExpress.XtraEditors.LookUpEdit();
this.txtSerialNo = new DevExpress.XtraEditors.TextEdit();
this.LookUpSwitchType = new DevExpress.XtraEditors.LookUpEdit();
this.LookUpSan = new DevExpress.XtraEditors.LookUpEdit();
this.LookUpLocation = new DevExpress.XtraEditors.LookUpEdit();
this.LookUpCoreSwitch = new DevExpress.XtraEditors.LookUpEdit();
this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem7 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem10 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem();
this.emptySpaceItem4 = new DevExpress.XtraLayout.EmptySpaceItem();
this.layoutControlItem11 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem12 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem13 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem9 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem14 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem15 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem16 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem17 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem18 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem8 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem19 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem20 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem21 = new DevExpress.XtraLayout.LayoutControlItem();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.LookUpLcUrmStartNo.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtCountLcUrm.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CBoxLcUrmMeter.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtIPNO4.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtIPNO3.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpBlechType.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpVTPort.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtIPNO2.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtIpNo.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpBlech.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpRoom.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpSwitchModel.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtSerialNo.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpSwitchType.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpSan.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpLocation.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpCoreSwitch.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem7)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem10)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem11)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem12)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem13)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem14)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem15)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem16)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem17)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem18)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem8)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem19)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem20)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem21)).BeginInit();
this.SuspendLayout();
//
// layoutControl1
//
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.LookUpLcUrmStartNo);
this.layoutControl1.Controls.Add(this.txtCountLcUrm);
this.layoutControl1.Controls.Add(this.CBoxLcUrmMeter);
this.layoutControl1.Controls.Add(this.txtIPNO4);
this.layoutControl1.Controls.Add(this.txtIPNO3);
this.layoutControl1.Controls.Add(this.LookUpBlechType);
this.layoutControl1.Controls.Add(this.BtnCreateVTPort);
this.layoutControl1.Controls.Add(this.LookUpVTPort);
this.layoutControl1.Controls.Add(this.BtnCancel);
this.layoutControl1.Controls.Add(this.txtIPNO2);
this.layoutControl1.Controls.Add(this.txtIpNo);
this.layoutControl1.Controls.Add(this.BtnCreateBlech);
this.layoutControl1.Controls.Add(this.LookUpBlech);
this.layoutControl1.Controls.Add(this.LookUpRoom);
this.layoutControl1.Controls.Add(this.LookUpSwitchModel);
this.layoutControl1.Controls.Add(this.txtSerialNo);
this.layoutControl1.Controls.Add(this.LookUpSwitchType);
this.layoutControl1.Controls.Add(this.LookUpSan);
this.layoutControl1.Controls.Add(this.LookUpLocation);
this.layoutControl1.Controls.Add(this.LookUpCoreSwitch);
this.layoutControl1.Controls.Add(this.simpleButton1);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.Location = new System.Drawing.Point(0, 0);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
this.layoutControl1.Size = new System.Drawing.Size(398, 411);
this.layoutControl1.TabIndex = 0;
this.layoutControl1.Text = "layoutControl1";
//
// LookUpLcUrmStartNo
//
this.LookUpLcUrmStartNo.Location = new System.Drawing.Point(129, 352);
this.LookUpLcUrmStartNo.Name = "LookUpLcUrmStartNo";
this.LookUpLcUrmStartNo.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.LookUpLcUrmStartNo.Size = new System.Drawing.Size(263, 20);
this.LookUpLcUrmStartNo.StyleController = this.layoutControl1;
this.LookUpLcUrmStartNo.TabIndex = 1;
//
// txtCountLcUrm
//
this.txtCountLcUrm.Location = new System.Drawing.Point(342, 321);
this.txtCountLcUrm.Name = "txtCountLcUrm";
this.txtCountLcUrm.Size = new System.Drawing.Size(50, 20);
this.txtCountLcUrm.StyleController = this.layoutControl1;
this.txtCountLcUrm.TabIndex = 1;
//
// CBoxLcUrmMeter
//
this.CBoxLcUrmMeter.Location = new System.Drawing.Point(129, 321);
this.CBoxLcUrmMeter.Name = "CBoxLcUrmMeter";
this.CBoxLcUrmMeter.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.CBoxLcUrmMeter.Properties.Items.AddRange(new object[] {
"2",
"3",
"4"});
this.CBoxLcUrmMeter.Size = new System.Drawing.Size(80, 20);
this.CBoxLcUrmMeter.StyleController = this.layoutControl1;
this.CBoxLcUrmMeter.TabIndex = 1;
this.CBoxLcUrmMeter.SelectedIndexChanged += new System.EventHandler(this.CBoxLcUrmMeter_SelectedIndexChanged);
//
// txtIPNO4
//
this.txtIPNO4.Location = new System.Drawing.Point(332, 290);
this.txtIPNO4.Name = "txtIPNO4";
this.txtIPNO4.Size = new System.Drawing.Size(60, 20);
this.txtIPNO4.StyleController = this.layoutControl1;
this.txtIPNO4.TabIndex = 1;
//
// txtIPNO3
//
this.txtIPNO3.Location = new System.Drawing.Point(262, 290);
this.txtIPNO3.Name = "txtIPNO3";
this.txtIPNO3.Size = new System.Drawing.Size(59, 20);
this.txtIPNO3.StyleController = this.layoutControl1;
this.txtIPNO3.TabIndex = 1;
//
// LookUpBlechType
//
this.LookUpBlechType.Location = new System.Drawing.Point(129, 195);
this.LookUpBlechType.Name = "LookUpBlechType";
this.LookUpBlechType.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.LookUpBlechType.Properties.NullText = "Select to Blech Type!";
this.LookUpBlechType.Size = new System.Drawing.Size(263, 20);
this.LookUpBlechType.StyleController = this.layoutControl1;
this.LookUpBlechType.TabIndex = 1;
this.LookUpBlechType.EditValueChanged += new System.EventHandler(this.LookUpBlechType_EditValueChanged);
//
// BtnCreateVTPort
//
this.BtnCreateVTPort.Location = new System.Drawing.Point(304, 100);
this.BtnCreateVTPort.Name = "BtnCreateVTPort";
this.BtnCreateVTPort.Size = new System.Drawing.Size(88, 22);
this.BtnCreateVTPort.StyleController = this.layoutControl1;
this.BtnCreateVTPort.TabIndex = 1;
this.BtnCreateVTPort.Text = "Create VT Port";
this.BtnCreateVTPort.Click += new System.EventHandler(this.BtnCreateVTPort_Click);
//
// LookUpVTPort
//
this.LookUpVTPort.Location = new System.Drawing.Point(129, 100);
this.LookUpVTPort.Name = "LookUpVTPort";
this.LookUpVTPort.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.LookUpVTPort.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "Name", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.LookUpVTPort.Properties.NullText = "Select to VT Port!";
this.LookUpVTPort.Size = new System.Drawing.Size(164, 20);
this.LookUpVTPort.StyleController = this.layoutControl1;
this.LookUpVTPort.TabIndex = 1;
//
// BtnCancel
//
this.BtnCancel.Appearance.BackColor = System.Drawing.SystemColors.ButtonFace;
this.BtnCancel.Appearance.BackColor2 = System.Drawing.SystemColors.ButtonHighlight;
this.BtnCancel.Appearance.BorderColor = System.Drawing.Color.DimGray;
this.BtnCancel.Appearance.Options.UseBackColor = true;
this.BtnCancel.Appearance.Options.UseBorderColor = true;
this.BtnCancel.Appearance.Options.UseForeColor = true;
this.BtnCancel.Location = new System.Drawing.Point(291, 383);
this.BtnCancel.Name = "BtnCancel";
this.BtnCancel.Size = new System.Drawing.Size(101, 22);
this.BtnCancel.StyleController = this.layoutControl1;
this.BtnCancel.TabIndex = 1;
this.BtnCancel.Text = "Cancel";
this.BtnCancel.Click += new System.EventHandler(this.BtnCancel_Click);
//
// txtIPNO2
//
this.txtIPNO2.Location = new System.Drawing.Point(190, 290);
this.txtIPNO2.Name = "txtIPNO2";
this.txtIPNO2.Size = new System.Drawing.Size(61, 20);
this.txtIPNO2.StyleController = this.layoutControl1;
this.txtIPNO2.TabIndex = 5;
//
// txtIpNo
//
this.txtIpNo.Location = new System.Drawing.Point(129, 290);
this.txtIpNo.Name = "txtIpNo";
this.txtIpNo.Size = new System.Drawing.Size(50, 20);
this.txtIpNo.StyleController = this.layoutControl1;
this.txtIpNo.TabIndex = 1;
//
// BtnCreateBlech
//
this.BtnCreateBlech.Location = new System.Drawing.Point(304, 226);
this.BtnCreateBlech.Name = "BtnCreateBlech";
this.BtnCreateBlech.Size = new System.Drawing.Size(88, 22);
this.BtnCreateBlech.StyleController = this.layoutControl1;
this.BtnCreateBlech.TabIndex = 1;
this.BtnCreateBlech.Text = "Create Blech";
this.BtnCreateBlech.Click += new System.EventHandler(this.BtnCreateBlech_Click);
//
// LookUpBlech
//
this.LookUpBlech.EditValue = "<Null>";
this.LookUpBlech.Location = new System.Drawing.Point(129, 226);
this.LookUpBlech.Name = "LookUpBlech";
this.LookUpBlech.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.LookUpBlech.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "Name", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.LookUpBlech.Properties.NullText = "Select to Blech!";
this.LookUpBlech.Size = new System.Drawing.Size(164, 20);
this.LookUpBlech.StyleController = this.layoutControl1;
this.LookUpBlech.TabIndex = 1;
//
// LookUpRoom
//
this.LookUpRoom.EditValue = "<Null>";
this.LookUpRoom.Location = new System.Drawing.Point(129, 38);
this.LookUpRoom.Name = "LookUpRoom";
this.LookUpRoom.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.LookUpRoom.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("RoomName", "Room", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.LookUpRoom.Properties.NullText = "Select to Data Center!";
this.LookUpRoom.Size = new System.Drawing.Size(263, 20);
this.LookUpRoom.StyleController = this.layoutControl1;
this.LookUpRoom.TabIndex = 1;
this.LookUpRoom.Tag = "";
//
// LookUpSwitchModel
//
this.LookUpSwitchModel.Location = new System.Drawing.Point(129, 164);
this.LookUpSwitchModel.Name = "LookUpSwitchModel";
this.LookUpSwitchModel.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.LookUpSwitchModel.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "Switch Model", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None),
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Port", "Port Count", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.LookUpSwitchModel.Properties.NullText = "Select to Switch Model!";
this.LookUpSwitchModel.Size = new System.Drawing.Size(263, 20);
this.LookUpSwitchModel.StyleController = this.layoutControl1;
this.LookUpSwitchModel.TabIndex = 1;
this.LookUpSwitchModel.EditValueChanged += new System.EventHandler(this.LookUpSwitchModel_EditValueChanged);
//
// txtSerialNo
//
this.txtSerialNo.Location = new System.Drawing.Point(129, 259);
this.txtSerialNo.Name = "txtSerialNo";
this.txtSerialNo.Size = new System.Drawing.Size(263, 20);
this.txtSerialNo.StyleController = this.layoutControl1;
this.txtSerialNo.TabIndex = 1;
//
// LookUpSwitchType
//
this.LookUpSwitchType.Location = new System.Drawing.Point(129, 133);
this.LookUpSwitchType.Name = "LookUpSwitchType";
this.LookUpSwitchType.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.LookUpSwitchType.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Type", "Switch Type", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.LookUpSwitchType.Properties.NullText = "Select to Switch Type!";
this.LookUpSwitchType.Size = new System.Drawing.Size(80, 20);
this.LookUpSwitchType.StyleController = this.layoutControl1;
this.LookUpSwitchType.TabIndex = 1;
this.LookUpSwitchType.EditValueChanged += new System.EventHandler(this.LookUpSwitchType_EditValueChanged);
//
// LookUpSan
//
this.LookUpSan.Location = new System.Drawing.Point(129, 69);
this.LookUpSan.Name = "LookUpSan";
this.LookUpSan.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.LookUpSan.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("San", "SAN", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.LookUpSan.Properties.NullText = "Select to SAN!";
this.LookUpSan.Size = new System.Drawing.Size(263, 20);
this.LookUpSan.StyleController = this.layoutControl1;
this.LookUpSan.TabIndex = 1;
this.LookUpSan.Tag = "";
this.LookUpSan.EditValueChanged += new System.EventHandler(this.LookUpSan_EditValueChanged);
//
// LookUpLocation
//
this.LookUpLocation.Location = new System.Drawing.Point(129, 7);
this.LookUpLocation.Name = "LookUpLocation";
this.LookUpLocation.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.LookUpLocation.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("LocationName", "Location", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None),
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("LocationCoord", "Coordinate", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.LookUpLocation.Properties.NullText = "Select to Location!";
this.LookUpLocation.Size = new System.Drawing.Size(263, 20);
this.LookUpLocation.StyleController = this.layoutControl1;
this.LookUpLocation.TabIndex = 4;
this.LookUpLocation.Tag = "";
this.LookUpLocation.EditValueChanged += new System.EventHandler(this.LookUpLocation_EditValueChanged);
//
// LookUpCoreSwitch
//
this.LookUpCoreSwitch.EditValue = "";
this.LookUpCoreSwitch.Location = new System.Drawing.Point(342, 133);
this.LookUpCoreSwitch.Name = "LookUpCoreSwitch";
this.LookUpCoreSwitch.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.LookUpCoreSwitch.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("SwName", "Switch Name", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.LookUpCoreSwitch.Size = new System.Drawing.Size(50, 20);
this.LookUpCoreSwitch.StyleController = this.layoutControl1;
this.LookUpCoreSwitch.TabIndex = 1;
this.LookUpCoreSwitch.EditValueChanged += new System.EventHandler(this.LookUpCoreSwitch_EditValueChanged);
//
// simpleButton1
//
this.simpleButton1.Appearance.BackColor = System.Drawing.SystemColors.ButtonFace;
this.simpleButton1.Appearance.BackColor2 = System.Drawing.SystemColors.ButtonHighlight;
this.simpleButton1.Appearance.BorderColor = System.Drawing.Color.DimGray;
this.simpleButton1.Appearance.Options.UseBackColor = true;
this.simpleButton1.Appearance.Options.UseBorderColor = true;
this.simpleButton1.Appearance.Options.UseForeColor = true;
this.simpleButton1.Location = new System.Drawing.Point(187, 383);
this.simpleButton1.Name = "simpleButton1";
this.simpleButton1.Size = new System.Drawing.Size(93, 22);
this.simpleButton1.StyleController = this.layoutControl1;
this.simpleButton1.TabIndex = 1;
this.simpleButton1.Text = "Save";
this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click);
//
// layoutControlGroup1
//
this.layoutControlGroup1.CustomizationFormText = "Root";
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem3,
this.layoutControlItem1,
this.layoutControlItem4,
this.layoutControlItem6,
this.layoutControlItem7,
this.layoutControlItem2,
this.layoutControlItem10,
this.layoutControlItem5,
this.emptySpaceItem4,
this.layoutControlItem11,
this.layoutControlItem12,
this.layoutControlItem13,
this.layoutControlItem9,
this.layoutControlItem14,
this.layoutControlItem15,
this.layoutControlItem16,
this.layoutControlItem17,
this.layoutControlItem18,
this.layoutControlItem8,
this.layoutControlItem19,
this.layoutControlItem20,
this.layoutControlItem21});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "Root";
this.layoutControlGroup1.Size = new System.Drawing.Size(398, 411);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.Text = "Root";
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem3
//
this.layoutControlItem3.Control = this.LookUpSan;
this.layoutControlItem3.CustomizationFormText = "SAN :";
this.layoutControlItem3.Location = new System.Drawing.Point(0, 62);
this.layoutControlItem3.Name = "layoutControlItem3";
this.layoutControlItem3.Size = new System.Drawing.Size(396, 31);
this.layoutControlItem3.Text = "SAN :";
this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem3.TextSize = new System.Drawing.Size(117, 20);
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.LookUpLocation;
this.layoutControlItem1.CustomizationFormText = "Location :";
this.layoutControlItem1.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(396, 31);
this.layoutControlItem1.Text = "Location :";
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(117, 20);
//
// layoutControlItem4
//
this.layoutControlItem4.Control = this.LookUpSwitchType;
this.layoutControlItem4.CustomizationFormText = "Switch Type :";
this.layoutControlItem4.Location = new System.Drawing.Point(0, 126);
this.layoutControlItem4.Name = "layoutControlItem4";
this.layoutControlItem4.Size = new System.Drawing.Size(213, 31);
this.layoutControlItem4.Text = "Switch Type :";
this.layoutControlItem4.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem4.TextSize = new System.Drawing.Size(117, 20);
//
// layoutControlItem6
//
this.layoutControlItem6.Control = this.txtSerialNo;
this.layoutControlItem6.CustomizationFormText = "Serial Number :";
this.layoutControlItem6.Location = new System.Drawing.Point(0, 252);
this.layoutControlItem6.Name = "layoutControlItem6";
this.layoutControlItem6.Size = new System.Drawing.Size(396, 31);
this.layoutControlItem6.Text = "Serial Number :";
this.layoutControlItem6.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem6.TextSize = new System.Drawing.Size(117, 20);
//
// layoutControlItem7
//
this.layoutControlItem7.Control = this.LookUpSwitchModel;
this.layoutControlItem7.CustomizationFormText = "Switch Model :";
this.layoutControlItem7.Location = new System.Drawing.Point(0, 157);
this.layoutControlItem7.Name = "layoutControlItem7";
this.layoutControlItem7.Size = new System.Drawing.Size(396, 31);
this.layoutControlItem7.Text = "Switch Model :";
this.layoutControlItem7.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem7.TextSize = new System.Drawing.Size(117, 20);
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.LookUpRoom;
this.layoutControlItem2.CustomizationFormText = "Room :";
this.layoutControlItem2.Location = new System.Drawing.Point(0, 31);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(396, 31);
this.layoutControlItem2.Text = "Data Center :";
this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem2.TextSize = new System.Drawing.Size(117, 20);
//
// layoutControlItem10
//
this.layoutControlItem10.Control = this.txtIpNo;
this.layoutControlItem10.CustomizationFormText = "Ip No :";
this.layoutControlItem10.Location = new System.Drawing.Point(0, 283);
this.layoutControlItem10.Name = "layoutControlItem10";
this.layoutControlItem10.Size = new System.Drawing.Size(183, 31);
this.layoutControlItem10.Text = "IP Nr.";
this.layoutControlItem10.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem10.TextSize = new System.Drawing.Size(117, 20);
//
// layoutControlItem5
//
this.layoutControlItem5.ContentVisible = false;
this.layoutControlItem5.Control = this.LookUpCoreSwitch;
this.layoutControlItem5.CustomizationFormText = "Core Switch :";
this.layoutControlItem5.Location = new System.Drawing.Point(213, 126);
this.layoutControlItem5.Name = "layoutControlItem5";
this.layoutControlItem5.Size = new System.Drawing.Size(183, 31);
this.layoutControlItem5.Text = "Core Switch :";
this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem5.TextSize = new System.Drawing.Size(117, 20);
//
// emptySpaceItem4
//
this.emptySpaceItem4.CustomizationFormText = "emptySpaceItem4";
this.emptySpaceItem4.Location = new System.Drawing.Point(0, 376);
this.emptySpaceItem4.Name = "emptySpaceItem4";
this.emptySpaceItem4.Size = new System.Drawing.Size(180, 33);
this.emptySpaceItem4.Text = "emptySpaceItem4";
this.emptySpaceItem4.TextSize = new System.Drawing.Size(0, 0);
//
// layoutControlItem11
//
this.layoutControlItem11.Control = this.BtnCancel;
this.layoutControlItem11.CustomizationFormText = "layoutControlItem11";
this.layoutControlItem11.Location = new System.Drawing.Point(284, 376);
this.layoutControlItem11.Name = "layoutControlItem11";
this.layoutControlItem11.Size = new System.Drawing.Size(112, 33);
this.layoutControlItem11.Text = "layoutControlItem11";
this.layoutControlItem11.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem11.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem11.TextToControlDistance = 0;
this.layoutControlItem11.TextVisible = false;
//
// layoutControlItem12
//
this.layoutControlItem12.Control = this.LookUpVTPort;
this.layoutControlItem12.CustomizationFormText = "VT Port :";
this.layoutControlItem12.Location = new System.Drawing.Point(0, 93);
this.layoutControlItem12.Name = "layoutControlItem12";
this.layoutControlItem12.Size = new System.Drawing.Size(297, 33);
this.layoutControlItem12.Text = "VT Port :";
this.layoutControlItem12.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem12.TextSize = new System.Drawing.Size(117, 20);
//
// layoutControlItem13
//
this.layoutControlItem13.Control = this.BtnCreateVTPort;
this.layoutControlItem13.CustomizationFormText = "layoutControlItem13";
this.layoutControlItem13.Location = new System.Drawing.Point(297, 93);
this.layoutControlItem13.Name = "layoutControlItem13";
this.layoutControlItem13.Size = new System.Drawing.Size(99, 33);
this.layoutControlItem13.Text = "layoutControlItem13";
this.layoutControlItem13.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem13.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem13.TextToControlDistance = 0;
this.layoutControlItem13.TextVisible = false;
//
// layoutControlItem9
//
this.layoutControlItem9.Control = this.LookUpBlech;
this.layoutControlItem9.CustomizationFormText = "Blech :";
this.layoutControlItem9.Location = new System.Drawing.Point(0, 219);
this.layoutControlItem9.Name = "layoutControlItem9";
this.layoutControlItem9.Size = new System.Drawing.Size(297, 33);
this.layoutControlItem9.Text = "Blech :";
this.layoutControlItem9.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem9.TextSize = new System.Drawing.Size(117, 20);
//
// layoutControlItem14
//
this.layoutControlItem14.Control = this.BtnCreateBlech;
this.layoutControlItem14.CustomizationFormText = "layoutControlItem14";
this.layoutControlItem14.Location = new System.Drawing.Point(297, 219);
this.layoutControlItem14.Name = "layoutControlItem14";
this.layoutControlItem14.Size = new System.Drawing.Size(99, 33);
this.layoutControlItem14.Text = "layoutControlItem14";
this.layoutControlItem14.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem14.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem14.TextToControlDistance = 0;
this.layoutControlItem14.TextVisible = false;
//
// layoutControlItem15
//
this.layoutControlItem15.Control = this.LookUpBlechType;
this.layoutControlItem15.CustomizationFormText = "Blech Type :";
this.layoutControlItem15.Location = new System.Drawing.Point(0, 188);
this.layoutControlItem15.Name = "layoutControlItem15";
this.layoutControlItem15.Size = new System.Drawing.Size(396, 31);
this.layoutControlItem15.Text = "Blech Type :";
this.layoutControlItem15.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem15.TextSize = new System.Drawing.Size(117, 20);
//
// layoutControlItem16
//
this.layoutControlItem16.Control = this.txtIPNO2;
this.layoutControlItem16.CustomizationFormText = "layoutControlItem16";
this.layoutControlItem16.Location = new System.Drawing.Point(183, 283);
this.layoutControlItem16.Name = "layoutControlItem16";
this.layoutControlItem16.Size = new System.Drawing.Size(72, 31);
this.layoutControlItem16.Text = "layoutControlItem16";
this.layoutControlItem16.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem16.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem16.TextToControlDistance = 0;
this.layoutControlItem16.TextVisible = false;
//
// layoutControlItem17
//
this.layoutControlItem17.Control = this.txtIPNO3;
this.layoutControlItem17.CustomizationFormText = "layoutControlItem17";
this.layoutControlItem17.Location = new System.Drawing.Point(255, 283);
this.layoutControlItem17.Name = "layoutControlItem17";
this.layoutControlItem17.Size = new System.Drawing.Size(70, 31);
this.layoutControlItem17.Text = "layoutControlItem17";
this.layoutControlItem17.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem17.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem17.TextToControlDistance = 0;
this.layoutControlItem17.TextVisible = false;
//
// layoutControlItem18
//
this.layoutControlItem18.Control = this.txtIPNO4;
this.layoutControlItem18.CustomizationFormText = "layoutControlItem18";
this.layoutControlItem18.Location = new System.Drawing.Point(325, 283);
this.layoutControlItem18.Name = "layoutControlItem18";
this.layoutControlItem18.Size = new System.Drawing.Size(71, 31);
this.layoutControlItem18.Text = "layoutControlItem18";
this.layoutControlItem18.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem18.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem18.TextToControlDistance = 0;
this.layoutControlItem18.TextVisible = false;
//
// layoutControlItem8
//
this.layoutControlItem8.Control = this.simpleButton1;
this.layoutControlItem8.CustomizationFormText = "layoutControlItem8";
this.layoutControlItem8.Location = new System.Drawing.Point(180, 376);
this.layoutControlItem8.Name = "layoutControlItem8";
this.layoutControlItem8.Size = new System.Drawing.Size(104, 33);
this.layoutControlItem8.Text = "layoutControlItem8";
this.layoutControlItem8.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem8.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem8.TextToControlDistance = 0;
this.layoutControlItem8.TextVisible = false;
//
// layoutControlItem19
//
this.layoutControlItem19.Control = this.CBoxLcUrmMeter;
this.layoutControlItem19.CustomizationFormText = "LC URM Cable Meter :";
this.layoutControlItem19.Location = new System.Drawing.Point(0, 314);
this.layoutControlItem19.Name = "layoutControlItem19";
this.layoutControlItem19.Size = new System.Drawing.Size(213, 31);
this.layoutControlItem19.Text = "LC URM Cable Meter :";
this.layoutControlItem19.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem19.TextSize = new System.Drawing.Size(117, 20);
//
// layoutControlItem20
//
this.layoutControlItem20.Control = this.txtCountLcUrm;
this.layoutControlItem20.CustomizationFormText = "Count LC URM Cable :";
this.layoutControlItem20.Location = new System.Drawing.Point(213, 314);
this.layoutControlItem20.Name = "layoutControlItem20";
this.layoutControlItem20.Size = new System.Drawing.Size(183, 31);
this.layoutControlItem20.Text = "Count LC URM Cable :";
this.layoutControlItem20.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem20.TextSize = new System.Drawing.Size(117, 20);
//
// layoutControlItem21
//
this.layoutControlItem21.Control = this.LookUpLcUrmStartNo;
this.layoutControlItem21.CustomizationFormText = "LC URM Cable Start No :";
this.layoutControlItem21.Location = new System.Drawing.Point(0, 345);
this.layoutControlItem21.Name = "layoutControlItem21";
this.layoutControlItem21.Size = new System.Drawing.Size(396, 31);
this.layoutControlItem21.Text = "LC URM Cable Start No :";
this.layoutControlItem21.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem21.TextSize = new System.Drawing.Size(117, 20);
//
// NewSwitch
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(398, 411);
this.Controls.Add(this.layoutControl1);
this.Name = "NewSwitch";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "New Switch";
this.Load += new System.EventHandler(this.NewSwitch_Load);
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.LookUpLcUrmStartNo.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtCountLcUrm.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CBoxLcUrmMeter.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtIPNO4.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtIPNO3.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpBlechType.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpVTPort.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtIPNO2.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtIpNo.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpBlech.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpRoom.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpSwitchModel.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtSerialNo.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpSwitchType.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpSan.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpLocation.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.LookUpCoreSwitch.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem7)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem10)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem11)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem12)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem13)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem14)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem15)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem16)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem17)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem18)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem8)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem19)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem20)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem21)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraEditors.LookUpEdit LookUpLocation;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraEditors.LookUpEdit LookUpSwitchType;
private DevExpress.XtraEditors.LookUpEdit LookUpSan;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4;
private DevExpress.XtraEditors.TextEdit txtSerialNo;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6;
private DevExpress.XtraEditors.LookUpEdit LookUpSwitchModel;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem7;
private DevExpress.XtraEditors.SimpleButton simpleButton1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem8;
private DevExpress.XtraEditors.LookUpEdit LookUpRoom;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraEditors.LookUpEdit LookUpBlech;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem9;
private DevExpress.XtraEditors.TextEdit txtIpNo;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem10;
private DevExpress.XtraEditors.LookUpEdit LookUpCoreSwitch;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5;
private DevExpress.XtraEditors.SimpleButton BtnCancel;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem4;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem11;
private DevExpress.XtraEditors.LookUpEdit LookUpVTPort;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem12;
private DevExpress.XtraEditors.SimpleButton BtnCreateVTPort;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem13;
private DevExpress.XtraEditors.SimpleButton BtnCreateBlech;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem14;
private DevExpress.XtraEditors.LookUpEdit LookUpBlechType;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem15;
private DevExpress.XtraEditors.TextEdit txtIPNO2;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem16;
private DevExpress.XtraEditors.TextEdit txtIPNO4;
private DevExpress.XtraEditors.TextEdit txtIPNO3;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem17;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem18;
private DevExpress.XtraEditors.TextEdit txtCountLcUrm;
private DevExpress.XtraEditors.ComboBoxEdit CBoxLcUrmMeter;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem19;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem20;
private DevExpress.XtraEditors.LookUpEdit LookUpLcUrmStartNo;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem21;
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.Collections.Generic;
using System.Drawing;
using HtmlRenderer.Entities;
using HtmlRenderer.Utils;
namespace HtmlRenderer.Dom
{
/// <summary>
/// Helps on CSS Layout.
/// </summary>
internal static class CssLayoutEngine
{
/// <summary>
/// Measure image box size by the width\height set on the box and the actual rendered image size.<br/>
/// If no image exists for the box error icon will be set.
/// </summary>
/// <param name="imageWord">the image word to measure</param>
public static void MeasureImageSize(CssRectImage imageWord)
{
ArgChecker.AssertArgNotNull(imageWord, "imageWord");
ArgChecker.AssertArgNotNull(imageWord.OwnerBox, "imageWord.OwnerBox");
var width = new CssLength(imageWord.OwnerBox.Width);
var height = new CssLength(imageWord.OwnerBox.Height);
bool hasImageTagWidth = width.Number > 0 && width.Unit == CssUnit.Pixels;
bool hasImageTagHeight = height.Number > 0 && height.Unit == CssUnit.Pixels;
bool scaleImageHeight = false;
if (hasImageTagWidth)
{
imageWord.Width = width.Number;
}
else if(width.Number > 0 && width.IsPercentage)
{
imageWord.Width = width.Number*imageWord.OwnerBox.ContainingBlock.Size.Width;
scaleImageHeight = true;
}
else if (imageWord.Image != null)
{
imageWord.Width = imageWord.ImageRectangle == Rectangle.Empty ? imageWord.Image.Width : imageWord.ImageRectangle.Width;
}
else
{
imageWord.Width = hasImageTagHeight ? height.Number / 1.14f : 20;
}
var maxWidth = new CssLength(imageWord.OwnerBox.MaxWidth);
if (maxWidth.Number > 0)
{
float maxWidthVal = -1;
if (maxWidth.Unit == CssUnit.Pixels)
{
maxWidthVal = maxWidth.Number;
}
else if (maxWidth.IsPercentage)
{
maxWidthVal = maxWidth.Number * imageWord.OwnerBox.ContainingBlock.Size.Width;
}
if (maxWidthVal > -1 && imageWord.Width > maxWidthVal)
{
imageWord.Width = maxWidthVal;
scaleImageHeight = !hasImageTagHeight;
}
}
if (hasImageTagHeight)
{
imageWord.Height = height.Number;
}
else if (imageWord.Image != null)
{
imageWord.Height = imageWord.ImageRectangle == Rectangle.Empty ? imageWord.Image.Height : imageWord.ImageRectangle.Height;
}
else
{
imageWord.Height = imageWord.Width > 0 ? imageWord.Width * 1.14f : 22.8f;
}
if (imageWord.Image != null)
{
// If only the width was set in the html tag, ratio the height.
if ((hasImageTagWidth && !hasImageTagHeight) || scaleImageHeight)
{
// Divide the given tag width with the actual image width, to get the ratio.
float ratio = imageWord.Width / imageWord.Image.Width;
imageWord.Height = imageWord.Image.Height * ratio;
}
// If only the height was set in the html tag, ratio the width.
else if (hasImageTagHeight && !hasImageTagWidth)
{
// Divide the given tag height with the actual image height, to get the ratio.
float ratio = imageWord.Height / imageWord.Image.Height;
imageWord.Width = imageWord.Image.Width * ratio;
}
}
imageWord.Height += imageWord.OwnerBox.ActualBorderBottomWidth + imageWord.OwnerBox.ActualBorderTopWidth + imageWord.OwnerBox.ActualPaddingTop + imageWord.OwnerBox.ActualPaddingBottom;
}
/// <summary>
/// Creates line boxes for the specified blockbox
/// </summary>
/// <param name="g"></param>
/// <param name="blockBox"></param>
public static void CreateLineBoxes(IGraphics g, CssBox blockBox)
{
ArgChecker.AssertArgNotNull(g, "g");
ArgChecker.AssertArgNotNull(blockBox, "blockBox");
blockBox.LineBoxes.Clear();
float limitRight = blockBox.ActualRight - blockBox.ActualPaddingRight - blockBox.ActualBorderRightWidth;
//Get the start x and y of the blockBox
float startx = blockBox.Location.X + blockBox.ActualPaddingLeft - 0 + blockBox.ActualBorderLeftWidth;
float starty = blockBox.Location.Y + blockBox.ActualPaddingTop - 0 + blockBox.ActualBorderTopWidth;
float curx = startx + blockBox.ActualTextIndent;
float cury = starty;
//Reminds the maximum bottom reached
float maxRight = startx;
float maxBottom = starty;
//First line box
CssLineBox line = new CssLineBox(blockBox);
//Flow words and boxes
FlowBox(g, blockBox, blockBox, limitRight, 0, startx, ref line, ref curx, ref cury, ref maxRight, ref maxBottom);
// if width is not restricted we need to lower it to the actual width
if( blockBox.ActualRight >= 90999 )
{
blockBox.ActualRight = maxRight + blockBox.ActualPaddingRight + blockBox.ActualBorderRightWidth;
}
//Gets the rectangles for each line-box
foreach (var linebox in blockBox.LineBoxes)
{
ApplyAlignment(g, linebox);
ApplyRightToLeft(blockBox, linebox);
BubbleRectangles(blockBox, linebox);
linebox.AssignRectanglesToBoxes();
}
blockBox.ActualBottom = maxBottom + blockBox.ActualPaddingBottom + blockBox.ActualBorderBottomWidth;
// handle limiting block height when overflow is hidden
if( blockBox.Height != null && blockBox.Height != CssConstants.Auto && blockBox.Overflow == CssConstants.Hidden && blockBox.ActualBottom - blockBox.Location.Y > blockBox.ActualHeight )
{
blockBox.ActualBottom = blockBox.Location.Y + blockBox.ActualHeight;
}
}
/// <summary>
/// Applies special vertical alignment for table-cells
/// </summary>
/// <param name="g"></param>
/// <param name="cell"></param>
public static void ApplyCellVerticalAlignment(IGraphics g, CssBox cell)
{
ArgChecker.AssertArgNotNull(g, "g");
ArgChecker.AssertArgNotNull(cell, "cell");
if (cell.VerticalAlign == CssConstants.Top || cell.VerticalAlign == CssConstants.Baseline) return;
float cellbot = cell.ClientBottom;
float bottom = cell.GetMaximumBottom(cell, 0f);
float dist = 0f;
if (cell.VerticalAlign == CssConstants.Bottom)
{
dist = cellbot - bottom;
}
else if (cell.VerticalAlign == CssConstants.Middle)
{
dist = (cellbot - bottom) / 2;
}
foreach (CssBox b in cell.Boxes)
{
b.OffsetTop(dist);
}
//float top = cell.ClientTop;
//float bottom = cell.ClientBottom;
//bool middle = cell.VerticalAlign == CssConstants.Middle;
//foreach (LineBox line in cell.LineBoxes)
//{
// for (int i = 0; i < line.RelatedBoxes.Count; i++)
// {
// float diff = bottom - line.RelatedBoxes[i].Rectangles[line].Bottom;
// if (middle) diff /= 2f;
// RectangleF r = line.RelatedBoxes[i].Rectangles[line];
// line.RelatedBoxes[i].Rectangles[line] = new RectangleF(r.X, r.Y + diff, r.Width, r.Height);
// }
// foreach (BoxWord word in line.Words)
// {
// float gap = word.Top - top;
// word.Top = bottom - gap - word.Height;
// }
//}
}
#region Private methods
/// <summary>
/// Recursively flows the content of the box using the inline model
/// </summary>
/// <param name="g">Device Info</param>
/// <param name="blockbox">Blockbox that contains the text flow</param>
/// <param name="box">Current box to flow its content</param>
/// <param name="limitRight">Maximum reached right</param>
/// <param name="linespacing">Space to use between rows of text</param>
/// <param name="startx">x starting coordinate for when breaking lines of text</param>
/// <param name="line">Current linebox being used</param>
/// <param name="curx">Current x coordinate that will be the left of the next word</param>
/// <param name="cury">Current y coordinate that will be the top of the next word</param>
/// <param name="maxRight">Maximum right reached so far</param>
/// <param name="maxbottom">Maximum bottom reached so far</param>
private static void FlowBox(IGraphics g, CssBox blockbox, CssBox box, float limitRight, float linespacing, float startx, ref CssLineBox line, ref float curx, ref float cury, ref float maxRight, ref float maxbottom)
{
var startX = curx;
var startY = cury;
box.FirstHostingLineBox = line;
var localCurx = curx;
var localMaxRight = maxRight;
var localmaxbottom = maxbottom;
foreach (CssBox b in box.Boxes)
{
float leftspacing = b.Position != CssConstants.Absolute ? b.ActualMarginLeft + b.ActualBorderLeftWidth + b.ActualPaddingLeft : 0;
float rightspacing = b.Position != CssConstants.Absolute ? b.ActualMarginRight + b.ActualBorderRightWidth + b.ActualPaddingRight : 0;
b.RectanglesReset();
b.MeasureWordsSize(g);
curx += leftspacing;
if (b.Words.Count > 0)
{
bool wrapNoWrapBox = false;
if (b.WhiteSpace == CssConstants.NoWrap && curx > startx)
{
var boxRight = curx;
foreach(var word in b.Words)
boxRight += word.FullWidth;
if( boxRight > limitRight )
wrapNoWrapBox = true;
}
if( DomUtils.IsBoxHasWhitespace(b) )
curx += box.ActualWordSpacing;
foreach (var word in b.Words)
{
if (maxbottom - cury < box.ActualLineHeight)
maxbottom += box.ActualLineHeight - (maxbottom - cury);
if ((b.WhiteSpace != CssConstants.NoWrap && b.WhiteSpace != CssConstants.Pre && curx + word.Width + rightspacing > limitRight) || word.IsLineBreak || wrapNoWrapBox)
{
wrapNoWrapBox = false;
curx = startx;
// handle if line is wrapped for the first text element where parent has left margin\padding
if (b == box.Boxes[0] && !word.IsLineBreak && (word == b.Words[0] || (box.ParentBox != null && box.ParentBox.IsBlock)))
curx += box.ActualMarginLeft + box.ActualBorderLeftWidth + box.ActualPaddingLeft;
cury = maxbottom + linespacing;
line = new CssLineBox(blockbox);
if (word.IsImage || word.Equals(b.FirstWord))
{
curx += leftspacing;
}
}
line.ReportExistanceOf(word);
word.Left = curx;
word.Top = cury;
curx = word.Left + word.FullWidth;
maxRight = Math.Max(maxRight, word.Right);
maxbottom = Math.Max(maxbottom, word.Bottom);
if (b.Position == CssConstants.Absolute)
{
word.Left += box.ActualMarginLeft;
word.Top += box.ActualMarginTop;
}
}
}
else
{
FlowBox(g, blockbox, b, limitRight, linespacing, startx, ref line, ref curx, ref cury, ref maxRight, ref maxbottom);
}
curx += rightspacing;
}
// handle height setting
if (maxbottom - startY < box.ActualHeight)
{
maxbottom += box.ActualHeight - (maxbottom - startY);
}
// handle width setting
if (box.IsInline && 0 <= curx - startX && curx - startX < box.ActualWidth)
{
// hack for actual width handling
curx += box.ActualWidth - (curx - startX);
line.Rectangles.Add(box, new RectangleF(startX, startY, box.ActualWidth, box.ActualHeight));
}
// handle box that is only a whitespace
if (box.Text != null && box.Text.IsWhitespace() && !box.IsImage && box.IsInline && box.Boxes.Count == 0 && box.Words.Count == 0)
{
curx += box.ActualWordSpacing;
}
// hack to support specific absolute position elements
if (box.Position == CssConstants.Absolute)
{
curx = localCurx;
maxRight = localMaxRight;
maxbottom = localmaxbottom;
AdjustAbsolutePosition(box, 0, 0);
}
box.LastHostingLineBox = line;
}
/// <summary>
/// Adjust the position of absolute elements by letf and top margins.
/// </summary>
private static void AdjustAbsolutePosition(CssBox box, float left, float top)
{
left += box.ActualMarginLeft;
top += box.ActualMarginTop;
if (box.Words.Count > 0)
{
foreach (var word in box.Words)
{
word.Left += left;
word.Top += top;
}
}
else
{
foreach (var b in box.Boxes)
AdjustAbsolutePosition(b, left, top);
}
}
/// <summary>
/// Recursively creates the rectangles of the blockBox, by bubbling from deep to outside of the boxes
/// in the rectangle structure
/// </summary>
private static void BubbleRectangles(CssBox box, CssLineBox line)
{
if (box.Words.Count > 0)
{
float x = Single.MaxValue, y = Single.MaxValue, r = Single.MinValue, b = Single.MinValue;
List<CssRect> words = line.WordsOf(box);
if (words.Count > 0)
{
foreach (CssRect word in words)
{
// handle if line is wrapped for the first text element where parent has left margin\padding
var left = word.Left;
if (box == box.ParentBox.Boxes[0] && word == box.Words[0] && word == line.Words[0] && line != line.OwnerBox.LineBoxes[0] && !word.IsLineBreak)
left -= box.ParentBox.ActualMarginLeft + box.ParentBox.ActualBorderLeftWidth + box.ParentBox.ActualPaddingLeft;
x = Math.Min(x, left);
r = Math.Max(r, word.Right);
y = Math.Min(y, word.Top);
b = Math.Max(b, word.Bottom);
}
line.UpdateRectangle(box, x, y, r, b);
}
}
else
{
foreach (CssBox b in box.Boxes)
{
BubbleRectangles(b, line);
}
}
}
/// <summary>
/// Applies vertical and horizontal alignment to words in lineboxes
/// </summary>
/// <param name="g"></param>
/// <param name="lineBox"></param>
private static void ApplyAlignment(IGraphics g, CssLineBox lineBox)
{
#region Horizontal alignment
switch (lineBox.OwnerBox.TextAlign)
{
case CssConstants.Right:
ApplyRightAlignment(g, lineBox);
break;
case CssConstants.Center:
ApplyCenterAlignment(g, lineBox);
break;
case CssConstants.Justify:
ApplyJustifyAlignment(g, lineBox);
break;
default:
ApplyLeftAlignment(g, lineBox);
break;
}
#endregion
ApplyVerticalAlignment(g, lineBox);
}
/// <summary>
/// Applies right to left direction to words
/// </summary>
/// <param name="blockBox"></param>
/// <param name="lineBox"></param>
private static void ApplyRightToLeft(CssBox blockBox, CssLineBox lineBox)
{
if( blockBox.Direction == CssConstants.Rtl )
{
ApplyRightToLeftOnLine(lineBox);
}
else
{
foreach(var box in lineBox.RelatedBoxes)
{
if (box.Direction == CssConstants.Rtl)
{
ApplyRightToLeftOnSingleBox(lineBox, box);
}
}
}
}
/// <summary>
/// Applies RTL direction to all the words on the line.
/// </summary>
/// <param name="line">the line to apply RTL to</param>
private static void ApplyRightToLeftOnLine(CssLineBox line)
{
if (line.Words.Count > 0)
{
float left = line.Words[0].Left;
float right = line.Words[line.Words.Count - 1].Right;
foreach (CssRect word in line.Words)
{
float diff = word.Left - left;
float wright = right - diff;
word.Left = wright - word.Width;
}
}
}
/// <summary>
/// Applies RTL direction to specific box words on the line.
/// </summary>
/// <param name="lineBox"></param>
/// <param name="box"></param>
private static void ApplyRightToLeftOnSingleBox(CssLineBox lineBox, CssBox box)
{
int leftWordIdx = -1;
int rightWordIdx = -1;
for (int i = 0; i < lineBox.Words.Count; i++)
{
if (lineBox.Words[i].OwnerBox == box)
{
if (leftWordIdx < 0)
leftWordIdx = i;
rightWordIdx = i;
}
}
if (leftWordIdx > -1 && rightWordIdx > leftWordIdx)
{
float left = lineBox.Words[leftWordIdx].Left;
float right = lineBox.Words[rightWordIdx].Right;
for (int i = leftWordIdx; i <= rightWordIdx; i++)
{
float diff = lineBox.Words[i].Left - left;
float wright = right - diff;
lineBox.Words[i].Left = wright - lineBox.Words[i].Width;
}
}
}
/// <summary>
/// Applies vertical alignment to the linebox
/// </summary>
/// <param name="g"></param>
/// <param name="lineBox"></param>
private static void ApplyVerticalAlignment(IGraphics g, CssLineBox lineBox)
{
float baseline = Single.MinValue;
foreach (var box in lineBox.Rectangles.Keys)
{
baseline = Math.Max(baseline, lineBox.Rectangles[box].Top);
}
var boxes = new List<CssBox>(lineBox.Rectangles.Keys);
foreach (CssBox box in boxes)
{
//Important notes on http://www.w3.org/TR/CSS21/tables.html#height-layout
switch (box.VerticalAlign)
{
case CssConstants.Sub:
lineBox.SetBaseLine(g, box, baseline + lineBox.Rectangles[box].Height*.2f);
break;
case CssConstants.Super:
lineBox.SetBaseLine(g, box, baseline - lineBox.Rectangles[box].Height*.2f);
break;
case CssConstants.TextTop:
break;
case CssConstants.TextBottom:
break;
case CssConstants.Top:
break;
case CssConstants.Bottom:
break;
case CssConstants.Middle:
break;
default:
//case: baseline
lineBox.SetBaseLine(g, box, baseline);
break;
}
}
}
/// <summary>
/// Applies centered alignment to the text on the linebox
/// </summary>
/// <param name="g"></param>
/// <param name="lineBox"></param>
private static void ApplyJustifyAlignment(IGraphics g, CssLineBox lineBox)
{
if (lineBox.Equals(lineBox.OwnerBox.LineBoxes[lineBox.OwnerBox.LineBoxes.Count - 1])) return;
float indent = lineBox.Equals(lineBox.OwnerBox.LineBoxes[0]) ? lineBox.OwnerBox.ActualTextIndent : 0f;
float textSum = 0f;
float words = 0f;
float availWidth = lineBox.OwnerBox.ClientRectangle.Width - indent;
// Gather text sum
foreach (CssRect w in lineBox.Words)
{
textSum += w.Width;
words += 1f;
}
if (words <= 0f) return; //Avoid Zero division
float spacing = (availWidth - textSum)/words; //Spacing that will be used
float curx = lineBox.OwnerBox.ClientLeft + indent;
foreach (CssRect word in lineBox.Words)
{
word.Left = curx;
curx = word.Right + spacing;
if (word == lineBox.Words[lineBox.Words.Count - 1])
{
word.Left = lineBox.OwnerBox.ClientRight - word.Width;
}
}
}
/// <summary>
/// Applies centered alignment to the text on the linebox
/// </summary>
/// <param name="g"></param>
/// <param name="line"></param>
private static void ApplyCenterAlignment(IGraphics g, CssLineBox line)
{
if (line.Words.Count == 0) return;
CssRect lastWord = line.Words[line.Words.Count - 1];
float right = line.OwnerBox.ActualRight - line.OwnerBox.ActualPaddingRight - line.OwnerBox.ActualBorderRightWidth;
float diff = right - lastWord.Right - lastWord.OwnerBox.ActualBorderRightWidth - lastWord.OwnerBox.ActualPaddingRight;
diff /= 2;
if (diff > 0)
{
foreach (CssRect word in line.Words)
{
word.Left += diff;
}
foreach (CssBox b in line.Rectangles.Keys)
{
RectangleF r = b.Rectangles[line];
b.Rectangles[line] = new RectangleF(r.X + diff, r.Y, r.Width, r.Height);
}
}
}
/// <summary>
/// Applies right alignment to the text on the linebox
/// </summary>
/// <param name="g"></param>
/// <param name="line"></param>
private static void ApplyRightAlignment(IGraphics g, CssLineBox line)
{
if (line.Words.Count == 0) return;
CssRect lastWord = line.Words[line.Words.Count - 1];
float right = line.OwnerBox.ActualRight - line.OwnerBox.ActualPaddingRight - line.OwnerBox.ActualBorderRightWidth;
float diff = right - lastWord.Right - lastWord.OwnerBox.ActualBorderRightWidth - lastWord.OwnerBox.ActualPaddingRight;
if (diff > 0)
{
foreach (CssRect word in line.Words)
{
word.Left += diff;
}
foreach (CssBox b in line.Rectangles.Keys)
{
RectangleF r = b.Rectangles[line];
b.Rectangles[line] = new RectangleF(r.X + diff, r.Y, r.Width, r.Height);
}
}
}
/// <summary>
/// Simplest alignment, just arrange words.
/// </summary>
/// <param name="g"></param>
/// <param name="line"></param>
private static void ApplyLeftAlignment(IGraphics g, CssLineBox line)
{
//No alignment needed.
//foreach (LineBoxRectangle r in line.Rectangles)
//{
// float curx = r.Left + (r.Index == 0 ? r.OwnerBox.ActualPaddingLeft + r.OwnerBox.ActualBorderLeftWidth / 2 : 0);
// if (r.SpaceBefore) curx += r.OwnerBox.ActualWordSpacing;
// foreach (BoxWord word in r.Words)
// {
// word.Left = curx;
// word.Top = r.Top;// +r.OwnerBox.ActualPaddingTop + r.OwnerBox.ActualBorderTopWidth / 2;
// curx = word.Right + r.OwnerBox.ActualWordSpacing;
// }
//}
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using osu.Framework;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osuTK;
using osuTK.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Allocation;
using osu.Framework.Layout;
using osu.Framework.Threading;
namespace osu.Game.Screens.Play
{
public class SquareGraph : Container
{
private BufferedContainer<Column> columns;
public SquareGraph()
{
AddLayout(layout);
}
public int ColumnCount => columns?.Children.Count ?? 0;
private int progress;
public int Progress
{
get => progress;
set
{
if (value == progress) return;
progress = value;
redrawProgress();
}
}
private float[] calculatedValues = Array.Empty<float>(); // values but adjusted to fit the amount of columns
private int[] values;
public int[] Values
{
get => values;
set
{
if (value == values) return;
values = value;
layout.Invalidate();
}
}
private Color4 fillColour;
public Color4 FillColour
{
get => fillColour;
set
{
if (value == fillColour) return;
fillColour = value;
redrawFilled();
}
}
private readonly LayoutValue layout = new LayoutValue(Invalidation.DrawSize);
private ScheduledDelegate scheduledCreate;
protected override void Update()
{
base.Update();
if (values != null && !layout.IsValid)
{
columns?.FadeOut(500, Easing.OutQuint).Expire();
scheduledCreate?.Cancel();
scheduledCreate = Scheduler.AddDelayed(RecreateGraph, 500);
layout.Validate();
}
}
private CancellationTokenSource cts;
/// <summary>
/// Recreates the entire graph.
/// </summary>
protected virtual void RecreateGraph()
{
var newColumns = new BufferedContainer<Column>
{
CacheDrawnFrameBuffer = true,
RedrawOnScale = false,
RelativeSizeAxes = Axes.Both,
};
for (float x = 0; x < DrawWidth; x += Column.WIDTH)
{
newColumns.Add(new Column(DrawHeight)
{
LitColour = fillColour,
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Position = new Vector2(x, 0),
State = ColumnState.Dimmed,
});
}
cts?.Cancel();
LoadComponentAsync(newColumns, c =>
{
Child = columns = c;
columns.FadeInFromZero(500, Easing.OutQuint);
recalculateValues();
redrawFilled();
redrawProgress();
}, (cts = new CancellationTokenSource()).Token);
}
/// <summary>
/// Redraws all the columns to match their lit/dimmed state.
/// </summary>
private void redrawProgress()
{
for (int i = 0; i < ColumnCount; i++)
columns[i].State = i <= progress ? ColumnState.Lit : ColumnState.Dimmed;
columns?.ForceRedraw();
}
/// <summary>
/// Redraws the filled amount of all the columns.
/// </summary>
private void redrawFilled()
{
for (int i = 0; i < ColumnCount; i++)
columns[i].Filled = calculatedValues.ElementAtOrDefault(i);
columns?.ForceRedraw();
}
/// <summary>
/// Takes <see cref="Values"/> and adjusts it to fit the amount of columns.
/// </summary>
private void recalculateValues()
{
var newValues = new List<float>();
if (values == null)
{
for (float i = 0; i < ColumnCount; i++)
newValues.Add(0);
return;
}
var max = values.Max();
float step = values.Length / (float)ColumnCount;
for (float i = 0; i < values.Length; i += step)
{
newValues.Add((float)values[(int)i] / max);
}
calculatedValues = newValues.ToArray();
}
public class Column : Container, IStateful<ColumnState>
{
protected readonly Color4 EmptyColour = Color4.White.Opacity(20);
public Color4 LitColour = Color4.LightBlue;
protected readonly Color4 DimmedColour = Color4.White.Opacity(140);
private float cubeCount => DrawHeight / WIDTH;
private const float cube_size = 4;
private const float padding = 2;
public const float WIDTH = cube_size + padding;
public event Action<ColumnState> StateChanged;
private readonly List<Box> drawableRows = new List<Box>();
private float filled;
public float Filled
{
get => filled;
set
{
if (value == filled) return;
filled = value;
fillActive();
}
}
private ColumnState state;
public ColumnState State
{
get => state;
set
{
if (value == state) return;
state = value;
if (IsLoaded)
fillActive();
StateChanged?.Invoke(State);
}
}
public Column(float height)
{
Width = WIDTH;
Height = height;
}
[BackgroundDependencyLoader]
private void load()
{
drawableRows.AddRange(Enumerable.Range(0, (int)cubeCount).Select(r => new Box
{
Size = new Vector2(cube_size),
Position = new Vector2(0, r * WIDTH + padding),
}));
Children = drawableRows;
// Reverse drawableRows so when iterating through them they start at the bottom
drawableRows.Reverse();
}
protected override void LoadComplete()
{
base.LoadComplete();
fillActive();
}
private void fillActive()
{
Color4 colour = State == ColumnState.Lit ? LitColour : DimmedColour;
int countFilled = (int)Math.Clamp(filled * drawableRows.Count, 0, drawableRows.Count);
for (int i = 0; i < drawableRows.Count; i++)
drawableRows[i].Colour = i < countFilled ? colour : EmptyColour;
}
}
public enum ColumnState
{
Lit,
Dimmed
}
}
}
| |
//#define ASTARDEBUG
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
using Pathfinding.Util;
namespace Pathfinding {
[AddComponentMenu ("Pathfinding/Modifiers/Funnel")]
[System.Serializable]
/** Simplifies paths on navmesh graphs using the funnel algorithm.
* The funnel algorithm is an algorithm which can, given a path corridor with nodes in the path where the nodes have an area, like triangles, it can find the shortest path inside it.
* This makes paths on navmeshes look much cleaner and smoother.
* \image html images/funnelModifier_on.png
* \ingroup modifiers
*/
public class FunnelModifier : MonoModifier {
#if UNITY_EDITOR
[UnityEditor.MenuItem ("CONTEXT/Seeker/Add Funnel Modifier")]
public static void AddComp (UnityEditor.MenuCommand command) {
(command.context as Component).gameObject.AddComponent (typeof(FunnelModifier));
}
#endif
public override ModifierData input {
get { return ModifierData.StrictVectorPath; }
}
public override ModifierData output {
get { return ModifierData.VectorPath; }
}
public override void Apply (Path p, ModifierData source) {
List<GraphNode> path = p.path;
List<Vector3> vectorPath = p.vectorPath;
if (path == null || path.Count == 0 || vectorPath == null || vectorPath.Count != path.Count) {
return;
}
List<Vector3> funnelPath = ListPool<Vector3>.Claim ();
//Claim temporary lists and try to find lists with a high capacity
List<Vector3> left = ListPool<Vector3>.Claim (path.Count+1);
List<Vector3> right = ListPool<Vector3>.Claim (path.Count+1);
AstarProfiler.StartProfile ("Construct Funnel");
left.Add (vectorPath[0]);
right.Add (vectorPath[0]);
for (int i=0;i<path.Count-1;i++) {
bool a = path[i].GetPortal (path[i+1], left, right, false);
bool b = false;//path[i+1].GetPortal (path[i], right, left, true);
if (!a && !b) {
left.Add ((Vector3)path[i].position);
right.Add ((Vector3)path[i].position);
left.Add ((Vector3)path[i+1].position);
right.Add ((Vector3)path[i+1].position);
}
}
left.Add (vectorPath[vectorPath.Count-1]);
right.Add (vectorPath[vectorPath.Count-1]);
if (!RunFunnel (left,right,funnelPath)) {
//If funnel algorithm failed, degrade to simple line
funnelPath.Add (vectorPath[0]);
funnelPath.Add (vectorPath[vectorPath.Count-1]);
}
ListPool<Vector3>.Release (p.vectorPath);
p.vectorPath = funnelPath;
ListPool<Vector3>.Release (left);
ListPool<Vector3>.Release (right);
}
/** Calculate a funnel path from the \a left and \a right portal lists.
* The result will be appended to \a funnelPath
*/
public bool RunFunnel (List<Vector3> left, List<Vector3> right, List<Vector3> funnelPath) {
if (left == null) throw new System.ArgumentNullException("left");
if (right == null) throw new System.ArgumentNullException("right");
if (funnelPath == null) throw new System.ArgumentNullException("funnelPath");
if (left.Count != right.Count) throw new System.ArgumentException("left and right lists must have equal length");
if (left.Count <= 3) {
return false;
}
//Remove identical vertices
while (left[1] == left[2] && right[1] == right[2]) {
//System.Console.WriteLine ("Removing identical left and right");
left.RemoveAt (1);
right.RemoveAt (1);
if (left.Count <= 3) {
return false;
}
}
Vector3 swPoint = left[2];
if (swPoint == left[1]) {
swPoint = right[2];
}
//Test
while (Polygon.IsColinear (left[0],left[1],right[1]) || Polygon.Left (left[1],right[1],swPoint) == Polygon.Left (left[1],right[1],left[0])) {
#if ASTARDEBUG
Debug.DrawLine (left[1],right[1],new Color (0,0,0,0.5F));
Debug.DrawLine (left[0],swPoint,new Color (0,0,0,0.5F));
#endif
left.RemoveAt (1);
right.RemoveAt (1);
if (left.Count <= 3) {
return false;
}
swPoint = left[2];
if (swPoint == left[1]) {
swPoint = right[2];
}
}
//Switch left and right to really be on the "left" and "right" sides
if (!Polygon.IsClockwise (left[0],left[1],right[1]) && !Polygon.IsColinear (left[0],left[1],right[1])) {
//System.Console.WriteLine ("Wrong Side 2");
List<Vector3> tmp = left;
left = right;
right = tmp;
}
#if ASTARDEBUG
for (int i=0;i<left.Count-1;i++) {
Debug.DrawLine (left[i],left[i+1],Color.red);
Debug.DrawLine (right[i],right[i+1],Color.magenta);
Debug.DrawRay (right[i], Vector3.up,Color.magenta);
}
for (int i=0;i<left.Count;i++) {
//Debug.DrawLine (right[i],left[i], Color.cyan);
}
#endif
funnelPath.Add (left[0]);
Vector3 portalApex = left[0];
Vector3 portalLeft = left[1];
Vector3 portalRight = right[1];
int apexIndex = 0;
int rightIndex = 1;
int leftIndex = 1;
for (int i=2;i<left.Count;i++) {
if (funnelPath.Count > 2000) {
Debug.LogWarning ("Avoiding infinite loop. Remove this check if you have this long paths.");
break;
}
Vector3 pLeft = left[i];
Vector3 pRight = right[i];
/*Debug.DrawLine (portalApex,portalLeft,Color.red);
Debug.DrawLine (portalApex,portalRight,Color.yellow);
Debug.DrawLine (portalApex,left,Color.cyan);
Debug.DrawLine (portalApex,right,Color.cyan);*/
if (Polygon.TriangleArea2 (portalApex,portalRight,pRight) >= 0) {
if (portalApex == portalRight || Polygon.TriangleArea2 (portalApex,portalLeft,pRight) <= 0) {
portalRight = pRight;
rightIndex = i;
} else {
funnelPath.Add (portalLeft);
portalApex = portalLeft;
apexIndex = leftIndex;
portalLeft = portalApex;
portalRight = portalApex;
leftIndex = apexIndex;
rightIndex = apexIndex;
i = apexIndex;
continue;
}
}
if (Polygon.TriangleArea2 (portalApex,portalLeft,pLeft) <= 0) {
if (portalApex == portalLeft || Polygon.TriangleArea2 (portalApex,portalRight,pLeft) >= 0) {
portalLeft = pLeft;
leftIndex = i;
} else {
funnelPath.Add (portalRight);
portalApex = portalRight;
apexIndex = rightIndex;
portalLeft = portalApex;
portalRight = portalApex;
leftIndex = apexIndex;
rightIndex = apexIndex;
i = apexIndex;
continue;
}
}
}
funnelPath.Add (left[left.Count-1]);
return true;
}
}
/** Graphs implementing this interface have support for the Funnel modifier */
public interface IFunnelGraph {
void BuildFunnelCorridor (List<GraphNode> path, int sIndex, int eIndex, List<Vector3> left, List<Vector3> right);
/** Add the portal between node \a n1 and \a n2 to the funnel corridor. The left and right edges does not necesarily need to be the left and right edges (right can be left), they will be swapped if that is detected. But that works only as long as the edges do not switch between left and right in the middle of the path.
*/
void AddPortal (GraphNode n1, GraphNode n2, List<Vector3> left, List<Vector3> right);
}
}
| |
//
// Catalog.cs: Bindings for libintl
//
// Authors:
// Aaron Bockover (abockover@novell.com)
//
// (C) 2006 Novell, Inc.
//
using System;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
#if !win32
using Mono.Unix;
#endif
namespace Mono.Gettext
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = true)]
public class AssemblyCatalogAttribute : Attribute
{
private string domain;
private string localedir;
// Cornel 22-07-2007 - I will create win32 specific classes to handle this -- if needed
#if !win32
public AssemblyCatalogAttribute(string domain, string localedir)
{
this.domain = domain;
this.localedir = localedir;
}
public string Domain {
get { return domain; }
}
public string LocaleDir {
get { return localedir; }
}
}
public sealed /* static */ class Catalog
{
private Catalog()
{
}
private static Hashtable domain_assembly_map = new Hashtable();
private static ArrayList default_domain_assemblies = new ArrayList();
public static void Init(string domain, string localeDir)
{
if(domain == null || domain.Length == 0) {
throw new ArgumentException("No text domain specified");
}
IntPtr domain_ptr = UnixMarshal.StringToHeap(domain);
IntPtr localedir_ptr = IntPtr.Zero;
try {
BindTextDomainCodeset(domain_ptr);
if(localeDir != null && localeDir.Length > 0) {
localedir_ptr = UnixMarshal.StringToHeap(localeDir);
BindTextDomain(domain_ptr, localedir_ptr);
}
} finally {
UnixMarshal.FreeHeap(domain_ptr);
if(localedir_ptr != IntPtr.Zero) {
UnixMarshal.FreeHeap(localedir_ptr);
}
}
}
public static string GetString(string msgid)
{
return GetString(GetDomainForAssembly(Assembly.GetCallingAssembly()), msgid);
}
public static string GetString(string domain, string msgid)
{
IntPtr msgid_ptr = UnixMarshal.StringToHeap(msgid);
IntPtr domain_ptr = domain == null ? IntPtr.Zero : UnixMarshal.StringToHeap(domain);
if(domain == null) {
IntPtr ptr = UnixMarshal.StringToHeap("banshee");
UnixMarshal.FreeHeap(ptr);
}
try {
IntPtr ret_ptr = domain_ptr == IntPtr.Zero ?
gettext(msgid_ptr) :
dgettext(domain_ptr, msgid_ptr);
if(msgid_ptr != ret_ptr) {
return UnixMarshal.PtrToStringUnix(ret_ptr);
}
return msgid;
} finally {
UnixMarshal.FreeHeap(msgid_ptr);
if(domain_ptr != IntPtr.Zero) {
UnixMarshal.FreeHeap(domain_ptr);
}
}
}
public static string GetString(string msgid, string msgidPlural, int n)
{
return GetString(GetDomainForAssembly(Assembly.GetCallingAssembly()), msgid, msgidPlural, n);
}
public static string GetPluralString(string msgid, string msgidPlural, int n)
{
return GetString(GetDomainForAssembly(Assembly.GetCallingAssembly()), msgid, msgidPlural, n);
}
public static string GetString(string domain, string msgid, string msgidPlural, int n)
{
IntPtr msgid_ptr = UnixMarshal.StringToHeap(msgid);
IntPtr msgid_plural_ptr = UnixMarshal.StringToHeap(msgidPlural);
IntPtr domain_ptr = domain == null ? IntPtr.Zero : UnixMarshal.StringToHeap(domain);
try {
IntPtr ret_ptr = domain_ptr == IntPtr.Zero ?
ngettext(msgid_ptr, msgid_plural_ptr, n) :
dngettext(domain_ptr, msgid_ptr, msgid_plural_ptr, n);
if(ret_ptr == msgid_ptr) {
return msgid;
} else if(ret_ptr == msgid_plural_ptr) {
return msgidPlural;
}
return UnixMarshal.PtrToStringUnix(ret_ptr);
} finally {
UnixMarshal.FreeHeap(msgid_ptr);
UnixMarshal.FreeHeap(msgid_plural_ptr);
if(domain_ptr != IntPtr.Zero) {
UnixMarshal.FreeHeap(domain_ptr);
}
}
}
private static string GetDomainForAssembly(Assembly assembly)
{
if(default_domain_assemblies.Contains(assembly)) {
return null;
} else if(domain_assembly_map.ContainsKey(assembly)) {
return domain_assembly_map[assembly] as string;
}
AssemblyCatalogAttribute [] attributes = assembly.GetCustomAttributes(
typeof(AssemblyCatalogAttribute), true) as AssemblyCatalogAttribute [];
if(attributes == null || attributes.Length == 0) {
default_domain_assemblies.Add(assembly);
return null;
}
string domain = attributes[0].Domain;
Init(domain, attributes[0].LocaleDir);
domain_assembly_map.Add(assembly, domain);
return domain;
}
private static void BindTextDomainCodeset(IntPtr domain)
{
IntPtr codeset = UnixMarshal.StringToHeap("UTF-8");
try {
if(bind_textdomain_codeset(domain, codeset) == IntPtr.Zero) {
throw new UnixIOException(Mono.Unix.Native.Errno.ENOMEM);
}
} finally {
UnixMarshal.FreeHeap(codeset);
}
}
private static void BindTextDomain(IntPtr domain, IntPtr localedir)
{
if(bindtextdomain(domain, localedir) == IntPtr.Zero) {
throw new UnixIOException(Mono.Unix.Native.Errno.ENOMEM);
}
}
[DllImport("intl")]
private static extern IntPtr bind_textdomain_codeset(IntPtr domain, IntPtr codeset);
[DllImport("intl")]
private static extern IntPtr bindtextdomain(IntPtr domain, IntPtr locale_dir);
[DllImport("intl")]
private static extern IntPtr dgettext(IntPtr domain, IntPtr msgid);
[DllImport("intl")]
private static extern IntPtr dngettext(IntPtr domain, IntPtr msgid_singular, IntPtr msgid_plural, Int32 n);
[DllImport("intl")]
private static extern IntPtr gettext(IntPtr msgid);
[DllImport("intl")]
private static extern IntPtr ngettext(IntPtr msgid_singular, IntPtr msgid_plural, Int32 n);
#endif
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Practices.Unity;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Prism.IocContainer.Wpf.Tests.Support;
using Prism.IocContainer.Wpf.Tests.Support.Mocks;
using Prism.Logging;
using Prism.Modularity;
using Prism.Regions;
namespace Prism.Unity.Wpf.Tests
{
[TestClass]
public class UnityBootstrapperFixture: BootstrapperFixtureBase
{
[TestMethod]
public void ContainerDefaultsToNull()
{
var bootstrapper = new DefaultUnityBootstrapper();
var container = bootstrapper.BaseContainer;
Assert.IsNull(container);
}
[TestMethod]
public void CanCreateConcreteBootstrapper()
{
new DefaultUnityBootstrapper();
}
[TestMethod]
public void CreateContainerShouldInitializeContainer()
{
var bootstrapper = new DefaultUnityBootstrapper();
IUnityContainer container = bootstrapper.CallCreateContainer();
Assert.IsNotNull(container);
Assert.IsInstanceOfType(container, typeof(IUnityContainer));
}
[TestMethod]
public void ConfigureContainerAddsModuleCatalogToContainer()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var returnedCatalog = bootstrapper.BaseContainer.Resolve<IModuleCatalog>();
Assert.IsNotNull(returnedCatalog);
Assert.IsTrue(returnedCatalog is ModuleCatalog);
}
[TestMethod]
public void ConfigureContainerAddsLoggerFacadeToContainer()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var returnedCatalog = bootstrapper.BaseContainer.Resolve<ILoggerFacade>();
Assert.IsNotNull(returnedCatalog);
}
[TestMethod]
public void ConfigureContainerAddsRegionNavigationJournalEntryToContainer()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var actual1 = bootstrapper.BaseContainer.Resolve<IRegionNavigationJournalEntry>();
var actual2 = bootstrapper.BaseContainer.Resolve<IRegionNavigationJournalEntry>();
Assert.IsNotNull(actual1);
Assert.IsNotNull(actual2);
Assert.AreNotSame(actual1, actual2);
}
[TestMethod]
public void ConfigureContainerAddsRegionNavigationJournalToContainer()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var actual1 = bootstrapper.BaseContainer.Resolve<IRegionNavigationJournal>();
var actual2 = bootstrapper.BaseContainer.Resolve<IRegionNavigationJournal>();
Assert.IsNotNull(actual1);
Assert.IsNotNull(actual2);
Assert.AreNotSame(actual1, actual2);
}
[TestMethod]
public void ConfigureContainerAddsRegionNavigationServiceToContainer()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var actual1 = bootstrapper.BaseContainer.Resolve<IRegionNavigationService>();
var actual2 = bootstrapper.BaseContainer.Resolve<IRegionNavigationService>();
Assert.IsNotNull(actual1);
Assert.IsNotNull(actual2);
Assert.AreNotSame(actual1, actual2);
}
[TestMethod]
public void ConfigureContainerAddsNavigationTargetHandlerToContainer()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.Run();
var actual1 = bootstrapper.BaseContainer.Resolve<IRegionNavigationContentLoader>();
var actual2 = bootstrapper.BaseContainer.Resolve<IRegionNavigationContentLoader>();
Assert.IsNotNull(actual1);
Assert.IsNotNull(actual2);
Assert.AreSame(actual1, actual2);
}
[TestMethod]
public void RegisterFrameworkExceptionTypesShouldRegisterActivationException()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.CallRegisterFrameworkExceptionTypes();
Assert.IsTrue(ExceptionExtensions.IsFrameworkExceptionRegistered(
typeof(Microsoft.Practices.ServiceLocation.ActivationException)));
}
[TestMethod]
public void RegisterFrameworkExceptionTypesShouldRegisterResolutionFailedException()
{
var bootstrapper = new DefaultUnityBootstrapper();
bootstrapper.CallRegisterFrameworkExceptionTypes();
Assert.IsTrue(ExceptionExtensions.IsFrameworkExceptionRegistered(
typeof(Microsoft.Practices.Unity.ResolutionFailedException)));
}
}
internal class DefaultUnityBootstrapper : UnityBootstrapper
{
public List<string> MethodCalls = new List<string>();
public bool InitializeModulesCalled;
public bool ConfigureRegionAdapterMappingsCalled;
public RegionAdapterMappings DefaultRegionAdapterMappings;
public bool CreateLoggerCalled;
public bool CreateModuleCatalogCalled;
public bool ConfigureContainerCalled;
public bool CreateShellCalled;
public bool CreateContainerCalled;
public bool ConfigureModuleCatalogCalled;
public bool InitializeShellCalled;
public bool ConfigureServiceLocatorCalled;
public bool ConfigureDefaultRegionBehaviorsCalled;
public DependencyObject ShellObject = new UserControl();
public DependencyObject BaseShell
{
get { return base.Shell; }
}
public IUnityContainer BaseContainer
{
get { return base.Container; }
set { base.Container = value; }
}
public MockLoggerAdapter BaseLogger
{ get { return base.Logger as MockLoggerAdapter; } }
public IUnityContainer CallCreateContainer()
{
return this.CreateContainer();
}
protected override IUnityContainer CreateContainer()
{
this.MethodCalls.Add(MethodBase.GetCurrentMethod().Name);
this.CreateContainerCalled = true;
return base.CreateContainer();
}
protected override void ConfigureContainer()
{
this.MethodCalls.Add(MethodBase.GetCurrentMethod().Name);
this.ConfigureContainerCalled = true;
base.ConfigureContainer();
}
protected override ILoggerFacade CreateLogger()
{
this.MethodCalls.Add(MethodBase.GetCurrentMethod().Name);
this.CreateLoggerCalled = true;
return new MockLoggerAdapter();
}
protected override DependencyObject CreateShell()
{
this.MethodCalls.Add(MethodBase.GetCurrentMethod().Name);
this.CreateShellCalled = true;
return ShellObject;
}
protected override void ConfigureServiceLocator()
{
this.MethodCalls.Add(MethodBase.GetCurrentMethod().Name);
this.ConfigureServiceLocatorCalled = true;
base.ConfigureServiceLocator();
}
protected override IModuleCatalog CreateModuleCatalog()
{
this.MethodCalls.Add(MethodBase.GetCurrentMethod().Name);
this.CreateModuleCatalogCalled = true;
return base.CreateModuleCatalog();
}
protected override void ConfigureModuleCatalog()
{
this.MethodCalls.Add(MethodBase.GetCurrentMethod().Name);
this.ConfigureModuleCatalogCalled = true;
base.ConfigureModuleCatalog();
}
protected override void InitializeShell()
{
this.MethodCalls.Add(MethodBase.GetCurrentMethod().Name);
this.InitializeShellCalled = true;
// no op
}
protected override void InitializeModules()
{
this.MethodCalls.Add(MethodBase.GetCurrentMethod().Name);
this.InitializeModulesCalled = true;
base.InitializeModules();
}
protected override IRegionBehaviorFactory ConfigureDefaultRegionBehaviors()
{
this.MethodCalls.Add(MethodBase.GetCurrentMethod().Name);
this.ConfigureDefaultRegionBehaviorsCalled = true;
return base.ConfigureDefaultRegionBehaviors();
}
protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
{
this.MethodCalls.Add(MethodBase.GetCurrentMethod().Name);
ConfigureRegionAdapterMappingsCalled = true;
var regionAdapterMappings = base.ConfigureRegionAdapterMappings();
DefaultRegionAdapterMappings = regionAdapterMappings;
return regionAdapterMappings;
}
protected override void RegisterFrameworkExceptionTypes()
{
this.MethodCalls.Add(MethodBase.GetCurrentMethod().Name);
base.RegisterFrameworkExceptionTypes();
}
public void CallRegisterFrameworkExceptionTypes()
{
base.RegisterFrameworkExceptionTypes();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp.Swizzle
{
/// <summary>
/// Temporary vector of type bool with 2 components, used for implementing swizzling for bvec2.
/// </summary>
[Serializable]
[DataContract(Namespace = "swizzle")]
[StructLayout(LayoutKind.Sequential)]
public struct swizzle_bvec2
{
#region Fields
/// <summary>
/// x-component
/// </summary>
[DataMember]
internal readonly bool x;
/// <summary>
/// y-component
/// </summary>
[DataMember]
internal readonly bool y;
#endregion
#region Constructors
/// <summary>
/// Constructor for swizzle_bvec2.
/// </summary>
internal swizzle_bvec2(bool x, bool y)
{
this.x = x;
this.y = y;
}
#endregion
#region Properties
/// <summary>
/// Returns bvec2.xx swizzling.
/// </summary>
public bvec2 xx => new bvec2(x, x);
/// <summary>
/// Returns bvec2.rr swizzling (equivalent to bvec2.xx).
/// </summary>
public bvec2 rr => new bvec2(x, x);
/// <summary>
/// Returns bvec2.xxx swizzling.
/// </summary>
public bvec3 xxx => new bvec3(x, x, x);
/// <summary>
/// Returns bvec2.rrr swizzling (equivalent to bvec2.xxx).
/// </summary>
public bvec3 rrr => new bvec3(x, x, x);
/// <summary>
/// Returns bvec2.xxxx swizzling.
/// </summary>
public bvec4 xxxx => new bvec4(x, x, x, x);
/// <summary>
/// Returns bvec2.rrrr swizzling (equivalent to bvec2.xxxx).
/// </summary>
public bvec4 rrrr => new bvec4(x, x, x, x);
/// <summary>
/// Returns bvec2.xxxy swizzling.
/// </summary>
public bvec4 xxxy => new bvec4(x, x, x, y);
/// <summary>
/// Returns bvec2.rrrg swizzling (equivalent to bvec2.xxxy).
/// </summary>
public bvec4 rrrg => new bvec4(x, x, x, y);
/// <summary>
/// Returns bvec2.xxy swizzling.
/// </summary>
public bvec3 xxy => new bvec3(x, x, y);
/// <summary>
/// Returns bvec2.rrg swizzling (equivalent to bvec2.xxy).
/// </summary>
public bvec3 rrg => new bvec3(x, x, y);
/// <summary>
/// Returns bvec2.xxyx swizzling.
/// </summary>
public bvec4 xxyx => new bvec4(x, x, y, x);
/// <summary>
/// Returns bvec2.rrgr swizzling (equivalent to bvec2.xxyx).
/// </summary>
public bvec4 rrgr => new bvec4(x, x, y, x);
/// <summary>
/// Returns bvec2.xxyy swizzling.
/// </summary>
public bvec4 xxyy => new bvec4(x, x, y, y);
/// <summary>
/// Returns bvec2.rrgg swizzling (equivalent to bvec2.xxyy).
/// </summary>
public bvec4 rrgg => new bvec4(x, x, y, y);
/// <summary>
/// Returns bvec2.xy swizzling.
/// </summary>
public bvec2 xy => new bvec2(x, y);
/// <summary>
/// Returns bvec2.rg swizzling (equivalent to bvec2.xy).
/// </summary>
public bvec2 rg => new bvec2(x, y);
/// <summary>
/// Returns bvec2.xyx swizzling.
/// </summary>
public bvec3 xyx => new bvec3(x, y, x);
/// <summary>
/// Returns bvec2.rgr swizzling (equivalent to bvec2.xyx).
/// </summary>
public bvec3 rgr => new bvec3(x, y, x);
/// <summary>
/// Returns bvec2.xyxx swizzling.
/// </summary>
public bvec4 xyxx => new bvec4(x, y, x, x);
/// <summary>
/// Returns bvec2.rgrr swizzling (equivalent to bvec2.xyxx).
/// </summary>
public bvec4 rgrr => new bvec4(x, y, x, x);
/// <summary>
/// Returns bvec2.xyxy swizzling.
/// </summary>
public bvec4 xyxy => new bvec4(x, y, x, y);
/// <summary>
/// Returns bvec2.rgrg swizzling (equivalent to bvec2.xyxy).
/// </summary>
public bvec4 rgrg => new bvec4(x, y, x, y);
/// <summary>
/// Returns bvec2.xyy swizzling.
/// </summary>
public bvec3 xyy => new bvec3(x, y, y);
/// <summary>
/// Returns bvec2.rgg swizzling (equivalent to bvec2.xyy).
/// </summary>
public bvec3 rgg => new bvec3(x, y, y);
/// <summary>
/// Returns bvec2.xyyx swizzling.
/// </summary>
public bvec4 xyyx => new bvec4(x, y, y, x);
/// <summary>
/// Returns bvec2.rggr swizzling (equivalent to bvec2.xyyx).
/// </summary>
public bvec4 rggr => new bvec4(x, y, y, x);
/// <summary>
/// Returns bvec2.xyyy swizzling.
/// </summary>
public bvec4 xyyy => new bvec4(x, y, y, y);
/// <summary>
/// Returns bvec2.rggg swizzling (equivalent to bvec2.xyyy).
/// </summary>
public bvec4 rggg => new bvec4(x, y, y, y);
/// <summary>
/// Returns bvec2.yx swizzling.
/// </summary>
public bvec2 yx => new bvec2(y, x);
/// <summary>
/// Returns bvec2.gr swizzling (equivalent to bvec2.yx).
/// </summary>
public bvec2 gr => new bvec2(y, x);
/// <summary>
/// Returns bvec2.yxx swizzling.
/// </summary>
public bvec3 yxx => new bvec3(y, x, x);
/// <summary>
/// Returns bvec2.grr swizzling (equivalent to bvec2.yxx).
/// </summary>
public bvec3 grr => new bvec3(y, x, x);
/// <summary>
/// Returns bvec2.yxxx swizzling.
/// </summary>
public bvec4 yxxx => new bvec4(y, x, x, x);
/// <summary>
/// Returns bvec2.grrr swizzling (equivalent to bvec2.yxxx).
/// </summary>
public bvec4 grrr => new bvec4(y, x, x, x);
/// <summary>
/// Returns bvec2.yxxy swizzling.
/// </summary>
public bvec4 yxxy => new bvec4(y, x, x, y);
/// <summary>
/// Returns bvec2.grrg swizzling (equivalent to bvec2.yxxy).
/// </summary>
public bvec4 grrg => new bvec4(y, x, x, y);
/// <summary>
/// Returns bvec2.yxy swizzling.
/// </summary>
public bvec3 yxy => new bvec3(y, x, y);
/// <summary>
/// Returns bvec2.grg swizzling (equivalent to bvec2.yxy).
/// </summary>
public bvec3 grg => new bvec3(y, x, y);
/// <summary>
/// Returns bvec2.yxyx swizzling.
/// </summary>
public bvec4 yxyx => new bvec4(y, x, y, x);
/// <summary>
/// Returns bvec2.grgr swizzling (equivalent to bvec2.yxyx).
/// </summary>
public bvec4 grgr => new bvec4(y, x, y, x);
/// <summary>
/// Returns bvec2.yxyy swizzling.
/// </summary>
public bvec4 yxyy => new bvec4(y, x, y, y);
/// <summary>
/// Returns bvec2.grgg swizzling (equivalent to bvec2.yxyy).
/// </summary>
public bvec4 grgg => new bvec4(y, x, y, y);
/// <summary>
/// Returns bvec2.yy swizzling.
/// </summary>
public bvec2 yy => new bvec2(y, y);
/// <summary>
/// Returns bvec2.gg swizzling (equivalent to bvec2.yy).
/// </summary>
public bvec2 gg => new bvec2(y, y);
/// <summary>
/// Returns bvec2.yyx swizzling.
/// </summary>
public bvec3 yyx => new bvec3(y, y, x);
/// <summary>
/// Returns bvec2.ggr swizzling (equivalent to bvec2.yyx).
/// </summary>
public bvec3 ggr => new bvec3(y, y, x);
/// <summary>
/// Returns bvec2.yyxx swizzling.
/// </summary>
public bvec4 yyxx => new bvec4(y, y, x, x);
/// <summary>
/// Returns bvec2.ggrr swizzling (equivalent to bvec2.yyxx).
/// </summary>
public bvec4 ggrr => new bvec4(y, y, x, x);
/// <summary>
/// Returns bvec2.yyxy swizzling.
/// </summary>
public bvec4 yyxy => new bvec4(y, y, x, y);
/// <summary>
/// Returns bvec2.ggrg swizzling (equivalent to bvec2.yyxy).
/// </summary>
public bvec4 ggrg => new bvec4(y, y, x, y);
/// <summary>
/// Returns bvec2.yyy swizzling.
/// </summary>
public bvec3 yyy => new bvec3(y, y, y);
/// <summary>
/// Returns bvec2.ggg swizzling (equivalent to bvec2.yyy).
/// </summary>
public bvec3 ggg => new bvec3(y, y, y);
/// <summary>
/// Returns bvec2.yyyx swizzling.
/// </summary>
public bvec4 yyyx => new bvec4(y, y, y, x);
/// <summary>
/// Returns bvec2.gggr swizzling (equivalent to bvec2.yyyx).
/// </summary>
public bvec4 gggr => new bvec4(y, y, y, x);
/// <summary>
/// Returns bvec2.yyyy swizzling.
/// </summary>
public bvec4 yyyy => new bvec4(y, y, y, y);
/// <summary>
/// Returns bvec2.gggg swizzling (equivalent to bvec2.yyyy).
/// </summary>
public bvec4 gggg => new bvec4(y, y, y, y);
#endregion
}
}
| |
using Gaming.Audio;
using Gaming.Game;
using Gaming.Graphics;
using MatterHackers.Agg;
using MatterHackers.Agg.Image;
using MatterHackers.Agg.UI;
using MatterHackers.VectorMath;
/*
* Created by SharpDevelop.
* User: Lars Brubaker
* Date: 10/13/2007
* Time: 12:07 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
namespace RockBlaster
{
public class PlayerStyleSheet : GameObject
{
#region GameObjectStuff
public PlayerStyleSheet()
{
}
public static new GameObject Load(String PathName)
{
return GameObject.Load(PathName);
}
#endregion GameObjectStuff
[GameDataNumberAttribute("TurnRate")]
public double TurnRate = 6;
[GameDataNumberAttribute("ShipThrust")]
public double ThrustAcceleration = 600;
[GameDataNumberAttribute("Friction")]
public double Friction = .99;
[GameDataNumberAttribute("DistanceToFrontOfShip")]
public double DistanceToFrontOfShip = 10;
[GameDataNumberAttribute("DamageOnCollide")]
public double DamageOnCollide = 100;
[GameData("FireSound")]
public AssetReference<Sound> FireSoundReference = new AssetReference<Sound>("PlayerSmallShot");
}
/// <summary>
/// Description of Player.
/// </summary>
public class Player : Entity
{
#region GameObjectStuff
public Player()
{
}
public static new GameObject Load(String PathName)
{
return GameObject.Load(PathName);
}
#endregion GameObjectStuff
[GameData("StyleSheet")]
public AssetReference<PlayerStyleSheet> m_PlayerStyleSheetReference = new AssetReference<PlayerStyleSheet>();
[GameData("IntArrayTest")]
public int[] m_IntArray = new int[] { 0, 1, 23, 234 };
private static int[] s_DefaultList = new int[] { 0, 1, 23, 234 };
[GameDataList("IntListTest")]
public List<int> m_IntList = new List<int>(s_DefaultList);
[GameDataNumberAttribute("Rotation")] // This is for save game
public double m_Rotation = Math.PI / 2;
[GameDataList("BulletList")]
public List<Entity> m_BulletList = new List<Entity>();
private Vector2 m_Acceleration;
public Player m_LastPlayerToShot;
public int m_Score;
private int m_JoyStickIndex;
private bool m_TurningLeft;
private bool m_TurningRight;
private bool m_Thrusting;
private bool m_FiredBullet;
private bool m_FireKeyDown;
private Keys leftKey;
private Keys rightKey;
private Keys thrustKey;
private Keys fireKey;
private int playerIndex;
public Player(int in_playerIndex, int joyStickIndex, Keys in_leftKey, Keys in_rightKey,
Keys in_thrustKey, Keys in_fireKey)
: base(26)
{
playerIndex = in_playerIndex;
leftKey = in_leftKey;
rightKey = in_rightKey;
thrustKey = in_thrustKey;
fireKey = in_fireKey;
int playerSequenceIndex = GetPlayerIndex();
GameImageSequence playerShip = (GameImageSequence)DataAssetCache.Instance.GetAsset(typeof(GameImageSequence), "Player" + (playerSequenceIndex + 1).ToString() + "Ship");
m_Radius = playerShip.GetImageByIndex(0).Width / 2;
m_JoyStickIndex = joyStickIndex;
Position = new Vector2(GameWidth / 2, GameHeight / 2);
m_Velocity = Vector2.Zero;
}
private int GetPlayerIndex()
{
return playerIndex;
}
protected override void DoDraw(Graphics2D destRenderer)
{
int playerSequenceIndex = GetPlayerIndex();
GameImageSequence playerShip = (GameImageSequence)DataAssetCache.Instance.GetAsset(typeof(GameImageSequence), "Player" + (playerSequenceIndex + 1).ToString() + "Ship");
destRenderer.Render(playerShip.GetImageByRatio(m_Rotation / (2 * Math.PI)), m_Position.X, m_Position.Y);
}
internal void DrawBullets(Graphics2D destRenderer)
{
int playerSequenceIndex = GetPlayerIndex();
GameImageSequence bulletImage = (GameImageSequence)DataAssetCache.Instance.GetAsset(typeof(GameImageSequence), "Player" + (playerSequenceIndex + 1).ToString() + "Bullet");
foreach (Bullet aBullet in m_BulletList)
{
destRenderer.Render(bulletImage.GetImageByIndex(0), aBullet.Position.X, aBullet.Position.Y, aBullet.Velocity.GetAngle0To2PI(), 1, 1);
}
}
public void DrawScore(Graphics2D destRenderer)
{
int playerSequenceIndex = GetPlayerIndex();
GameImageSequence scoreSequence = (GameImageSequence)DataAssetCache.Instance.GetAsset(typeof(GameImageSequence), "ScoreNumbers");
string score = m_Score.ToString();
int x = 43;
int y = 577;
switch (playerSequenceIndex)
{
case 0:
break;
case 1:
x = 700;
break;
case 2:
x = 45;
y = 5;
break;
case 3:
x = 700;
y = 5;
break;
default:
break;
}
for (int i = 0; i < score.Length; i++)
{
int digit = (int)(score[i] - '0');
ImageBuffer numberImage = scoreSequence.GetImageByIndex(digit);
destRenderer.Render(numberImage, x, y);
x += numberImage.Width;
}
}
public void KeyDown(KeyEventArgs keyEvent)
{
if (keyEvent.KeyCode == leftKey)
{
m_TurningLeft = true;
}
if (keyEvent.KeyCode == rightKey)
{
m_TurningRight = true;
}
if (keyEvent.KeyCode == thrustKey)
{
m_Thrusting = true;
}
if (keyEvent.KeyCode == fireKey)
{
m_FireKeyDown = true;
}
}
public void KeyUp(KeyEventArgs keyEvent)
{
if (keyEvent.KeyCode == leftKey)
{
m_TurningLeft = false;
}
if (keyEvent.KeyCode == rightKey)
{
m_TurningRight = false;
}
if (keyEvent.KeyCode == thrustKey)
{
m_Thrusting = false;
}
if (keyEvent.KeyCode == fireKey)
{
m_FireKeyDown = false;
}
}
public override void Update(double numSecondsPassed)
{
#if false
Joystick joyStick = new Joystick(m_JoyStickIndex);
joyStick.Read();
bool joyThrusting = false;
if (m_JoyStickIndex != -1)
{
Vector2D joyDir;
joyDir.x = joyStick.xAxis1; joyDir.y = joyStick.yAxis1;
if (joyDir.GetLength() > .2)
{
Vector2D shipDir;
shipDir.x = Math.Cos(m_Rotation); shipDir.y = Math.Sin(m_Rotation);
double deltaAngle = shipDir.GetDeltaAngle(joyDir);
double maxAnglePerUpdate = Math.PI / 22;
if (deltaAngle > maxAnglePerUpdate) deltaAngle = maxAnglePerUpdate;
if (deltaAngle < -maxAnglePerUpdate) deltaAngle = -maxAnglePerUpdate;
m_Rotation += deltaAngle;
double stickAngle = Math.Atan2(joyDir.y, joyDir.x);
if (joyDir.GetLength() > .8)
{
joyThrusting = true;
}
}
}
#endif
if (m_Thrusting)// || joyThrusting)
{
m_Acceleration = new Vector2(Math.Cos(m_Rotation) * m_PlayerStyleSheetReference.Instance.ThrustAcceleration, Math.Sin(m_Rotation) * m_PlayerStyleSheetReference.Instance.ThrustAcceleration);
}
else
{
m_Acceleration = Vector2.Zero;
}
if (m_TurningLeft)
{
m_Rotation += m_PlayerStyleSheetReference.Instance.TurnRate * numSecondsPassed;
}
if (m_TurningRight)
{
m_Rotation -= m_PlayerStyleSheetReference.Instance.TurnRate * numSecondsPassed;
}
if (m_FireKeyDown)// || joyStick.button1)
{
if (!m_FiredBullet)
{
double bulletVelocity = 320;
// WIP: have a weapon and tell it to fire.
// set something to fire down
Vector2 DirectionVector = new Vector2(Math.Cos(m_Rotation), Math.Sin(m_Rotation));
m_BulletList.Add(new Bullet(Position + DirectionVector * m_PlayerStyleSheetReference.Instance.DistanceToFrontOfShip,
m_Velocity + DirectionVector * bulletVelocity));
m_FiredBullet = true;
m_PlayerStyleSheetReference.Instance.FireSoundReference.Instance.PlayAnAvailableCopy();
}
}
else
{
m_FiredBullet = false;
}
m_Rotation = MathHelper.Range0ToTau(m_Rotation);
m_Velocity += m_Acceleration * numSecondsPassed;
m_Velocity *= m_PlayerStyleSheetReference.Instance.Friction;
foreach (Bullet aBullet in m_BulletList)
{
aBullet.Update(numSecondsPassed);
}
base.Update(numSecondsPassed);
}
public void Respawn()
{
m_LastPlayerToShot = null;
Random rand = new Random();
Position = new Vector2(rand.NextDouble() * GameWidth, rand.NextDouble() * GameHeight);
m_Velocity = Vector2.Zero;
}
public override double GiveDamage()
{
// The player just hit something.
if (m_LastPlayerToShot != null)
{
m_LastPlayerToShot.m_Score += 1;
}
Respawn();
return m_PlayerStyleSheetReference.Instance.DamageOnCollide;
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using RestSharp;
using DocuSign.eSign.Client;
using DocuSign.eSign.Model;
namespace DocuSign.eSign.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface ICustomTabsApi
{
/// <summary>
/// Gets a list of all account tabs.
/// </summary>
/// <remarks>
/// Retrieves a list of all tabs associated with the account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="options">Options for modifying the behavior of the function.</param>
/// <returns>1TabMetadataList</returns>
TabMetadataList List (string accountId, CustomTabsApi.ListOptions options = null);
/// <summary>
/// Gets a list of all account tabs.
/// </summary>
/// <remarks>
/// Retrieves a list of all tabs associated with the account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="options">Options for modifying the behavior of the function.</param>
/// <returns>2ApiResponse of TabMetadataList</returns>
ApiResponse<TabMetadataList> ListWithHttpInfo (string accountId, CustomTabsApi.ListOptions options = null);
/// <summary>
/// Gets a list of all account tabs.
/// </summary>
/// <remarks>
/// Retrieves a list of all tabs associated with the account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="options">Options for modifying the behavior of the function.</param>
/// <returns>3Task of TabMetadataList</returns>
System.Threading.Tasks.Task<TabMetadataList> ListAsync (string accountId, CustomTabsApi.ListOptions options = null);
/// <summary>
/// Gets a list of all account tabs.
/// </summary>
/// <remarks>
/// Retrieves a list of all tabs associated with the account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="options">Options for modifying the behavior of the function.</param>
/// <returns>4Task of ApiResponse (TabMetadataList)</returns>
System.Threading.Tasks.Task<ApiResponse<TabMetadataList>> ListAsyncWithHttpInfo (string accountId, CustomTabsApi.ListOptions options = null);
/// <summary>
/// Creates a custom tab.
/// </summary>
/// <remarks>
/// Creates a tab with pre-defined properties, such as a text tab with a certain font type and validation pattern. Users can access the custom tabs when sending documents through the DocuSign web application.\n\nCustom tabs can be created for approve, checkbox, company, date, date signed, decline, email, email address, envelope ID, first name, formula, full name, initial here, last name, list, note, number, radio, sign here, signer attachment, SSN, text, title, and zip tabs.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="tabMetadata">TBD Description</param>
/// <returns>1TabMetadata</returns>
TabMetadata Create (string accountId, TabMetadata tabMetadata);
/// <summary>
/// Creates a custom tab.
/// </summary>
/// <remarks>
/// Creates a tab with pre-defined properties, such as a text tab with a certain font type and validation pattern. Users can access the custom tabs when sending documents through the DocuSign web application.\n\nCustom tabs can be created for approve, checkbox, company, date, date signed, decline, email, email address, envelope ID, first name, formula, full name, initial here, last name, list, note, number, radio, sign here, signer attachment, SSN, text, title, and zip tabs.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="tabMetadata">TBD Description</param>
/// <returns>2ApiResponse of TabMetadata</returns>
ApiResponse<TabMetadata> CreateWithHttpInfo (string accountId, TabMetadata tabMetadata);
/// <summary>
/// Creates a custom tab.
/// </summary>
/// <remarks>
/// Creates a tab with pre-defined properties, such as a text tab with a certain font type and validation pattern. Users can access the custom tabs when sending documents through the DocuSign web application.\n\nCustom tabs can be created for approve, checkbox, company, date, date signed, decline, email, email address, envelope ID, first name, formula, full name, initial here, last name, list, note, number, radio, sign here, signer attachment, SSN, text, title, and zip tabs.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="tabMetadata">TBD Description</param>
/// <returns>3Task of TabMetadata</returns>
System.Threading.Tasks.Task<TabMetadata> CreateAsync (string accountId, TabMetadata tabMetadata);
/// <summary>
/// Creates a custom tab.
/// </summary>
/// <remarks>
/// Creates a tab with pre-defined properties, such as a text tab with a certain font type and validation pattern. Users can access the custom tabs when sending documents through the DocuSign web application.\n\nCustom tabs can be created for approve, checkbox, company, date, date signed, decline, email, email address, envelope ID, first name, formula, full name, initial here, last name, list, note, number, radio, sign here, signer attachment, SSN, text, title, and zip tabs.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="tabMetadata">TBD Description</param>
/// <returns>4Task of ApiResponse (TabMetadata)</returns>
System.Threading.Tasks.Task<ApiResponse<TabMetadata>> CreateAsyncWithHttpInfo (string accountId, TabMetadata tabMetadata);
/// <summary>
/// Gets custom tab information.
/// </summary>
/// <remarks>
/// Retrieves information about the requested custom tab on the specified account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>1TabMetadata</returns>
TabMetadata Get (string accountId, string customTabId);
/// <summary>
/// Gets custom tab information.
/// </summary>
/// <remarks>
/// Retrieves information about the requested custom tab on the specified account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>2ApiResponse of TabMetadata</returns>
ApiResponse<TabMetadata> GetWithHttpInfo (string accountId, string customTabId);
/// <summary>
/// Gets custom tab information.
/// </summary>
/// <remarks>
/// Retrieves information about the requested custom tab on the specified account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>3Task of TabMetadata</returns>
System.Threading.Tasks.Task<TabMetadata> GetAsync (string accountId, string customTabId);
/// <summary>
/// Gets custom tab information.
/// </summary>
/// <remarks>
/// Retrieves information about the requested custom tab on the specified account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>4Task of ApiResponse (TabMetadata)</returns>
System.Threading.Tasks.Task<ApiResponse<TabMetadata>> GetAsyncWithHttpInfo (string accountId, string customTabId);
/// <summary>
/// Updates custom tab information.
/// </summary>
/// <remarks>
/// Updates the information in a custom tab for the specified account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param> <param name="tabMetadata">TBD Description</param>
/// <returns>1TabMetadata</returns>
TabMetadata Update (string accountId, string customTabId, TabMetadata tabMetadata);
/// <summary>
/// Updates custom tab information.
/// </summary>
/// <remarks>
/// Updates the information in a custom tab for the specified account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param> <param name="tabMetadata">TBD Description</param>
/// <returns>2ApiResponse of TabMetadata</returns>
ApiResponse<TabMetadata> UpdateWithHttpInfo (string accountId, string customTabId, TabMetadata tabMetadata);
/// <summary>
/// Updates custom tab information.
/// </summary>
/// <remarks>
/// Updates the information in a custom tab for the specified account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param> <param name="tabMetadata">TBD Description</param>
/// <returns>3Task of TabMetadata</returns>
System.Threading.Tasks.Task<TabMetadata> UpdateAsync (string accountId, string customTabId, TabMetadata tabMetadata);
/// <summary>
/// Updates custom tab information.
/// </summary>
/// <remarks>
/// Updates the information in a custom tab for the specified account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param> <param name="tabMetadata">TBD Description</param>
/// <returns>4Task of ApiResponse (TabMetadata)</returns>
System.Threading.Tasks.Task<ApiResponse<TabMetadata>> UpdateAsyncWithHttpInfo (string accountId, string customTabId, TabMetadata tabMetadata);
/// <summary>
/// Deletes custom tab information.
/// </summary>
/// <remarks>
/// Deletes the custom from the specified account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>1</returns>
void Delete (string accountId, string customTabId);
/// <summary>
/// Deletes custom tab information.
/// </summary>
/// <remarks>
/// Deletes the custom from the specified account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>2ApiResponse of Object(void)</returns>
ApiResponse<Object> DeleteWithHttpInfo (string accountId, string customTabId);
/// <summary>
/// Deletes custom tab information.
/// </summary>
/// <remarks>
/// Deletes the custom from the specified account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>3Task of void</returns>
System.Threading.Tasks.Task DeleteAsync (string accountId, string customTabId);
/// <summary>
/// Deletes custom tab information.
/// </summary>
/// <remarks>
/// Deletes the custom from the specified account.
/// </remarks>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>4Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> DeleteAsyncWithHttpInfo (string accountId, string customTabId);
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class CustomTabsApi : ICustomTabsApi
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomTabsApi"/> class.
/// </summary>
/// <returns></returns>
public CustomTabsApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
}
/// <summary>
/// Initializes a new instance of the <see cref="CustomTabsApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public CustomTabsApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Gets a list of all account tabs. Retrieves a list of all tabs associated with the account.
/// </summary>
public class ListOptions
{
/// When set to **true**, only custom tabs are returned in the response.
public string customTabOnly {get; set;}
}
/// <summary>
/// Gets a list of all account tabs. Retrieves a list of all tabs associated with the account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="options">Options for modifying the behavior of the function.</param>
/// <returns>5TabMetadataList</returns>
public TabMetadataList List (string accountId, CustomTabsApi.ListOptions options = null)
{
ApiResponse<TabMetadataList> response = ListWithHttpInfo(accountId, options);
return response.Data;
}
/// <summary>
/// Gets a list of all account tabs. Retrieves a list of all tabs associated with the account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="options">Options for modifying the behavior of the function.</param>
/// <returns>6ApiResponse of TabMetadataList</returns>
public ApiResponse< TabMetadataList > ListWithHttpInfo (string accountId, CustomTabsApi.ListOptions options = null)
{
// verify the required parameter 'accountId' is set
if (accountId == null) throw new ApiException(400, "Missing required parameter 'accountId' when calling List");
var path_ = "/v2/accounts/{accountId}/tab_definitions";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// to determine the Accept header
String[] http_header_accepts = new String[] {
"application/json"
};
String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts);
if (http_header_accept != null)
headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts));
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
pathParams.Add("format", "json");
if (accountId != null) pathParams.Add("accountId", Configuration.ApiClient.ParameterToString(accountId)); // path parameter
if (options != null)
{
if (options.customTabOnly != null) queryParams.Add("custom_tab_only", Configuration.ApiClient.ParameterToString(options.customTabOnly)); // query parameter
}
// make the HTTP request
IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams);
int statusCode = (int) response.StatusCode;
if (statusCode >= 400)
throw new ApiException (statusCode, "Error calling List: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException (statusCode, "Error calling List: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<TabMetadataList>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(TabMetadataList) Configuration.ApiClient.Deserialize(response, typeof(TabMetadataList)));
}
/// <summary>
/// Gets a list of all account tabs. Retrieves a list of all tabs associated with the account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="options">Options for modifying the behavior of the function.</param>
/// <returns>7Task of TabMetadataList</returns>
public async System.Threading.Tasks.Task<TabMetadataList> ListAsync (string accountId, CustomTabsApi.ListOptions options = null)
{
ApiResponse<TabMetadataList> response = await ListAsyncWithHttpInfo(accountId, options);
return response.Data;
}
/// <summary>
/// Gets a list of all account tabs. Retrieves a list of all tabs associated with the account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="options">Options for modifying the behavior of the function.</param>
/// <returns>8Task of ApiResponse (TabMetadataList)</returns>
public async System.Threading.Tasks.Task<ApiResponse<TabMetadataList>> ListAsyncWithHttpInfo (string accountId, CustomTabsApi.ListOptions options = null)
{
// verify the required parameter 'accountId' is set
if (accountId == null) throw new ApiException(400, "Missing required parameter 'accountId' when calling List");
var path_ = "/v2/accounts/{accountId}/tab_definitions";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// to determine the Accept header
String[] http_header_accepts = new String[] {
"application/json"
};
String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts);
if (http_header_accept != null)
headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts));
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
pathParams.Add("format", "json");
if (accountId != null) pathParams.Add("accountId", Configuration.ApiClient.ParameterToString(accountId)); // path parameter
if (options != null)
{
if (options.customTabOnly != null) queryParams.Add("custom_tab_only", Configuration.ApiClient.ParameterToString(options.customTabOnly)); // query parameter
}
// make the HTTP request
IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams);
int statusCode = (int) response.StatusCode;
if (statusCode >= 400)
throw new ApiException (statusCode, "Error calling List: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException (statusCode, "Error calling List: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<TabMetadataList>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(TabMetadataList) Configuration.ApiClient.Deserialize(response, typeof(TabMetadataList)));
}
/// <summary>
/// Creates a custom tab. Creates a tab with pre-defined properties, such as a text tab with a certain font type and validation pattern. Users can access the custom tabs when sending documents through the DocuSign web application.\n\nCustom tabs can be created for approve, checkbox, company, date, date signed, decline, email, email address, envelope ID, first name, formula, full name, initial here, last name, list, note, number, radio, sign here, signer attachment, SSN, text, title, and zip tabs.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="tabMetadata">TBD Description</param>
/// <returns>5TabMetadata</returns>
public TabMetadata Create (string accountId, TabMetadata tabMetadata)
{
ApiResponse<TabMetadata> response = CreateWithHttpInfo(accountId, tabMetadata);
return response.Data;
}
/// <summary>
/// Creates a custom tab. Creates a tab with pre-defined properties, such as a text tab with a certain font type and validation pattern. Users can access the custom tabs when sending documents through the DocuSign web application.\n\nCustom tabs can be created for approve, checkbox, company, date, date signed, decline, email, email address, envelope ID, first name, formula, full name, initial here, last name, list, note, number, radio, sign here, signer attachment, SSN, text, title, and zip tabs.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="tabMetadata">TBD Description</param>
/// <returns>6ApiResponse of TabMetadata</returns>
public ApiResponse< TabMetadata > CreateWithHttpInfo (string accountId, TabMetadata tabMetadata)
{
// verify the required parameter 'accountId' is set
if (accountId == null) throw new ApiException(400, "Missing required parameter 'accountId' when calling Create");
var path_ = "/v2/accounts/{accountId}/tab_definitions";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// to determine the Accept header
String[] http_header_accepts = new String[] {
"application/json"
};
String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts);
if (http_header_accept != null)
headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts));
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
pathParams.Add("format", "json");
if (accountId != null) pathParams.Add("accountId", Configuration.ApiClient.ParameterToString(accountId)); // path parameter
postBody = Configuration.ApiClient.Serialize(tabMetadata); // http body (model) parameter
// make the HTTP request
IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams);
int statusCode = (int) response.StatusCode;
if (statusCode >= 400)
throw new ApiException (statusCode, "Error calling Create: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException (statusCode, "Error calling Create: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<TabMetadata>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(TabMetadata) Configuration.ApiClient.Deserialize(response, typeof(TabMetadata)));
}
/// <summary>
/// Creates a custom tab. Creates a tab with pre-defined properties, such as a text tab with a certain font type and validation pattern. Users can access the custom tabs when sending documents through the DocuSign web application.\n\nCustom tabs can be created for approve, checkbox, company, date, date signed, decline, email, email address, envelope ID, first name, formula, full name, initial here, last name, list, note, number, radio, sign here, signer attachment, SSN, text, title, and zip tabs.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="tabMetadata">TBD Description</param>
/// <returns>7Task of TabMetadata</returns>
public async System.Threading.Tasks.Task<TabMetadata> CreateAsync (string accountId, TabMetadata tabMetadata)
{
ApiResponse<TabMetadata> response = await CreateAsyncWithHttpInfo(accountId, tabMetadata);
return response.Data;
}
/// <summary>
/// Creates a custom tab. Creates a tab with pre-defined properties, such as a text tab with a certain font type and validation pattern. Users can access the custom tabs when sending documents through the DocuSign web application.\n\nCustom tabs can be created for approve, checkbox, company, date, date signed, decline, email, email address, envelope ID, first name, formula, full name, initial here, last name, list, note, number, radio, sign here, signer attachment, SSN, text, title, and zip tabs.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param> <param name="tabMetadata">TBD Description</param>
/// <returns>8Task of ApiResponse (TabMetadata)</returns>
public async System.Threading.Tasks.Task<ApiResponse<TabMetadata>> CreateAsyncWithHttpInfo (string accountId, TabMetadata tabMetadata)
{
// verify the required parameter 'accountId' is set
if (accountId == null) throw new ApiException(400, "Missing required parameter 'accountId' when calling Create");
var path_ = "/v2/accounts/{accountId}/tab_definitions";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// to determine the Accept header
String[] http_header_accepts = new String[] {
"application/json"
};
String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts);
if (http_header_accept != null)
headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts));
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
pathParams.Add("format", "json");
if (accountId != null) pathParams.Add("accountId", Configuration.ApiClient.ParameterToString(accountId)); // path parameter
postBody = Configuration.ApiClient.Serialize(tabMetadata); // http body (model) parameter
// make the HTTP request
IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams);
int statusCode = (int) response.StatusCode;
if (statusCode >= 400)
throw new ApiException (statusCode, "Error calling Create: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException (statusCode, "Error calling Create: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<TabMetadata>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(TabMetadata) Configuration.ApiClient.Deserialize(response, typeof(TabMetadata)));
}
/// <summary>
/// Gets custom tab information. Retrieves information about the requested custom tab on the specified account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>5TabMetadata</returns>
public TabMetadata Get (string accountId, string customTabId)
{
ApiResponse<TabMetadata> response = GetWithHttpInfo(accountId, customTabId);
return response.Data;
}
/// <summary>
/// Gets custom tab information. Retrieves information about the requested custom tab on the specified account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>6ApiResponse of TabMetadata</returns>
public ApiResponse< TabMetadata > GetWithHttpInfo (string accountId, string customTabId)
{
// verify the required parameter 'accountId' is set
if (accountId == null) throw new ApiException(400, "Missing required parameter 'accountId' when calling Get");
// verify the required parameter 'customTabId' is set
if (customTabId == null) throw new ApiException(400, "Missing required parameter 'customTabId' when calling Get");
var path_ = "/v2/accounts/{accountId}/tab_definitions/{customTabId}";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// to determine the Accept header
String[] http_header_accepts = new String[] {
"application/json"
};
String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts);
if (http_header_accept != null)
headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts));
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
pathParams.Add("format", "json");
if (accountId != null) pathParams.Add("accountId", Configuration.ApiClient.ParameterToString(accountId)); // path parameter
if (customTabId != null) pathParams.Add("customTabId", Configuration.ApiClient.ParameterToString(customTabId)); // path parameter
// make the HTTP request
IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams);
int statusCode = (int) response.StatusCode;
if (statusCode >= 400)
throw new ApiException (statusCode, "Error calling Get: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException (statusCode, "Error calling Get: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<TabMetadata>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(TabMetadata) Configuration.ApiClient.Deserialize(response, typeof(TabMetadata)));
}
/// <summary>
/// Gets custom tab information. Retrieves information about the requested custom tab on the specified account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>7Task of TabMetadata</returns>
public async System.Threading.Tasks.Task<TabMetadata> GetAsync (string accountId, string customTabId)
{
ApiResponse<TabMetadata> response = await GetAsyncWithHttpInfo(accountId, customTabId);
return response.Data;
}
/// <summary>
/// Gets custom tab information. Retrieves information about the requested custom tab on the specified account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>8Task of ApiResponse (TabMetadata)</returns>
public async System.Threading.Tasks.Task<ApiResponse<TabMetadata>> GetAsyncWithHttpInfo (string accountId, string customTabId)
{
// verify the required parameter 'accountId' is set
if (accountId == null) throw new ApiException(400, "Missing required parameter 'accountId' when calling Get");
// verify the required parameter 'customTabId' is set
if (customTabId == null) throw new ApiException(400, "Missing required parameter 'customTabId' when calling Get");
var path_ = "/v2/accounts/{accountId}/tab_definitions/{customTabId}";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// to determine the Accept header
String[] http_header_accepts = new String[] {
"application/json"
};
String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts);
if (http_header_accept != null)
headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts));
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
pathParams.Add("format", "json");
if (accountId != null) pathParams.Add("accountId", Configuration.ApiClient.ParameterToString(accountId)); // path parameter
if (customTabId != null) pathParams.Add("customTabId", Configuration.ApiClient.ParameterToString(customTabId)); // path parameter
// make the HTTP request
IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams);
int statusCode = (int) response.StatusCode;
if (statusCode >= 400)
throw new ApiException (statusCode, "Error calling Get: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException (statusCode, "Error calling Get: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<TabMetadata>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(TabMetadata) Configuration.ApiClient.Deserialize(response, typeof(TabMetadata)));
}
/// <summary>
/// Updates custom tab information. Updates the information in a custom tab for the specified account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param> <param name="tabMetadata">TBD Description</param>
/// <returns>5TabMetadata</returns>
public TabMetadata Update (string accountId, string customTabId, TabMetadata tabMetadata)
{
ApiResponse<TabMetadata> response = UpdateWithHttpInfo(accountId, customTabId, tabMetadata);
return response.Data;
}
/// <summary>
/// Updates custom tab information. Updates the information in a custom tab for the specified account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param> <param name="tabMetadata">TBD Description</param>
/// <returns>6ApiResponse of TabMetadata</returns>
public ApiResponse< TabMetadata > UpdateWithHttpInfo (string accountId, string customTabId, TabMetadata tabMetadata)
{
// verify the required parameter 'accountId' is set
if (accountId == null) throw new ApiException(400, "Missing required parameter 'accountId' when calling Update");
// verify the required parameter 'customTabId' is set
if (customTabId == null) throw new ApiException(400, "Missing required parameter 'customTabId' when calling Update");
var path_ = "/v2/accounts/{accountId}/tab_definitions/{customTabId}";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// to determine the Accept header
String[] http_header_accepts = new String[] {
"application/json"
};
String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts);
if (http_header_accept != null)
headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts));
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
pathParams.Add("format", "json");
if (accountId != null) pathParams.Add("accountId", Configuration.ApiClient.ParameterToString(accountId)); // path parameter
if (customTabId != null) pathParams.Add("customTabId", Configuration.ApiClient.ParameterToString(customTabId)); // path parameter
postBody = Configuration.ApiClient.Serialize(tabMetadata); // http body (model) parameter
// make the HTTP request
IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams);
int statusCode = (int) response.StatusCode;
if (statusCode >= 400)
throw new ApiException (statusCode, "Error calling Update: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException (statusCode, "Error calling Update: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<TabMetadata>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(TabMetadata) Configuration.ApiClient.Deserialize(response, typeof(TabMetadata)));
}
/// <summary>
/// Updates custom tab information. Updates the information in a custom tab for the specified account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param> <param name="tabMetadata">TBD Description</param>
/// <returns>7Task of TabMetadata</returns>
public async System.Threading.Tasks.Task<TabMetadata> UpdateAsync (string accountId, string customTabId, TabMetadata tabMetadata)
{
ApiResponse<TabMetadata> response = await UpdateAsyncWithHttpInfo(accountId, customTabId, tabMetadata);
return response.Data;
}
/// <summary>
/// Updates custom tab information. Updates the information in a custom tab for the specified account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param> <param name="tabMetadata">TBD Description</param>
/// <returns>8Task of ApiResponse (TabMetadata)</returns>
public async System.Threading.Tasks.Task<ApiResponse<TabMetadata>> UpdateAsyncWithHttpInfo (string accountId, string customTabId, TabMetadata tabMetadata)
{
// verify the required parameter 'accountId' is set
if (accountId == null) throw new ApiException(400, "Missing required parameter 'accountId' when calling Update");
// verify the required parameter 'customTabId' is set
if (customTabId == null) throw new ApiException(400, "Missing required parameter 'customTabId' when calling Update");
var path_ = "/v2/accounts/{accountId}/tab_definitions/{customTabId}";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// to determine the Accept header
String[] http_header_accepts = new String[] {
"application/json"
};
String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts);
if (http_header_accept != null)
headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts));
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
pathParams.Add("format", "json");
if (accountId != null) pathParams.Add("accountId", Configuration.ApiClient.ParameterToString(accountId)); // path parameter
if (customTabId != null) pathParams.Add("customTabId", Configuration.ApiClient.ParameterToString(customTabId)); // path parameter
postBody = Configuration.ApiClient.Serialize(tabMetadata); // http body (model) parameter
// make the HTTP request
IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams);
int statusCode = (int) response.StatusCode;
if (statusCode >= 400)
throw new ApiException (statusCode, "Error calling Update: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException (statusCode, "Error calling Update: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<TabMetadata>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(TabMetadata) Configuration.ApiClient.Deserialize(response, typeof(TabMetadata)));
}
/// <summary>
/// Deletes custom tab information. Deletes the custom from the specified account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>5</returns>
public void Delete (string accountId, string customTabId)
{
DeleteWithHttpInfo(accountId, customTabId);
}
/// <summary>
/// Deletes custom tab information. Deletes the custom from the specified account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>6ApiResponse of Object(void)</returns>
public ApiResponse<Object> DeleteWithHttpInfo (string accountId, string customTabId)
{
// verify the required parameter 'accountId' is set
if (accountId == null) throw new ApiException(400, "Missing required parameter 'accountId' when calling Delete");
// verify the required parameter 'customTabId' is set
if (customTabId == null) throw new ApiException(400, "Missing required parameter 'customTabId' when calling Delete");
var path_ = "/v2/accounts/{accountId}/tab_definitions/{customTabId}";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// to determine the Accept header
String[] http_header_accepts = new String[] {
"application/json"
};
String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts);
if (http_header_accept != null)
headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts));
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
pathParams.Add("format", "json");
if (accountId != null) pathParams.Add("accountId", Configuration.ApiClient.ParameterToString(accountId)); // path parameter
if (customTabId != null) pathParams.Add("customTabId", Configuration.ApiClient.ParameterToString(customTabId)); // path parameter
// make the HTTP request
IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams);
int statusCode = (int) response.StatusCode;
if (statusCode >= 400)
throw new ApiException (statusCode, "Error calling Delete: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException (statusCode, "Error calling Delete: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<Object>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Deletes custom tab information. Deletes the custom from the specified account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>7Task of void</returns>
public async System.Threading.Tasks.Task DeleteAsync (string accountId, string customTabId)
{
await DeleteAsyncWithHttpInfo(accountId, customTabId);
}
/// <summary>
/// Deletes custom tab information. Deletes the custom from the specified account.
/// </summary>
///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="customTabId"></param>
/// <returns>8Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> DeleteAsyncWithHttpInfo (string accountId, string customTabId)
{
// verify the required parameter 'accountId' is set
if (accountId == null) throw new ApiException(400, "Missing required parameter 'accountId' when calling Delete");
// verify the required parameter 'customTabId' is set
if (customTabId == null) throw new ApiException(400, "Missing required parameter 'customTabId' when calling Delete");
var path_ = "/v2/accounts/{accountId}/tab_definitions/{customTabId}";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// to determine the Accept header
String[] http_header_accepts = new String[] {
"application/json"
};
String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts);
if (http_header_accept != null)
headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts));
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
pathParams.Add("format", "json");
if (accountId != null) pathParams.Add("accountId", Configuration.ApiClient.ParameterToString(accountId)); // path parameter
if (customTabId != null) pathParams.Add("customTabId", Configuration.ApiClient.ParameterToString(customTabId)); // path parameter
// make the HTTP request
IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams);
int statusCode = (int) response.StatusCode;
if (statusCode >= 400)
throw new ApiException (statusCode, "Error calling Delete: " + response.Content, response.Content);
else if (statusCode == 0)
throw new ApiException (statusCode, "Error calling Delete: " + response.ErrorMessage, response.ErrorMessage);
return new ApiResponse<Object>(statusCode,
response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
}
}
| |
using System;
using System.Collections.Generic;
#if !(NET_35 || NET_40)
using System.Threading.Tasks;
#endif
using BackendlessAPI.Exception;
using BackendlessAPI.Engine;
using BackendlessAPI.Service;
using BackendlessAPI.Persistence;
using BackendlessAPI.Async;
#if WITHRT
using BackendlessAPI.RT.Data;
#endif
namespace BackendlessAPI.Data
{
class DictionaryDrivenDataStore : IDataStore<Dictionary<String, Object>>
{
private const String PERSISTENCE_MANAGER_SERVER_ALIAS = "com.backendless.services.persistence.PersistenceService";
//private EventHandlerFactory<Dictionary<String, Object>> eventHandlerFactory = new EventHandlerFactory<Dictionary<String, Object>>();
private readonly String tableName;
public DictionaryDrivenDataStore( String tableName )
{
this.tableName = tableName;
#if WITHRT
eventHandler = EventHandlerFactory.Of( tableName );
#endif
}
#region RT
#if WITHRT
private readonly IEventHandler<Dictionary<String, Object>> eventHandler;
public IEventHandler<Dictionary<String, Object>> RT()
{
return this.eventHandler;
}
#endif
#endregion
#region Bulk Update
public Int32 Update( String whereClause, Dictionary<String, Object> changes )
{
return Update( whereClause, changes, null, false );
}
#if !(NET_35 || NET_40)
public async Task<Int32> UpdateAsync( String whereClause, Dictionary<String, Object> changes )
{
return await Task.Run( () => Update( whereClause, changes ) ).ConfigureAwait( false );
}
#endif
public void Update( String whereClause, Dictionary<String, Object> changes, AsyncCallback<Int32> callback )
{
Update( whereClause, changes, callback, true );
}
private Int32 Update( String whereClause, Dictionary<String, Object> changes, AsyncCallback<Int32> callback,
Boolean async )
{
if( whereClause == null || whereClause.Trim().Length == 0 )
throw new ArgumentNullException( String.Format( ExceptionMessage.NULL_OR_EMPTY_TEMPLATE, "Where clause" ) );
if( changes == null || changes.Count == 0 )
throw new ArgumentNullException( String.Format( ExceptionMessage.NULL_OR_EMPTY_TEMPLATE,
"Object with changes" ) );
Object[] args = { tableName, whereClause, changes };
if( async )
Invoker.InvokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "updateBulk", args, callback );
else
return Invoker.InvokeSync<Int32>( PERSISTENCE_MANAGER_SERVER_ALIAS, "updateBulk", args );
// not used
return -1;
}
#endregion
#region Bulk Create
public IList<String> Create( IList<Dictionary<String, Object>> objects )
{
if( objects == null )
throw new ArgumentNullException( String.Format( ExceptionMessage.NULL_OR_EMPTY_TEMPLATE,
"Object collection" ) );
if( objects.Count == 0 )
return new List<String>();
Object[] args = new Object[] { tableName, objects };
return Invoker.InvokeSync<IList<String>>( PERSISTENCE_MANAGER_SERVER_ALIAS, "createBulk", args );
}
#if !(NET_35 || NET_40)
public async Task<IList<String>> CreateAsync( IList<Dictionary<String, Object>> objects )
{
return await Task.Run( () => Create( objects ) ).ConfigureAwait( false );
}
#endif
public void Create( IList<Dictionary<String, Object>> objects, AsyncCallback<IList<String>> callback )
{
if( objects == null )
throw new ArgumentNullException( String.Format( ExceptionMessage.NULL_OR_EMPTY_TEMPLATE,
"Object collection" ) );
if( objects.Count == 0 )
callback.ResponseHandler( new List<String>() );
Object[] args = new Object[] { tableName, objects };
Invoker.InvokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "createBulk", args, callback );
}
#endregion
#region Bulk Delete
public Int32 Remove( String whereClause )
{
return Remove( whereClause, null, false );
}
#if !(NET_35 || NET_40)
public async Task<Int32> RemoveAsync( String whereClause )
{
return await Task.Run( () => Remove( whereClause ) ).ConfigureAwait( false );
}
#endif
public void Remove( String whereClause, AsyncCallback<Int32> callback )
{
Remove( whereClause, callback, true );
}
private Int32 Remove( String whereClause, AsyncCallback<Int32> callback, Boolean async )
{
if( whereClause == null || whereClause.Trim().Length == 0 )
throw new ArgumentNullException( String.Format( ExceptionMessage.NULL_OR_EMPTY_TEMPLATE, "Where clause" ) );
Object[] args = new Object[] { tableName, whereClause };
if( async )
Invoker.InvokeAsync<Int32>( PERSISTENCE_MANAGER_SERVER_ALIAS, "removeBulk", args, callback );
else
return Invoker.InvokeSync<Int32>( PERSISTENCE_MANAGER_SERVER_ALIAS, "removeBulk", args );
// not used
return -1;
}
#endregion
#region Save
public Dictionary<String, Object> Save( Dictionary<String, Object> entity, Boolean isUpsert = false )
{
if( entity == null )
throw new ArgumentNullException( ExceptionMessage.NULL_ENTITY );
String operation = "save";
if( isUpsert )
operation = "upsert";
Object[] args = new Object[] { tableName, entity };
return Invoker.InvokeSync<Dictionary<String, Object>>( PERSISTENCE_MANAGER_SERVER_ALIAS, operation, args );
}
#if !(NET_35 || NET_40)
public async Task<Dictionary<String, Object>> SaveAsync( Dictionary<String, Object> entity, Boolean isUpsert = false )
{
return await Task.Run( () => Save( entity, isUpsert ) ).ConfigureAwait( false );
}
#endif
public void Save( Dictionary<String, Object> entity, AsyncCallback<Dictionary<String, Object>> callback, Boolean isUpsert = false )
{
if( entity == null )
throw new ArgumentNullException( ExceptionMessage.NULL_ENTITY );
String operation = "save";
if( isUpsert )
operation = "upsert";
Object[] args = new Object[] { tableName, entity };
Invoker.InvokeAsync<Dictionary<String, Object>>( PERSISTENCE_MANAGER_SERVER_ALIAS, operation, args, callback );
}
#endregion
#region Deep Save
public Dictionary<String, Object> DeepSave( Dictionary<String, Object> map )
{
if( map == null )
throw new ArgumentException( ExceptionMessage.NULL_MAP );
return Invoker.InvokeSync<Dictionary<String, Object>>( PERSISTENCE_MANAGER_SERVER_ALIAS, "deepSave", new Object[] { tableName, map } );
}
#if !(NET_35 || NET_40)
public async Task<Dictionary<String, Object>> DeepSaveAsync( Dictionary<String, Object> map )
{
return await Task.Run( () => DeepSave( map ) ).ConfigureAwait( false );
}
#endif
public void DeepSave( Dictionary<String, Object> map, AsyncCallback<Dictionary<String, Object>> callback )
{
if( map == null )
throw new ArgumentException( ExceptionMessage.NULL_MAP );
Invoker.InvokeAsync<Dictionary<String, Object>>( PERSISTENCE_MANAGER_SERVER_ALIAS, "deepSave",
new Object[] { tableName, map }, true, callback );
}
#endregion
#region Remove
public long Remove( Dictionary<String, Object> entity )
{
if( entity == null )
throw new ArgumentNullException( ExceptionMessage.NULL_ENTITY );
Object[] args = new Object[] { tableName, entity };
return Invoker.InvokeSync<long>( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", args );
}
#if !( NET_35 || NET_40 )
public async Task<long> RemoveAsync( Dictionary<String, Object> entity )
{
return await Task.Run( () => Remove( entity ) ).ConfigureAwait( false );
}
#endif
public void Remove( Dictionary<String, Object> entity, AsyncCallback<long> responder )
{
if( entity == null )
throw new ArgumentNullException( ExceptionMessage.NULL_ENTITY );
Object[] args = new Object[] { tableName, entity };
Invoker.InvokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", args, responder );
}
#endregion
#region First
public Dictionary<String, Object> FindFirst()
{
return Invoker.InvokeSync<Dictionary<String, Object>>( PERSISTENCE_MANAGER_SERVER_ALIAS, "first", new Object[] { tableName } );
}
#if !( NET_35 || NET_40 )
public async Task<Dictionary<String, Object>> FindFirstAsync()
{
return await Task.Run( () => FindFirst() ).ConfigureAwait( false );
}
#endif
public void FindFirst( AsyncCallback<Dictionary<String, Object>> responder )
{
Invoker.InvokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "first", new Object[] { tableName }, responder );
}
#endregion
#region Last
public Dictionary<String, Object> FindLast()
{
return Invoker.InvokeSync<Dictionary<String, Object>>( PERSISTENCE_MANAGER_SERVER_ALIAS, "last", new Object[] { tableName } );
}
#if !( NET_35 || NET_40 )
public async Task<Dictionary<String, Object>> FindLastAsync()
{
return await Task.Run( () => FindLast() ).ConfigureAwait( false );
}
#endif
public void FindLast( AsyncCallback<Dictionary<String, Object>> responder )
{
Invoker.InvokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "last", new Object[] { tableName }, responder );
}
#endregion
#region Find
public IList<Dictionary<String, Object>> Find()
{
return Find( (DataQueryBuilder) null );
}
public IList<Dictionary<String, Object>> Find( DataQueryBuilder dataQueryBuilder )
{
if( dataQueryBuilder == null )
dataQueryBuilder = DataQueryBuilder.Create();
BackendlessDataQuery dataQuery = dataQueryBuilder.Build();
PersistenceService.CheckPageSizeAndOffset( dataQuery );
Object[] args = { tableName, dataQuery };
return Invoker.InvokeSync<IList<Dictionary<String, Object>>>( PERSISTENCE_MANAGER_SERVER_ALIAS, "find", args );
}
#if !( NET_35 || NET_40 )
public async Task<IList<Dictionary<String, Object>>> FindAsync()
{
return await Task.Run( () => Find() ).ConfigureAwait( false );
}
public async Task<IList<Dictionary<String, Object>>> FindAsync( DataQueryBuilder queryBuilder )
{
return await Task.Run( () => Find( queryBuilder ) ).ConfigureAwait( false );
}
#endif
public void Find( AsyncCallback<IList<Dictionary<String, Object>>> responder )
{
Find( (DataQueryBuilder) null, responder );
}
public void Find( DataQueryBuilder dataQueryBuilder, AsyncCallback<IList<Dictionary<String, Object>>> callback )
{
var responder = new AsyncCallback<IList<Dictionary<String, Object>>>(
r =>
{
if( callback != null )
callback.ResponseHandler.Invoke( r );
},
f =>
{
if( callback != null )
callback.ErrorHandler.Invoke( f );
else
throw new BackendlessException( f );
} );
if( dataQueryBuilder == null )
dataQueryBuilder = DataQueryBuilder.Create();
BackendlessDataQuery dataQuery = dataQueryBuilder.Build();
Object[] args = { tableName, dataQuery };
Invoker.InvokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "find", args, responder );
}
#endregion
#region Find By Id
public Dictionary<String, Object> FindById( String id )
{
return FindById( id, 0 );
}
public Dictionary<String, Object> FindById( String id, DataQueryBuilder queryBuilder )
{
return Invoker.InvokeSync<Dictionary<String, Object>>( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", new Object[] { tableName, id, queryBuilder.Build() } );
}
public Dictionary<String, Object> FindById( Dictionary<String, Object> entity, DataQueryBuilder queryBuilder )
{
return Invoker.InvokeSync<Dictionary<String, Object>>( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", new Object[] { tableName, entity, queryBuilder.Build() } );
}
public void FindById( String id, DataQueryBuilder queryBuilder, AsyncCallback<Dictionary<String, Object>> callback )
{
Invoker.InvokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", new Object[] { tableName, id, queryBuilder.Build() }, callback );
}
public void FindById( Dictionary<String, Object> entity, DataQueryBuilder queryBuilder, AsyncCallback<Dictionary<String, Object>> callback )
{
Invoker.InvokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", new Object[] { tableName, entity, queryBuilder.Build() }, callback );
}
public Dictionary<String, Object> FindById( String id, Int32? relationsDepth )
{
return FindById( id, null, relationsDepth );
}
public Dictionary<String, Object> FindById( String id, IList<String> relations )
{
return FindById( id, relations, 0 );
}
public Dictionary<String, Object> FindById( String id, IList<String> relations, Int32? relationsDepth )
{
return Invoker.InvokeSync<Dictionary<String, Object>>( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", CreateArgs( id, relations, relationsDepth ) );
}
public Dictionary<String, Object> FindById( Dictionary<String, Object> entity )
{
return FindById( entity, null, 0 );
}
public Dictionary<String, Object> FindById( Dictionary<String, Object> entity, Int32? relationsDepth )
{
return FindById( entity, null, relationsDepth );
}
public Dictionary<String, Object> FindById( Dictionary<String, Object> entity, IList<String> relations )
{
return FindById( entity, relations, 0 );
}
public Dictionary<String, Object> FindById( Dictionary<String, Object> entity, IList<String> relations, Int32? relationsDepth )
{
return Invoker.InvokeSync<Dictionary<String, Object>>( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById",
CreateArgs( entity, relations, relationsDepth ) );
}
#if !( NET_35 || NET_40 )
public async Task<Dictionary<String, Object>> FindByIdAsync( String id )
{
return await Task.Run( () => FindById( id ) ).ConfigureAwait( false );
}
public async Task<Dictionary<String, Object>> FindByIdAsync( String id, DataQueryBuilder queryBuilder )
{
return await Task.Run( () => FindById( id, queryBuilder ) ).ConfigureAwait( false );
}
public async Task<Dictionary<String, Object>> FindByIdAsync( Dictionary<String, Object> entity, DataQueryBuilder queryBuilder )
{
return await Task.Run( () => FindById( entity, queryBuilder ) ).ConfigureAwait( false );
}
public async Task<Dictionary<String, Object>> FindByIdAsync( String id, Int32? relationsDepth )
{
return await Task.Run( () => FindById( id, relationsDepth ) ).ConfigureAwait( false );
}
public async Task<Dictionary<String, Object>> FindByIdAsync( String id, IList<String> relations )
{
return await Task.Run( () => FindById( id, relations ) ).ConfigureAwait( false );
}
public async Task<Dictionary<String, Object>> FindByIdAsync( String id, IList<String> relations,
Int32? relationsDepth )
{
return await Task.Run( () => FindById( id, relations, relationsDepth ) ).ConfigureAwait( false );
}
public async Task<Dictionary<String, Object>> FindByIdAsync( Dictionary<String, Object> entity )
{
return await Task.Run( () => FindById( entity ) ).ConfigureAwait( false );
}
public async Task<Dictionary<String, Object>> FindByIdAsync( Dictionary<String, Object> entity, Int32? relationsDepth )
{
return await Task.Run( () => FindById( entity, relationsDepth ) ).ConfigureAwait( false );
}
public async Task<Dictionary<String, Object>> FindByIdAsync( Dictionary<String, Object> entity, IList<String> relations )
{
return await Task.Run( () => FindById( entity, relations ) ).ConfigureAwait( false );
}
public async Task<Dictionary<String, Object>> FindByIdAsync( Dictionary<String, Object> entity, IList<String> relations,
Int32? relationsDepth )
{
return await Task.Run( () => FindById( entity, relations, relationsDepth ) ).ConfigureAwait( false );
}
#endif
public void FindById( String id, AsyncCallback<Dictionary<String, Object>> responder )
{
FindById( id, null, 0, responder );
}
public void FindById( String id, Int32? relationsDepth, AsyncCallback<Dictionary<String, Object>> responder )
{
FindById( id, null, relationsDepth, responder );
}
public void FindById( String id, IList<String> relations, AsyncCallback<Dictionary<String, Object>> responder )
{
FindById( id, relations, 0, responder );
}
public void FindById( String id, IList<String> relations, Int32? relationsDepth,
AsyncCallback<Dictionary<String, Object>> responder )
{
Invoker.InvokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", CreateArgs( id, relations, relationsDepth ), responder );
}
public void FindById( Dictionary<String, Object> entity, AsyncCallback<Dictionary<String, Object>> responder )
{
FindById( entity, null, 0, responder );
}
public void FindById( Dictionary<String, Object> entity, Int32? relationsDepth,
AsyncCallback<Dictionary<String, Object>> responder )
{
FindById( entity, null, relationsDepth, responder );
}
public void FindById( Dictionary<String, Object> entity, IList<String> relations,
AsyncCallback<Dictionary<String, Object>> responder )
{
FindById( entity, relations, 0, responder );
}
public void FindById( Dictionary<String, Object> entity, IList<String> relations, Int32? relationsDepth,
AsyncCallback<Dictionary<String, Object>> responder )
{
Invoker.InvokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", CreateArgs( entity, relations, relationsDepth ), responder );
}
#endregion
#region Load Relations
public IList<M> LoadRelations<M>( String objectId, LoadRelationsQueryBuilder<M> queryBuilder )
{
return Backendless.Persistence.LoadRelations<M>( tableName, objectId, queryBuilder );
}
#if !( NET_35 || NET_40 )
public async Task<IList<M>> LoadRelationsAsync<M>( String objectId, LoadRelationsQueryBuilder<M> queryBuilder )
{
return await Task.Run( () => LoadRelations( objectId, queryBuilder ) ).ConfigureAwait( false );
}
#endif
public void LoadRelations<M>( String objectId, LoadRelationsQueryBuilder<M> queryBuilder,
AsyncCallback<IList<M>> responder )
{
Backendless.Persistence.LoadRelations<M>( tableName, objectId, queryBuilder, responder );
}
#endregion
#region Get Object Count
public Int32 GetObjectCount()
{
return Invoker.InvokeSync<Int32>( PERSISTENCE_MANAGER_SERVER_ALIAS, "count", new Object[] { tableName }, true );
}
public Int32 GetObjectCount( DataQueryBuilder dataQueryBuilder )
{
BackendlessDataQuery dataQuery = dataQueryBuilder.Build();
return Invoker.InvokeSync<Int32>( PERSISTENCE_MANAGER_SERVER_ALIAS, "count", new Object[] { tableName, dataQuery },
true );
}
#if !( NET_35 || NET_40 )
public async Task<Int32> GetObjectCountAsync()
{
return await Task.Run( () => GetObjectCount() ).ConfigureAwait( false );
}
public async Task<Int32> GetObjectCountAsync( DataQueryBuilder dataQueryBuilder )
{
return await Task.Run( () => GetObjectCount( dataQueryBuilder ) ).ConfigureAwait( false );
}
#endif
public void GetObjectCount( AsyncCallback<Int32> responder )
{
Invoker.InvokeAsync<Int32>( PERSISTENCE_MANAGER_SERVER_ALIAS, "count", new Object[] { tableName }, true,
responder );
}
public void GetObjectCount( DataQueryBuilder dataQueryBuilder, AsyncCallback<Int32> responder )
{
BackendlessDataQuery dataQuery = dataQueryBuilder.Build();
Invoker.InvokeAsync<Int32>( PERSISTENCE_MANAGER_SERVER_ALIAS, "count", new Object[] { tableName, dataQuery }, true,
responder );
}
#endregion
#region ADD RELATION
public void AddRelation( Dictionary<String, Object> parent, String columnName, Object[] children )
{
Backendless.Data.AddRelation<Dictionary<String, Object>>( tableName, parent, columnName, children );
}
public Int32 AddRelation( Dictionary<String, Object> parent, String columnName, String whereClause )
{
return Backendless.Data.AddRelation<Dictionary<String, Object>>( tableName, parent, columnName, whereClause );
}
#if !( NET_35 || NET_40 )
public async Task AddRelationAsync( Dictionary<String, Object> parent, String columnName, Object[] children )
{
await Task.Run( () => AddRelation( parent, columnName, children) ).ConfigureAwait( false );
}
public async Task<Int32> AddRelationAsync( Dictionary<String, Object> parent, String columnName, String whereClause )
{
return await Task.Run( () => AddRelation( parent, columnName, whereClause ) ).ConfigureAwait( false );
}
#endif
public void AddRelation( Dictionary<String, Object> parent, String columnName, String whereClause,
AsyncCallback<Int32> callback )
{
Backendless.Data.AddRelation<Dictionary<String, Object>>( tableName, parent, columnName, whereClause, callback );
}
public void AddRelation( Dictionary<String, Object> parent, String columnName, Object[] children,
AsyncCallback<Int32> callback )
{
Backendless.Data.AddRelation<Dictionary<String, Object>>( tableName, parent, columnName, children, callback );
}
#endregion
#region SET RELATION
public Int32 SetRelation( Dictionary<String, Object> parent, String columnName, Object[] children )
{
return Backendless.Data.SetRelation<Dictionary<String, Object>>( tableName, parent, columnName, children );
}
public Int32 SetRelation( Dictionary<String, Object> parent, String columnName, String whereClause )
{
return Backendless.Data.SetRelation<Dictionary<String, Object>>( tableName, parent, columnName, whereClause );
}
#if !( NET_35 || NET_40 )
public async Task<Int32> SetRelationAsync( Dictionary<String, Object> parent, String columnName, Object[] children )
{
return await Task.Run( () => SetRelation( parent, columnName, children) ).ConfigureAwait( false );
}
public async Task<Int32> SetRelationAsync( Dictionary<String, Object> parent, String columnName, String whereClause )
{
return await Task.Run( () => SetRelation( parent, columnName, whereClause ) ).ConfigureAwait( false );
}
#endif
public void SetRelation( Dictionary<String, Object> parent, String columnName, String whereClause,
AsyncCallback<Int32> callback )
{
Backendless.Data.SetRelation<Dictionary<String, Object>>( tableName, parent, columnName, whereClause, callback );
}
public void SetRelation( Dictionary<String, Object> parent, String columnName, Object[] children,
AsyncCallback<Int32> callback )
{
Backendless.Data.SetRelation<Dictionary<String, Object>>( tableName, parent, columnName, children, callback );
}
#endregion
#region DELETE RELATION
public Int32 DeleteRelation( Dictionary<String, Object> parent, String columnName, Object[] children )
{
return Backendless.Data.DeleteRelation<Dictionary<String, Object>>( tableName, parent, columnName, children );
}
public Int32 DeleteRelation( Dictionary<String, Object> parent, String columnName, String whereClause )
{
return Backendless.Data.DeleteRelation<Dictionary<String, Object>>( tableName, parent, columnName, whereClause );
}
#if !( NET_35 || NET_40 )
public async Task<Int32> DeleteRelationAsync( Dictionary<String, Object> parent, String columnName, Object[] children )
{
return await Task.Run( () => DeleteRelation( parent, columnName, children) ).ConfigureAwait( false );
}
public async Task<Int32> DeleteRelationAsync( Dictionary<String, Object> parent, String columnName, String whereClause )
{
return await Task.Run( () => DeleteRelation( parent, columnName, whereClause ) ).ConfigureAwait( false );
}
#endif
public void DeleteRelation( Dictionary<String, Object> parent, String columnName, String whereClause,
AsyncCallback<Int32> callback )
{
Backendless.Data.DeleteRelation<Dictionary<String, Object>>( tableName, parent, columnName, whereClause,
callback );
}
public void DeleteRelation( Dictionary<String, Object> parent, String columnName, Object[] children,
AsyncCallback<Int32> callback )
{
Backendless.Data.DeleteRelation<Dictionary<String, Object>>( tableName, parent, columnName, children, callback );
}
#endregion
#region CREATE_ARGS
private Object[] CreateArgs( DataQueryBuilder qb )
{
return SubArgsCreator( qb.GetRelated(), qb.GetRelationsDepth() );
}
private Object[] CreateArgs( String id, IList<String> relations, Int32? relationsDepth )
{
if( id == null )
throw new ArgumentNullException( ExceptionMessage.NULL_ID );
return SubArgsCreator( relations, relationsDepth, id );
}
private Object[] CreateArgs( Dictionary<String, Object> entity, IList<String> relations, Int32? relationsDepth )
{
if( entity == null )
throw new ArgumentNullException( ExceptionMessage.NULL_ENTITY );
return SubArgsCreator( relations, relationsDepth, entity );
}
private Object[] SubArgsCreator( IList<String> relations, Int32? Depth, Object obj = null )
{
if( relations == null )
relations = new List<String>();
List<Object> args = new List<Object> { tableName };
if( obj != null )
args.Add( obj );
args.Add( relations );
if( Depth != null )
args.Add( Depth );
return args.ToArray();
}
#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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class ConstantTests
{
#region Test methods
[Fact]
public static void CheckBoolConstantTest()
{
foreach (bool value in new bool[] { true, false })
{
VerifyBoolConstant(value);
}
}
[Fact]
public static void CheckByteConstantTest()
{
foreach (byte value in new byte[] { 0, 1, byte.MaxValue })
{
VerifyByteConstant(value);
}
}
[Fact]
public static void CheckCustomConstantTest()
{
foreach (C value in new C[] { null, new C(), new D(), new D(0), new D(5) })
{
VerifyCustomConstant(value);
}
}
[Fact]
public static void CheckCharConstantTest()
{
foreach (char value in new char[] { '\0', '\b', 'A', '\uffff' })
{
VerifyCharConstant(value);
}
}
[Fact]
public static void CheckCustom2ConstantTest()
{
foreach (D value in new D[] { null, new D(), new D(0), new D(5) })
{
VerifyCustom2Constant(value);
}
}
[Fact]
public static void CheckDecimalConstantTest()
{
foreach (decimal value in new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue })
{
VerifyDecimalConstant(value);
}
}
[Fact]
public static void CheckDelegateConstantTest()
{
foreach (Delegate value in new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } })
{
VerifyDelegateConstant(value);
}
}
[Fact]
public static void CheckDoubleConstantTest()
{
foreach (double value in new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN })
{
VerifyDoubleConstant(value);
}
}
[Fact]
public static void CheckEnumConstantTest()
{
foreach (E value in new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue })
{
VerifyEnumConstant(value);
}
}
[Fact]
public static void CheckEnumLongConstantTest()
{
foreach (El value in new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue })
{
VerifyEnumLongConstant(value);
}
}
[Fact]
public static void CheckFloatConstantTest()
{
foreach (float value in new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN })
{
VerifyFloatConstant(value);
}
}
[Fact]
public static void CheckFuncOfObjectConstantTest()
{
foreach (Func<object> value in new Func<object>[] { null, (Func<object>)delegate () { return null; } })
{
VerifyFuncOfObjectConstant(value);
}
}
[Fact]
public static void CheckInterfaceConstantTest()
{
foreach (I value in new I[] { null, new C(), new D(), new D(0), new D(5) })
{
VerifyInterfaceConstant(value);
}
}
[Fact]
public static void CheckIEquatableOfCustomConstantTest()
{
foreach (IEquatable<C> value in new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) })
{
VerifyIEquatableOfCustomConstant(value);
}
}
[Fact]
public static void CheckIEquatableOfCustom2ConstantTest()
{
foreach (IEquatable<D> value in new IEquatable<D>[] { null, new D(), new D(0), new D(5) })
{
VerifyIEquatableOfCustom2Constant(value);
}
}
[Fact]
public static void CheckIntConstantTest()
{
foreach (int value in new int[] { 0, 1, -1, int.MinValue, int.MaxValue })
{
VerifyIntConstant(value);
}
}
[Fact]
public static void CheckLongConstantTest()
{
foreach (long value in new long[] { 0, 1, -1, long.MinValue, long.MaxValue })
{
VerifyLongConstant(value);
}
}
[Fact]
public static void CheckObjectConstantTest()
{
foreach (object value in new object[] { null, new object(), new C(), new D(3) })
{
VerifyObjectConstant(value);
}
}
[Fact]
public static void CheckStructConstantTest()
{
foreach (S value in new S[] { default(S), new S() })
{
VerifyStructConstant(value);
}
}
[Fact]
public static void CheckSByteConstantTest()
{
foreach (sbyte value in new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue })
{
VerifySByteConstant(value);
}
}
[Fact]
public static void CheckStructWithStringConstantTest()
{
foreach (Sc value in new Sc[] { default(Sc), new Sc(), new Sc(null) })
{
VerifyStructWithStringConstant(value);
}
}
[Fact]
public static void CheckStructWithStringAndFieldConstantTest()
{
foreach (Scs value in new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) })
{
VerifyStructWithStringAndFieldConstant(value);
}
}
[Fact]
public static void CheckShortConstantTest()
{
foreach (short value in new short[] { 0, 1, -1, short.MinValue, short.MaxValue })
{
VerifyShortConstant(value);
}
}
[Fact]
public static void CheckStructWithTwoValuesConstantTest()
{
foreach (Sp value in new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) })
{
VerifyStructWithTwoValuesConstant(value);
}
}
[Fact]
public static void CheckStructWithValueConstantTest()
{
foreach (Ss value in new Ss[] { default(Ss), new Ss(), new Ss(new S()) })
{
VerifyStructWithValueConstant(value);
}
}
[Fact]
public static void CheckStringConstantTest()
{
foreach (string value in new string[] { null, "", "a", "foo" })
{
VerifyStringConstant(value);
}
}
[Fact]
public static void CheckUIntConstantTest()
{
foreach (uint value in new uint[] { 0, 1, uint.MaxValue })
{
VerifyUIntConstant(value);
}
}
[Fact]
public static void CheckULongConstantTest()
{
foreach (ulong value in new ulong[] { 0, 1, ulong.MaxValue })
{
VerifyULongConstant(value);
}
}
[Fact]
public static void CheckUShortConstantTest()
{
foreach (ushort value in new ushort[] { 0, 1, ushort.MaxValue })
{
VerifyUShortConstant(value);
}
}
[Fact]
public static void CheckGenericWithStructRestrictionWithEnumConstantTest()
{
CheckGenericWithStructRestrictionConstantHelper<E>();
}
[Fact]
public static void CheckGenericWithStructRestrictionWithStructConstantTest()
{
CheckGenericWithStructRestrictionConstantHelper<S>();
}
[Fact]
public static void CheckGenericWithStructRestrictionWithStructWithStringAndValueConstantTest()
{
CheckGenericWithStructRestrictionConstantHelper<Scs>();
}
[Fact]
public static void CheckGenericWithCustomTest()
{
CheckGenericHelper<C>();
}
[Fact]
public static void CheckGenericWithEnumTest()
{
CheckGenericHelper<E>();
}
[Fact]
public static void CheckGenericWithObjectTest()
{
CheckGenericHelper<object>();
}
[Fact]
public static void CheckGenericWithStructTest()
{
CheckGenericHelper<S>();
}
[Fact]
public static void CheckGenericWithStructWithStringAndValueTest()
{
CheckGenericHelper<Scs>();
}
[Fact]
public static void CheckGenericWithClassRestrictionWithCustomTest()
{
CheckGenericWithClassRestrictionHelper<C>();
}
[Fact]
public static void CheckGenericWithClassRestrictionWithObjectTest()
{
CheckGenericWithClassRestrictionHelper<object>();
}
[Fact]
public static void CheckGenericWithClassAndNewRestrictionWithCustomTest()
{
CheckGenericWithClassAndNewRestrictionHelper<C>();
}
[Fact]
public static void CheckGenericWithClassAndNewRestrictionWithObjectTest()
{
CheckGenericWithClassAndNewRestrictionHelper<object>();
}
[Fact]
public static void CheckGenericWithSubClassRestrictionTest()
{
CheckGenericWithSubClassRestrictionHelper<C>();
}
[Fact]
public static void CheckGenericWithSubClassAndNewRestrictionTest()
{
CheckGenericWithSubClassAndNewRestrictionHelper<C>();
}
#endregion
#region Generic helpers
public static void CheckGenericWithStructRestrictionConstantHelper<Ts>() where Ts : struct
{
foreach (Ts value in new Ts[] { default(Ts), new Ts() })
{
VerifyGenericWithStructRestriction<Ts>(value);
}
}
public static void CheckGenericHelper<T>()
{
foreach (T value in new T[] { default(T) })
{
VerifyGeneric<T>(value);
}
}
public static void CheckGenericWithClassRestrictionHelper<Tc>() where Tc : class
{
foreach (Tc value in new Tc[] { null, default(Tc) })
{
VerifyGenericWithClassRestriction<Tc>(value);
}
}
public static void CheckGenericWithClassAndNewRestrictionHelper<Tcn>() where Tcn : class, new()
{
foreach (Tcn value in new Tcn[] { null, default(Tcn), new Tcn() })
{
VerifyGenericWithClassAndNewRestriction<Tcn>(value);
}
}
public static void CheckGenericWithSubClassRestrictionHelper<TC>() where TC : C
{
foreach (TC value in new TC[] { null, default(TC), (TC)new C() })
{
VerifyGenericWithSubClassRestriction<TC>(value);
}
}
public static void CheckGenericWithSubClassAndNewRestrictionHelper<TCn>() where TCn : C, new()
{
foreach (TCn value in new TCn[] { null, default(TCn), new TCn(), (TCn)new C() })
{
VerifyGenericWithSubClassAndNewRestriction<TCn>(value);
}
}
#endregion
#region Test verifiers
private static void VerifyBoolConstant(bool value)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.Constant(value, typeof(bool)),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyByteConstant(byte value)
{
Expression<Func<byte>> e =
Expression.Lambda<Func<byte>>(
Expression.Constant(value, typeof(byte)),
Enumerable.Empty<ParameterExpression>());
Func<byte> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyCustomConstant(C value)
{
Expression<Func<C>> e =
Expression.Lambda<Func<C>>(
Expression.Constant(value, typeof(C)),
Enumerable.Empty<ParameterExpression>());
Func<C> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyCharConstant(char value)
{
Expression<Func<char>> e =
Expression.Lambda<Func<char>>(
Expression.Constant(value, typeof(char)),
Enumerable.Empty<ParameterExpression>());
Func<char> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyCustom2Constant(D value)
{
Expression<Func<D>> e =
Expression.Lambda<Func<D>>(
Expression.Constant(value, typeof(D)),
Enumerable.Empty<ParameterExpression>());
Func<D> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyDecimalConstant(decimal value)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Constant(value, typeof(decimal)),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyDelegateConstant(Delegate value)
{
Expression<Func<Delegate>> e =
Expression.Lambda<Func<Delegate>>(
Expression.Constant(value, typeof(Delegate)),
Enumerable.Empty<ParameterExpression>());
Func<Delegate> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyDoubleConstant(double value)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Constant(value, typeof(double)),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyEnumConstant(E value)
{
Expression<Func<E>> e =
Expression.Lambda<Func<E>>(
Expression.Constant(value, typeof(E)),
Enumerable.Empty<ParameterExpression>());
Func<E> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyEnumLongConstant(El value)
{
Expression<Func<El>> e =
Expression.Lambda<Func<El>>(
Expression.Constant(value, typeof(El)),
Enumerable.Empty<ParameterExpression>());
Func<El> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyFloatConstant(float value)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Constant(value, typeof(float)),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyFuncOfObjectConstant(Func<object> value)
{
Expression<Func<Func<object>>> e =
Expression.Lambda<Func<Func<object>>>(
Expression.Constant(value, typeof(Func<object>)),
Enumerable.Empty<ParameterExpression>());
Func<Func<object>> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyInterfaceConstant(I value)
{
Expression<Func<I>> e =
Expression.Lambda<Func<I>>(
Expression.Constant(value, typeof(I)),
Enumerable.Empty<ParameterExpression>());
Func<I> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyIEquatableOfCustomConstant(IEquatable<C> value)
{
Expression<Func<IEquatable<C>>> e =
Expression.Lambda<Func<IEquatable<C>>>(
Expression.Constant(value, typeof(IEquatable<C>)),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<C>> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyIEquatableOfCustom2Constant(IEquatable<D> value)
{
Expression<Func<IEquatable<D>>> e =
Expression.Lambda<Func<IEquatable<D>>>(
Expression.Constant(value, typeof(IEquatable<D>)),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<D>> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyIntConstant(int value)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Constant(value, typeof(int)),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyLongConstant(long value)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Constant(value, typeof(long)),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyObjectConstant(object value)
{
Expression<Func<object>> e =
Expression.Lambda<Func<object>>(
Expression.Constant(value, typeof(object)),
Enumerable.Empty<ParameterExpression>());
Func<object> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyStructConstant(S value)
{
Expression<Func<S>> e =
Expression.Lambda<Func<S>>(
Expression.Constant(value, typeof(S)),
Enumerable.Empty<ParameterExpression>());
Func<S> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifySByteConstant(sbyte value)
{
Expression<Func<sbyte>> e =
Expression.Lambda<Func<sbyte>>(
Expression.Constant(value, typeof(sbyte)),
Enumerable.Empty<ParameterExpression>());
Func<sbyte> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyStructWithStringConstant(Sc value)
{
Expression<Func<Sc>> e =
Expression.Lambda<Func<Sc>>(
Expression.Constant(value, typeof(Sc)),
Enumerable.Empty<ParameterExpression>());
Func<Sc> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyStructWithStringAndFieldConstant(Scs value)
{
Expression<Func<Scs>> e =
Expression.Lambda<Func<Scs>>(
Expression.Constant(value, typeof(Scs)),
Enumerable.Empty<ParameterExpression>());
Func<Scs> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyShortConstant(short value)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Constant(value, typeof(short)),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyStructWithTwoValuesConstant(Sp value)
{
Expression<Func<Sp>> e =
Expression.Lambda<Func<Sp>>(
Expression.Constant(value, typeof(Sp)),
Enumerable.Empty<ParameterExpression>());
Func<Sp> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyStructWithValueConstant(Ss value)
{
Expression<Func<Ss>> e =
Expression.Lambda<Func<Ss>>(
Expression.Constant(value, typeof(Ss)),
Enumerable.Empty<ParameterExpression>());
Func<Ss> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyStringConstant(string value)
{
Expression<Func<string>> e =
Expression.Lambda<Func<string>>(
Expression.Constant(value, typeof(string)),
Enumerable.Empty<ParameterExpression>());
Func<string> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyUIntConstant(uint value)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Constant(value, typeof(uint)),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyULongConstant(ulong value)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Constant(value, typeof(ulong)),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyUShortConstant(ushort value)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Constant(value, typeof(ushort)),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyGenericWithStructRestriction<Ts>(Ts value) where Ts : struct
{
Expression<Func<Ts>> e =
Expression.Lambda<Func<Ts>>(
Expression.Constant(value, typeof(Ts)),
Enumerable.Empty<ParameterExpression>());
Func<Ts> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyGeneric<T>(T value)
{
Expression<Func<T>> e =
Expression.Lambda<Func<T>>(
Expression.Constant(value, typeof(T)),
Enumerable.Empty<ParameterExpression>());
Func<T> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyGenericWithClassRestriction<Tc>(Tc value) where Tc : class
{
Expression<Func<Tc>> e =
Expression.Lambda<Func<Tc>>(
Expression.Constant(value, typeof(Tc)),
Enumerable.Empty<ParameterExpression>());
Func<Tc> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyGenericWithClassAndNewRestriction<Tcn>(Tcn value) where Tcn : class, new()
{
Expression<Func<Tcn>> e =
Expression.Lambda<Func<Tcn>>(
Expression.Constant(value, typeof(Tcn)),
Enumerable.Empty<ParameterExpression>());
Func<Tcn> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyGenericWithSubClassRestriction<TC>(TC value) where TC : C
{
Expression<Func<TC>> e =
Expression.Lambda<Func<TC>>(
Expression.Constant(value, typeof(TC)),
Enumerable.Empty<ParameterExpression>());
Func<TC> f = e.Compile();
Assert.Equal(value, f());
}
private static void VerifyGenericWithSubClassAndNewRestriction<TCn>(TCn value) where TCn : C, new()
{
Expression<Func<TCn>> e =
Expression.Lambda<Func<TCn>>(
Expression.Constant(value, typeof(TCn)),
Enumerable.Empty<ParameterExpression>());
Func<TCn> f = e.Compile();
Assert.Equal(value, f());
}
#endregion
}
}
| |
#if !DISABLE_PLAYFABCLIENT_API
using PlayFab.ClientModels;
namespace PlayFab.Events
{
public partial class PlayFabEvents
{
public event PlayFabResultEvent<LoginResult> OnLoginResultEvent;
public event PlayFabRequestEvent<GetPhotonAuthenticationTokenRequest> OnGetPhotonAuthenticationTokenRequestEvent;
public event PlayFabResultEvent<GetPhotonAuthenticationTokenResult> OnGetPhotonAuthenticationTokenResultEvent;
public event PlayFabRequestEvent<LoginWithAndroidDeviceIDRequest> OnLoginWithAndroidDeviceIDRequestEvent;
public event PlayFabRequestEvent<LoginWithCustomIDRequest> OnLoginWithCustomIDRequestEvent;
public event PlayFabRequestEvent<LoginWithEmailAddressRequest> OnLoginWithEmailAddressRequestEvent;
public event PlayFabRequestEvent<LoginWithFacebookRequest> OnLoginWithFacebookRequestEvent;
public event PlayFabRequestEvent<LoginWithGameCenterRequest> OnLoginWithGameCenterRequestEvent;
public event PlayFabRequestEvent<LoginWithGoogleAccountRequest> OnLoginWithGoogleAccountRequestEvent;
public event PlayFabRequestEvent<LoginWithIOSDeviceIDRequest> OnLoginWithIOSDeviceIDRequestEvent;
public event PlayFabRequestEvent<LoginWithKongregateRequest> OnLoginWithKongregateRequestEvent;
public event PlayFabRequestEvent<LoginWithPlayFabRequest> OnLoginWithPlayFabRequestEvent;
public event PlayFabRequestEvent<LoginWithSteamRequest> OnLoginWithSteamRequestEvent;
public event PlayFabRequestEvent<LoginWithTwitchRequest> OnLoginWithTwitchRequestEvent;
public event PlayFabRequestEvent<RegisterPlayFabUserRequest> OnRegisterPlayFabUserRequestEvent;
public event PlayFabResultEvent<RegisterPlayFabUserResult> OnRegisterPlayFabUserResultEvent;
public event PlayFabRequestEvent<AddGenericIDRequest> OnAddGenericIDRequestEvent;
public event PlayFabResultEvent<AddGenericIDResult> OnAddGenericIDResultEvent;
public event PlayFabRequestEvent<AddUsernamePasswordRequest> OnAddUsernamePasswordRequestEvent;
public event PlayFabResultEvent<AddUsernamePasswordResult> OnAddUsernamePasswordResultEvent;
public event PlayFabRequestEvent<GetAccountInfoRequest> OnGetAccountInfoRequestEvent;
public event PlayFabResultEvent<GetAccountInfoResult> OnGetAccountInfoResultEvent;
public event PlayFabRequestEvent<GetPlayerCombinedInfoRequest> OnGetPlayerCombinedInfoRequestEvent;
public event PlayFabResultEvent<GetPlayerCombinedInfoResult> OnGetPlayerCombinedInfoResultEvent;
public event PlayFabRequestEvent<GetPlayFabIDsFromFacebookIDsRequest> OnGetPlayFabIDsFromFacebookIDsRequestEvent;
public event PlayFabResultEvent<GetPlayFabIDsFromFacebookIDsResult> OnGetPlayFabIDsFromFacebookIDsResultEvent;
public event PlayFabRequestEvent<GetPlayFabIDsFromGameCenterIDsRequest> OnGetPlayFabIDsFromGameCenterIDsRequestEvent;
public event PlayFabResultEvent<GetPlayFabIDsFromGameCenterIDsResult> OnGetPlayFabIDsFromGameCenterIDsResultEvent;
public event PlayFabRequestEvent<GetPlayFabIDsFromGenericIDsRequest> OnGetPlayFabIDsFromGenericIDsRequestEvent;
public event PlayFabResultEvent<GetPlayFabIDsFromGenericIDsResult> OnGetPlayFabIDsFromGenericIDsResultEvent;
public event PlayFabRequestEvent<GetPlayFabIDsFromGoogleIDsRequest> OnGetPlayFabIDsFromGoogleIDsRequestEvent;
public event PlayFabResultEvent<GetPlayFabIDsFromGoogleIDsResult> OnGetPlayFabIDsFromGoogleIDsResultEvent;
public event PlayFabRequestEvent<GetPlayFabIDsFromKongregateIDsRequest> OnGetPlayFabIDsFromKongregateIDsRequestEvent;
public event PlayFabResultEvent<GetPlayFabIDsFromKongregateIDsResult> OnGetPlayFabIDsFromKongregateIDsResultEvent;
public event PlayFabRequestEvent<GetPlayFabIDsFromSteamIDsRequest> OnGetPlayFabIDsFromSteamIDsRequestEvent;
public event PlayFabResultEvent<GetPlayFabIDsFromSteamIDsResult> OnGetPlayFabIDsFromSteamIDsResultEvent;
public event PlayFabRequestEvent<GetPlayFabIDsFromTwitchIDsRequest> OnGetPlayFabIDsFromTwitchIDsRequestEvent;
public event PlayFabResultEvent<GetPlayFabIDsFromTwitchIDsResult> OnGetPlayFabIDsFromTwitchIDsResultEvent;
public event PlayFabRequestEvent<GetUserCombinedInfoRequest> OnGetUserCombinedInfoRequestEvent;
public event PlayFabResultEvent<GetUserCombinedInfoResult> OnGetUserCombinedInfoResultEvent;
public event PlayFabRequestEvent<LinkAndroidDeviceIDRequest> OnLinkAndroidDeviceIDRequestEvent;
public event PlayFabResultEvent<LinkAndroidDeviceIDResult> OnLinkAndroidDeviceIDResultEvent;
public event PlayFabRequestEvent<LinkCustomIDRequest> OnLinkCustomIDRequestEvent;
public event PlayFabResultEvent<LinkCustomIDResult> OnLinkCustomIDResultEvent;
public event PlayFabRequestEvent<LinkFacebookAccountRequest> OnLinkFacebookAccountRequestEvent;
public event PlayFabResultEvent<LinkFacebookAccountResult> OnLinkFacebookAccountResultEvent;
public event PlayFabRequestEvent<LinkGameCenterAccountRequest> OnLinkGameCenterAccountRequestEvent;
public event PlayFabResultEvent<LinkGameCenterAccountResult> OnLinkGameCenterAccountResultEvent;
public event PlayFabRequestEvent<LinkGoogleAccountRequest> OnLinkGoogleAccountRequestEvent;
public event PlayFabResultEvent<LinkGoogleAccountResult> OnLinkGoogleAccountResultEvent;
public event PlayFabRequestEvent<LinkIOSDeviceIDRequest> OnLinkIOSDeviceIDRequestEvent;
public event PlayFabResultEvent<LinkIOSDeviceIDResult> OnLinkIOSDeviceIDResultEvent;
public event PlayFabRequestEvent<LinkKongregateAccountRequest> OnLinkKongregateRequestEvent;
public event PlayFabResultEvent<LinkKongregateAccountResult> OnLinkKongregateResultEvent;
public event PlayFabRequestEvent<LinkSteamAccountRequest> OnLinkSteamAccountRequestEvent;
public event PlayFabResultEvent<LinkSteamAccountResult> OnLinkSteamAccountResultEvent;
public event PlayFabRequestEvent<LinkTwitchAccountRequest> OnLinkTwitchRequestEvent;
public event PlayFabResultEvent<LinkTwitchAccountResult> OnLinkTwitchResultEvent;
public event PlayFabRequestEvent<RemoveGenericIDRequest> OnRemoveGenericIDRequestEvent;
public event PlayFabResultEvent<RemoveGenericIDResult> OnRemoveGenericIDResultEvent;
public event PlayFabRequestEvent<ReportPlayerClientRequest> OnReportPlayerRequestEvent;
public event PlayFabResultEvent<ReportPlayerClientResult> OnReportPlayerResultEvent;
public event PlayFabRequestEvent<SendAccountRecoveryEmailRequest> OnSendAccountRecoveryEmailRequestEvent;
public event PlayFabResultEvent<SendAccountRecoveryEmailResult> OnSendAccountRecoveryEmailResultEvent;
public event PlayFabRequestEvent<UnlinkAndroidDeviceIDRequest> OnUnlinkAndroidDeviceIDRequestEvent;
public event PlayFabResultEvent<UnlinkAndroidDeviceIDResult> OnUnlinkAndroidDeviceIDResultEvent;
public event PlayFabRequestEvent<UnlinkCustomIDRequest> OnUnlinkCustomIDRequestEvent;
public event PlayFabResultEvent<UnlinkCustomIDResult> OnUnlinkCustomIDResultEvent;
public event PlayFabRequestEvent<UnlinkFacebookAccountRequest> OnUnlinkFacebookAccountRequestEvent;
public event PlayFabResultEvent<UnlinkFacebookAccountResult> OnUnlinkFacebookAccountResultEvent;
public event PlayFabRequestEvent<UnlinkGameCenterAccountRequest> OnUnlinkGameCenterAccountRequestEvent;
public event PlayFabResultEvent<UnlinkGameCenterAccountResult> OnUnlinkGameCenterAccountResultEvent;
public event PlayFabRequestEvent<UnlinkGoogleAccountRequest> OnUnlinkGoogleAccountRequestEvent;
public event PlayFabResultEvent<UnlinkGoogleAccountResult> OnUnlinkGoogleAccountResultEvent;
public event PlayFabRequestEvent<UnlinkIOSDeviceIDRequest> OnUnlinkIOSDeviceIDRequestEvent;
public event PlayFabResultEvent<UnlinkIOSDeviceIDResult> OnUnlinkIOSDeviceIDResultEvent;
public event PlayFabRequestEvent<UnlinkKongregateAccountRequest> OnUnlinkKongregateRequestEvent;
public event PlayFabResultEvent<UnlinkKongregateAccountResult> OnUnlinkKongregateResultEvent;
public event PlayFabRequestEvent<UnlinkSteamAccountRequest> OnUnlinkSteamAccountRequestEvent;
public event PlayFabResultEvent<UnlinkSteamAccountResult> OnUnlinkSteamAccountResultEvent;
public event PlayFabRequestEvent<UnlinkTwitchAccountRequest> OnUnlinkTwitchRequestEvent;
public event PlayFabResultEvent<UnlinkTwitchAccountResult> OnUnlinkTwitchResultEvent;
public event PlayFabRequestEvent<UpdateUserTitleDisplayNameRequest> OnUpdateUserTitleDisplayNameRequestEvent;
public event PlayFabResultEvent<UpdateUserTitleDisplayNameResult> OnUpdateUserTitleDisplayNameResultEvent;
public event PlayFabRequestEvent<GetFriendLeaderboardRequest> OnGetFriendLeaderboardRequestEvent;
public event PlayFabResultEvent<GetLeaderboardResult> OnGetFriendLeaderboardResultEvent;
public event PlayFabRequestEvent<GetFriendLeaderboardAroundCurrentUserRequest> OnGetFriendLeaderboardAroundCurrentUserRequestEvent;
public event PlayFabResultEvent<GetFriendLeaderboardAroundCurrentUserResult> OnGetFriendLeaderboardAroundCurrentUserResultEvent;
public event PlayFabRequestEvent<GetFriendLeaderboardAroundPlayerRequest> OnGetFriendLeaderboardAroundPlayerRequestEvent;
public event PlayFabResultEvent<GetFriendLeaderboardAroundPlayerResult> OnGetFriendLeaderboardAroundPlayerResultEvent;
public event PlayFabRequestEvent<GetLeaderboardRequest> OnGetLeaderboardRequestEvent;
public event PlayFabResultEvent<GetLeaderboardResult> OnGetLeaderboardResultEvent;
public event PlayFabRequestEvent<GetLeaderboardAroundCurrentUserRequest> OnGetLeaderboardAroundCurrentUserRequestEvent;
public event PlayFabResultEvent<GetLeaderboardAroundCurrentUserResult> OnGetLeaderboardAroundCurrentUserResultEvent;
public event PlayFabRequestEvent<GetLeaderboardAroundPlayerRequest> OnGetLeaderboardAroundPlayerRequestEvent;
public event PlayFabResultEvent<GetLeaderboardAroundPlayerResult> OnGetLeaderboardAroundPlayerResultEvent;
public event PlayFabRequestEvent<GetPlayerStatisticsRequest> OnGetPlayerStatisticsRequestEvent;
public event PlayFabResultEvent<GetPlayerStatisticsResult> OnGetPlayerStatisticsResultEvent;
public event PlayFabRequestEvent<GetPlayerStatisticVersionsRequest> OnGetPlayerStatisticVersionsRequestEvent;
public event PlayFabResultEvent<GetPlayerStatisticVersionsResult> OnGetPlayerStatisticVersionsResultEvent;
public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserDataRequestEvent;
public event PlayFabResultEvent<GetUserDataResult> OnGetUserDataResultEvent;
public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserPublisherDataRequestEvent;
public event PlayFabResultEvent<GetUserDataResult> OnGetUserPublisherDataResultEvent;
public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserPublisherReadOnlyDataRequestEvent;
public event PlayFabResultEvent<GetUserDataResult> OnGetUserPublisherReadOnlyDataResultEvent;
public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserReadOnlyDataRequestEvent;
public event PlayFabResultEvent<GetUserDataResult> OnGetUserReadOnlyDataResultEvent;
public event PlayFabRequestEvent<GetUserStatisticsRequest> OnGetUserStatisticsRequestEvent;
public event PlayFabResultEvent<GetUserStatisticsResult> OnGetUserStatisticsResultEvent;
public event PlayFabRequestEvent<UpdatePlayerStatisticsRequest> OnUpdatePlayerStatisticsRequestEvent;
public event PlayFabResultEvent<UpdatePlayerStatisticsResult> OnUpdatePlayerStatisticsResultEvent;
public event PlayFabRequestEvent<UpdateUserDataRequest> OnUpdateUserDataRequestEvent;
public event PlayFabResultEvent<UpdateUserDataResult> OnUpdateUserDataResultEvent;
public event PlayFabRequestEvent<UpdateUserDataRequest> OnUpdateUserPublisherDataRequestEvent;
public event PlayFabResultEvent<UpdateUserDataResult> OnUpdateUserPublisherDataResultEvent;
public event PlayFabRequestEvent<UpdateUserStatisticsRequest> OnUpdateUserStatisticsRequestEvent;
public event PlayFabResultEvent<UpdateUserStatisticsResult> OnUpdateUserStatisticsResultEvent;
public event PlayFabRequestEvent<GetCatalogItemsRequest> OnGetCatalogItemsRequestEvent;
public event PlayFabResultEvent<GetCatalogItemsResult> OnGetCatalogItemsResultEvent;
public event PlayFabRequestEvent<GetPublisherDataRequest> OnGetPublisherDataRequestEvent;
public event PlayFabResultEvent<GetPublisherDataResult> OnGetPublisherDataResultEvent;
public event PlayFabRequestEvent<GetStoreItemsRequest> OnGetStoreItemsRequestEvent;
public event PlayFabResultEvent<GetStoreItemsResult> OnGetStoreItemsResultEvent;
public event PlayFabRequestEvent<GetTimeRequest> OnGetTimeRequestEvent;
public event PlayFabResultEvent<GetTimeResult> OnGetTimeResultEvent;
public event PlayFabRequestEvent<GetTitleDataRequest> OnGetTitleDataRequestEvent;
public event PlayFabResultEvent<GetTitleDataResult> OnGetTitleDataResultEvent;
public event PlayFabRequestEvent<GetTitleNewsRequest> OnGetTitleNewsRequestEvent;
public event PlayFabResultEvent<GetTitleNewsResult> OnGetTitleNewsResultEvent;
public event PlayFabRequestEvent<AddUserVirtualCurrencyRequest> OnAddUserVirtualCurrencyRequestEvent;
public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnAddUserVirtualCurrencyResultEvent;
public event PlayFabRequestEvent<ConfirmPurchaseRequest> OnConfirmPurchaseRequestEvent;
public event PlayFabResultEvent<ConfirmPurchaseResult> OnConfirmPurchaseResultEvent;
public event PlayFabRequestEvent<ConsumeItemRequest> OnConsumeItemRequestEvent;
public event PlayFabResultEvent<ConsumeItemResult> OnConsumeItemResultEvent;
public event PlayFabRequestEvent<GetCharacterInventoryRequest> OnGetCharacterInventoryRequestEvent;
public event PlayFabResultEvent<GetCharacterInventoryResult> OnGetCharacterInventoryResultEvent;
public event PlayFabRequestEvent<GetPurchaseRequest> OnGetPurchaseRequestEvent;
public event PlayFabResultEvent<GetPurchaseResult> OnGetPurchaseResultEvent;
public event PlayFabRequestEvent<GetUserInventoryRequest> OnGetUserInventoryRequestEvent;
public event PlayFabResultEvent<GetUserInventoryResult> OnGetUserInventoryResultEvent;
public event PlayFabRequestEvent<PayForPurchaseRequest> OnPayForPurchaseRequestEvent;
public event PlayFabResultEvent<PayForPurchaseResult> OnPayForPurchaseResultEvent;
public event PlayFabRequestEvent<PurchaseItemRequest> OnPurchaseItemRequestEvent;
public event PlayFabResultEvent<PurchaseItemResult> OnPurchaseItemResultEvent;
public event PlayFabRequestEvent<RedeemCouponRequest> OnRedeemCouponRequestEvent;
public event PlayFabResultEvent<RedeemCouponResult> OnRedeemCouponResultEvent;
public event PlayFabRequestEvent<StartPurchaseRequest> OnStartPurchaseRequestEvent;
public event PlayFabResultEvent<StartPurchaseResult> OnStartPurchaseResultEvent;
public event PlayFabRequestEvent<SubtractUserVirtualCurrencyRequest> OnSubtractUserVirtualCurrencyRequestEvent;
public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnSubtractUserVirtualCurrencyResultEvent;
public event PlayFabRequestEvent<UnlockContainerInstanceRequest> OnUnlockContainerInstanceRequestEvent;
public event PlayFabResultEvent<UnlockContainerItemResult> OnUnlockContainerInstanceResultEvent;
public event PlayFabRequestEvent<UnlockContainerItemRequest> OnUnlockContainerItemRequestEvent;
public event PlayFabResultEvent<UnlockContainerItemResult> OnUnlockContainerItemResultEvent;
public event PlayFabRequestEvent<AddFriendRequest> OnAddFriendRequestEvent;
public event PlayFabResultEvent<AddFriendResult> OnAddFriendResultEvent;
public event PlayFabRequestEvent<GetFriendsListRequest> OnGetFriendsListRequestEvent;
public event PlayFabResultEvent<GetFriendsListResult> OnGetFriendsListResultEvent;
public event PlayFabRequestEvent<RemoveFriendRequest> OnRemoveFriendRequestEvent;
public event PlayFabResultEvent<RemoveFriendResult> OnRemoveFriendResultEvent;
public event PlayFabRequestEvent<SetFriendTagsRequest> OnSetFriendTagsRequestEvent;
public event PlayFabResultEvent<SetFriendTagsResult> OnSetFriendTagsResultEvent;
public event PlayFabRequestEvent<RegisterForIOSPushNotificationRequest> OnRegisterForIOSPushNotificationRequestEvent;
public event PlayFabResultEvent<RegisterForIOSPushNotificationResult> OnRegisterForIOSPushNotificationResultEvent;
public event PlayFabRequestEvent<RestoreIOSPurchasesRequest> OnRestoreIOSPurchasesRequestEvent;
public event PlayFabResultEvent<RestoreIOSPurchasesResult> OnRestoreIOSPurchasesResultEvent;
public event PlayFabRequestEvent<ValidateIOSReceiptRequest> OnValidateIOSReceiptRequestEvent;
public event PlayFabResultEvent<ValidateIOSReceiptResult> OnValidateIOSReceiptResultEvent;
public event PlayFabRequestEvent<CurrentGamesRequest> OnGetCurrentGamesRequestEvent;
public event PlayFabResultEvent<CurrentGamesResult> OnGetCurrentGamesResultEvent;
public event PlayFabRequestEvent<GameServerRegionsRequest> OnGetGameServerRegionsRequestEvent;
public event PlayFabResultEvent<GameServerRegionsResult> OnGetGameServerRegionsResultEvent;
public event PlayFabRequestEvent<MatchmakeRequest> OnMatchmakeRequestEvent;
public event PlayFabResultEvent<MatchmakeResult> OnMatchmakeResultEvent;
public event PlayFabRequestEvent<StartGameRequest> OnStartGameRequestEvent;
public event PlayFabResultEvent<StartGameResult> OnStartGameResultEvent;
public event PlayFabRequestEvent<AndroidDevicePushNotificationRegistrationRequest> OnAndroidDevicePushNotificationRegistrationRequestEvent;
public event PlayFabResultEvent<AndroidDevicePushNotificationRegistrationResult> OnAndroidDevicePushNotificationRegistrationResultEvent;
public event PlayFabRequestEvent<ValidateGooglePlayPurchaseRequest> OnValidateGooglePlayPurchaseRequestEvent;
public event PlayFabResultEvent<ValidateGooglePlayPurchaseResult> OnValidateGooglePlayPurchaseResultEvent;
public event PlayFabRequestEvent<LogEventRequest> OnLogEventRequestEvent;
public event PlayFabResultEvent<LogEventResult> OnLogEventResultEvent;
public event PlayFabRequestEvent<WriteClientCharacterEventRequest> OnWriteCharacterEventRequestEvent;
public event PlayFabResultEvent<WriteEventResponse> OnWriteCharacterEventResultEvent;
public event PlayFabRequestEvent<WriteClientPlayerEventRequest> OnWritePlayerEventRequestEvent;
public event PlayFabResultEvent<WriteEventResponse> OnWritePlayerEventResultEvent;
public event PlayFabRequestEvent<WriteTitleEventRequest> OnWriteTitleEventRequestEvent;
public event PlayFabResultEvent<WriteEventResponse> OnWriteTitleEventResultEvent;
public event PlayFabRequestEvent<AddSharedGroupMembersRequest> OnAddSharedGroupMembersRequestEvent;
public event PlayFabResultEvent<AddSharedGroupMembersResult> OnAddSharedGroupMembersResultEvent;
public event PlayFabRequestEvent<CreateSharedGroupRequest> OnCreateSharedGroupRequestEvent;
public event PlayFabResultEvent<CreateSharedGroupResult> OnCreateSharedGroupResultEvent;
public event PlayFabRequestEvent<GetSharedGroupDataRequest> OnGetSharedGroupDataRequestEvent;
public event PlayFabResultEvent<GetSharedGroupDataResult> OnGetSharedGroupDataResultEvent;
public event PlayFabRequestEvent<RemoveSharedGroupMembersRequest> OnRemoveSharedGroupMembersRequestEvent;
public event PlayFabResultEvent<RemoveSharedGroupMembersResult> OnRemoveSharedGroupMembersResultEvent;
public event PlayFabRequestEvent<UpdateSharedGroupDataRequest> OnUpdateSharedGroupDataRequestEvent;
public event PlayFabResultEvent<UpdateSharedGroupDataResult> OnUpdateSharedGroupDataResultEvent;
public event PlayFabRequestEvent<ExecuteCloudScriptRequest> OnExecuteCloudScriptRequestEvent;
public event PlayFabResultEvent<ExecuteCloudScriptResult> OnExecuteCloudScriptResultEvent;
public event PlayFabRequestEvent<GetCloudScriptUrlRequest> OnGetCloudScriptUrlRequestEvent;
public event PlayFabResultEvent<GetCloudScriptUrlResult> OnGetCloudScriptUrlResultEvent;
public event PlayFabRequestEvent<RunCloudScriptRequest> OnRunCloudScriptRequestEvent;
public event PlayFabResultEvent<RunCloudScriptResult> OnRunCloudScriptResultEvent;
public event PlayFabRequestEvent<GetContentDownloadUrlRequest> OnGetContentDownloadUrlRequestEvent;
public event PlayFabResultEvent<GetContentDownloadUrlResult> OnGetContentDownloadUrlResultEvent;
public event PlayFabRequestEvent<ListUsersCharactersRequest> OnGetAllUsersCharactersRequestEvent;
public event PlayFabResultEvent<ListUsersCharactersResult> OnGetAllUsersCharactersResultEvent;
public event PlayFabRequestEvent<GetCharacterLeaderboardRequest> OnGetCharacterLeaderboardRequestEvent;
public event PlayFabResultEvent<GetCharacterLeaderboardResult> OnGetCharacterLeaderboardResultEvent;
public event PlayFabRequestEvent<GetCharacterStatisticsRequest> OnGetCharacterStatisticsRequestEvent;
public event PlayFabResultEvent<GetCharacterStatisticsResult> OnGetCharacterStatisticsResultEvent;
public event PlayFabRequestEvent<GetLeaderboardAroundCharacterRequest> OnGetLeaderboardAroundCharacterRequestEvent;
public event PlayFabResultEvent<GetLeaderboardAroundCharacterResult> OnGetLeaderboardAroundCharacterResultEvent;
public event PlayFabRequestEvent<GetLeaderboardForUsersCharactersRequest> OnGetLeaderboardForUserCharactersRequestEvent;
public event PlayFabResultEvent<GetLeaderboardForUsersCharactersResult> OnGetLeaderboardForUserCharactersResultEvent;
public event PlayFabRequestEvent<GrantCharacterToUserRequest> OnGrantCharacterToUserRequestEvent;
public event PlayFabResultEvent<GrantCharacterToUserResult> OnGrantCharacterToUserResultEvent;
public event PlayFabRequestEvent<UpdateCharacterStatisticsRequest> OnUpdateCharacterStatisticsRequestEvent;
public event PlayFabResultEvent<UpdateCharacterStatisticsResult> OnUpdateCharacterStatisticsResultEvent;
public event PlayFabRequestEvent<GetCharacterDataRequest> OnGetCharacterDataRequestEvent;
public event PlayFabResultEvent<GetCharacterDataResult> OnGetCharacterDataResultEvent;
public event PlayFabRequestEvent<GetCharacterDataRequest> OnGetCharacterReadOnlyDataRequestEvent;
public event PlayFabResultEvent<GetCharacterDataResult> OnGetCharacterReadOnlyDataResultEvent;
public event PlayFabRequestEvent<UpdateCharacterDataRequest> OnUpdateCharacterDataRequestEvent;
public event PlayFabResultEvent<UpdateCharacterDataResult> OnUpdateCharacterDataResultEvent;
public event PlayFabRequestEvent<ValidateAmazonReceiptRequest> OnValidateAmazonIAPReceiptRequestEvent;
public event PlayFabResultEvent<ValidateAmazonReceiptResult> OnValidateAmazonIAPReceiptResultEvent;
public event PlayFabRequestEvent<AcceptTradeRequest> OnAcceptTradeRequestEvent;
public event PlayFabResultEvent<AcceptTradeResponse> OnAcceptTradeResultEvent;
public event PlayFabRequestEvent<CancelTradeRequest> OnCancelTradeRequestEvent;
public event PlayFabResultEvent<CancelTradeResponse> OnCancelTradeResultEvent;
public event PlayFabRequestEvent<GetPlayerTradesRequest> OnGetPlayerTradesRequestEvent;
public event PlayFabResultEvent<GetPlayerTradesResponse> OnGetPlayerTradesResultEvent;
public event PlayFabRequestEvent<GetTradeStatusRequest> OnGetTradeStatusRequestEvent;
public event PlayFabResultEvent<GetTradeStatusResponse> OnGetTradeStatusResultEvent;
public event PlayFabRequestEvent<OpenTradeRequest> OnOpenTradeRequestEvent;
public event PlayFabResultEvent<OpenTradeResponse> OnOpenTradeResultEvent;
public event PlayFabRequestEvent<AttributeInstallRequest> OnAttributeInstallRequestEvent;
public event PlayFabResultEvent<AttributeInstallResult> OnAttributeInstallResultEvent;
public event PlayFabRequestEvent<GetPlayerSegmentsRequest> OnGetPlayerSegmentsRequestEvent;
public event PlayFabResultEvent<GetPlayerSegmentsResult> OnGetPlayerSegmentsResultEvent;
public event PlayFabRequestEvent<GetPlayerTagsRequest> OnGetPlayerTagsRequestEvent;
public event PlayFabResultEvent<GetPlayerTagsResult> OnGetPlayerTagsResultEvent;
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Gtk;
using ResxTranslator.Common;
using GLib;
using System.Windows.Forms;
namespace ResxTranslatorGtk
{
[Controller(typeof(MainWindowController))]
public partial class MainWindow : Gtk.Window, IMainWindowView
{
private LocalizationGroup _model;
public MainWindow()
: base(Gtk.WindowType.Toplevel)
{
Build();
}
private ListStore ListStore
{
get
{
return (ListStore)treeview1.Model;
}
}
#region IMainWindowView implementation
public event EventHandler FileNew;
public event EventHandler FileOpen;
public event EventHandler FileSave;
public event EventHandler KeyAdd;
public event EventHandler KeyRemove;
public event EventHandler CultureAdd;
public event EventHandler CultureRemove;
public event EventHandler HelpAbout;
public event FormClosingEventHandler FormClosing;
/// <summary>
/// Gets or sets the model.
/// </summary>
/// <value>
/// The model.
/// </value>
public LocalizationGroup Model
{
get { return _model; }
set
{
_model = value;
RebuildUI();
}
}
public void ModelChanged()
{
RebuildUI();
}
public IOpenDialogView CreateOpenDialogView()
{
return new OpenDialogView(this);
}
public System.Windows.Forms.DialogResult ShowSavePendingChangesDialog()
{
Gtk.MessageDialog dlg = new Gtk.MessageDialog(this, DialogFlags.Modal, MessageType.Question,
ButtonsType.None, false, "Save pending changes?");
dlg.AddButton ("Yes", ResponseType.Yes);
dlg.AddButton ("No", ResponseType.No);
dlg.AddButton("Cancel", ResponseType.Cancel);
int response = dlg.Run();
dlg.Destroy();
switch ((ResponseType)response)
{
case ResponseType.Yes:
return System.Windows.Forms.DialogResult.Yes;
case ResponseType.No:
return System.Windows.Forms.DialogResult.No;
case ResponseType.Cancel:
case ResponseType.DeleteEvent: // dialog close button
return System.Windows.Forms.DialogResult.Cancel;
default: // should never happen
return System.Windows.Forms.DialogResult.Abort;
}
}
public void ShowInfo(string message)
{
Gtk.MessageDialog dlg = new Gtk.MessageDialog(this, DialogFlags.Modal, MessageType.Info,
ButtonsType.Ok, false, message);
dlg.Run();
dlg.Destroy();
}
public void ShowError(string message)
{
Gtk.MessageDialog dlg = new Gtk.MessageDialog(this, DialogFlags.Modal, MessageType.Error,
ButtonsType.Ok, false, message);
dlg.Run();
dlg.Destroy();
}
public ISaveDialogView CreateSaveDialogView()
{
return new SaveDialog();
}
public IAddCultureDialogView CreateAddCultureDialogView()
{
return ViewFactory.Create<CultureDialog>();
}
public void KeyAdded(string key)
{
try
{
object[] values = new object[Columns];
values[0] = key;
for (int i = 1; i < values.Length; i++)
{
values[i] = string.Empty;
}
ListStore.AppendValues(values);
}
catch (Exception ex)
{
ShowError(ex);
}
}
/// <summary>
/// Gets the selected key indices.
/// </summary>
/// <returns>
/// The selected key indices.
/// </returns>
public IEnumerable<int> GetSelectedKeyIndices()
{
SortedSet<int> result = new SortedSet<int>();
TreePath[] selectedRows = treeview1.Selection.GetSelectedRows();
if (selectedRows != null)
{
foreach (TreePath path in selectedRows)
{
int[] indices = path.Indices;
if (indices != null && indices.Length > 0)
{
result.Add(indices[0]);
}
}
}
return result;
}
/// <summary>
/// Notifies the view that one or more keys were deleted.
/// </summary>
/// <param name='keyIndices'>
/// Key indices.
/// </param>
public void KeysDeleted(IEnumerable<int> keyIndices)
{
foreach (int idx in keyIndices)
{
TreePath path = new TreePath(new[] { idx });
TreeIter iter;
if (ListStore.GetIter(out iter, path))
{
ListStore.Remove(ref iter);
}
}
}
public void CultureAdded(string culture)
{
// TODO: Improve
RebuildUI();
}
public void CultureDeleted(string culture)
{
// TODO: Improve
RebuildUI();
}
public string GetSelectedCulture()
{
TreePath treePath;
TreeViewColumn focusColumn;
treeview1.GetCursor(out treePath, out focusColumn);
if (focusColumn != null && focusColumn.SortColumnId > 0)
{
return Model.Cultures[(focusColumn.SortColumnId - 1)/2];
}
return null;
}
#endregion
#region Window Event Handlers
protected void OnDeleteEvent(object sender, DeleteEventArgs a)
{
if (!PendingChangesExist())
{
Gtk.Application.Quit();
a.RetVal = false;
}
else
{
// prevent the window from closing
a.RetVal = true;
}
}
protected virtual void OnNewActionActivated(object sender, System.EventArgs e)
{
if (FileNew != null)
{
FileNew(this, e);
}
}
protected virtual void OnOpenActionActivated(object sender, System.EventArgs e)
{
if (FileOpen != null)
{
FileOpen(this, e);
}
}
protected virtual void OnSaveActionActivated(object sender, System.EventArgs e)
{
if (FileSave != null)
{
FileSave(this, e);
}
}
protected void OnFileExit(object sender, System.EventArgs e)
{
if (!PendingChangesExist())
{
Gtk.Application.Quit();
}
}
protected virtual void OnAddActionActivated(object sender, System.EventArgs e)
{
if (KeyAdd != null)
{
KeyAdd(this, e);
}
}
protected virtual void OnRemoveActionActivated(object sender, System.EventArgs e)
{
if (KeyRemove != null)
{
KeyRemove(this, e);
}
}
protected void OnAddCulture(object sender, System.EventArgs e)
{
if (CultureAdd != null)
{
CultureAdd(this, e);
}
}
protected void OnRemoveCulture(object sender, System.EventArgs e)
{
if (CultureRemove != null)
{
CultureRemove(this, e);
}
}
protected void OnHelpAbout(object sender, System.EventArgs e)
{
if (HelpAbout != null)
{
HelpAbout(this, e);
}
}
#endregion
private int Columns
{
get { return 1 + 2 * Model.Cultures.Count(); }
}
/// <summary>
/// The last folder used in the UI in the File Open or File Save dialogs.
/// </summary>
private string LastUsedFolder
{
get;
set;
}
/// <summary>
/// Sets the current folder of the given file chooser to the last used value.
/// </summary>
/// <param name="dlg">
/// A <see cref="FileChooserDialog"/>
/// </param>
private void PrepareLastUsedFolder(FileChooserDialog dlg)
{
if (!string.IsNullOrEmpty(LastUsedFolder))
{
dlg.SetCurrentFolder(LastUsedFolder);
}
}
/// <summary>
/// Saves the folder selected in the given dialog in order to use it the next
/// time a file chooser dialog is created.
/// </summary>
/// <param name="dlg">
/// A <see cref="FileChooserDialog"/>
/// </param>
private void SaveLastUsedFolder(FileChooserDialog dlg)
{
LastUsedFolder = dlg.CurrentFolder;
}
private ListStore BuildListStore()
{
Type[] types = new Type[Columns];
for (int i = 0; i < types.Length; i++)
{
types[i] = typeof(string);
}
ListStore listStore = new ListStore(types);
foreach (string key in Model.Keys)
{
object[] values = new object[types.Length];
values[0] = key;
int idx = 1;
foreach (string culture in Model.Cultures)
{
LocalizedValue translation = Model[key, culture];
values[idx++] = translation.Value;
values[idx++] = translation.Comment;
}
listStore.AppendValues(values);
}
return listStore;
}
private void RebuildUI()
{
ListStore listStore = BuildListStore();
// remove all columns
while (treeview1.Columns.Length > 0)
{
treeview1.RemoveColumn(treeview1.Columns[0]);
}
// add key column
AddStringColumn("Key", 0);
foreach (string culture in Model.Cultures)
{
AddCultureColumns(culture);
}
treeview1.Model = listStore;
}
private void AddCultureColumns(string culture)
{
string suffix = culture == string.Empty ? "default" : culture;
AddStringColumn("Value (" + suffix + ")", treeview1.Columns.Length);
AddStringColumn("Description (" + suffix + ")", treeview1.Columns.Length);
}
private void AddStringColumn(string caption, int index)
{
TreeViewColumn column = new TreeViewColumn();
column.Title = caption;
column.SortColumnId = index;
column.SortIndicator = true;
CellRendererText cell = new CellRendererText();
cell.Editable = true;
cell.Edited += (o, args) => OnCellEdited(o, args, index);
column.Resizable = true;
column.PackStart(cell, true);
column.AddAttribute(cell, "text", index);
treeview1.AppendColumn(column);
}
private void OnCellEdited(object o, EditedArgs args, int index)
{
TreeIter iter;
treeview1.Model.GetIter(out iter, new TreePath(args.Path));
string oldKey = (string)treeview1.Model.GetValue(iter, 0);
if (index == 0)
{
if (oldKey != args.NewText)
{
if (Model.Keys.Contains(args.NewText))
{
ShowError("Duplicate key");
return;
}
Model.Keys.Rename(oldKey, args.NewText);
}
}
else
{
int fileIndex = (index - 1) / 2;
string culture = Model.Cultures[fileIndex];
LocalizedValue localizedValue = Model[oldKey, culture];
if (index % 2 == 0)
{
// set comment
localizedValue.Comment = args.NewText;
}
else
{
// set value
localizedValue.Value = args.NewText;
}
}
treeview1.Model.SetValue(iter, index, args.NewText);
}
private void ShowError(Exception ex)
{
Gtk.MessageDialog dlg = new Gtk.MessageDialog(this, DialogFlags.Modal, MessageType.Error,
ButtonsType.Ok, false, "Error: {0}", ex.Message);
dlg.Run();
dlg.Destroy();
}
private bool PendingChangesExist()
{
if (FormClosing != null)
{
FormClosingEventArgs args = new FormClosingEventArgs(CloseReason.UserClosing, false);
FormClosing(this, args);
return args.Cancel;
}
return false;
}
class OpenDialogView : IOpenDialogView
{
private readonly MainWindow _owner;
private FileChooserDialog dlgOpen;
public OpenDialogView(MainWindow owner)
{
_owner = owner;
dlgOpen = new FileChooserDialog("Choose file to open", _owner, FileChooserAction.Open, "Canel", ResponseType.Cancel, "Open", ResponseType.Accept) { SelectMultiple = true };
dlgOpen.Filter = new FileFilter();
dlgOpen.Filter.AddPattern("*.resx");
dlgOpen.Filter.Name = "Resource files";
_owner.PrepareLastUsedFolder(dlgOpen);
}
public event EventHandler Load;
public System.Windows.Forms.DialogResult ShowDialog()
{
var result = dlgOpen.Run() == (int)ResponseType.Accept ? System.Windows.Forms.DialogResult.OK : System.Windows.Forms.DialogResult.Cancel;
if (result == System.Windows.Forms.DialogResult.OK)
{
_owner.SaveLastUsedFolder(dlgOpen);
}
return result;
}
public string[] SelectedFiles
{
get { return dlgOpen.Filenames; }
}
public void Dispose()
{
dlgOpen.Destroy();
dlgOpen.Dispose();
}
}
}
}
| |
" NAME Flippy
AUTHOR cgreuter@calum.csclub.uwaterloo.ca (Chris Reuter)
URL (none)
FUNCTION silly game
KEYWORDS game Morphic demo
ST-VERSIONS Squeak
PREREQUISITES CurveButton 1.0 (or better?)
CONFLICTS (none known)
DISTRIBUTION world
VERSION 1.0
DATE 16-Apr-98
SUMMARY
This is a simple logic puzzle that uses the newMorphic UI in Squeak. It's a great time-killerand looks pretty cool.
Chris Reuter
"!
'From Squeak 1.31 of Feb 4, 1998 on 16 April 1998 at 12:48:00 pm'!
"Change Set: Flippy
Date: 16 April 1998
Author: Chris Reuter
This is a little logic puzzle written to use Morphic. The object of the game is to
make the central square red and all the rest green. Clicking on a square toggles it
and some others.
I've been told that it's provably possible to solve any Flippy configuration in seven
moves or less.
"!
SimpleButtonMorph subclass: #FlippyButtonMorph
instanceVariableNames: 'isRed '
classVariableNames: ''
poolDictionaries: ''
category: 'Morphic-Widgets'!
Object subclass: #FlippyGame
instanceVariableNames: 'state '
classVariableNames: 'FinalState Masks '
poolDictionaries: ''
category: 'Flippy'!
CurveButton subclass: #FlippyHelpButton
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Morphic-Widgets'!
CurveMorph subclass: #FlippyMorph
instanceVariableNames: 'buttons countMorph counter gameData titleMorph titleColor flashCount '
classVariableNames: ''
poolDictionaries: ''
category: 'Morphic-Demo'!
CurveButton subclass: #FlippyQuitButton
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Morphic-Widgets'!
CurveButton subclass: #FlippyScrambleButton
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Morphic-Widgets'!
Object subclass: #FlippyState
instanceVariableNames: 'top middle bottom '
classVariableNames: ''
poolDictionaries: ''
category: 'Flippy'!
!FlippyButtonMorph commentStamp: 'cr 4/16/98 12:48' prior: 0!
One of the red or green square grid buttons.!
!FlippyButtonMorph reorganize!
('non-labels' label label: label:font:)
('colouring' colourByBit: green red toggle)
('initialization' initialize)
('accessing' isRed)
!
!FlippyButtonMorph methodsFor: 'non-labels' stamp: 'cr 3/22/98 04:27'!
label
"Labels are not allowed, so this is a no-op."
^''.
! !
!FlippyButtonMorph methodsFor: 'non-labels' stamp: 'cr 3/22/98 04:25'!
label: aString
"Labels are not allowed, so this is a no-op."
^self
! !
!FlippyButtonMorph methodsFor: 'non-labels' stamp: 'cr 3/22/98 04:27'!
label: aString font: aFont
"Labels are not allowed, so this is a no-op."
^self
! !
!FlippyButtonMorph methodsFor: 'colouring' stamp: 'cr 3/22/98 07:09'!
colourByBit: colourRed
colourRed
ifTrue: [isRed or: [self red]]
ifFalse: [self green].! !
!FlippyButtonMorph methodsFor: 'colouring' stamp: 'cr 3/22/98 07:00'!
green
"color green."
self color: (Color r: 0.4 g: 0.8 b: 0.6).
isRed := false.! !
!FlippyButtonMorph methodsFor: 'colouring' stamp: 'cr 3/22/98 07:00'!
red
"color red."
self color: (Color r: 1.0 g: 0.199 b: 0.199).
isRed := true.! !
!FlippyButtonMorph methodsFor: 'colouring' stamp: 'cr 3/22/98 07:01'!
toggle
self isRed
ifTrue: [self green]
ifFalse: [self red]. ! !
!FlippyButtonMorph methodsFor: 'initialization' stamp: 'cr 3/25/98 02:31'!
initialize
super initialize.
self borderWidth: 3.
self borderColor: #raised.
self green.
target _ nil.
actionSelector _ nil.
arguments _ nil.
actWhen _ #buttonUp.
self extent: 34@34.
! !
!FlippyButtonMorph methodsFor: 'accessing' stamp: 'cr 3/22/98 07:00'!
isRed
"Return value of instance variable 'isRed'"
^isRed! !
!FlippyButtonMorph class reorganize!
('all' includeInNewMorphMenu)
!
!FlippyButtonMorph class methodsFor: 'all' stamp: 'cr 4/1/98 02:16'!
includeInNewMorphMenu
"Return true for all classes that can be instantiated from the menu"
^ false! !
!FlippyGame reorganize!
('playing' clickedOn: colourAt: isDone reset)
('initialization' initialize)
('accessing' state)
!
!FlippyGame methodsFor: 'playing' stamp: 'cr 3/22/98 06:50'!
clickedOn: location
"A square has been clicked. Change the state. ('location' is an integer representing a square
arranged just like a phone keypad (i.e. 1 is top-left, 2 is top-middle, etc.))"
state := state flipBy: (Masks at: location).
! !
!FlippyGame methodsFor: 'playing' stamp: 'cr 3/22/98 06:50'!
colourAt: location
"Return the colour (1 or 0, that is) of the square indicated by location, an int, in
touch-tone phone layout."
| bits |
bits := (state bottom bitOr: (state middle << 3)) bitOr: state top << 6.
^bits anyMask: (1 << (9 - location)).! !
!FlippyGame methodsFor: 'playing' stamp: 'cr 3/25/98 00:43'!
isDone
"Do we have a finished state?"
^self state = FinalState.! !
!FlippyGame methodsFor: 'playing' stamp: 'cr 1/30/98 19:44'!
reset
"Initialize state."
state := FlippyState from: ((1 to: 3) collect: [ :dummy | (0 to: 7) atRandom]). ! !
!FlippyGame methodsFor: 'initialization' stamp: 'cr 3/22/98 05:07'!
initialize
state := FlippyState new.
self reset.! !
!FlippyGame methodsFor: 'accessing' stamp: 'cr 3/25/98 00:43'!
state
"Return value of instance variable 'state'"
^state! !
!FlippyGame class methodsFor: 'instance creation' stamp: 'cr 3/22/98 05:06'!
new
^super new initialize.! !
!FlippyGame class methodsFor: 'class initialization' stamp: 'cr 4/1/98 02:31'!
initialize
"Initialize the class variables."
| |
FinalState := FlippyState from: #( 2r000
2r010
2r000 ).
Masks := #(
#( 2r110
2r110
2r000 )
#( 2r111
2r000
2r000 )
#( 2r011
2r011
2r000 )
#( 2r100
2r100
2r100 )
#( 2r010
2r111
2r010 )
#( 2r001
2r001
2r001 )
#( 2r000
2r110
2r110 )
#( 2r000
2r000
2r111 )
#( 2r000
2r011
2r011 )) collect: [ :item | FlippyState from: item].
"FlippyGame initializeClass"! !
!FlippyHelpButton commentStamp: 'cr 4/16/98 12:48' prior: 0!
The help button.!
!FlippyHelpButton reorganize!
('initialization' defaultVertices initialize)
!
!FlippyHelpButton methodsFor: 'initialization' stamp: 'cr 3/22/98 05:24'!
defaultVertices
"Return a collection of vertices to initialize self with. The array was created by cutting from
the vertices list a Morph inspector produced."
| result |
result := WriteStream on: Array new.
(#(310@54 323@41 338@51 341@79 341@167 338@179 331@189 315@180 307@96 )
reject: [:item | item == #@]
) pairsDo: [:x :y | result nextPut: x @ y].
^ result contents.! !
!FlippyHelpButton methodsFor: 'initialization' stamp: 'cr 3/22/98 05:26'!
initialize
super initialize.
self color: (Color r: 0.599 g: 0.8 b: 1.0).
self label: 'Help'.! !
!FlippyHelpButton class reorganize!
('all' includeInNewMorphMenu)
!
!FlippyHelpButton class methodsFor: 'all' stamp: 'cr 4/1/98 02:16'!
includeInNewMorphMenu
"Return true for all classes that can be instantiated from the menu"
^ false! !
Smalltalk renameClassNamed: #FlippyMain as: #FlippyMorph!
!FlippyMorph reorganize!
('stepping' startStepping step stepTime)
('game play' helpScreen pressed: resetGame winner)
('display' updateDisplay)
('creation' initialize makeButtons)
('accessing' buttons counter countMorph gameData)
('handles' installModelIn:)
!
!FlippyMorph methodsFor: 'stepping' stamp: 'cr 4/1/98 02:04'!
startStepping
"Stepping should only start when a game ends."
flashCount := 0.
self gameData isDone
ifTrue: [super startStepping].! !
!FlippyMorph methodsFor: 'stepping' stamp: 'cr 4/1/98 02:08'!
step
"Toggle the buttons."
flashCount := flashCount + 1.
flashCount > 10 ifTrue: [^self stopStepping].
buttons do: [ :button | button toggle].
titleMorph color:
(Color r: (0.0 to: 1.0 by: 0.0001) atRandom
g: (0.0 to: 1.0 by: 0.0001) atRandom
b: (0.0 to: 1.0 by: 0.0001) atRandom)
! !
!FlippyMorph methodsFor: 'stepping' stamp: 'cr 3/25/98 01:07'!
stepTime
^300! !
!FlippyMorph methodsFor: 'game play' stamp: 'cr 4/1/98 02:39'!
helpScreen
"Bring up a help screen."
| b |
b := SimpleButtonMorph new
label: 'To win, make the innermost button red and the rest green.';
yourself.
b target: b;
actionSelector: #delete;
bounds: (self bounds withWidth: (b findA: StringMorph) bounds width * 1.2).
self addMorph: b.
! !
!FlippyMorph methodsFor: 'game play' stamp: 'cr 3/25/98 01:39'!
pressed: anInt
"Button pressed."
gameData isDone
ifTrue: [^self].
gameData clickedOn: anInt.
counter := counter + 1.
self updateDisplay.
gameData isDone
ifTrue: [
self winner.
].
! !
!FlippyMorph methodsFor: 'game play' stamp: 'cr 3/25/98 01:43'!
resetGame
"New game."
gameData reset.
counter := 0.
self stopStepping.
titleMorph contents: 'Flippy!!';
color: titleColor.
self updateDisplay.
! !
!FlippyMorph methodsFor: 'game play' stamp: 'cr 3/25/98 01:43'!
winner
"The player has won."
titleMorph contents: 'Solved!!!!!!'.
self startStepping.! !
!FlippyMorph methodsFor: 'display' stamp: 'cr 3/22/98 06:20'!
updateDisplay
"Make the display synch with the game."
countMorph contents: counter printString.
buttons withIndexDo: [ :button :index | button colourByBit: (gameData colourAt: index)].
! !
!FlippyMorph methodsFor: 'creation' stamp: 'cr 4/1/98 02:11'!
initialize
"Initialize to tweaked defaults."
| pts |
counter := 0.
"Create the game object."
gameData := FlippyGame new.
pts := OrderedCollection new.
pts add: 239@63;
add: (365@76);
add: (414@69);
add: (436@239);
add: (324@227);
add: (234@233);
add: (219@108).
self vertices: pts asArray
color: (Color r: 0.8 g: 0.599 b: 1.0)
borderWidth: 2
borderColor: #raised.
self makeButtons.
self addMorph: (FlippyScrambleButton new
position: self bounds topLeft + (147@162);
actionSelector: #resetGame;
target: self;
yourself).
self addMorph: (FlippyHelpButton new
position: self bounds topLeft + (5@22);
actionSelector: #helpScreen;
target: self;
yourself).
countMorph := StringMorph new.
countMorph contents: '0';
position: self bounds topLeft + (180@76);
color: (Color r: 0 g: 0.4 b: 0.4).
self addMorph: countMorph.
titleColor := Color r: 1.0 g: 1.0 b: 0.4.
titleMorph := TextMorph new
contents: 'Flippy!!!!!!';
position: self bounds topLeft + (87@34);
color: titleColor;
lock;
yourself.
self addMorph: titleMorph.
self addMorph: (FlippyQuitButton new
position: self bounds topLeft + (153@11);
actionSelector: #delete;
target: self;
yourself).
self stopStepping.
self updateDisplay.
! !
!FlippyMorph methodsFor: 'creation' stamp: 'cr 3/22/98 06:41'!
makeButtons
"Create the 9 flippy buttons."
| b bList n |
bList := OrderedCollection new.
n := 1.
0 to: 2 do: [ :ypos |
0 to: 2 do: [ :xpos |
b := FlippyButtonMorph new.
b position: self bounds topLeft + (46@54) + ((xpos @ ypos) * (b extent + 2));
target: self;
actionSelector: #pressed:;
arguments: (Array with: n).
self addMorph: b.
bList add: b.
n := n + 1.
].
].
buttons := bList asArray.! !
!FlippyMorph methodsFor: 'accessing' stamp: 'cr 3/25/98 01:11'!
buttons
"Return value of instance variable 'buttons'"
^buttons! !
!FlippyMorph methodsFor: 'accessing' stamp: 'cr 3/25/98 01:11'!
counter
"Return value of instance variable 'counter'"
^counter! !
!FlippyMorph methodsFor: 'accessing' stamp: 'cr 3/25/98 01:11'!
countMorph
"Return value of instance variable 'countMorph'"
^countMorph! !
!FlippyMorph methodsFor: 'accessing' stamp: 'cr 3/25/98 01:11'!
gameData
"Return value of instance variable 'gameData'"
^gameData! !
!FlippyMorph methodsFor: 'handles' stamp: 'cr 3/25/98 02:28'!
installModelIn: mode
"Override initially displaying those #$%@ handles."! !
!FlippyQuitButton commentStamp: 'cr 4/16/98 12:48' prior: 0!
The quit button.!
!FlippyQuitButton reorganize!
('creation' defaultVertices initialize)
!
!FlippyQuitButton methodsFor: 'creation' stamp: 'cr 3/25/98 01:58'!
defaultVertices
"Return a collection of vertices to initialize self with. The array was created by cutting from
the vertices list a Morph inspector produced."
| result |
result := WriteStream on: Array new.
(#(246@173 270@165 281@199 262@198 238@196)
reject: [:item | item == #@]
) pairsDo: [:x :y | result nextPut: x @ y].
^ result contents.! !
!FlippyQuitButton methodsFor: 'creation' stamp: 'cr 3/25/98 02:13'!
initialize
super initialize.
self color: (Color r: 1.0 g: 0.599 b: 1.0).
self label: 'Quit'.! !
!FlippyQuitButton class reorganize!
('all' includeInNewMorphMenu)
!
!FlippyQuitButton class methodsFor: 'all' stamp: 'cr 4/1/98 02:16'!
includeInNewMorphMenu
"Return true for all classes that can be instantiated from the menu"
^ false! !
Smalltalk renameClassNamed: #Flippy as: #FlippyScrambleButton!
!FlippyScrambleButton commentStamp: 'cr 4/16/98 12:48' prior: 0!
The Scramble button!
!FlippyScrambleButton reorganize!
('initialization' defaultVertices initialize)
!
!FlippyScrambleButton methodsFor: 'initialization' stamp: 'cr 3/22/98 04:32'!
defaultVertices
"Return a collection of vertices to initialize self with. The array was created by cutting from
the vertices list a Morph inspector produced."
| result |
result := WriteStream on: Array new.
(#(477@182 503@182 520@185 512@206 488@209 454@199 449@195 448@189 455@183 )
reject: [:item | item == #@]
) pairsDo: [:x :y | result nextPut: x @ y].
^ result contents.! !
!FlippyScrambleButton methodsFor: 'initialization' stamp: 'cr 3/22/98 05:18'!
initialize
super initialize.
self color: (Color r: 0.4 g: 1.0 b: 1.0).
self label: 'Scramble'.! !
!FlippyScrambleButton commentStamp: 'cr 4/16/98 12:48' prior: 0!
The Scramble button!
!FlippyScrambleButton class reorganize!
('all' includeInNewMorphMenu)
!
!FlippyScrambleButton class methodsFor: 'all' stamp: 'cr 4/1/98 02:16'!
includeInNewMorphMenu
"Return true for all classes that can be instantiated from the menu"
^ false! !
!FlippyState methodsFor: 'operations' stamp: 'cr 1/30/98 19:20'!
flipBy: mask
"Toggle all bits in self which are one in 'mask'."
^FlippyState
top: (mask top bitXor: self top)
middle: (mask middle bitXor: self middle)
bottom: (mask bottom bitXor: self bottom).
! !
!FlippyState methodsFor: 'accessing' stamp: 'cr 1/30/98 19:03'!
bottom
"Return value of instance variable 'bottom'"
^bottom! !
!FlippyState methodsFor: 'accessing' stamp: 'cr 1/30/98 19:03'!
bottom: newValue
"Set value of instance variable 'bottom'."
bottom := newValue! !
!FlippyState methodsFor: 'accessing' stamp: 'cr 1/30/98 19:03'!
middle
"Return value of instance variable 'middle'"
^middle! !
!FlippyState methodsFor: 'accessing' stamp: 'cr 1/30/98 19:03'!
middle: newValue
"Set value of instance variable 'middle'."
middle := newValue! !
!FlippyState methodsFor: 'accessing' stamp: 'cr 1/30/98 19:03'!
top
"Return value of instance variable 'top'"
^top! !
!FlippyState methodsFor: 'accessing' stamp: 'cr 1/30/98 19:03'!
top: newValue
"Set value of instance variable 'top'."
top := newValue! !
!FlippyState methodsFor: 'initialization' stamp: 'cr 3/22/98 04:42'!
initialize
"Create a blank state."
top := 0.
middle := 0.
bottom := 0.! !
!FlippyState methodsFor: 'testing' stamp: 'cr 1/30/98 19:30'!
= aFlippyState
"Basic = operation."
^ (self top = aFlippyState top) & (self middle = aFlippyState middle) & (self bottom = aFlippyState bottom).! !
!FlippyState class reorganize!
('instance creation' from: new top:middle:bottom:)
!
!FlippyState class methodsFor: 'instance creation' stamp: 'cr 1/30/98 19:26'!
from: anArray
"Create a new FlippyState using array contents."
^FlippyState
top: (anArray at: 1)
middle: (anArray at: 2)
bottom: (anArray at: 3).! !
!FlippyState class methodsFor: 'instance creation' stamp: 'cr 3/22/98 04:43'!
new
^super new initialize.! !
!FlippyState class methodsFor: 'instance creation' stamp: 'cr 1/30/98 19:04'!
top: t middle: m bottom: b
"Create a new instance."
^self new top: t; middle: m; bottom: b; yourself.
! !
FlippyGame initialize!
Smalltalk removeClassNamed: #FinMorph!
Smalltalk removeClassNamed: #FooBarMorph!
Smalltalk removeClassNamed: #FlippyGridButton!
FlippyGame initialize.!
| |
using System;
using System.Diagnostics;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using System.Collections.Generic;
using RaptorDB.Common;
using System.Threading;
namespace RaptorDB
{
// high frequency storage file with overwrite old values
internal class StorageFileHF
{
FileStream _datawrite;
WahBitArray _freeList;
private string _filename = "";
private object _readlock = new object();
ILog _log = LogManager.GetLogger(typeof(StorageFileHF));
// **** change this if storage format changed ****
internal static int _CurrentVersion = 1;
int _lastBlockNumber = 0;
private ushort _BLOCKSIZE = 4096;
private string _Path = "";
private string _S = Path.DirectorySeparatorChar.ToString();
public static byte[] _fileheader = { (byte)'M', (byte)'G', (byte)'H', (byte)'F',
0, // 4 -- storage file version number,
0,2, // 5,6 -- block size ushort low, hi
1 // 7 -- key type 0 = guid, 1 = string
};
public StorageFileHF(string filename, ushort blocksize)
{
_Path = Path.GetDirectoryName(filename);
if (_Path.EndsWith(_S) == false) _Path += _S;
_filename = Path.GetFileNameWithoutExtension(filename);
Initialize(filename, blocksize);
}
public void Shutdown()
{
FlushClose(_datawrite);
// write free list
WriteFreeListBMPFile(_Path + _filename + ".free");
_datawrite = null;
}
public ushort GetBlockSize()
{
return _BLOCKSIZE;
}
internal void FreeBlocks(List<int> list)
{
list.ForEach(x => _freeList.Set(x, true));
}
internal byte[] ReadBlock(int blocknumber)
{
SeekBlock(blocknumber);
byte[] data = new byte[_BLOCKSIZE];
_datawrite.Read(data, 0, _BLOCKSIZE);
return data;
}
internal byte[] ReadBlockBytes(int blocknumber, int bytes)
{
SeekBlock(blocknumber);
byte[] data = new byte[bytes];
_datawrite.Read(data, 0, bytes);
return data;
}
internal int GetFreeBlockNumber()
{
// get the first free block or append to the end
if (_freeList.CountOnes() > 0)
{
int i = _freeList.GetFirstIndex();
_freeList.Set(i, false);
return i;
}
else
return Interlocked.Increment(ref _lastBlockNumber);//++;
}
internal void SeekBlock(int blocknumber)
{
long offset = (long)_fileheader.Length + blocknumber * _BLOCKSIZE;
_datawrite.Seek(offset, SeekOrigin.Begin);// wiil seek past the end of file on fs.Write will zero the difference
}
internal void WriteBlockBytes(byte[] data, int start, int len)
{
_datawrite.Write(data, start, len);
}
#region [ private / internal ]
private void WriteFreeListBMPFile(string filename)
{
WahBitArrayState t;
uint[] ints = _freeList.GetCompressed(out t);
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write((byte)t);// write new format with the data type byte
foreach (var i in ints)
{
bw.Write(i);
}
File.WriteAllBytes(filename, ms.ToArray());
}
private void ReadFreeListBMPFile(string filename)
{
byte[] b = File.ReadAllBytes(filename);
WahBitArrayState t = WahBitArrayState.Wah;
int j = 0;
if (b.Length % 4 > 0) // new format with the data type byte
{
t = (WahBitArrayState)Enum.ToObject(typeof(WahBitArrayState), b[0]);
j = 1;
}
List<uint> ints = new List<uint>();
for (int i = 0; i < b.Length / 4; i++)
{
ints.Add((uint)Helper.ToInt32(b, (i * 4) + j));
}
_freeList = new WahBitArray(t, ints.ToArray());
}
private void Initialize(string filename, ushort blocksize)
{
if (File.Exists(filename) == false)
_datawrite = new FileStream(filename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
else
_datawrite = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
if (_datawrite.Length == 0)
{
CreateFileHeader(blocksize);
// new file
_datawrite.Write(_fileheader, 0, _fileheader.Length);
_datawrite.Flush();
}
else
{
ReadFileHeader();
_lastBlockNumber = (int)((_datawrite.Length - _fileheader.Length) / _BLOCKSIZE);
_lastBlockNumber++;
}
_freeList = new WahBitArray();
if (File.Exists(_Path + _filename + ".free"))
{
ReadFreeListBMPFile(_Path + _filename + ".free");
// delete file so if failure no big deal on restart
File.Delete(_Path + _filename + ".free");
}
}
private void ReadFileHeader()
{
// set _blockize
_datawrite.Seek(0L, SeekOrigin.Begin);
byte[] hdr = new byte[_fileheader.Length];
_datawrite.Read(hdr, 0, _fileheader.Length);
_BLOCKSIZE = 0;
_BLOCKSIZE = (ushort)((int)hdr[5] + ((int)hdr[6]) << 8);
}
private void CreateFileHeader(int blocksize)
{
// add version number
_fileheader[4] = (byte)_CurrentVersion;
// block size
_fileheader[5] = (byte)(blocksize & 0xff);
_fileheader[6] = (byte)(blocksize >> 8);
_BLOCKSIZE = (ushort)blocksize;
}
private void FlushClose(FileStream st)
{
if (st != null)
{
st.Flush(true);
st.Close();
}
}
#endregion
internal int NumberofBlocks()
{
return (int)((_datawrite.Length / (int)_BLOCKSIZE) + 1);
}
internal void FreeBlock(int i)
{
_freeList.Set(i, true);
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable
{
internal abstract partial class AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax>
{
private partial class GenerateVariableCodeAction : CodeAction
{
private readonly TService _service;
private readonly State _state;
private readonly bool _generateProperty;
private readonly bool _isReadonly;
private readonly bool _isConstant;
private readonly Document _document;
private readonly string _equivalenceKey;
public GenerateVariableCodeAction(
TService service,
Document document,
State state,
bool generateProperty,
bool isReadonly,
bool isConstant)
{
_service = service;
_document = document;
_state = state;
_generateProperty = generateProperty;
_isReadonly = isReadonly;
_isConstant = isConstant;
_equivalenceKey = Title;
}
protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
{
var syntaxTree = await _document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var generateUnsafe = _state.TypeMemberType.IsUnsafe() &&
!_state.IsContainedInUnsafeType;
if (_generateProperty)
{
var getAccessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: null,
accessibility: DetermineMaximalAccessibility(_state),
statements: null);
var setAccessor = _isReadonly ? null : CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: null,
accessibility: DetermineMinimalAccessibility(_state),
statements: null);
var result = await CodeGenerator.AddPropertyDeclarationAsync(
_document.Project.Solution,
_state.TypeToGenerateIn,
CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: null,
accessibility: DetermineMaximalAccessibility(_state),
modifiers: new DeclarationModifiers(isStatic: _state.IsStatic, isUnsafe: generateUnsafe),
type: _state.TypeMemberType,
explicitInterfaceSymbol: null,
name: _state.IdentifierToken.ValueText,
isIndexer: _state.IsIndexer,
parameters: _state.Parameters,
getMethod: getAccessor,
setMethod: setAccessor),
new CodeGenerationOptions(contextLocation: _state.IdentifierToken.GetLocation()),
cancellationToken: cancellationToken)
.ConfigureAwait(false);
return result;
}
else
{
var result = await CodeGenerator.AddFieldDeclarationAsync(
_document.Project.Solution,
_state.TypeToGenerateIn,
CodeGenerationSymbolFactory.CreateFieldSymbol(
attributes: null,
accessibility: DetermineMinimalAccessibility(_state),
modifiers: _isConstant ?
new DeclarationModifiers(isConst: true, isUnsafe: generateUnsafe) :
new DeclarationModifiers(isStatic: _state.IsStatic, isReadOnly: _isReadonly, isUnsafe: generateUnsafe),
type: _state.TypeMemberType,
name: _state.IdentifierToken.ValueText),
new CodeGenerationOptions(contextLocation: _state.IdentifierToken.GetLocation()),
cancellationToken: cancellationToken)
.ConfigureAwait(false);
return result;
}
}
private Accessibility DetermineMaximalAccessibility(State state)
{
if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface)
{
return Accessibility.NotApplicable;
}
var accessibility = Accessibility.Public;
// Ensure that we're not overly exposing a type.
var containingTypeAccessibility = state.TypeToGenerateIn.DetermineMinimalAccessibility();
var effectiveAccessibility = CommonAccessibilityUtilities.Minimum(
containingTypeAccessibility, accessibility);
var returnTypeAccessibility = state.TypeMemberType.DetermineMinimalAccessibility();
if (CommonAccessibilityUtilities.Minimum(effectiveAccessibility, returnTypeAccessibility) !=
effectiveAccessibility)
{
return returnTypeAccessibility;
}
return accessibility;
}
private Accessibility DetermineMinimalAccessibility(State state)
{
if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface)
{
return Accessibility.NotApplicable;
}
// Otherwise, figure out what accessibility modifier to use and optionally mark
// it as static.
var syntaxFacts = _document.GetLanguageService<ISyntaxFactsService>();
if (syntaxFacts.IsAttributeNamedArgumentIdentifier(state.SimpleNameOrMemberAccessExpressionOpt))
{
return Accessibility.Public;
}
else if (state.ContainingType.IsContainedWithin(state.TypeToGenerateIn))
{
return Accessibility.Private;
}
else if (DerivesFrom(state, state.ContainingType) && state.IsStatic)
{
// NOTE(cyrusn): We only generate protected in the case of statics. Consider
// the case where we're generating into one of our base types. i.e.:
//
// class B : A { void Foo() { A a; a.Foo(); }
//
// In this case we can *not* mark the method as protected. 'B' can only
// access protected members of 'A' through an instance of 'B' (or a subclass
// of B). It can not access protected members through an instance of the
// superclass. In this case we need to make the method public or internal.
//
// However, this does not apply if the method will be static. i.e.
//
// class B : A { void Foo() { A.Foo(); }
//
// B can access the protected statics of A, and so we generate 'Foo' as
// protected.
return Accessibility.Protected;
}
else if (state.ContainingType.ContainingAssembly.IsSameAssemblyOrHasFriendAccessTo(state.TypeToGenerateIn.ContainingAssembly))
{
return Accessibility.Internal;
}
else
{
// TODO: Code coverage - we need a unit-test that generates across projects
return Accessibility.Public;
}
}
private bool DerivesFrom(State state, INamedTypeSymbol containingType)
{
return containingType.GetBaseTypes().Select(t => t.OriginalDefinition)
.Contains(state.TypeToGenerateIn);
}
public override string Title
{
get
{
var text = _isConstant
? FeaturesResources.GenerateConstantIn
: _generateProperty
? _isReadonly ? FeaturesResources.GenerateReadonlyProperty : FeaturesResources.GeneratePropertyIn
: _isReadonly ? FeaturesResources.GenerateReadonlyField : FeaturesResources.GenerateFieldIn;
return string.Format(
text,
_state.IdentifierToken.ValueText,
_state.TypeToGenerateIn.Name);
}
}
public override string EquivalenceKey
{
get
{
return _equivalenceKey;
}
}
}
}
}
| |
/***************************************************************************
copyright : (C) 2005 by Brian Nickel
email : brian.nickel@gmail.com
based on : id3v2frame.cpp from TagLib
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* 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.Collections;
using System;
namespace TagLib.Id3v2
{
public class FrameHeader
{
///////////////////////////////////////////////////////////////////////
// private properties
///////////////////////////////////////////////////////////////////////
private ByteVector frame_id;
private uint frame_size;
private uint version;
// flags
private bool tag_alter_preservation;
private bool file_alter_preservation;
private bool read_only;
private bool grouping_identity;
private bool compression;
private bool encryption;
private bool unsyncronisation;
private bool data_length_indicator;
///////////////////////////////////////////////////////////////////////
// public methods
///////////////////////////////////////////////////////////////////////
public FrameHeader (ByteVector data, uint version)
{
frame_id = null;
frame_size = 0;
this.version = 4;
tag_alter_preservation = false;
file_alter_preservation = false;
read_only = false;
grouping_identity = false;
compression = false;
encryption = false;
unsyncronisation = false;
data_length_indicator = false;
SetData (data, version);
}
public void SetData (ByteVector data, uint version)
{
this.version = version;
if (version < 3)
{
// ID3v2.2
if (data.Count < 3)
{
Debugger.Debug("You must at least specify a frame ID.");
return;
}
// Set the frame ID -- the first three bytes
frame_id = data.Mid (0, 3);
// If the full header information was not passed in, do not continue to the
// steps to parse the frame size and flags.
if (data.Count < 6)
{
frame_size = 0;
return;
}
frame_size = data.Mid (3, 3).ToUInt ();
}
else if (version == 3)
{
// ID3v2.3
if (data.Count < 4)
{
Debugger.Debug("You must at least specify a frame ID.");
return;
}
// Set the frame ID -- the first four bytes
frame_id = data.Mid (0, 4);
// If the full header information was not passed in, do not continue to the
// steps to parse the frame size and flags.
if(data.Count < 10)
{
frame_size = 0;
return;
}
// Set the size -- the frame size is the four bytes starting at byte four in
// the frame header (structure 4)
frame_size = data.Mid (4, 4).ToUInt ();
// read the first byte of flags
tag_alter_preservation = ((data[8] >> 7) & 1) == 1; // (structure 3.3.1.a)
file_alter_preservation = ((data[8] >> 6) & 1) == 1; // (structure 3.3.1.b)
read_only = ((data[8] >> 5) & 1) == 1; // (structure 3.3.1.c)
// read the second byte of flags
compression = ((data[9] >> 7) & 1) == 1; // (structure 3.3.1.i)
encryption = ((data[9] >> 6) & 1) == 1; // (structure 3.3.1.j)
grouping_identity = ((data[9] >> 5) & 1) == 1; // (structure 3.3.1.k)
}
else
{
// ID3v2.4
if (data.Count < 4)
{
Debugger.Debug("You must at least specify a frame ID.");
return;
}
// Set the frame ID -- the first four bytes
frame_id = data.Mid (0, 4);
// If the full header information was not passed in, do not continue to the
// steps to parse the frame size and flags.
if(data.Count < 10)
{
frame_size = 0;
return;
}
// Set the size -- the frame size is the four bytes starting at byte four in
// the frame header (structure 4)
frame_size = SynchData.ToUInt (data.Mid (4, 4));
// read the first byte of flags
tag_alter_preservation = ((data[8] >> 6) & 1) == 1; // (structure 4.1.1.a)
file_alter_preservation = ((data[8] >> 5) & 1) == 1; // (structure 4.1.1.b)
read_only = ((data[8] >> 4) & 1) == 1; // (structure 4.1.1.c)
// read the second byte of flags
grouping_identity = ((data[9] >> 6) & 1) == 1; // (structure 4.1.2.h)
compression = ((data[9] >> 3) & 1) == 1; // (structure 4.1.2.k)
encryption = ((data[9] >> 2) & 1) == 1; // (structure 4.1.2.m)
unsyncronisation = ((data[9] >> 1) & 1) == 1; // (structure 4.1.2.n)
data_length_indicator = (data[9] & 1) == 1; // (structure 4.1.2.p)
}
}
public void SetData (ByteVector data)
{
SetData (data, 4);
}
public ByteVector Render ()
{
ByteVector flags = new ByteVector (2, (byte) 0); // just blank for the moment
flags.Insert (0, SynchData.FromUInt (frame_size));
flags.Insert (0, frame_id);
return flags;
}
public static uint Size (uint version)
{
return (uint) (version < 3 ? 6 : 10);
}
///////////////////////////////////////////////////////////////////////
// public properties
///////////////////////////////////////////////////////////////////////
public FrameHeader (ByteVector data) : this (data, 4) {}
public ByteVector FrameId
{
get {return frame_id;}
set {if (value != null) frame_id = value.Mid (0, 4);}
}
public uint FrameSize
{
get {return frame_size;}
set {frame_size = value;}
}
public uint Version {get {return version;}}
public bool TagAlterPreservation
{
get {return tag_alter_preservation;}
set {tag_alter_preservation = value;}
}
public bool FileAlterPreservation
{
get {return file_alter_preservation;}
set {file_alter_preservation = value;}
}
public bool ReadOnly
{
get {return read_only;}
set {read_only = value;}
}
public bool GroupingIdentity {get {return grouping_identity;}}
public bool Compression {get {return compression;}}
public bool Encryption {get {return encryption;}}
public bool Unsycronisation {get {return unsyncronisation;}}
public bool DataLengthIndicator {get {return data_length_indicator;}}
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// 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;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using gov.va.medora.mdo.exceptions;
using gov.va.medora.utils;
using gov.va.medora.mdo.dao.sql.UserValidation;
using gov.va.medora.mdo.src.mdo;
namespace gov.va.medora.mdo.dao.vista
{
public class VistaAccount : AbstractAccount
{
static Dictionary<string, string> administrativeDfns = new conf.AppConfig(true, "app.conf").AllConfigs[conf.ConfigFileConstants.SERVICE_ACCOUNT_CONFIG_SECTION];
public VistaAccount(AbstractConnection cxn) : base(cxn) { }
public override string authenticate(AbstractCredentials credentials, DataSource validationDataSource = null)
{
if (Cxn == null || !Cxn.IsConnected)
{
throw new MdoException(MdoExceptionCode.USAGE_NO_CONNECTION, "Must have connection");
}
if (credentials == null)
{
throw new MdoException(MdoExceptionCode.ARGUMENT_NULL, "Missing credentials");
}
if (string.IsNullOrEmpty(AuthenticationMethod))
{
throw new MdoException(MdoExceptionCode.ARGUMENT_NULL, "Missing Account AuthenticationMethod");
}
if (AuthenticationMethod == VistaConstants.LOGIN_CREDENTIALS)
{
return login(credentials);
}
// Temporarily disabled - will do only V2WEB for now
//else if (AuthenticationMethod == VistaConstants.BSE_CREDENTIALS_V2V)
//{
// VisitTemplate visitTemplate = new BseVista2VistaVisit(this, credentials);
// return visitTemplate.visit();
//}
else if (AuthenticationMethod == VistaConstants.BSE_CREDENTIALS_V2WEB)
{
VisitTemplate visitTemplate = new BseVista2WebVisit(this, credentials, validationDataSource);
return visitTemplate.visit();
}
else if (AuthenticationMethod == VistaConstants.NON_BSE_CREDENTIALS)
{
VisitTemplate visitTemplate = new NonBseVisit(this, credentials);
return visitTemplate.visit();
}
else
{
throw new ArgumentException("Invalid credentials");
}
}
internal string login(AbstractCredentials credentials)
{
if (String.IsNullOrEmpty(credentials.AccountName))
{
throw new MdoException(MdoExceptionCode.ARGUMENT_NULL, "Missing Access Code");
}
if (String.IsNullOrEmpty(credentials.AccountPassword))
{
throw new MdoException(MdoExceptionCode.ARGUMENT_NULL, "Missing Verify Code");
}
VistaQuery vq = new VistaQuery("XUS SIGNON SETUP");
string rtn = (string)Cxn.query(vq);
if (rtn == null)
{
throw new UnexpectedDataException("Unable to setup authentication");
}
vq = new VistaQuery("XUS AV CODE");
// This is here so we can test with MockConnection
if (Cxn.GetType().Name != "MockConnection")
{
vq.addEncryptedParameter(vq.LITERAL, credentials.AccountName + ';' + credentials.AccountPassword);
}
else
{
vq.addParameter(vq.LITERAL, credentials.AccountName + ';' + credentials.AccountPassword);
}
rtn = (string)Cxn.query(vq);
//TODO - need to catch renew verify id error
string[] flds = StringUtils.split(rtn, StringUtils.CRLF);
if (flds[0] == "0")
{
throw new UnauthorizedAccessException(flds[3]);
}
AccountId = flds[0];
// Set the connection's UID
Cxn.Uid = AccountId;
// Save the credentials
credentials.LocalUid = AccountId;
credentials.AuthenticationSource = Cxn.DataSource;
credentials.AuthenticationToken = Cxn.DataSource.SiteId.Id + '_' + AccountId;
IsAuthenticated = true;
Cxn.IsRemote = false;
// Set the greeting if there is one
if (flds.Length > 7)
{
return flds[7];
}
return "OK";
}
public override User authorize(AbstractCredentials credentials, AbstractPermission permission)
{
if (permission == null)
{
throw new ArgumentNullException("permission");
}
checkAuthorizeReadiness();
checkPermissionString(permission.Name);
doTheAuthorize(credentials, permission);
return toUser(credentials);
}
internal void doTheAuthorize(AbstractCredentials credentials, AbstractPermission permission)
{
//// if we are requesting CPRS context with a visit and user does not have it - add it to their account
if (permission.Name == VistaConstants.CPRS_CONTEXT &&
!Cxn.Account.Permissions.ContainsKey(VistaConstants.CPRS_CONTEXT) &&
!Cxn.Account.AuthenticationMethod.Equals(VistaConstants.LOGIN_CREDENTIALS))
{
addContextInVista(Cxn.Uid, permission);
}
else
{
setContext(permission);
}
if (String.IsNullOrEmpty(Cxn.Uid))
{
if (String.IsNullOrEmpty(credentials.FederatedUid))
{
throw new MdoException("Missing federated UID, cannot get local UID");
}
VistaUserDao dao = new VistaUserDao(Cxn);
Cxn.Uid = dao.getUserIdBySsn(credentials.FederatedUid);
if (String.IsNullOrEmpty(Cxn.Uid))
{
throw new MdoException("Unable to get local UID for federated ID " + credentials.FederatedUid);
}
}
if (!credentials.Complete)
{
VistaUserDao dao = new VistaUserDao(Cxn);
dao.addVisitorInfo(credentials);
}
}
internal User toUser(AbstractCredentials credentials)
{
User u = new User();
u.Uid = Cxn.Uid;
u.Name = new PersonName(credentials.SubjectName);
u.SSN = new SocSecNum(credentials.FederatedUid);
u.LogonSiteId = Cxn.DataSource.SiteId;
return u;
}
internal void checkAuthorizeReadiness()
{
if (Cxn == null || !Cxn.IsConnected)
{
throw new ConnectionException("Must have connection");
}
if (!isAuthenticated)
{
throw new UnauthorizedAccessException("Account must be authenticated");
}
}
internal void checkPermissionString(string permission)
{
if (String.IsNullOrEmpty(permission))
{
throw new UnauthorizedAccessException("Must have a context");
}
}
internal void setContext(AbstractPermission permission)
{
if (permission == null || string.IsNullOrEmpty(permission.Name))
{
throw new ArgumentNullException("permission");
}
MdoQuery request = buildSetContextRequest(permission.Name);
string response = "";
try
{
response = (string)Cxn.query(request);
}
catch (MdoException e)
{
response = e.Message;
}
if (response != "1")
{
throw getException(response);
}
if (!Cxn.Account.Permissions.ContainsKey(permission.Name))
{
Cxn.Account.Permissions.Add(permission.Name, permission);
}
isAuthorized = isAuthorized || permission.IsPrimary;
}
internal MdoQuery buildSetContextRequest(string context)
{
VistaQuery vq = new VistaQuery("XWB CREATE CONTEXT");
if (Cxn.GetType().Name != "MockConnection")
{
vq.addEncryptedParameter(vq.LITERAL, context);
}
else
{
vq.addParameter(vq.LITERAL, context);
}
return vq;
}
internal Exception getException(string result)
{
if (result.IndexOf("The context") != -1 &&
result.IndexOf("does not exist on server") != -1)
{
return new PermissionNotFoundException(result);
}
if (result.IndexOf("User") != -1 &&
result.IndexOf("does not have access to option") != -1)
{
return new UnauthorizedAccessException(result);
}
if (result.StartsWith("Option locked"))
{
return new PermissionLockedException(result);
}
return new Exception(result);
}
//internal void setVisitorContext(AbstractPermission requestedContext, string DUZ)
//{
// try
// {
// setContext(requestedContext);
// return;
// }
// catch (UnauthorizedAccessException uae)
// {
// addContextInVista(DUZ, requestedContext);
// setContext(requestedContext);
// }
// catch (Exception e)
// {
// throw;
// }
//}
// This is how the visitor gets the requested context - typically
// OR CPRS GUI CHART. The visitor comes back from VistA with CAPRI
// context only.
internal void addContextInVista(string duz, AbstractPermission requestedContext)
{
if (Permissions.ContainsKey(requestedContext.Name))
{
return;
}
VistaUserDao dao = new VistaUserDao(Cxn);
// try/catch should fix: http://trac.medora.va.gov/web/ticket/2288
try
{
setContext(requestedContext);
}
catch (Exception)
{
try
{
// will get CONTEXT HAS NOT BEEN CREATED if we don't set this again after failed attempt
setContext(new MenuOption(VistaConstants.DDR_CONTEXT));
dao.addPermission(duz, requestedContext);
setContext(requestedContext);
}
catch (Exception)
{
throw;
}
}
}
public override User authenticateAndAuthorize(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource = null)
{
string msg = authenticate(credentials, validationDataSource);
User u = authorize(credentials, permission);
u.Greeting = msg;
return u;
}
public string getAuthenticationTokenFromVista()
{
VistaQuery vq = new VistaQuery("XUS SET VISITOR");
return (string)Cxn.query(vq);
}
public string makeAuthenticationTokenInVista(string duz)
{
string token1 = getAuthenticationTokenFromVista2();
string token2 = setAuthenticationTokenInVista(token1, duz);
token2 = getXtmpToken(token1);
return token1;
}
internal string getXtmpToken(string token)
{
string arg = "$G(^XTMP(\"" + token + "\",1))";
return VistaUtils.getVariableValue(Cxn, arg);
}
internal string setAuthenticationTokenInVista(string token, string duz)
{
DdrLister query = buildSetAuthenticationTokenInVistaQuery(token, duz);
string[] response = query.execute();
if (response.Length != 1)
{
throw new MdoException(MdoExceptionCode.DATA_UNEXPECTED_FORMAT);
}
return response[0];
}
internal string getAuthenticationTokenFromVista2()
{
DdrLister query = buildGetAuthenticationTokenFromVista2Query();
string[] response = query.execute();
if (response == null || response.Length != 1)
{
throw new MdoException(MdoExceptionCode.DATA_UNEXPECTED_FORMAT);
}
string[] flds = response[0].Split(new char[] { '^' });
if (flds.Length != 3)
{
throw new MdoException(MdoExceptionCode.DATA_UNEXPECTED_FORMAT);
}
return flds[2];
}
internal DdrLister buildGetAuthenticationTokenFromVista2Query()
{
DdrLister query = new DdrLister(Cxn);
query.File = "200";
query.Fields = ".01";
query.Flags = "IP";
query.Max = "1";
query.Xref = "#";
query.Id = "D EN^DDIOL($$HANDLE^XUSRB4(\"XUSBSE\",1))";
return query;
}
internal DdrLister buildSetAuthenticationTokenInVistaQuery(string token, string duz)
{
DdrLister query = new DdrLister(Cxn);
query.File = "200";
query.Fields = ".01";
query.Flags = "IP";
query.Max = "1";
query.Xref = "#";
query.Id = "S ^XTMP(\"" + token + "\",1)=$$GET^XUESSO1(" + duz + ")";
//"D EN^DDIOL(\"^XMTP(\"" + token + "\",1)";
return query;
}
public static string getAdminLocalUid(string siteId)
{
if (administrativeDfns.ContainsKey(siteId))
{
return administrativeDfns[siteId];
}
else
{
return "1";
}
}
}
abstract class VisitTemplate
{
protected VistaAccount acct;
protected AbstractConnection cxn;
protected AbstractCredentials creds;
public VisitTemplate(VistaAccount acct, AbstractCredentials credentials)
{
this.acct = acct;
cxn = acct.Cxn;
creds = credentials;
}
public abstract void setupVisit();
public abstract MdoQuery buildVisitRequest();
public abstract bool success(string[] flds);
public string visit()
{
//if (creds.FederatedUid == VistaConstants.ADMINISTRATIVE_FEDERATED_UID)
//{
// creds.LocalUid = VistaAccount.getAdminLocalUid(creds.AuthenticationSource.SiteId.Id);
//}
validateCredentials();
setupVisit();
MdoQuery request = buildVisitRequest();
string response = (string)cxn.query(request);
string[] flds = StringUtils.split(response, StringUtils.CRLF);
if (!success(flds))
{
throw new UnauthorizedAccessException("Visit failed: Invalid credentials?");
}
if (flds.Length >= 8)
{
cxn.IsTestSource = (flds[7] == "0");
}
acct.IsAuthenticated = true;
cxn.IsRemote = true;
//creds.AuthenticatorId = cxn.DataSource.SiteId.Id;
//creds.AuthenticatorName = cxn.DataSource.SiteId.Name;
return "OK";
}
internal void validateCredentials()
{
// Need an app password (the security phrase)...
if (String.IsNullOrEmpty(creds.SecurityPhrase))
{
throw new UnauthorizedAccessException("Missing application password");
}
// BSE visit uses just the authentication token, so...
if (String.IsNullOrEmpty(creds.AuthenticationToken))
{
throw new UnauthorizedAccessException("Cannot visit without authentication token");
}
//string[] flds = creds.AuthenticationToken.Split(new char[] { '_' });
//if (flds.Length != 2)
//{
// throw new UnauthorizedAccessException("Invalid authentication token");
//}
if (String.IsNullOrEmpty(creds.SubjectPhone))
{
creds.SubjectPhone = "No phone";
}
if (String.IsNullOrEmpty(creds.FederatedUid))
{
throw new UnauthorizedAccessException("Missing FederatedUid");
}
if (String.IsNullOrEmpty(creds.SubjectName))
{
throw new UnauthorizedAccessException("Mising SubjectName");
}
if (creds.AuthenticationSource == null)
{
throw new UnauthorizedAccessException("Missing AuthenticationSource");
}
if (creds.AuthenticationSource.SiteId == null)
{
throw new UnauthorizedAccessException("Missing AuthenticationSource.SiteId");
}
if (String.IsNullOrEmpty(creds.AuthenticationSource.SiteId.Id))
{
throw new UnauthorizedAccessException("Missing AuthenticatorId");
}
if (String.IsNullOrEmpty(creds.AuthenticationSource.SiteId.Name))
{
throw new UnauthorizedAccessException("Missing AuthenticatorName");
}
if (String.IsNullOrEmpty(creds.LocalUid))
{
throw new UnauthorizedAccessException("Missing LocalUid");
}
if (String.IsNullOrEmpty(creds.SubjectPhone))
{
throw new UnauthorizedAccessException("Missing SubjectPhone");
}
// Is the connection to a production system with a test visitor from a different site?
if (!cxn.IsTestSource && creds.AreTest && creds.AuthenticationSource.SiteId.Id != cxn.DataSource.SiteId.Id)
{
throw new UnauthorizedAccessException("Cannot visit production system with test credentials");
}
}
}
// Temporarily disabled - only V2WEB BSE visits for now.
//class BseVista2VistaVisit : VisitTemplate
//{
// public BseVista2VistaVisit(VistaAccount acct, AbstractCredentials creds) : base(acct, creds) { }
// public override void setupVisit() { }
// public override MdoQuery buildVisitRequest()
// {
// VistaQuery vq = new VistaQuery("XUS SIGNON SETUP");
// string phrase = creds.SecurityPhrase + '^' +
// creds.AuthenticationToken + '^' +
// creds.AuthenticationSource.SiteId.Id + '^' +
// creds.AuthenticationSource.Port;
// string arg = "-35^" + VistaUtils.encrypt(phrase);
// vq.addParameter(vq.LITERAL, arg);
// return vq;
// }
// public override bool success(string[] flds)
// {
// if (String.IsNullOrEmpty(creds.AuthenticationMethod))
// {
// creds.AuthenticationMethod = VistaConstants.BSE_CREDENTIALS_V2V;
// }
// // NB: Do NOT remove this code. It is the only way to detect that a BSE visit has
// // failed. If this is bypassed, the subsequent context call seems to succeed when
// // it doesn't.
// if (flds.Length < 6 || flds[5] != "1")
// {
// return false;
// }
// return true;
// }
//}
class BseVista2WebVisit : VisitTemplate
{
DataSource _validatorDataSource;
public BseVista2WebVisit(VistaAccount acct, AbstractCredentials creds, DataSource validatorDataSource)
: base(acct, creds)
{
if (validatorDataSource != null)
{
_validatorDataSource = validatorDataSource;
}
}
public override void setupVisit()
{
insertUserValidationRecord();
}
public override MdoQuery buildVisitRequest()
{
VistaQuery vq = new VistaQuery("XUS SIGNON SETUP");
string token = SSTCryptographer.Encrypt(creds.AuthenticationToken, VistaConstants.ENCRYPTION_KEY);
token = UserValidationDao.escapeString(token);
string arg = "-35^" + VistaUtils.encrypt(creds.SecurityPhrase + '^' + token);
vq.addParameter(vq.LITERAL, arg);
return vq;
}
public override bool success(string[] flds)
{
// NB: Do NOT remove this code. It is the only way to detect that a BSE visit has
// failed. If this is bypassed, the subsequent context call seems to succeed when
// it doesn't.
if (flds.Length < 6 || flds[5] != "1")
{
deleteUserValidationRecord();
return false;
}
return true;
}
internal void insertUserValidationRecord()
{
UserValidationDao dao = new UserValidationDao(new UserValidationConnection(_validatorDataSource));
dao.addRecord(creds, VistaConstants.ENCRYPTION_KEY);
}
internal void deleteUserValidationRecord()
{
UserValidationDao dao = new UserValidationDao(new UserValidationConnection(_validatorDataSource));
dao.deleteRecord(creds.AuthenticationToken, VistaConstants.ENCRYPTION_KEY);
}
}
class NonBseVisit : VisitTemplate
{
public NonBseVisit(VistaAccount acct, AbstractCredentials creds) : base(acct, creds) { }
public override void setupVisit() { }
public override MdoQuery buildVisitRequest()
{
string arg = "-31^DVBA_^";
arg += creds.FederatedUid + '^' +
creds.SubjectName + '^' +
creds.AuthenticationSource.SiteId.Name + '^' +
creds.AuthenticationSource.SiteId.Id + '^' +
creds.LocalUid + '^' +
creds.SubjectPhone;
VistaQuery vq = new VistaQuery("XUS SIGNON SETUP");
vq.addParameter(vq.LITERAL, arg);
return vq;
}
public override bool success(string[] flds)
{
AbstractPermission ddrContext = new MenuOption(VistaConstants.DDR_CONTEXT);
acct.setContext(ddrContext);
VistaUserDao dao = new VistaUserDao(cxn);
cxn.Uid = dao.getUserIdBySsn(creds.FederatedUid);
return true;
}
}
}
| |
using System;
using System.IO;
using FluentAssertions;
using FluentAssertions.Extensions;
using TestableFileSystem.Fakes.Builders;
using TestableFileSystem.Interfaces;
using Xunit;
namespace TestableFileSystem.Fakes.Tests.Specs.FakeDirectory
{
public sealed class DirectoryTimeLastAccessSpecs
{
private static readonly DateTime DefaultTimeUtc = 1.February(2034).At(12, 34, 56).AsUtc();
private static readonly DateTime DefaultTime = DefaultTimeUtc.ToLocalTime();
private static readonly DateTime HighTime = DateTime.MaxValue.AddDays(-2).AsUtc().ToLocalTime();
private static readonly DateTime ZeroFileTime = 1.January(1601).AsUtc().ToLocalTime();
[Fact]
private void When_getting_last_access_time_in_local_zone_for_null_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
// ReSharper disable once AssignNullToNotNullAttribute
Action action = () => fileSystem.Directory.GetLastAccessTime(null);
// Assert
action.Should().ThrowExactly<ArgumentNullException>();
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_null_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
// ReSharper disable once AssignNullToNotNullAttribute
Action action = () => fileSystem.Directory.SetLastAccessTime(null, DefaultTime);
// Assert
action.Should().ThrowExactly<ArgumentNullException>();
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_empty_string_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.GetLastAccessTime(string.Empty);
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("The path is not of a legal form.*");
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_empty_string_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime(string.Empty, DefaultTime);
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("The path is not of a legal form.*");
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_whitespace_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.GetLastAccessTime(" ");
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("The path is not of a legal form.*");
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_whitespace_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime(" ", DefaultTime);
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("The path is not of a legal form.*");
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_invalid_drive_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.GetLastAccessTime("_:");
// Assert
action.Should().ThrowExactly<NotSupportedException>().WithMessage("The given path's format is not supported.");
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_invalid_drive_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime("_:", DefaultTime);
// Assert
action.Should().ThrowExactly<NotSupportedException>().WithMessage("The given path's format is not supported.");
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_wildcard_characters_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.GetLastAccessTime(@"c:\dir?i");
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("Illegal characters in path.*");
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_wildcard_characters_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime(@"c:\dir?i", DefaultTime);
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("Illegal characters in path.*");
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_missing_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\some")
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTime(@"C:\some\nested");
// Assert
time.Should().Be(ZeroFileTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_missing_directory_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\some")
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime(@"C:\some\nested", DefaultTime);
// Assert
action.Should().ThrowExactly<FileNotFoundException>().WithMessage(@"Could not find file 'C:\some\nested'.");
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_existing_directory_it_must_succeed()
{
// Arrange
const string path = @"C:\some";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
fileSystem.Directory.SetLastAccessTime(path, DefaultTime);
// Assert
fileSystem.Directory.GetLastAccessTime(path).Should().Be(DefaultTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_existing_directory_with_trailing_whitespace_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\some")
.Build();
// Act
fileSystem.Directory.SetLastAccessTime(@"C:\some ", DefaultTime);
// Assert
fileSystem.Directory.GetLastAccessTime(@"C:\some ").Should().Be(DefaultTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_existing_readonly_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\some", FileAttributes.ReadOnly)
.Build();
// Act
fileSystem.Directory.SetLastAccessTime(@"C:\some", DefaultTime);
// Assert
fileSystem.Directory.GetLastAccessTime(@"C:\some").Should().Be(DefaultTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_existing_subdirectory_in_readonly_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"c:\folder", FileAttributes.ReadOnly)
.IncludingDirectory(@"C:\folder\some")
.Build();
// Act
fileSystem.Directory.SetLastAccessTime(@"C:\folder\some", DefaultTime);
// Assert
fileSystem.Directory.GetLastAccessTime(@"C:\folder\some").Should().Be(DefaultTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_current_directory_it_must_succeed()
{
// Arrange
const string path = @"C:\some\folder";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
fileSystem.Directory.SetCurrentDirectory(path);
// Act
fileSystem.Directory.SetLastAccessTime(path, DefaultTime);
// Assert
fileSystem.Directory.GetLastAccessTime(path).Should().Be(DefaultTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_existing_directory_to_MinValue_it_must_fail()
{
// Arrange
const string path = @"C:\some";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime(path, DateTime.MinValue);
// Assert
action.Should().ThrowExactly<ArgumentOutOfRangeException>().WithMessage("Not a valid Win32 FileTime.*");
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_existing_directory_to_MaxValue_it_must_succeed()
{
// Arrange
const string path = @"C:\some";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
fileSystem.Directory.SetLastAccessTime(path, HighTime);
// Assert
fileSystem.Directory.GetLastAccessTime(path).Should().Be(HighTime);
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_drive_it_must_succeed()
{
// Arrange
const string path = @"C:\";
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(path)
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTime(path);
// Assert
time.Should().Be(DefaultTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_drive_it_must_fail()
{
// Arrange
const string path = @"C:\";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime(path, DefaultTime);
// Assert
action.Should().ThrowExactly<ArgumentException>().WithMessage("Path must not be a drive.*");
}
[Fact]
private void When_getting_last_access_time_in_local_zone_using_absolute_path_without_drive_letter_it_must_succeed()
{
// Arrange
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(@"c:\some")
.IncludingDirectory(@"C:\folder")
.Build();
fileSystem.Directory.SetCurrentDirectory(@"C:\some");
// Act
DateTime time = fileSystem.Directory.GetLastAccessTime(@"\folder");
// Assert
time.Should().Be(DefaultTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_using_absolute_path_without_drive_letter_it_must_succeed()
{
// Arrange
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(@"c:\some")
.IncludingDirectory(@"C:\folder")
.Build();
fileSystem.Directory.SetCurrentDirectory(@"C:\some");
// Act
fileSystem.Directory.SetLastAccessTime(@"\folder", DefaultTime);
// Assert
fileSystem.Directory.GetLastAccessTime(@"c:\folder").Should().Be(DefaultTime);
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_existing_relative_local_directory_it_must_succeed()
{
// Arrange
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(@"C:\folder\some")
.Build();
fileSystem.Directory.SetCurrentDirectory(@"c:\folder");
// Act
DateTime time = fileSystem.Directory.GetLastAccessTime(@"some");
// Assert
time.Should().Be(DefaultTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_existing_relative_local_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\folder\some")
.Build();
fileSystem.Directory.SetCurrentDirectory(@"c:\folder");
// Act
fileSystem.Directory.SetLastAccessTime(@"some", DefaultTime);
// Assert
fileSystem.Directory.GetLastAccessTime(@"C:\folder\some").Should().Be(DefaultTime);
}
[Fact]
private void
When_getting_last_access_time_in_local_zone_for_existing_local_directory_with_different_casing_it_must_succeed()
{
// Arrange
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(@"C:\FOLDER\some")
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTime(@"C:\folder\SOME");
// Assert
time.Should().Be(DefaultTime);
}
[Fact]
private void
When_setting_last_access_time_in_local_zone_for_existing_local_directory_with_different_casing_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\FOLDER\some")
.Build();
// Act
fileSystem.Directory.SetLastAccessTime(@"C:\folder\SOME", DefaultTime);
// Assert
fileSystem.Directory.GetLastAccessTime(@"C:\FOLDER\some").Should().Be(DefaultTime);
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_missing_parent_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTime(@"C:\some\folder");
// Assert
time.Should().Be(ZeroFileTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_missing_parent_directory_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime(@"C:\some\folder", DefaultTime);
// Assert
action.Should().ThrowExactly<DirectoryNotFoundException>().WithMessage(
@"Could not find a part of the path 'C:\some\folder'.");
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_existing_file_it_must_succeed()
{
// Arrange
const string path = @"C:\some\file.txt";
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingEmptyFile(path)
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTime(path);
// Assert
time.Should().Be(DefaultTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_existing_file_it_must_succeed()
{
// Arrange
const string path = @"C:\some\file.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(path)
.Build();
// Act
fileSystem.Directory.SetLastAccessTime(path, DefaultTime);
// Assert
fileSystem.Directory.GetLastAccessTime(path).Should().Be(DefaultTime);
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_parent_directory_that_exists_as_file_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"c:\some\file.txt")
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTime(@"c:\some\file.txt\nested.txt");
// Assert
time.Should().Be(ZeroFileTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_parent_directory_that_exists_as_file_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"c:\some\file.txt")
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime(@"c:\some\file.txt\nested", DefaultTime);
// Assert
action.Should().ThrowExactly<DirectoryNotFoundException>().WithMessage(
@"Could not find a part of the path 'c:\some\file.txt\nested'.");
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_parent_parent_directory_that_exists_as_file_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"c:\some\file.txt")
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTime(@"c:\some\file.txt\nested\more");
// Assert
time.Should().Be(ZeroFileTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_parent_parent_directory_that_exists_as_file_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingEmptyFile(@"c:\some\file.txt")
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime(@"c:\some\file.txt\nested\more", DefaultTime);
// Assert
action.Should().ThrowExactly<DirectoryNotFoundException>().WithMessage(
@"Could not find a part of the path 'c:\some\file.txt\nested\more'.");
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_missing_network_share_it_must_fail()
{
// Arrange
const string path = @"\\server\share\missing";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.GetLastAccessTime(path);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("The network path was not found.");
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_missing_network_share_it_must_fail()
{
// Arrange
const string path = @"\\server\share\missing";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime(path, DefaultTime);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("The network path was not found.");
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_existing_network_share_it_must_succeed()
{
// Arrange
const string path = @"\\server\share";
var clock = new SystemClock(() => DefaultTimeUtc);
IFileSystem fileSystem = new FakeFileSystemBuilder(clock)
.IncludingDirectory(path)
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTime(path);
// Assert
time.Should().Be(DefaultTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_existing_network_share_it_must_succeed()
{
// Arrange
const string path = @"\\server\share";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
fileSystem.Directory.SetLastAccessTime(path, DefaultTime);
// Assert
fileSystem.Directory.GetLastAccessTime(path).Should().Be(DefaultTime);
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_missing_remote_directory_it_must_succeed()
{
// Arrange
const string path = @"\\server\share\missing";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"\\server\share")
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTime(path);
// Assert
time.Should().Be(ZeroFileTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_missing_remote_directory_it_must_fail()
{
// Arrange
const string path = @"\\server\share\missing";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"\\server\share")
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime(path, DefaultTime);
// Assert
action.Should().ThrowExactly<FileNotFoundException>().WithMessage(@"Could not find file '\\server\share\missing'.");
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_existing_remote_directory_it_must_succeed()
{
// Arrange
const string path = @"\\server\share\personal";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(path)
.Build();
// Act
fileSystem.Directory.SetLastAccessTime(path, DefaultTime);
// Assert
fileSystem.Directory.GetLastAccessTime(path).Should().Be(DefaultTime);
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_reserved_name_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.GetLastAccessTime("COM1");
// Assert
action.Should().ThrowExactly<PlatformNotSupportedException>().WithMessage("Reserved names are not supported.");
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_reserved_name_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime("COM1", DefaultTime);
// Assert
action.Should().ThrowExactly<PlatformNotSupportedException>().WithMessage("Reserved names are not supported.");
}
[Fact]
private void When_getting_last_access_time_in_local_zone_for_missing_extended_local_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"c:\some")
.Build();
// Act
DateTime time = fileSystem.Directory.GetLastAccessTime(@"\\?\C:\some\missing");
// Assert
time.Should().Be(ZeroFileTime);
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_missing_extended_local_directory_it_must_fail()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"c:\some")
.Build();
// Act
Action action = () => fileSystem.Directory.SetLastAccessTime(@"\\?\C:\some\missing", DefaultTime);
// Assert
action.Should().ThrowExactly<FileNotFoundException>().WithMessage(@"Could not find file '\\?\C:\some\missing'.");
}
[Fact]
private void When_setting_last_access_time_in_local_zone_for_existing_extended_local_directory_it_must_succeed()
{
// Arrange
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingDirectory(@"C:\some\other")
.Build();
// Act
fileSystem.Directory.SetLastAccessTime(@"\\?\C:\some\other", DefaultTime);
// Assert
fileSystem.Directory.GetLastAccessTime(@"\\?\C:\some\other").Should().Be(DefaultTime);
}
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.IO;
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.VisualStudio.Services.Agent.Worker.Maintenance;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Diagnostics;
using Microsoft.TeamFoundation.DistributedTask.Pipelines;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Build
{
public static class RepositoryResourceExtensions
{
public static string GetSourceDirectoryHashKey(this RepositoryResource repository, IExecutionContext executionContext)
{
// Validate parameters.
ArgUtil.NotNull(executionContext, nameof(executionContext));
ArgUtil.NotNull(executionContext.Variables, nameof(executionContext.Variables));
ArgUtil.NotNull(repository.Url, nameof(repository.Url));
// Calculate the hash key.
const string Format = "{{{{ \r\n \"system\" : \"build\", \r\n \"collectionId\" = \"{0}\", \r\n \"definitionId\" = \"{1}\", \r\n \"repositoryUrl\" = \"{2}\", \r\n \"sourceFolder\" = \"{{0}}\",\r\n \"hashKey\" = \"{{1}}\"\r\n}}}}";
string hashInput = string.Format(
CultureInfo.InvariantCulture,
Format,
executionContext.Variables.System_CollectionId,
executionContext.Variables.System_DefinitionId,
repository.Url.AbsoluteUri);
using (SHA1 sha1Hash = SHA1.Create())
{
byte[] data = sha1Hash.ComputeHash(Encoding.UTF8.GetBytes(hashInput));
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
hexString.Append(data[i].ToString("x2"));
}
return hexString.ToString();
}
}
public static Boolean TestOverrideBuildDirectory(this RepositoryResource repository, AgentSettings settings)
{
if (repository.Type == TeamFoundation.DistributedTask.Pipelines.RepositoryTypes.Tfvc)
{
return settings.IsHosted;
}
else
{
return false;
}
}
}
[ServiceLocator(Default = typeof(BuildDirectoryManager))]
public interface IBuildDirectoryManager : IAgentService
{
TrackingConfig PrepareDirectory(
IExecutionContext executionContext,
RepositoryResource repository,
WorkspaceOptions workspace);
void CreateDirectory(
IExecutionContext executionContext,
string description, string path,
bool deleteExisting);
}
public sealed class BuildDirectoryManager : AgentService, IBuildDirectoryManager, IMaintenanceServiceProvider
{
public string MaintenanceDescription => StringUtil.Loc("DeleteUnusedBuildDir");
public Type ExtensionType => typeof(IMaintenanceServiceProvider);
public TrackingConfig PrepareDirectory(
IExecutionContext executionContext,
RepositoryResource repository,
WorkspaceOptions workspace)
{
// Validate parameters.
Trace.Entering();
ArgUtil.NotNull(executionContext, nameof(executionContext));
ArgUtil.NotNull(executionContext.Variables, nameof(executionContext.Variables));
ArgUtil.NotNull(repository, nameof(repository));
var trackingManager = HostContext.GetService<ITrackingManager>();
// Defer to the source provider to calculate the hash key.
Trace.Verbose("Calculating build directory hash key.");
string hashKey = repository.GetSourceDirectoryHashKey(executionContext);
Trace.Verbose($"Hash key: {hashKey}");
// Load the existing tracking file if one already exists.
string trackingFile = Path.Combine(
HostContext.GetDirectory(WellKnownDirectory.Work),
Constants.Build.Path.SourceRootMappingDirectory,
executionContext.Variables.System_CollectionId,
executionContext.Variables.System_DefinitionId,
Constants.Build.Path.TrackingConfigFile);
Trace.Verbose($"Loading tracking config if exists: {trackingFile}");
TrackingConfigBase existingConfig = trackingManager.LoadIfExists(executionContext, trackingFile);
// Check if the build needs to be garbage collected. If the hash key
// has changed, then the existing build directory cannot be reused.
TrackingConfigBase garbageConfig = null;
if (existingConfig != null
&& !string.Equals(existingConfig.HashKey, hashKey, StringComparison.OrdinalIgnoreCase))
{
// Just store a reference to the config for now. It can safely be
// marked for garbage collection only after the new build directory
// config has been created.
Trace.Verbose($"Hash key from existing tracking config does not match. Existing key: {existingConfig.HashKey}");
garbageConfig = existingConfig;
existingConfig = null;
}
// Create a new tracking config if required.
TrackingConfig newConfig;
if (existingConfig == null)
{
Trace.Verbose("Creating a new tracking config file.");
var agentSetting = HostContext.GetService<IConfigurationStore>().GetSettings();
newConfig = trackingManager.Create(
executionContext,
repository,
hashKey,
trackingFile,
repository.TestOverrideBuildDirectory(agentSetting));
ArgUtil.NotNull(newConfig, nameof(newConfig));
}
else
{
// Convert legacy format to the new format if required.
newConfig = ConvertToNewFormat(executionContext, repository, existingConfig);
// Fill out repository type if it's not there.
// repository type is a new property introduced for maintenance job
if (string.IsNullOrEmpty(newConfig.RepositoryType))
{
newConfig.RepositoryType = repository.Type;
}
// For existing tracking config files, update the job run properties.
Trace.Verbose("Updating job run properties.");
trackingManager.UpdateJobRunProperties(executionContext, newConfig, trackingFile);
}
// Mark the old configuration for garbage collection.
if (garbageConfig != null)
{
Trace.Verbose("Marking existing config for garbage collection.");
trackingManager.MarkForGarbageCollection(executionContext, garbageConfig);
}
// Prepare the build directory.
// There are 2 ways to provide build directory clean policy.
// 1> set definition variable build.clean or agent.clean.buildDirectory. (on-prem user need to use this, since there is no Web UI in TFS 2016)
// 2> select source clean option in definition repository tab. (VSTS will have this option in definition designer UI)
BuildCleanOption cleanOption = GetBuildDirectoryCleanOption(executionContext, workspace);
CreateDirectory(
executionContext,
description: "build directory",
path: Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), newConfig.BuildDirectory),
deleteExisting: cleanOption == BuildCleanOption.All);
CreateDirectory(
executionContext,
description: "artifacts directory",
path: Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), newConfig.ArtifactsDirectory),
deleteExisting: true);
CreateDirectory(
executionContext,
description: "test results directory",
path: Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), newConfig.TestResultsDirectory),
deleteExisting: true);
CreateDirectory(
executionContext,
description: "binaries directory",
path: Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), newConfig.BuildDirectory, Constants.Build.Path.BinariesDirectory),
deleteExisting: cleanOption == BuildCleanOption.Binary);
CreateDirectory(
executionContext,
description: "source directory",
path: Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), newConfig.BuildDirectory, Constants.Build.Path.SourcesDirectory),
deleteExisting: cleanOption == BuildCleanOption.Source);
return newConfig;
}
public async Task RunMaintenanceOperation(IExecutionContext executionContext)
{
Trace.Entering();
ArgUtil.NotNull(executionContext, nameof(executionContext));
// this might be not accurate when the agent is configured for old TFS server
int totalAvailableTimeInMinutes = executionContext.Variables.GetInt("maintenance.jobtimeoutinminutes") ?? 60;
// start a timer to track how much time we used
Stopwatch totalTimeSpent = Stopwatch.StartNew();
var trackingManager = HostContext.GetService<ITrackingManager>();
int staleBuildDirThreshold = executionContext.Variables.GetInt("maintenance.deleteworkingdirectory.daysthreshold") ?? 0;
if (staleBuildDirThreshold > 0)
{
// scan unused build directories
executionContext.Output(StringUtil.Loc("DiscoverBuildDir", staleBuildDirThreshold));
trackingManager.MarkExpiredForGarbageCollection(executionContext, TimeSpan.FromDays(staleBuildDirThreshold));
}
else
{
executionContext.Output(StringUtil.Loc("GCBuildDirNotEnabled"));
return;
}
executionContext.Output(StringUtil.Loc("GCBuildDir"));
// delete unused build directories
trackingManager.DisposeCollectedGarbage(executionContext);
// give source provider a chance to run maintenance operation
Trace.Info("Scan all SourceFolder tracking files.");
string searchRoot = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), Constants.Build.Path.SourceRootMappingDirectory);
if (!Directory.Exists(searchRoot))
{
executionContext.Output(StringUtil.Loc("GCDirNotExist", searchRoot));
return;
}
// <tracking config, tracking file path>
List<Tuple<TrackingConfig, string>> optimizeTrackingFiles = new List<Tuple<TrackingConfig, string>>();
var allTrackingFiles = Directory.EnumerateFiles(searchRoot, Constants.Build.Path.TrackingConfigFile, SearchOption.AllDirectories);
Trace.Verbose($"Find {allTrackingFiles.Count()} tracking files.");
foreach (var trackingFile in allTrackingFiles)
{
executionContext.Output(StringUtil.Loc("EvaluateTrackingFile", trackingFile));
TrackingConfigBase tracking = trackingManager.LoadIfExists(executionContext, trackingFile);
// detect whether the tracking file is in new format.
TrackingConfig newTracking = tracking as TrackingConfig;
if (newTracking == null)
{
executionContext.Output(StringUtil.Loc("GCOldFormatTrackingFile", trackingFile));
}
else if (string.IsNullOrEmpty(newTracking.RepositoryType))
{
// repository not been set.
executionContext.Output(StringUtil.Loc("SkipTrackingFileWithoutRepoType", trackingFile));
}
else
{
optimizeTrackingFiles.Add(new Tuple<TrackingConfig, string>(newTracking, trackingFile));
}
}
// Sort the all tracking file ASC by last maintenance attempted time
foreach (var trackingInfo in optimizeTrackingFiles.OrderBy(x => x.Item1.LastMaintenanceAttemptedOn))
{
// maintenance has been cancelled.
executionContext.CancellationToken.ThrowIfCancellationRequested();
bool runMainenance = false;
TrackingConfig trackingConfig = trackingInfo.Item1;
string trackingFile = trackingInfo.Item2;
if (trackingConfig.LastMaintenanceAttemptedOn == null)
{
// this folder never run maintenance before, we will do maintenance if there is more than half of the time remains.
if (totalTimeSpent.Elapsed.TotalMinutes < totalAvailableTimeInMinutes / 2) // 50% time left
{
runMainenance = true;
}
else
{
executionContext.Output($"Working directory '{trackingConfig.BuildDirectory}' has never run maintenance before. Skip since we may not have enough time.");
}
}
else if (trackingConfig.LastMaintenanceCompletedOn == null)
{
// this folder did finish maintenance last time, this might indicate we need more time for this working directory
if (totalTimeSpent.Elapsed.TotalMinutes < totalAvailableTimeInMinutes / 4) // 75% time left
{
runMainenance = true;
}
else
{
executionContext.Output($"Working directory '{trackingConfig.BuildDirectory}' didn't finish maintenance last time. Skip since we may not have enough time.");
}
}
else
{
// estimate time for running maintenance
TimeSpan estimateTime = trackingConfig.LastMaintenanceCompletedOn.Value - trackingConfig.LastMaintenanceAttemptedOn.Value;
// there is more than 10 mins left after we run maintenance on this repository directory
if (totalAvailableTimeInMinutes > totalTimeSpent.Elapsed.TotalMinutes + estimateTime.TotalMinutes + 10)
{
runMainenance = true;
}
else
{
executionContext.Output($"Working directory '{trackingConfig.BuildDirectory}' may take about '{estimateTime.TotalMinutes}' mins to finish maintenance. It's too risky since we only have '{totalAvailableTimeInMinutes - totalTimeSpent.Elapsed.TotalMinutes}' mins left for maintenance.");
}
}
if (runMainenance)
{
var extensionManager = HostContext.GetService<IExtensionManager>();
ISourceProvider sourceProvider = extensionManager.GetExtensions<ISourceProvider>().FirstOrDefault(x => string.Equals(x.RepositoryType, trackingConfig.RepositoryType, StringComparison.OrdinalIgnoreCase));
if (sourceProvider != null)
{
try
{
trackingManager.MaintenanceStarted(trackingConfig, trackingFile);
string repositoryPath = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), trackingConfig.SourcesDirectory);
await sourceProvider.RunMaintenanceOperations(executionContext, repositoryPath);
trackingManager.MaintenanceCompleted(trackingConfig, trackingFile);
}
catch (Exception ex)
{
executionContext.Error(StringUtil.Loc("ErrorDuringBuildGC", trackingFile));
executionContext.Error(ex);
}
}
}
}
}
private TrackingConfig ConvertToNewFormat(
IExecutionContext executionContext,
RepositoryResource repository,
TrackingConfigBase config)
{
Trace.Entering();
// If it's already in the new format, return it.
TrackingConfig newConfig = config as TrackingConfig;
if (newConfig != null)
{
return newConfig;
}
// Delete the legacy artifact/staging directories.
LegacyTrackingConfig legacyConfig = config as LegacyTrackingConfig;
DeleteDirectory(
executionContext,
description: "legacy artifacts directory",
path: Path.Combine(legacyConfig.BuildDirectory, Constants.Build.Path.LegacyArtifactsDirectory));
DeleteDirectory(
executionContext,
description: "legacy staging directory",
path: Path.Combine(legacyConfig.BuildDirectory, Constants.Build.Path.LegacyStagingDirectory));
// Determine the source directory name. Check if the directory is named "s" already.
// Convert the source directory to be named "s" if there is a problem with the old name.
string sourcesDirectoryNameOnly = Constants.Build.Path.SourcesDirectory;
string repositoryName = repository.Properties.Get<string>(RepositoryPropertyNames.Name);
if (!Directory.Exists(Path.Combine(legacyConfig.BuildDirectory, sourcesDirectoryNameOnly))
&& !String.Equals(repositoryName, Constants.Build.Path.ArtifactsDirectory, StringComparison.OrdinalIgnoreCase)
&& !String.Equals(repositoryName, Constants.Build.Path.LegacyArtifactsDirectory, StringComparison.OrdinalIgnoreCase)
&& !String.Equals(repositoryName, Constants.Build.Path.LegacyStagingDirectory, StringComparison.OrdinalIgnoreCase)
&& !String.Equals(repositoryName, Constants.Build.Path.TestResultsDirectory, StringComparison.OrdinalIgnoreCase)
&& !repositoryName.Contains("\\")
&& !repositoryName.Contains("/")
&& Directory.Exists(Path.Combine(legacyConfig.BuildDirectory, repositoryName)))
{
sourcesDirectoryNameOnly = repositoryName;
}
// Convert to the new format.
newConfig = new TrackingConfig(
executionContext,
legacyConfig,
sourcesDirectoryNameOnly,
repository.Type,
// The legacy artifacts directory has been deleted at this point - see above - so
// switch the configuration to using the new naming scheme.
useNewArtifactsDirectoryName: true);
return newConfig;
}
public void CreateDirectory(IExecutionContext executionContext, string description, string path, bool deleteExisting)
{
// Delete.
if (deleteExisting)
{
executionContext.Debug($"Delete existing {description}: '{path}'");
DeleteDirectory(executionContext, description, path);
}
// Create.
if (!Directory.Exists(path))
{
executionContext.Debug($"Creating {description}: '{path}'");
Trace.Info($"Creating {description}.");
Directory.CreateDirectory(path);
}
}
private void DeleteDirectory(IExecutionContext executionContext, string description, string path)
{
Trace.Info($"Checking if {description} exists: '{path}'");
if (Directory.Exists(path))
{
executionContext.Debug($"Deleting {description}: '{path}'");
IOUtil.DeleteDirectory(path, executionContext.CancellationToken);
}
}
// Prefer variable over endpoint data when get build directory clean option.
// Prefer agent.clean.builddirectory over build.clean when use variable
// available value for build.clean or agent.clean.builddirectory:
// Delete entire build directory if build.clean=all is set.
// Recreate binaries dir if clean=binary is set.
// Recreate source dir if clean=src is set.
private BuildCleanOption GetBuildDirectoryCleanOption(IExecutionContext executionContext, WorkspaceOptions workspace)
{
BuildCleanOption? cleanOption = executionContext.Variables.Build_Clean;
if (cleanOption != null)
{
return cleanOption.Value;
}
if (workspace == null)
{
return BuildCleanOption.None;
}
else
{
Dictionary<string, string> workspaceClean = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
workspaceClean["clean"] = workspace.Clean;
executionContext.Variables.ExpandValues(target: workspaceClean);
VarUtil.ExpandEnvironmentVariables(HostContext, target: workspaceClean);
string expandedClean = workspaceClean["clean"];
if (string.Equals(expandedClean, PipelineConstants.WorkspaceCleanOptions.All, StringComparison.OrdinalIgnoreCase))
{
return BuildCleanOption.All;
}
else if (string.Equals(expandedClean, PipelineConstants.WorkspaceCleanOptions.Resources, StringComparison.OrdinalIgnoreCase))
{
return BuildCleanOption.Source;
}
else if (string.Equals(expandedClean, PipelineConstants.WorkspaceCleanOptions.Outputs, StringComparison.OrdinalIgnoreCase))
{
return BuildCleanOption.Binary;
}
else
{
return BuildCleanOption.None;
}
}
}
}
// TODO: use enum defined in build2.webapi when it's available.
public enum RepositoryCleanOptions
{
Source,
SourceAndOutput,
SourceDir,
AllBuildDir,
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AndNotUInt16()
{
var test = new SimpleBinaryOpTest__AndNotUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndNotUInt16
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[ElementCount];
private static UInt16[] _data2 = new UInt16[ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private SimpleBinaryOpTest__DataTable<UInt16> _dataTable;
static SimpleBinaryOpTest__AndNotUInt16()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AndNotUInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt16>(_data1, _data2, new UInt16[ElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.AndNot(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.AndNot(
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.AndNot(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndNotUInt16();
var result = Avx2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.AndNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<UInt16> left, Vector256<UInt16> right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[ElementCount];
UInt16[] inArray2 = new UInt16[ElementCount];
UInt16[] outArray = new UInt16[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[ElementCount];
UInt16[] inArray2 = new UInt16[ElementCount];
UInt16[] outArray = new UInt16[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
if ((ushort)(~left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((ushort)(~left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.AndNot)}<UInt16>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.BackupServices;
using Microsoft.Azure.Management.BackupServices.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.BackupServices
{
/// <summary>
/// Definition of Job operations for Azure backup extension.
/// </summary>
internal partial class JobOperations : IServiceOperations<BackupServicesManagementClient>, IJobOperations
{
/// <summary>
/// Initializes a new instance of the JobOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal JobOperations(BackupServicesManagementClient client)
{
this._client = client;
}
private BackupServicesManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.BackupServices.BackupServicesManagementClient.
/// </summary>
public BackupServicesManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Get details of a particular job.
/// </summary>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='name'>
/// Optional. Name of the job whose details should be retrieved.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response model for job details operation
/// </returns>
public async Task<CSMJobDetails> GetAsync(string resourceGroupName, string resourceName, string name, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("name", name);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/jobs/";
if (name != null)
{
url = url + Uri.EscapeDataString(name);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-09-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CSMJobDetails result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CSMJobDetails();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
CSMJobDetailsResponse valueInstance = new CSMJobDetailsResponse();
result.Value = valueInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
CSMJobDetailedProperties propertiesInstance = new CSMJobDetailedProperties();
valueInstance.JobDetailedProperties = propertiesInstance;
JToken tasksListArray = propertiesValue["tasksList"];
if (tasksListArray != null && tasksListArray.Type != JTokenType.Null)
{
foreach (JToken tasksListValue in ((JArray)tasksListArray))
{
CSMJobTaskDetails cSMJobTaskDetailsInstance = new CSMJobTaskDetails();
propertiesInstance.TasksList.Add(cSMJobTaskDetailsInstance);
JToken taskIdValue = tasksListValue["taskId"];
if (taskIdValue != null && taskIdValue.Type != JTokenType.Null)
{
string taskIdInstance = ((string)taskIdValue);
cSMJobTaskDetailsInstance.TaskId = taskIdInstance;
}
JToken startTimeValue = tasksListValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTime startTimeInstance = ((DateTime)startTimeValue);
cSMJobTaskDetailsInstance.StartTime = startTimeInstance;
}
JToken endTimeValue = tasksListValue["endTime"];
if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
{
DateTime endTimeInstance = ((DateTime)endTimeValue);
cSMJobTaskDetailsInstance.EndTime = endTimeInstance;
}
JToken durationValue = tasksListValue["duration"];
if (durationValue != null && durationValue.Type != JTokenType.Null)
{
TimeSpan durationInstance = TimeSpan.Parse(((string)durationValue), CultureInfo.InvariantCulture);
cSMJobTaskDetailsInstance.Duration = durationInstance;
}
JToken statusValue = tasksListValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
cSMJobTaskDetailsInstance.Status = statusInstance;
}
JToken progressPercentageValue = tasksListValue["progressPercentage"];
if (progressPercentageValue != null && progressPercentageValue.Type != JTokenType.Null)
{
double progressPercentageInstance = ((double)progressPercentageValue);
cSMJobTaskDetailsInstance.ProgressPercentage = progressPercentageInstance;
}
}
}
JToken propertyBagSequenceElement = ((JToken)propertiesValue["propertyBag"]);
if (propertyBagSequenceElement != null && propertyBagSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in propertyBagSequenceElement)
{
string propertyBagKey = ((string)property.Name);
string propertyBagValue = ((string)property.Value);
propertiesInstance.PropertyBag.Add(propertyBagKey, propertyBagValue);
}
}
JToken progressPercentageValue2 = propertiesValue["progressPercentage"];
if (progressPercentageValue2 != null && progressPercentageValue2.Type != JTokenType.Null)
{
double progressPercentageInstance2 = ((double)progressPercentageValue2);
propertiesInstance.ProgressPercentage = progressPercentageInstance2;
}
JToken dynamicErrorMessageValue = propertiesValue["dynamicErrorMessage"];
if (dynamicErrorMessageValue != null && dynamicErrorMessageValue.Type != JTokenType.Null)
{
string dynamicErrorMessageInstance = ((string)dynamicErrorMessageValue);
propertiesInstance.DynamicErrorMessage = dynamicErrorMessageInstance;
}
JToken workloadTypeValue = propertiesValue["workloadType"];
if (workloadTypeValue != null && workloadTypeValue.Type != JTokenType.Null)
{
string workloadTypeInstance = ((string)workloadTypeValue);
propertiesInstance.WorkloadType = workloadTypeInstance;
}
JToken operationValue = propertiesValue["operation"];
if (operationValue != null && operationValue.Type != JTokenType.Null)
{
string operationInstance = ((string)operationValue);
propertiesInstance.Operation = operationInstance;
}
JToken statusValue2 = propertiesValue["status"];
if (statusValue2 != null && statusValue2.Type != JTokenType.Null)
{
string statusInstance2 = ((string)statusValue2);
propertiesInstance.Status = statusInstance2;
}
JToken startTimestampValue = propertiesValue["startTimestamp"];
if (startTimestampValue != null && startTimestampValue.Type != JTokenType.Null)
{
DateTime startTimestampInstance = ((DateTime)startTimestampValue);
propertiesInstance.StartTimestamp = startTimestampInstance;
}
JToken endTimestampValue = propertiesValue["endTimestamp"];
if (endTimestampValue != null && endTimestampValue.Type != JTokenType.Null)
{
DateTime endTimestampInstance = ((DateTime)endTimestampValue);
propertiesInstance.EndTimestamp = endTimestampInstance;
}
JToken durationValue2 = propertiesValue["duration"];
if (durationValue2 != null && durationValue2.Type != JTokenType.Null)
{
TimeSpan durationInstance2 = TimeSpan.Parse(((string)durationValue2), CultureInfo.InvariantCulture);
propertiesInstance.Duration = durationInstance2;
}
JToken entityFriendlyNameValue = propertiesValue["entityFriendlyName"];
if (entityFriendlyNameValue != null && entityFriendlyNameValue.Type != JTokenType.Null)
{
string entityFriendlyNameInstance = ((string)entityFriendlyNameValue);
propertiesInstance.EntityFriendlyName = entityFriendlyNameInstance;
}
JToken actionsInfoArray = propertiesValue["actionsInfo"];
if (actionsInfoArray != null && actionsInfoArray.Type != JTokenType.Null)
{
foreach (JToken actionsInfoValue in ((JArray)actionsInfoArray))
{
propertiesInstance.ActionsInfo.Add(((JobSupportedAction)Enum.Parse(typeof(JobSupportedAction), ((string)actionsInfoValue), true)));
}
}
JToken errorDetailsArray = propertiesValue["errorDetails"];
if (errorDetailsArray != null && errorDetailsArray.Type != JTokenType.Null)
{
foreach (JToken errorDetailsValue in ((JArray)errorDetailsArray))
{
CSMJobErrorInfo cSMJobErrorInfoInstance = new CSMJobErrorInfo();
propertiesInstance.ErrorDetails.Add(cSMJobErrorInfoInstance);
JToken errorCodeValue = errorDetailsValue["errorCode"];
if (errorCodeValue != null && errorCodeValue.Type != JTokenType.Null)
{
int errorCodeInstance = ((int)errorCodeValue);
cSMJobErrorInfoInstance.ErrorCode = errorCodeInstance;
}
JToken errorTitleValue = errorDetailsValue["errorTitle"];
if (errorTitleValue != null && errorTitleValue.Type != JTokenType.Null)
{
string errorTitleInstance = ((string)errorTitleValue);
cSMJobErrorInfoInstance.ErrorTitle = errorTitleInstance;
}
JToken errorStringValue = errorDetailsValue["errorString"];
if (errorStringValue != null && errorStringValue.Type != JTokenType.Null)
{
string errorStringInstance = ((string)errorStringValue);
cSMJobErrorInfoInstance.ErrorString = errorStringInstance;
}
JToken recommendationsArray = errorDetailsValue["recommendations"];
if (recommendationsArray != null && recommendationsArray.Type != JTokenType.Null)
{
foreach (JToken recommendationsValue in ((JArray)recommendationsArray))
{
cSMJobErrorInfoInstance.Recommendations.Add(((string)recommendationsValue));
}
}
}
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
valueInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
valueInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
valueInstance.Type = typeInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of all jobs queried by specified filters.
/// </summary>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='parameters'>
/// Optional. Job query parameter.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Powershell response object
/// </returns>
public async Task<CSMJobList> ListAsync(string resourceGroupName, string resourceName, CSMJobQueryObject parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId.ToString());
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/jobs";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-09-01");
List<string> odataFilter = new List<string>();
if (parameters != null && parameters.Status != null)
{
odataFilter.Add("status eq '" + Uri.EscapeDataString(parameters.Status) + "'");
}
if (parameters != null && parameters.WorkloadType != null)
{
odataFilter.Add("workloadType eq '" + Uri.EscapeDataString(parameters.WorkloadType) + "'");
}
if (parameters != null && parameters.Operation != null)
{
odataFilter.Add("operation eq '" + Uri.EscapeDataString(parameters.Operation) + "'");
}
if (parameters != null && parameters.Name != null)
{
odataFilter.Add("name eq '" + Uri.EscapeDataString(parameters.Name) + "'");
}
if (parameters != null && parameters.StartTime != null)
{
odataFilter.Add("startTime eq '" + Uri.EscapeDataString(parameters.StartTime) + "'");
}
if (parameters != null && parameters.EndTime != null)
{
odataFilter.Add("endTime eq '" + Uri.EscapeDataString(parameters.EndTime) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(" and ", odataFilter));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CSMJobList result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CSMJobList();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
CSMJobListResponse listInstance = new CSMJobListResponse();
result.List = listInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
CSMJobResponse cSMJobResponseInstance = new CSMJobResponse();
listInstance.Value.Add(cSMJobResponseInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
CSMJobProperties propertiesInstance = new CSMJobProperties();
cSMJobResponseInstance.Properties = propertiesInstance;
JToken workloadTypeValue = propertiesValue["workloadType"];
if (workloadTypeValue != null && workloadTypeValue.Type != JTokenType.Null)
{
string workloadTypeInstance = ((string)workloadTypeValue);
propertiesInstance.WorkloadType = workloadTypeInstance;
}
JToken operationValue = propertiesValue["operation"];
if (operationValue != null && operationValue.Type != JTokenType.Null)
{
string operationInstance = ((string)operationValue);
propertiesInstance.Operation = operationInstance;
}
JToken statusValue = propertiesValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
propertiesInstance.Status = statusInstance;
}
JToken startTimestampValue = propertiesValue["startTimestamp"];
if (startTimestampValue != null && startTimestampValue.Type != JTokenType.Null)
{
DateTime startTimestampInstance = ((DateTime)startTimestampValue);
propertiesInstance.StartTimestamp = startTimestampInstance;
}
JToken endTimestampValue = propertiesValue["endTimestamp"];
if (endTimestampValue != null && endTimestampValue.Type != JTokenType.Null)
{
DateTime endTimestampInstance = ((DateTime)endTimestampValue);
propertiesInstance.EndTimestamp = endTimestampInstance;
}
JToken durationValue = propertiesValue["duration"];
if (durationValue != null && durationValue.Type != JTokenType.Null)
{
TimeSpan durationInstance = TimeSpan.Parse(((string)durationValue), CultureInfo.InvariantCulture);
propertiesInstance.Duration = durationInstance;
}
JToken entityFriendlyNameValue = propertiesValue["entityFriendlyName"];
if (entityFriendlyNameValue != null && entityFriendlyNameValue.Type != JTokenType.Null)
{
string entityFriendlyNameInstance = ((string)entityFriendlyNameValue);
propertiesInstance.EntityFriendlyName = entityFriendlyNameInstance;
}
JToken actionsInfoArray = propertiesValue["actionsInfo"];
if (actionsInfoArray != null && actionsInfoArray.Type != JTokenType.Null)
{
foreach (JToken actionsInfoValue in ((JArray)actionsInfoArray))
{
propertiesInstance.ActionsInfo.Add(((JobSupportedAction)Enum.Parse(typeof(JobSupportedAction), ((string)actionsInfoValue), true)));
}
}
JToken errorDetailsArray = propertiesValue["errorDetails"];
if (errorDetailsArray != null && errorDetailsArray.Type != JTokenType.Null)
{
foreach (JToken errorDetailsValue in ((JArray)errorDetailsArray))
{
CSMJobErrorInfo cSMJobErrorInfoInstance = new CSMJobErrorInfo();
propertiesInstance.ErrorDetails.Add(cSMJobErrorInfoInstance);
JToken errorCodeValue = errorDetailsValue["errorCode"];
if (errorCodeValue != null && errorCodeValue.Type != JTokenType.Null)
{
int errorCodeInstance = ((int)errorCodeValue);
cSMJobErrorInfoInstance.ErrorCode = errorCodeInstance;
}
JToken errorTitleValue = errorDetailsValue["errorTitle"];
if (errorTitleValue != null && errorTitleValue.Type != JTokenType.Null)
{
string errorTitleInstance = ((string)errorTitleValue);
cSMJobErrorInfoInstance.ErrorTitle = errorTitleInstance;
}
JToken errorStringValue = errorDetailsValue["errorString"];
if (errorStringValue != null && errorStringValue.Type != JTokenType.Null)
{
string errorStringInstance = ((string)errorStringValue);
cSMJobErrorInfoInstance.ErrorString = errorStringInstance;
}
JToken recommendationsArray = errorDetailsValue["recommendations"];
if (recommendationsArray != null && recommendationsArray.Type != JTokenType.Null)
{
foreach (JToken recommendationsValue in ((JArray)recommendationsArray))
{
cSMJobErrorInfoInstance.Recommendations.Add(((string)recommendationsValue));
}
}
}
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
cSMJobResponseInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
cSMJobResponseInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
cSMJobResponseInstance.Type = typeInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
listInstance.NextLink = nextLinkInstance;
}
JToken idValue2 = responseDoc["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
listInstance.Id = idInstance2;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
listInstance.Name = nameInstance2;
}
JToken typeValue2 = responseDoc["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
listInstance.Type = typeInstance2;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Trigger cancellation of a job.
/// </summary>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='name'>
/// Optional. Name of the job which should be stopped.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Custom request headers to make the call.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The definition of a Operation Response.
/// </returns>
public async Task<OperationResponse> StopAsync(string resourceGroupName, string resourceName, string name, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("name", name);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "StopAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/jobs/";
if (name != null)
{
url = url + Uri.EscapeDataString(name);
}
url = url + "/cancel";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-09-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Guid operationIdInstance = Guid.Parse(((string)responseDoc));
result.OperationId = operationIdInstance;
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.SS.Formula.Functions;
namespace NPOI.SS.Formula.Functions
{
using System;
using NPOI.SS.Formula.Eval;
internal class AVEDEV : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return StatsLib.avedev(values);
}
}
internal class AVERAGE : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return MathX.average(values);
}
}
internal class DEVSQ : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return StatsLib.devsq(values);
}
}
internal class SUM : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return MathX.sum(values);
}
}
internal class LARGE : AggregateFunction
{
protected internal override double Evaluate(double[] ops)
{
if (ops.Length < 2)
{
throw new EvaluationException(ErrorEval.NUM_ERROR);
}
double[] values = new double[ops.Length - 1];
int k = (int)ops[ops.Length - 1];
System.Array.Copy(ops, 0, values, 0, values.Length);
return StatsLib.kthLargest(values, k);
}
}
internal class MAX : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return values.Length > 0 ? MathX.max(values) : 0;
}
}
internal class MIN : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return values.Length > 0 ? MathX.min(values) : 0;
}
}
internal class MEDIAN : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return StatsLib.median(values);
}
}
internal class PRODUCT : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return MathX.product(values);
}
}
internal class SMALL : AggregateFunction
{
protected internal override double Evaluate(double[] ops)
{
if (ops.Length < 2)
{
throw new EvaluationException(ErrorEval.NUM_ERROR);
}
double[] values = new double[ops.Length - 1];
int k = (int)ops[ops.Length - 1];
System.Array.Copy(ops, 0, values, 0, values.Length);
return StatsLib.kthSmallest(values, k);
}
}
internal class STDEV : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return StatsLib.stdev(values);
}
}
internal class SUMSQ : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
return MathX.sumsq(values);
}
}
internal class VAR : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return StatsLib.var(values);
}
};
internal class VARP : AggregateFunction
{
protected internal override double Evaluate(double[] values)
{
if (values.Length < 1)
{
throw new EvaluationException(ErrorEval.DIV_ZERO);
}
return StatsLib.varp(values);
}
};
internal class SubtotalInstance : AggregateFunction
{
private AggregateFunction _func;
public SubtotalInstance(AggregateFunction func)
{
_func = func;
}
protected internal override double Evaluate(double[] values)
{
return _func.Evaluate(values);
}
/**
* ignore nested subtotals.
*/
public override bool IsSubtotalCounted
{
get
{
return false;
}
}
}
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*
*/
internal abstract class AggregateFunction : MultiOperandNumericFunction
{
public static Function SubtotalInstance(Function func)
{
AggregateFunction arg = (AggregateFunction)func;
return new SubtotalInstance(arg);
}
internal class ValueCollector : MultiOperandNumericFunction
{
private static ValueCollector instance = new ValueCollector();
public ValueCollector() :
base(false, false)
{
}
public static double[] CollectValues(params ValueEval[] operands)
{
return instance.GetNumberArray(operands);
}
protected internal override double Evaluate(double[] values)
{
throw new InvalidOperationException("should not be called");
}
}
protected AggregateFunction()
: base(false, false)
{
}
public static Function AVEDEV = new AVEDEV();
public static Function AVERAGE = new AVERAGE();
public static Function DEVSQ = new DEVSQ();
public static Function LARGE = new LARGE();
public static Function MAX = new MAX();
public static Function MEDIAN = new MEDIAN();
public static Function MIN = new MIN();
public static Function PRODUCT = new PRODUCT();
public static Function SMALL = new SMALL();
public static Function STDEV = new STDEV();
public static Function SUM = new SUM();
public static Function SUMSQ = new SUMSQ();
public static Function VAR = new VAR();
public static Function VARP = new VARP();
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class ElementFindingTest : DriverTestFixture
{
[Test]
public void ShouldReturnTitleOfPageIfSet()
{
driver.Url = xhtmlTestPage;
Assert.AreEqual(driver.Title, "XHTML Test Page");
driver.Url = simpleTestPage;
Assert.AreEqual(driver.Title, "Hello WebDriver");
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToLocateASingleElementThatDoesNotExist()
{
driver.Url = formsPage;
driver.FindElement(By.Id("nonExistantButton"));
}
[Test]
public void ShouldBeAbleToClickOnLinkIdentifiedByText()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.LinkText("click me")).Click();
WaitFor(() => { return driver.Title == "We Arrive Here"; });
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void DriverShouldBeAbleToFindElementsAfterLoadingMoreThanOnePageAtATime()
{
driver.Url = formsPage;
driver.Url = xhtmlTestPage;
driver.FindElement(By.LinkText("click me")).Click();
WaitFor(() => { return driver.Title == "We Arrive Here"; });
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldBeAbleToClickOnLinkIdentifiedById()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.Id("linkId")).Click();
WaitFor(() => { return driver.Title == "We Arrive Here"; });
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldThrowAnExceptionWhenThereIsNoLinkToClickAndItIsFoundWithLinkText()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.LinkText("Not here either"));
}
[Test]
public void ShouldFindAnElementBasedOnId()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("checky"));
Assert.IsFalse(element.Selected);
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToFindElementsBasedOnIdIfTheElementIsNotThere()
{
driver.Url = formsPage;
driver.FindElement(By.Id("notThere"));
}
[Test]
public void ShouldBeAbleToFindChildrenOfANode()
{
driver.Url = selectableItemsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("/html/head"));
IWebElement head = elements[0];
ReadOnlyCollection<IWebElement> importedScripts = head.FindElements(By.TagName("script"));
Assert.AreEqual(importedScripts.Count, 3);
}
[Test]
public void ReturnAnEmptyListWhenThereAreNoChildrenOfANode()
{
driver.Url = xhtmlTestPage;
IWebElement table = driver.FindElement(By.Id("table"));
ReadOnlyCollection<IWebElement> rows = table.FindElements(By.TagName("tr"));
Assert.AreEqual(rows.Count, 0);
}
[Test]
public void ShouldFindElementsByName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("checky"));
Assert.AreEqual(element.GetAttribute("value"), "furrfu");
}
[Test]
public void ShouldFindElementsByClass()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("extraDiv"));
Assert.IsTrue(element.Text.StartsWith("Another div starts here."));
}
[Test]
public void ShouldFindElementsByClassWhenItIsTheFirstNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameA"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindElementsByClassWhenItIsTheLastNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameC"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindElementsByClassWhenItIsInTheMiddleAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameBnoise"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindElementByClassWhenItsNameIsSurroundedByWhitespace()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("spaceAround"));
Assert.AreEqual("Spaced out", element.Text);
}
[Test]
public void ShouldFindElementsByClassWhenItsNameIsSurroundedByWhitespace()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("spaceAround"));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("Spaced out", elements[0].Text);
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotFindElementsByClassWhenTheNameQueriedIsShorterThanCandidateName()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.ClassName("nameB"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByXPath()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("//div"));
Assert.IsTrue(elements.Count > 1);
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByLinkText()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("click me"));
Assert.IsTrue(elements.Count == 2, "Expected 2 links, got " + elements.Count);
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByPartialLinkText()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.PartialLinkText("ick me"));
Assert.IsTrue(elements.Count == 2);
}
[Test]
public void ShouldBeAbleToFindElementByPartialLinkText()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.PartialLinkText("anon"));
}
[Test]
public void ShouldFindElementByLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.LinkText("Link=equalssign"));
Assert.AreEqual("linkWithEqualsSign", element.GetAttribute("id"));
}
[Test]
public void ShouldFindElementByPartialLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.PartialLinkText("Link="));
Assert.AreEqual("linkWithEqualsSign", element.GetAttribute("id"));
}
[Test]
public void ShouldFindElementsByLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("Link=equalssign"));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("linkWithEqualsSign", elements[0].GetAttribute("id"));
}
[Test]
public void ShouldFindElementsByPartialLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.PartialLinkText("Link="));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("linkWithEqualsSign", elements[0].GetAttribute("id"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByName()
{
driver.Url = nestedPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name("checky"));
Assert.IsTrue(elements.Count > 1);
}
[Test]
public void ShouldBeAbleToFindMultipleElementsById()
{
driver.Url = nestedPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("2"));
Assert.AreEqual(8, elements.Count);
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByClassName()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("nameC"));
Assert.IsTrue(elements.Count > 1);
}
[Test]
// You don't want to ask why this is here
public void WhenFindingByNameShouldNotReturnById()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("id-name1"));
Assert.AreEqual(element.GetAttribute("value"), "name");
element = driver.FindElement(By.Id("id-name1"));
Assert.AreEqual(element.GetAttribute("value"), "id");
element = driver.FindElement(By.Name("id-name2"));
Assert.AreEqual(element.GetAttribute("value"), "name");
element = driver.FindElement(By.Id("id-name2"));
Assert.AreEqual(element.GetAttribute("value"), "id");
}
[Test]
public void ShouldFindGrandChildren()
{
driver.Url = formsPage;
IWebElement form = driver.FindElement(By.Id("nested_form"));
form.FindElement(By.Name("x"));
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotFindElementOutSideTree()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("login"));
element.FindElement(By.Name("x"));
}
[Test]
public void ShouldReturnElementsThatDoNotSupportTheNameProperty()
{
driver.Url = nestedPage;
driver.FindElement(By.Name("div1"));
// If this works, we're all good
}
[Test]
public void ShouldFindHiddenElementsByName()
{
driver.Url = formsPage;
driver.FindElement(By.Name("hidden"));
}
[Test]
public void ShouldFindAnElementBasedOnTagName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.TagName("input"));
Assert.IsNotNull(element);
}
[Test]
public void ShouldFindElementsBasedOnTagName()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("input"));
Assert.IsNotNull(elements);
}
[Test]
[ExpectedException(typeof(IllegalLocatorException))]
public void FindingElementByCompoundClassNameIsAnError()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.ClassName("a b"));
}
[Test]
[ExpectedException(typeof(IllegalLocatorException))]
public void FindingElementCollectionByCompoundClassNameIsAnError()
{
driver.FindElements(By.ClassName("a b"));
}
[Test]
[Category("Javascript")]
public void ShouldBeAbleToClickOnLinksWithNoHrefAttribute()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.LinkText("No href"));
element.Click();
// if any exception is thrown, we won't get this far. Sanity check
Assert.AreEqual("Changed", driver.Title);
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToFindAnElementOnABlankPage()
{
driver.Url = "about:blank";
driver.FindElement(By.TagName("a"));
}
[Test]
[NeedsFreshDriver(BeforeTest = true)]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToLocateASingleElementOnABlankPage()
{
// Note we're on the default start page for the browser at this point.
driver.FindElement(By.Id("nonExistantButton"));
}
[Test]
[Category("Javascript")]
[ExpectedException(typeof(StaleElementReferenceException))]
public void RemovingAnElementDynamicallyFromTheDomShouldCauseAStaleRefException()
{
driver.Url = javascriptPage;
IWebElement toBeDeleted = driver.FindElement(By.Id("deleted"));
Assert.IsTrue(toBeDeleted.Displayed);
driver.FindElement(By.Id("delete")).Click();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(500));
bool displayedAfterDelete = toBeDeleted.Displayed;
}
[Test]
public void FindingALinkByXpathUsingContainsKeywordShouldWork()
{
driver.Url = nestedPage;
driver.FindElement(By.XPath("//a[contains(.,'hello world')]"));
}
[Test]
[Category("Javascript")]
public void ShouldBeAbleToFindAnElementByCssSelector()
{
if (!SupportsSelectorApi())
{
Assert.Ignore("Skipping test: selector API not supported");
}
driver.Url = xhtmlTestPage;
driver.FindElement(By.CssSelector("div.content"));
}
[Test]
[Category("Javascript")]
public void ShouldBeAbleToFindAnElementsByCssSelector()
{
if (!SupportsSelectorApi())
{
Assert.Ignore("Skipping test: selector API not supported");
}
driver.Url = xhtmlTestPage;
driver.FindElements(By.CssSelector("p"));
}
[Test]
public void FindingByXPathShouldNotIncludeParentElementIfSameTagType()
{
driver.Url = xhtmlTestPage;
IWebElement parent = driver.FindElement(By.Id("my_span"));
Assert.AreEqual(2, parent.FindElements(By.TagName("div")).Count);
Assert.AreEqual(2, parent.FindElements(By.TagName("span")).Count);
}
[Test]
[ExpectedException(typeof(StaleElementReferenceException))]
public void AnElementFoundInADifferentFrameIsStale()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("missedJsReference.html");
driver.SwitchTo().Frame("inner");
IWebElement element = driver.FindElement(By.Id("oneline"));
driver.SwitchTo().DefaultContent();
string text = element.Text;
}
[Test]
[Category("JavaScript")]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void AnElementFoundInADifferentFrameViaJsCanBeUsed()
{
String url = EnvironmentManager.Instance.UrlBuilder.WhereIs("missedJsReference.html");
driver.Url = url;
try
{
driver.SwitchTo().Frame("inner");
IWebElement first = driver.FindElement(By.Id("oneline"));
driver.SwitchTo().DefaultContent();
IWebElement element = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript("return frames[0].document.getElementById('oneline');");
driver.SwitchTo().Frame("inner");
IWebElement second = driver.FindElement(By.Id("oneline"));
Assert.AreEqual(first, element);
Assert.AreEqual(second, element);
}
finally
{
driver.SwitchTo().DefaultContent();
}
}
/////////////////////////////////////////////////
// Tests unique to the .NET bindings
/////////////////////////////////////////////////
[Test]
public void ShouldBeAbleToInjectXPathEngineIfNeeded()
{
driver.Url = alertsPage;
driver.FindElement(By.XPath("//body"));
driver.FindElement(By.XPath("//h1"));
driver.FindElement(By.XPath("//div"));
driver.FindElement(By.XPath("//p"));
driver.FindElement(By.XPath("//a"));
}
[Test]
public void ShouldFindElementByLinkTextContainingDoubleQuote()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.LinkText("link with \" (double quote)"));
Assert.AreEqual("quote", element.GetAttribute("id"));
}
[Test]
public void ShouldFindElementByLinkTextContainingBackslash()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.LinkText("link with \\ (backslash)"));
Assert.AreEqual("backslash", element.GetAttribute("id"));
}
private bool SupportsSelectorApi()
{
IJavaScriptExecutor javascriptDriver = driver as IJavaScriptExecutor;
IFindsByCssSelector cssSelectorDriver = driver as IFindsByCssSelector;
return (cssSelectorDriver != null) && (javascriptDriver != null);
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Controls.dll
// Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 8/25/2008 2:46:23 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using DotSpatial.Data;
using DotSpatial.Symbology;
namespace DotSpatial.Controls
{
public class MapImageLayer : ImageLayer, IMapImageLayer
{
#region Events
/// <summary>
/// Fires an event that indicates to the parent map-frame that it should first
/// redraw the specified clip
/// </summary>
public event EventHandler<ClipArgs> BufferChanged;
#endregion
#region Private Variables
private Image _backBuffer; // draw to the back buffer, and swap to the stencil when done.
private Color transparent;
#endregion
#region Constructors
/// <summary>
/// Creates a new default instance of a MapImageLayer
/// </summary>
public MapImageLayer()
{
}
/// <summary>
/// Creates a new instance of GeoImageLayer
/// </summary>
public MapImageLayer(IImageData baseImage)
: base(baseImage) { }
/// <summary>
/// Creates a new instance of a GeoImageLayer
/// </summary>
/// <param name="baseImage">The image to draw as a layer</param>
/// <param name="container">The Layers collection that keeps track of the image layer</param>
public MapImageLayer(IImageData baseImage, ICollection<ILayer> container)
: base(baseImage, container) { }
/// <summary>
/// Creates a new instance of a GeoImageLayer
/// </summary>
/// <param name="baseImage">The image to draw as a layer</param>
/// <param name="transparent">The color to make transparent when drawing the image.</param>
public MapImageLayer(IImageData baseImage, Color transparent)
: base(baseImage)
{
this.transparent = transparent;
}
#endregion
#region Methods
protected override void OnDataSetChanged(IImageData value)
{
base.OnDataSetChanged(value);
BufferRectangle = value == null ? Rectangle.Empty : new Rectangle(0, 0, value.Width, value.Height);
BufferExtent = value == null ? null : value.Bounds.Extent;
MyExtent = value == null ? null : value.Extent;
OnFinishedLoading();
}
/// <summary>
/// This will draw any features that intersect this region. To specify the features
/// directly, use OnDrawFeatures. This will not clear existing buffer content.
/// For that call Initialize instead.
/// </summary>
/// <param name="args">A GeoArgs clarifying the transformation from geographic to image space</param>
/// <param name="regions">The geographic regions to draw</param>
public void DrawRegions(MapArgs args, List<Extent> regions)
{
List<Rectangle> clipRects = args.ProjToPixel(regions);
for (int i = clipRects.Count - 1; i >= 0; i--)
{
if (clipRects[i].Width != 0 && clipRects[i].Height != 0) continue;
regions.RemoveAt(i);
clipRects.RemoveAt(i);
}
DrawWindows(args, regions, clipRects);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the back buffer that will be drawn to as part of the initialization process.
/// </summary>
public Image BackBuffer
{
get { return _backBuffer; }
set { _backBuffer = value; }
}
/// <summary>
/// Gets the current buffer.
/// </summary>
public Image Buffer { get; set; }
/// <summary>
/// Gets or sets the geographic region represented by the buffer
/// Calling Initialize will set this automatically.
/// </summary>
public Extent BufferExtent { get; set; }
/// <summary>
/// Gets or sets the rectangle in pixels to use as the back buffer.
/// Calling Initialize will set this automatically.
/// </summary>
public Rectangle BufferRectangle { get; set; }
/// <summary>
/// Gets or sets whether the image layer is initialized
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new bool IsInitialized { get; set; }
#endregion
#region Protected Methods
/// <summary>
/// Fires the OnBufferChanged event
/// </summary>
/// <param name="clipRectangles">The Rectangle in pixels</param>
protected virtual void OnBufferChanged(List<Rectangle> clipRectangles)
{
if (BufferChanged != null)
{
BufferChanged(this, new ClipArgs(clipRectangles));
}
}
#endregion
#region Private Methods
/// <summary>
/// This draws to the back buffer. If the Backbuffer doesn't exist, this will create one.
/// This will not flip the back buffer to the front.
/// </summary>
/// <param name="args"></param>
/// <param name="regions"></param>
/// <param name="clipRectangles"></param>
private void DrawWindows(MapArgs args, IList<Extent> regions, IList<Rectangle> clipRectangles)
{
Graphics g;
if (args.Device != null)
{
g = args.Device; // A device on the MapArgs is optional, but overrides the normal buffering behaviors.
}
else
{
if (_backBuffer == null) _backBuffer = new Bitmap(BufferRectangle.Width, BufferRectangle.Height);
g = Graphics.FromImage(_backBuffer);
}
int numBounds = Math.Min(regions.Count, clipRectangles.Count);
for (int i = 0; i < numBounds; i++)
{
// For panning tiles, the region needs to be expanded.
// This is not always 1 pixel. When very zoomed in, this could be many pixels,
// but should correspond to 1 pixel in the source image.
int dx = (int)Math.Ceiling(DataSet.Bounds.AffineCoefficients[1] * clipRectangles[i].Width / regions[i].Width);
Rectangle r = clipRectangles[i].ExpandBy(dx * 2);
if (r.X < 0) r.X = 0;
if (r.Y < 0) r.Y = 0;
if (r.Width > 2 * clipRectangles[i].Width) r.Width = 2 * clipRectangles[i].Width;
if (r.Height > 2 * clipRectangles[i].Height) r.Height = 2 * clipRectangles[i].Height;
Extent env = regions[i].Reproportion(clipRectangles[i], r);
Bitmap bmp = null;
try
{
bmp = DataSet.GetBitmap(env, r);
if (!transparent.Name.Equals("0")) { bmp.MakeTransparent(transparent); }
}
catch
{
if (bmp != null) bmp.Dispose();
continue;
}
if (bmp == null) continue;
if (this.Symbolizer != null && this.Symbolizer.Opacity < 1)
{
ColorMatrix matrix = new ColorMatrix(); //draws the image not completely opaque
matrix.Matrix33 = Symbolizer.Opacity;
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
g.DrawImage(bmp, r, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, attributes);
attributes.Dispose();
}
else
{
g.DrawImage(bmp, r);
}
bmp.Dispose();
}
if (args.Device == null) g.Dispose();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class ArrayExpansionTests : CSharpResultProviderTestBase
{
[Fact]
public void Array()
{
var rootExpr = "new[] { 1, 2, 3 }";
var value = CreateDkmClrValue(new[] { 1, 2, 3 });
var evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{int[3]}", "int[]", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "int", "(new[] { 1, 2, 3 })[0]"),
EvalResult("[1]", "2", "int", "(new[] { 1, 2, 3 })[1]"),
EvalResult("[2]", "3", "int", "(new[] { 1, 2, 3 })[2]"));
}
[Fact]
public void ZeroLengthArray()
{
var rootExpr = "new object[0]";
var value = CreateDkmClrValue(new object[0]);
var evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{object[0]}", "object[]", rootExpr));
DkmEvaluationResultEnumContext enumContext;
var children = GetChildren(evalResult, 100, null, out enumContext);
Verify(children);
var items = GetItems(enumContext, 0, enumContext.Count);
Verify(items);
}
[Fact]
public void NestedArray()
{
var rootExpr = "new int[][] { new[] { 1, 2 }, new[] { 3 } }";
var value = CreateDkmClrValue(new int[][] { new[] { 1, 2 }, new[] { 3 } });
var evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{int[2][]}", "int[][]", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "{int[2]}", "int[]", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[0]", DkmEvaluationResultFlags.Expandable),
EvalResult("[1]", "{int[1]}", "int[]", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[1]", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[0]),
EvalResult("[0]", "1", "int", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[0][0]"),
EvalResult("[1]", "2", "int", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[0][1]"));
Verify(GetChildren(children[1]),
EvalResult("[0]", "3", "int", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[1][0]"));
}
[Fact]
public void MultiDimensionalArray()
{
var rootExpr = "new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } }";
var value = CreateDkmClrValue(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } });
var evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{int[3, 2]}", "int[,]", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0, 0]", "1", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[0, 0]"),
EvalResult("[0, 1]", "2", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[0, 1]"),
EvalResult("[1, 0]", "3", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[1, 0]"),
EvalResult("[1, 1]", "4", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[1, 1]"),
EvalResult("[2, 0]", "5", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[2, 0]"),
EvalResult("[2, 1]", "6", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[2, 1]"));
}
[Fact]
public void ZeroLengthMultiDimensionalArray()
{
var rootExpr = "new int[2, 3, 0]";
var value = CreateDkmClrValue(new int[2, 3, 0]);
var evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{int[2, 3, 0]}", "int[,,]", rootExpr));
Verify(GetChildren(evalResult));
rootExpr = "new int[2, 0, 3]";
value = CreateDkmClrValue(new int[2, 0, 3]);
evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{int[2, 0, 3]}", "int[,,]", rootExpr));
Verify(GetChildren(evalResult));
rootExpr = "new int[0, 2, 3]";
value = CreateDkmClrValue(new int[0, 2, 3]);
evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{int[0, 2, 3]}", "int[,,]", rootExpr));
Verify(GetChildren(evalResult));
rootExpr = "new int[0, 0, 0]";
value = CreateDkmClrValue(new int[0, 0, 0]);
evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{int[0, 0, 0]}", "int[,,]", rootExpr));
Verify(GetChildren(evalResult));
}
[Fact]
public void NullArray()
{
var rootExpr = "new int[][,,] { null, new int[2, 3, 4] }";
var evalResult = FormatResult(rootExpr, CreateDkmClrValue(new int[][,,] { null, new int[2, 3, 4] }));
Verify(evalResult,
EvalResult(rootExpr, "{int[2][,,]}", "int[][,,]", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "null", "int[,,]", "(new int[][,,] { null, new int[2, 3, 4] })[0]"),
EvalResult("[1]", "{int[2, 3, 4]}", "int[,,]", "(new int[][,,] { null, new int[2, 3, 4] })[1]", DkmEvaluationResultFlags.Expandable));
}
[Fact]
public void BaseType()
{
var source =
@"class C
{
object o = new int[] { 1, 2 };
System.Array a = new object[] { null };
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var rootExpr = "new C()";
var value = CreateDkmClrValue(Activator.CreateInstance(type));
var evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("a", "{object[1]}", "System.Array {object[]}", "(new C()).a", DkmEvaluationResultFlags.Expandable),
EvalResult("o", "{int[2]}", "object {int[]}", "(new C()).o", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[0]),
EvalResult("[0]", "null", "object", "((object[])(new C()).a)[0]"));
Verify(GetChildren(children[1]),
EvalResult("[0]", "1", "int", "((int[])(new C()).o)[0]"),
EvalResult("[1]", "2", "int", "((int[])(new C()).o)[1]"));
}
[WorkItem(933845)]
[Fact]
public void BaseElementType()
{
var source =
@"class A
{
internal object F;
}
class B : A
{
internal B(object f)
{
F = f;
}
internal object P { get { return this.F; } }
}";
var assembly = GetAssembly(source);
var typeB = assembly.GetType("B");
var value = CreateDkmClrValue(new object[] { 1, typeB.Instantiate(2) });
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{object[2]}", "object[]", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "object {int}", "o[0]"),
EvalResult("[1]", "{B}", "object {B}", "o[1]", DkmEvaluationResultFlags.Expandable));
children = GetChildren(children[1]);
Verify(children,
EvalResult("F", "2", "object {int}", "((A)o[1]).F"),
EvalResult("P", "2", "object {int}", "((B)o[1]).P", DkmEvaluationResultFlags.ReadOnly));
}
[WorkItem(1022157)]
[Fact(Skip = "1022157")]
public void Covariance()
{
var source =
@"interface I { }
class A
{
object F = 1;
}
class B : A, I { }
class C
{
object[] F = new[] { new A() };
A[] G = new[] { new B() };
I[] H = new[] { new B() };
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(Activator.CreateInstance(type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "{A[1]}", "object[] {A[]}", "o.F", DkmEvaluationResultFlags.Expandable),
EvalResult("G", "{B[1]}", "A[] {B[]}", "o.G", DkmEvaluationResultFlags.Expandable),
EvalResult("H", "{B[1]}", "I[] {B[]}", "o.H", DkmEvaluationResultFlags.Expandable));
var moreChildren = GetChildren(children[0]);
Verify(moreChildren,
EvalResult("[0]", "{A}", "object {A}", "o.F[0]", DkmEvaluationResultFlags.Expandable));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult("F", "1", "object {int}", "((A)o.F[0]).F"));
moreChildren = GetChildren(children[1]);
Verify(moreChildren,
EvalResult("[0]", "{B}", "A {B}", "o.G[0]", DkmEvaluationResultFlags.Expandable));
moreChildren = GetChildren(children[2]);
Verify(moreChildren,
EvalResult("[0]", "{B}", "I {B}", "o.H[0]", DkmEvaluationResultFlags.Expandable));
}
[WorkItem(1001844)]
[Fact]
public void Interface()
{
var source =
@"class C
{
char[] F = new char[] { '1' };
System.Collections.IEnumerable G = new char[] { '2' };
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(Activator.CreateInstance(type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "{char[1]}", "char[]", "o.F", DkmEvaluationResultFlags.Expandable),
EvalResult("G", "{char[1]}", "System.Collections.IEnumerable {char[]}", "o.G", DkmEvaluationResultFlags.Expandable));
var moreChildren = GetChildren(children[0]);
Verify(moreChildren,
EvalResult("[0]", "49 '1'", "char", "o.F[0]", editableValue: "'1'"));
moreChildren = GetChildren(children[1]);
Verify(moreChildren,
EvalResult("[0]", "50 '2'", "char", "((char[])o.G)[0]", editableValue: "'2'"));
}
[Fact]
public void NonZeroLowerBounds()
{
var rootExpr = "arrayExpr";
var array = (int[,])System.Array.CreateInstance(typeof(int), new[] { 2, 3 }, new[] { 3, 4 });
array[3, 4] = 1;
array[3, 5] = 2;
array[3, 6] = 3;
array[4, 4] = 4;
array[4, 5] = 5;
array[4, 6] = 6;
var value = CreateDkmClrValue(array);
var evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{int[3..4, 4..6]}", "int[,]", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[3, 4]", "1", "int", "arrayExpr[3, 4]"),
EvalResult("[3, 5]", "2", "int", "arrayExpr[3, 5]"),
EvalResult("[3, 6]", "3", "int", "arrayExpr[3, 6]"),
EvalResult("[4, 4]", "4", "int", "arrayExpr[4, 4]"),
EvalResult("[4, 5]", "5", "int", "arrayExpr[4, 5]"),
EvalResult("[4, 6]", "6", "int", "arrayExpr[4, 6]"));
}
/// <summary>
/// Expansion should be lazy so that the IDE can
/// reduce overhead by expanding a subset of rows.
/// </summary>
[Fact]
public void LazyExpansion()
{
var rootExpr = "new byte[10, 1000, 1000]";
var parenthesizedExpr = string.Format("({0})", rootExpr);
var value = CreateDkmClrValue(new byte[10, 1000, 1000]); // Array with 10M elements
var evalResults = new DkmEvaluationResult[100]; // 100 distinct evaluations of the array
for (int i = 0; i < evalResults.Length; i++)
{
var evalResult = FormatResult(rootExpr, value);
evalResults[i] = evalResult;
// Expand a subset.
int offset = i * 100 * 1000;
DkmEvaluationResultEnumContext enumContext;
GetChildren(evalResult, 0, null, out enumContext);
var items = GetItems(enumContext, offset, 2);
var indices1 = string.Format("{0}, {1}, {2}", offset / 1000000, (offset % 1000000) / 1000, 0);
var indices2 = string.Format("{0}, {1}, {2}", (offset + 1) / 1000000, ((offset + 1) % 1000000) / 1000, 1);
Verify(items,
EvalResult(string.Format("[{0}]", indices1), "0", "byte", string.Format("{0}[{1}]", parenthesizedExpr, indices1)),
EvalResult(string.Format("[{0}]", indices2), "0", "byte", string.Format("{0}[{1}]", parenthesizedExpr, indices2)));
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
/// <summary>
/// Generates symbols that describe declarations to be generated.
/// </summary>
internal static class CodeGenerationSymbolFactory
{
/// <summary>
/// Determines if the symbol is purely a code generation symbol.
/// </summary>
public static bool IsCodeGenerationSymbol(this ISymbol symbol)
{
return symbol is CodeGenerationSymbol;
}
/// <summary>
/// Creates an event symbol that can be used to describe an event declaration.
/// </summary>
public static IEventSymbol CreateEventSymbol(
ImmutableArray<AttributeData> attributes, Accessibility accessibility,
DeclarationModifiers modifiers, ITypeSymbol type,
ImmutableArray<IEventSymbol> explicitInterfaceImplementations,
string name,
IMethodSymbol addMethod = null,
IMethodSymbol removeMethod = null,
IMethodSymbol raiseMethod = null)
{
var result = new CodeGenerationEventSymbol(null, attributes, accessibility, modifiers, type, explicitInterfaceImplementations, name, addMethod, removeMethod, raiseMethod);
CodeGenerationEventInfo.Attach(result, modifiers.IsUnsafe);
return result;
}
internal static IPropertySymbol CreatePropertySymbol(
INamedTypeSymbol containingType,
ImmutableArray<AttributeData> attributes,
Accessibility accessibility,
DeclarationModifiers modifiers,
ITypeSymbol type,
bool returnsByRef,
ImmutableArray<IPropertySymbol> explicitInterfaceImplementations,
string name,
ImmutableArray<IParameterSymbol> parameters,
IMethodSymbol getMethod,
IMethodSymbol setMethod,
bool isIndexer = false,
SyntaxNode initializer = null)
{
var result = new CodeGenerationPropertySymbol(
containingType,
attributes,
accessibility,
modifiers,
type,
returnsByRef,
explicitInterfaceImplementations,
name,
isIndexer,
parameters,
getMethod,
setMethod);
CodeGenerationPropertyInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, initializer);
return result;
}
/// <summary>
/// Creates a property symbol that can be used to describe a property declaration.
/// </summary>
public static IPropertySymbol CreatePropertySymbol(
ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers,
ITypeSymbol type, bool returnsByRef, ImmutableArray<IPropertySymbol> explicitInterfaceImplementations, string name,
ImmutableArray<IParameterSymbol> parameters, IMethodSymbol getMethod, IMethodSymbol setMethod,
bool isIndexer = false)
{
return CreatePropertySymbol(
containingType: null,
attributes: attributes,
accessibility: accessibility,
modifiers: modifiers,
type: type,
returnsByRef: returnsByRef,
explicitInterfaceImplementations: explicitInterfaceImplementations,
name: name,
parameters: parameters,
getMethod: getMethod,
setMethod: setMethod,
isIndexer: isIndexer);
}
/// <summary>
/// Creates a field symbol that can be used to describe a field declaration.
/// </summary>
public static IFieldSymbol CreateFieldSymbol(
ImmutableArray<AttributeData> attributes,
Accessibility accessibility,
DeclarationModifiers modifiers,
ITypeSymbol type, string name,
bool hasConstantValue = false,
object constantValue = null,
SyntaxNode initializer = null)
{
var result = new CodeGenerationFieldSymbol(null, attributes, accessibility, modifiers, type, name, hasConstantValue, constantValue);
CodeGenerationFieldInfo.Attach(result, modifiers.IsUnsafe, modifiers.IsWithEvents, initializer);
return result;
}
/// <summary>
/// Creates a constructor symbol that can be used to describe a constructor declaration.
/// </summary>
public static IMethodSymbol CreateConstructorSymbol(
ImmutableArray<AttributeData> attributes,
Accessibility accessibility,
DeclarationModifiers modifiers,
string typeName,
ImmutableArray<IParameterSymbol> parameters,
ImmutableArray<SyntaxNode> statements = default(ImmutableArray<SyntaxNode>),
ImmutableArray<SyntaxNode> baseConstructorArguments = default(ImmutableArray<SyntaxNode>),
ImmutableArray<SyntaxNode> thisConstructorArguments = default(ImmutableArray<SyntaxNode>))
{
var result = new CodeGenerationConstructorSymbol(null, attributes, accessibility, modifiers, parameters);
CodeGenerationConstructorInfo.Attach(result, typeName, statements, baseConstructorArguments, thisConstructorArguments);
return result;
}
/// <summary>
/// Creates a destructor symbol that can be used to describe a destructor declaration.
/// </summary>
public static IMethodSymbol CreateDestructorSymbol(
ImmutableArray<AttributeData> attributes, string typeName,
ImmutableArray<SyntaxNode> statements = default(ImmutableArray<SyntaxNode>))
{
var result = new CodeGenerationDestructorSymbol(null, attributes);
CodeGenerationDestructorInfo.Attach(result, typeName, statements);
return result;
}
internal static IMethodSymbol CreateMethodSymbol(
INamedTypeSymbol containingType,
ImmutableArray<AttributeData> attributes,
Accessibility accessibility, DeclarationModifiers modifiers,
ITypeSymbol returnType, bool returnsByRef,
ImmutableArray<IMethodSymbol> explicitInterfaceImplementations, string name,
ImmutableArray<ITypeParameterSymbol> typeParameters,
ImmutableArray<IParameterSymbol> parameters,
ImmutableArray<SyntaxNode> statements = default(ImmutableArray<SyntaxNode>),
ImmutableArray<SyntaxNode> handlesExpressions = default(ImmutableArray<SyntaxNode>),
ImmutableArray<AttributeData> returnTypeAttributes = default(ImmutableArray<AttributeData>),
MethodKind methodKind = MethodKind.Ordinary)
{
var result = new CodeGenerationMethodSymbol(containingType, attributes, accessibility, modifiers, returnType, returnsByRef, explicitInterfaceImplementations, name, typeParameters, parameters, returnTypeAttributes, methodKind);
CodeGenerationMethodInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, modifiers.IsPartial, modifiers.IsAsync, statements, handlesExpressions);
return result;
}
/// <summary>
/// Creates a method symbol that can be used to describe a method declaration.
/// </summary>
public static IMethodSymbol CreateMethodSymbol(
ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers,
ITypeSymbol returnType, bool returnsByRef,
ImmutableArray<IMethodSymbol> explicitInterfaceImplementations, string name,
ImmutableArray<ITypeParameterSymbol> typeParameters,
ImmutableArray<IParameterSymbol> parameters,
ImmutableArray<SyntaxNode> statements = default(ImmutableArray<SyntaxNode>),
ImmutableArray<SyntaxNode> handlesExpressions = default(ImmutableArray<SyntaxNode>),
ImmutableArray<AttributeData> returnTypeAttributes = default(ImmutableArray<AttributeData>),
MethodKind methodKind = MethodKind.Ordinary)
{
return CreateMethodSymbol(null, attributes, accessibility, modifiers, returnType, returnsByRef, explicitInterfaceImplementations, name, typeParameters, parameters, statements, handlesExpressions, returnTypeAttributes, methodKind);
}
/// <summary>
/// Creates a method symbol that can be used to describe an operator declaration.
/// </summary>
public static IMethodSymbol CreateOperatorSymbol(
ImmutableArray<AttributeData> attributes,
Accessibility accessibility,
DeclarationModifiers modifiers,
ITypeSymbol returnType,
CodeGenerationOperatorKind operatorKind,
ImmutableArray<IParameterSymbol> parameters,
ImmutableArray<SyntaxNode> statements = default(ImmutableArray<SyntaxNode>),
ImmutableArray<AttributeData> returnTypeAttributes = default(ImmutableArray<AttributeData>))
{
int expectedParameterCount = CodeGenerationOperatorSymbol.GetParameterCount(operatorKind);
if (parameters.Length != expectedParameterCount)
{
var message = expectedParameterCount == 1 ?
WorkspacesResources.Invalid_number_of_parameters_for_unary_operator :
WorkspacesResources.Invalid_number_of_parameters_for_binary_operator;
throw new ArgumentException(message, nameof(parameters));
}
var result = new CodeGenerationOperatorSymbol(null, attributes, accessibility, modifiers, returnType, operatorKind, parameters, returnTypeAttributes);
CodeGenerationMethodInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, modifiers.IsPartial, modifiers.IsAsync, statements, handlesExpressions: default(ImmutableArray<SyntaxNode>));
return result;
}
/// <summary>
/// Creates a method symbol that can be used to describe a conversion declaration.
/// </summary>
public static IMethodSymbol CreateConversionSymbol(
ImmutableArray<AttributeData> attributes,
Accessibility accessibility,
DeclarationModifiers modifiers,
ITypeSymbol toType,
IParameterSymbol fromType,
bool isImplicit = false,
ImmutableArray<SyntaxNode> statements = default(ImmutableArray<SyntaxNode>),
ImmutableArray<AttributeData> toTypeAttributes = default(ImmutableArray<AttributeData>))
{
var result = new CodeGenerationConversionSymbol(null, attributes, accessibility, modifiers, toType, fromType, isImplicit, toTypeAttributes);
CodeGenerationMethodInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, modifiers.IsPartial, modifiers.IsAsync, statements, handlesExpressions: default(ImmutableArray<SyntaxNode>));
return result;
}
/// <summary>
/// Creates a parameter symbol that can be used to describe a parameter declaration.
/// </summary>
public static IParameterSymbol CreateParameterSymbol(ITypeSymbol type, string name)
{
return CreateParameterSymbol(
attributes: default(ImmutableArray<AttributeData>), refKind: RefKind.None, isParams: false, type: type, name: name, isOptional: false);
}
/// <summary>
/// Creates a parameter symbol that can be used to describe a parameter declaration.
/// </summary>
public static IParameterSymbol CreateParameterSymbol(
ImmutableArray<AttributeData> attributes, RefKind refKind, bool isParams, ITypeSymbol type, string name, bool isOptional = false, bool hasDefaultValue = false, object defaultValue = null)
{
return new CodeGenerationParameterSymbol(null, attributes, refKind, isParams, type, name, isOptional, hasDefaultValue, defaultValue);
}
/// <summary>
/// Creates a parameter symbol that can be used to describe a parameter declaration.
/// </summary>
public static ITypeParameterSymbol CreateTypeParameterSymbol(string name, int ordinal = 0)
{
return CreateTypeParameter(
attributes: default(ImmutableArray<AttributeData>), varianceKind: VarianceKind.None,
name: name, constraintTypes: ImmutableArray.Create<ITypeSymbol>(),
hasConstructorConstraint: false, hasReferenceConstraint: false, hasValueConstraint: false,
ordinal: ordinal);
}
/// <summary>
/// Creates a type parameter symbol that can be used to describe a type parameter declaration.
/// </summary>
public static ITypeParameterSymbol CreateTypeParameter(
ImmutableArray<AttributeData> attributes,
VarianceKind varianceKind, string name,
ImmutableArray<ITypeSymbol> constraintTypes,
bool hasConstructorConstraint = false,
bool hasReferenceConstraint = false,
bool hasValueConstraint = false, int ordinal = 0)
{
return new CodeGenerationTypeParameterSymbol(null, attributes, varianceKind, name, constraintTypes, hasConstructorConstraint, hasReferenceConstraint, hasValueConstraint, ordinal);
}
/// <summary>
/// Creates a pointer type symbol that can be used to describe a pointer type reference.
/// </summary>
public static IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType)
{
return new CodeGenerationPointerTypeSymbol(pointedAtType);
}
/// <summary>
/// Creates an array type symbol that can be used to describe an array type reference.
/// </summary>
public static IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1)
{
return new CodeGenerationArrayTypeSymbol(elementType, rank);
}
internal static IMethodSymbol CreateAccessorSymbol(
IMethodSymbol accessor,
ImmutableArray<AttributeData> attributes = default(ImmutableArray<AttributeData>),
Accessibility? accessibility = null,
ImmutableArray<IMethodSymbol> explicitInterfaceImplementations = default,
ImmutableArray<SyntaxNode> statements = default(ImmutableArray<SyntaxNode>))
{
return CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes,
accessibility ?? accessor.DeclaredAccessibility,
accessor.GetSymbolModifiers().WithIsAbstract(statements == null),
accessor.ReturnType,
accessor.ReturnsByRef,
explicitInterfaceImplementations.IsDefault ? accessor.ExplicitInterfaceImplementations : explicitInterfaceImplementations,
accessor.Name,
accessor.TypeParameters,
accessor.Parameters,
statements,
returnTypeAttributes: accessor.GetReturnTypeAttributes());
}
/// <summary>
/// Creates an method type symbol that can be used to describe an accessor method declaration.
/// </summary>
public static IMethodSymbol CreateAccessorSymbol(
ImmutableArray<AttributeData> attributes,
Accessibility accessibility,
ImmutableArray<SyntaxNode> statements)
{
return CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes,
accessibility,
new DeclarationModifiers(isAbstract: statements == null),
returnType: null,
returnsByRef: false,
explicitInterfaceImplementations: default,
name: string.Empty,
typeParameters: default(ImmutableArray<ITypeParameterSymbol>),
parameters: default(ImmutableArray<IParameterSymbol>),
statements: statements);
}
/// <summary>
/// Create attribute data that can be used in describing an attribute declaration.
/// </summary>
public static AttributeData CreateAttributeData(
INamedTypeSymbol attributeClass,
ImmutableArray<TypedConstant> constructorArguments = default(ImmutableArray<TypedConstant>),
ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments = default(ImmutableArray<KeyValuePair<string, TypedConstant>>))
{
return new CodeGenerationAttributeData(attributeClass, constructorArguments, namedArguments);
}
/// <summary>
/// Creates a named type symbol that can be used to describe a named type declaration.
/// </summary>
public static INamedTypeSymbol CreateNamedTypeSymbol(
ImmutableArray<AttributeData> attributes,
Accessibility accessibility,
DeclarationModifiers modifiers,
TypeKind typeKind, string name,
ImmutableArray<ITypeParameterSymbol> typeParameters = default(ImmutableArray<ITypeParameterSymbol>),
INamedTypeSymbol baseType = null,
ImmutableArray<INamedTypeSymbol> interfaces = default(ImmutableArray<INamedTypeSymbol>),
SpecialType specialType = SpecialType.None,
ImmutableArray<ISymbol> members = default(ImmutableArray<ISymbol>))
{
members = members.NullToEmpty();
return new CodeGenerationNamedTypeSymbol(
null, attributes, accessibility, modifiers, typeKind, name,
typeParameters, baseType, interfaces, specialType,
members.WhereAsArray(m => !(m is INamedTypeSymbol)),
members.OfType<INamedTypeSymbol>().Select(n => n.ToCodeGenerationSymbol()).ToImmutableArray(),
enumUnderlyingType: null);
}
/// <summary>
/// Creates a method type symbol that can be used to describe a delegate type declaration.
/// </summary>
public static CodeGenerationNamedTypeSymbol CreateDelegateTypeSymbol(
ImmutableArray<AttributeData> attributes,
Accessibility accessibility,
DeclarationModifiers modifiers,
ITypeSymbol returnType,
bool returnsByRef,
string name,
ImmutableArray<ITypeParameterSymbol> typeParameters = default(ImmutableArray<ITypeParameterSymbol>),
ImmutableArray<IParameterSymbol> parameters = default(ImmutableArray<IParameterSymbol>))
{
var invokeMethod = CreateMethodSymbol(
attributes: default(ImmutableArray<AttributeData>),
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(),
returnType: returnType,
returnsByRef: returnsByRef,
explicitInterfaceImplementations: default,
name: "Invoke",
typeParameters: default(ImmutableArray<ITypeParameterSymbol>),
parameters: parameters);
return new CodeGenerationNamedTypeSymbol(
containingType: null,
attributes: attributes,
declaredAccessibility: accessibility,
modifiers: modifiers,
typeKind: TypeKind.Delegate,
name: name,
typeParameters: typeParameters,
baseType: null,
interfaces: default(ImmutableArray<INamedTypeSymbol>),
specialType: SpecialType.None,
members: ImmutableArray.Create<ISymbol>(invokeMethod),
typeMembers: ImmutableArray<CodeGenerationAbstractNamedTypeSymbol>.Empty,
enumUnderlyingType: null);
}
/// <summary>
/// Creates a namespace symbol that can be used to describe a namespace declaration.
/// </summary>
public static INamespaceSymbol CreateNamespaceSymbol(string name, IList<ISymbol> imports = null, IList<INamespaceOrTypeSymbol> members = null)
{
var @namespace = new CodeGenerationNamespaceSymbol(name, members);
CodeGenerationNamespaceInfo.Attach(@namespace, imports);
return @namespace;
}
internal static IMethodSymbol CreateMethodSymbol(
IMethodSymbol method,
ImmutableArray<AttributeData> attributes = default(ImmutableArray<AttributeData>),
Accessibility? accessibility = null,
DeclarationModifiers? modifiers = null,
ImmutableArray<IMethodSymbol> explicitInterfaceImplementations = default,
string name = null,
ImmutableArray<SyntaxNode> statements = default(ImmutableArray<SyntaxNode>),
INamedTypeSymbol containingType = null)
{
return CreateMethodSymbol(
containingType,
attributes,
accessibility ?? method.DeclaredAccessibility,
modifiers ?? method.GetSymbolModifiers(),
method.ReturnType,
method.ReturnsByRef,
explicitInterfaceImplementations,
name ?? method.Name,
method.TypeParameters,
method.Parameters,
statements,
returnTypeAttributes: method.GetReturnTypeAttributes());
}
internal static IPropertySymbol CreatePropertySymbol(
IPropertySymbol property,
ImmutableArray<AttributeData> attributes = default(ImmutableArray<AttributeData>),
Accessibility? accessibility = null,
DeclarationModifiers? modifiers = null,
ImmutableArray<IPropertySymbol> explicitInterfaceImplementations = default,
string name = null,
bool? isIndexer = null,
IMethodSymbol getMethod = null,
IMethodSymbol setMethod = null)
{
return CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes,
accessibility ?? property.DeclaredAccessibility,
modifiers ?? property.GetSymbolModifiers(),
property.Type,
property.ReturnsByRef,
explicitInterfaceImplementations,
name ?? property.Name,
property.Parameters,
getMethod,
setMethod,
isIndexer ?? property.IsIndexer);
}
internal static IEventSymbol CreateEventSymbol(
IEventSymbol @event,
ImmutableArray<AttributeData> attributes = default(ImmutableArray<AttributeData>),
Accessibility? accessibility = null,
DeclarationModifiers? modifiers = null,
ImmutableArray<IEventSymbol> explicitInterfaceImplementations = default,
string name = null,
IMethodSymbol addMethod = null,
IMethodSymbol removeMethod = null)
{
return CodeGenerationSymbolFactory.CreateEventSymbol(
attributes,
accessibility ?? @event.DeclaredAccessibility,
modifiers ?? @event.GetSymbolModifiers(),
@event.Type,
explicitInterfaceImplementations,
name ?? @event.Name,
addMethod,
removeMethod);
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Pathfinding.Util;
using Pathfinding.Serialization.JsonFx;
using Pathfinding.Serialization;
namespace Pathfinding {
/** Base class for all graphs */
public abstract class NavGraph {
/** Used to store the guid value
* \see NavGraph.guid
*/
public byte[] _sguid;
/** Reference to the AstarPath object in the scene.
* Might not be entirely safe to use, it's better to use AstarPath.active
*/
public AstarPath active;
/** Used as an ID of the graph, considered to be unique.
* \note This is Pathfinding.Util.Guid not System.Guid. A replacement for System.Guid was coded for better compatibility with iOS
*/
[JsonMember]
public Guid guid {
get {
if (_sguid == null || _sguid.Length != 16) {
_sguid = Guid.NewGuid ().ToByteArray ();
}
return new Guid (_sguid);
}
set {
_sguid = value.ToByteArray ();
}
}
/** Default penalty to apply to all nodes */
[JsonMember]
public uint initialPenalty;
/** Is the graph open in the editor */
[JsonMember]
public bool open;
/** Index of the graph, used for identification purposes */
public uint graphIndex;
/** Name of the graph.
* Can be set in the unity editor
*/
[JsonMember]
public string name;
[JsonMember]
public bool drawGizmos = true;
/** Used in the editor to check if the info screen is open.
* Should be inside UNITY_EDITOR only \#ifs but just in case anyone tries to serialize a NavGraph instance using Unity, I have left it like this as it would otherwise cause a crash when building.
* Version 3.0.8.1 was released because of this bug only
*/
[JsonMember]
public bool infoScreenOpen;
/** Count nodes in the graph.
* Note that this is, unless the graph type has overriden it, an O(n) operation.
*
* \todo GridGraph should override this
*/
public virtual int CountNodes () {
int count = 0;
GraphNodeDelegateCancelable del = node => {
count++;
return true;
};
GetNodes (del);
return count;
}
/** Calls a delegate with all nodes in the graph.
* This is the primary way of "looping" through all nodes in a graph.
*
* This function should not change anything in the graph structure.
*
* \code
* myGraph.GetNodes ((node) => {
* Debug.Log ("I found a node at position " + (Vector3)node.Position);
* return true;
* });
* \endcode
*/
public abstract void GetNodes (GraphNodeDelegateCancelable del);
/** A matrix for translating/rotating/scaling the graph.
* Not all graph generators sets this variable though.
*
* \note Do not set directly, use SetMatrix
*
* \note This value is not serialized. It is expected that graphs regenerate this
* field after deserialization has completed.
*/
public Matrix4x4 matrix = Matrix4x4.identity;
/** Inverse of \a matrix.
*
* \note Do not set directly, use SetMatrix
*
* \see matrix
*/
public Matrix4x4 inverseMatrix = Matrix4x4.identity;
/** Use to set both matrix and inverseMatrix at the same time */
public void SetMatrix (Matrix4x4 m) {
matrix = m;
inverseMatrix = m.inverse;
}
/** Relocates the nodes in this graph.
* Assumes the nodes are already transformed using the "oldMatrix", then transforms them
* such that it will look like they have only been transformed using the "newMatrix".
* The "oldMatrix" is not required by all implementations of this function though (e.g the NavMesh generator).
*
* The matrix the graph is transformed with is typically stored in the #matrix field, so the typical usage for this method is
* \code
* var myNewMatrix = Matrix4x4.TRS (...);
* myGraph.RelocateNodes (myGraph.matrix, myNewMatrix);
* \endcode
*
* So for example if you want to move all your nodes in e.g a point graph 10 units along the X axis from the initial position
* \code
* var graph = AstarPath.astarData.pointGraph;
* var m = Matrix4x4.TRS (new Vector3(10,0,0), Quaternion.identity, Vector3.one);
* graph.RelocateNodes (graph.matrix, m);
* \endcode
*
* \note For grid graphs it is recommended to use the helper method RelocateNodes which takes parameters for
* center and nodeSize (and additional parameters) instead since it is both easier to use and is less likely
* to mess up pathfinding.
*
* \warning This method is lossy, so calling it many times may cause node positions to lose precision.
* For example if you set the scale to 0 in one call, and then to 1 in the next call, it will not be able to
* recover the correct positions since when the scale was 0, all nodes were scaled/moved to the same point.
* The same thing happens for other - less extreme - values as well, but to a lesser degree.
*
* \version Prior to version 3.6.1 the oldMatrix and newMatrix parameters were reversed by mistake.
*/
public virtual void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix) {
Matrix4x4 inv = oldMatrix.inverse;
Matrix4x4 m = newMatrix * inv;
GetNodes (delegate (GraphNode node) {
//Vector3 tmp = inv.MultiplyPoint3x4 ((Vector3)nodes[i].position);
node.position = ((Int3)m.MultiplyPoint ((Vector3)node.position));
return true;
});
SetMatrix (newMatrix);
}
/** Returns the nearest node to a position using the default NNConstraint.
* \param position The position to try to find a close node to
* \see Pathfinding.NNConstraint.None
*/
public NNInfo GetNearest (Vector3 position) {
return GetNearest (position, NNConstraint.None);
}
/** Returns the nearest node to a position using the specified NNConstraint.
* \param position The position to try to find a close node to
* \param constraint Can for example tell the function to try to return a walkable node. If you do not get a good node back, consider calling GetNearestForce. */
public NNInfo GetNearest (Vector3 position, NNConstraint constraint) {
return GetNearest (position, constraint, null);
}
/** Returns the nearest node to a position using the specified NNConstraint.
* \param position The position to try to find a close node to
* \param hint Can be passed to enable some graph generators to find the nearest node faster.
* \param constraint Can for example tell the function to try to return a walkable node. If you do not get a good node back, consider calling GetNearestForce. */
public virtual NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
// This is a default implementation and it is pretty slow
// Graphs usually override this to provide faster and more specialised implementations
float maxDistSqr = constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity;
float minDist = float.PositiveInfinity;
GraphNode minNode = null;
float minConstDist = float.PositiveInfinity;
GraphNode minConstNode = null;
// Loop through all nodes and find the closest suitable node
GetNodes (node => {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) {
minDist = dist;
minNode = node;
}
if (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node)) {
minConstDist = dist;
minConstNode = node;
}
return true;
});
var nnInfo = new NNInfo (minNode);
nnInfo.constrainedNode = minConstNode;
if (minConstNode != null) {
nnInfo.constClampedPosition = (Vector3)minConstNode.position;
} else if (minNode != null) {
nnInfo.constrainedNode = minNode;
nnInfo.constClampedPosition = (Vector3)minNode.position;
}
return nnInfo;
}
/**
* Returns the nearest node to a position using the specified \link Pathfinding.NNConstraint constraint \endlink.
* \returns an NNInfo. This method will only return an empty NNInfo if there are no nodes which comply with the specified constraint.
*/
public virtual NNInfo GetNearestForce (Vector3 position, NNConstraint constraint) {
return GetNearest (position, constraint);
}
/**
* This will be called on the same time as Awake on the gameObject which the AstarPath script is attached to. (remember, not in the editor)
* Use this for any initialization code which can't be placed in Scan
*/
public virtual void Awake () {
}
/** Function for cleaning up references.
* This will be called on the same time as OnDisable on the gameObject which the AstarPath script is attached to (remember, not in the editor).
* Use for any cleanup code such as cleaning up static variables which otherwise might prevent resources from being collected.
* Use by creating a function overriding this one in a graph class, but always call base.OnDestroy () in that function.
* All nodes should be destroyed in this function otherwise a memory leak will arise.
*/
public virtual void OnDestroy () {
//Destroy all nodes
GetNodes(delegate(GraphNode node) {
node.Destroy();
return true;
});
}
/*
* Consider using AstarPath.Scan () instead since this function might screw things up if there is more than one graph.
* This function does not perform all necessary postprocessing for the graph to work with pathfinding (e.g flood fill).
* See the source of the AstarPath.Scan function to see how it can be used.
* In almost all cases you should use AstarPath.Scan instead.
*/
public void ScanGraph () {
if (AstarPath.OnPreScan != null) {
AstarPath.OnPreScan (AstarPath.active);
}
if (AstarPath.OnGraphPreScan != null) {
AstarPath.OnGraphPreScan (this);
}
ScanInternal ();
if (AstarPath.OnGraphPostScan != null) {
AstarPath.OnGraphPostScan (this);
}
if (AstarPath.OnPostScan != null) {
AstarPath.OnPostScan (AstarPath.active);
}
}
[System.Obsolete("Please use AstarPath.active.Scan or if you really want this.ScanInternal which has the same functionality as this method had")]
public void Scan () {
throw new System.Exception ("This method is deprecated. Please use AstarPath.active.Scan or if you really want this.ScanInternal which has the same functionality as this method had.");
}
/** Internal method for scanning graphs */
public void ScanInternal () {
ScanInternal (null);
}
/**
* Scans the graph, called from AstarPath.ScanLoop.
* Override this function to implement custom scanning logic
* The statusCallback may be optionally called to show progress info in the editor
*/
public abstract void ScanInternal (OnScanStatus statusCallback);
/* Color to use for gizmos.
* Returns a color to be used for the specified node with the current debug settings (editor only).
*
* \version Since 3.6.1 this method will not handle null nodes
*/
public virtual Color NodeColor (GraphNode node, PathHandler data) {
Color c = AstarColor.NodeConnection;
switch (AstarPath.active.debugMode) {
case GraphDebugMode.Areas:
c = AstarColor.GetAreaColor (node.Area);
break;
case GraphDebugMode.Penalty:
c = Color.Lerp (AstarColor.ConnectionLowLerp,AstarColor.ConnectionHighLerp, ((float)node.Penalty-AstarPath.active.debugFloor) / (AstarPath.active.debugRoof-AstarPath.active.debugFloor));
break;
case GraphDebugMode.Tags:
c = AstarMath.IntToColor ((int)node.Tag,0.5F);
break;
default:
if (data == null) return AstarColor.NodeConnection;
PathNode nodeR = data.GetPathNode (node);
switch (AstarPath.active.debugMode) {
case GraphDebugMode.G:
c = Color.Lerp (AstarColor.ConnectionLowLerp,AstarColor.ConnectionHighLerp, ((float)nodeR.G-AstarPath.active.debugFloor) / (AstarPath.active.debugRoof-AstarPath.active.debugFloor));
break;
case GraphDebugMode.H:
c = Color.Lerp (AstarColor.ConnectionLowLerp,AstarColor.ConnectionHighLerp, ((float)nodeR.H-AstarPath.active.debugFloor) / (AstarPath.active.debugRoof-AstarPath.active.debugFloor));
break;
case GraphDebugMode.F:
c = Color.Lerp (AstarColor.ConnectionLowLerp,AstarColor.ConnectionHighLerp, ((float)nodeR.F-AstarPath.active.debugFloor) / (AstarPath.active.debugRoof-AstarPath.active.debugFloor));
break;
}
break;
}
c.a *= 0.5F;
return c;
}
/** Serializes graph type specific node data.
* This function can be overriden to serialize extra node information (or graph information for that matter)
* which cannot be serialized using the standard serialization.
* Serialize the data in any way you want and return a byte array.
* When loading, the exact same byte array will be passed to the DeserializeExtraInfo function.\n
* These functions will only be called if node serialization is enabled.\n
*/
public virtual void SerializeExtraInfo (GraphSerializationContext ctx) {
}
/** Deserializes graph type specific node data.
* \see SerializeExtraInfo
*/
public virtual void DeserializeExtraInfo (GraphSerializationContext ctx) {
}
/** Called after all deserialization has been done for all graphs.
* Can be used to set up more graph data which is not serialized
*/
public virtual void PostDeserialization () {
}
#if ASTAR_NO_JSON
public virtual void SerializeSettings ( GraphSerializationContext ctx ) {
ctx.writer.Write (guid.ToByteArray());
ctx.writer.Write (initialPenalty);
ctx.writer.Write (open);
ctx.writer.Write (name ?? "");
ctx.writer.Write (drawGizmos);
ctx.writer.Write (infoScreenOpen);
for ( int i = 0; i < 4; i++ ) {
for ( int j = 0; j < 4; j++ ) {
ctx.writer.Write (matrix.GetRow(i)[j]);
}
}
}
public virtual void DeserializeSettings ( GraphSerializationContext ctx ) {
guid = new Guid(ctx.reader.ReadBytes (16));
initialPenalty = ctx.reader.ReadUInt32 ();
open = ctx.reader.ReadBoolean();
name = ctx.reader.ReadString();
drawGizmos = ctx.reader.ReadBoolean();
infoScreenOpen = ctx.reader.ReadBoolean();
for ( int i = 0; i < 4; i++ ) {
Vector4 row = Vector4.zero;
for ( int j = 0; j < 4; j++ ) {
row[j] = ctx.reader.ReadSingle ();
}
matrix.SetRow (i, row);
}
}
#endif
/** Returns if the node is in the search tree of the path.
* Only guaranteed to be correct if \a path is the latest path calculated.
* Use for gizmo drawing only.
*/
public static bool InSearchTree (GraphNode node, Path path) {
if (path == null || path.pathHandler == null) return true;
PathNode nodeR = path.pathHandler.GetPathNode (node);
return nodeR.pathID == path.pathID;
}
/** Draw gizmos for the graph */
public virtual void OnDrawGizmos (bool drawNodes) {
if (!drawNodes) {
return;
}
PathHandler data = AstarPath.active.debugPathData;
GraphNode node = null;
// Use this delegate to draw connections
// from the #node variable to #otherNode
GraphNodeDelegate drawConnection = otherNode => Gizmos.DrawLine((Vector3)node.position, (Vector3)otherNode.position);
GetNodes (_node => {
// Set the #node variable so that #drawConnection can use it
node = _node;
Gizmos.color = NodeColor (node, AstarPath.active.debugPathData);
if (AstarPath.active.showSearchTree && !InSearchTree(node,AstarPath.active.debugPath)) return true;
PathNode nodeR = data != null ? data.GetPathNode (node) : null;
if (AstarPath.active.showSearchTree && nodeR != null && nodeR.parent != null) {
Gizmos.DrawLine ((Vector3)node.position,(Vector3)nodeR.parent.node.position);
} else {
node.GetConnections (drawConnection);
}
return true;
});
}
}
/** Handles collision checking for graphs.
* Mostly used by grid based graphs */
[System.Serializable]
public class GraphCollision {
/** Collision shape to use.
* Pathfinding.ColliderType */
public ColliderType type = ColliderType.Capsule;
/** Diameter of capsule or sphere when checking for collision.
* 1 equals \link Pathfinding.GridGraph.nodeSize nodeSize \endlink.
* If #type is set to Ray, this does not affect anything */
public float diameter = 1F;
/** Height of capsule or length of ray when checking for collision.
* If #type is set to Sphere, this does not affect anything
*/
public float height = 2F;
public float collisionOffset;
/** Direction of the ray when checking for collision.
* If #type is not Ray, this does not affect anything
* \note This variable is not used currently, it does not affect anything
*/
public RayDirection rayDirection = RayDirection.Both;
/** Layer mask to use for collision check.
* This should only contain layers of objects defined as obstacles */
public LayerMask mask;
/** Layer mask to use for height check. */
public LayerMask heightMask = -1;
/** The height to check from when checking height */
public float fromHeight = 100;
/** Toggles thick raycast */
public bool thickRaycast;
/** Diameter of the thick raycast in nodes.
* 1 equals \link Pathfinding.GridGraph.nodeSize nodeSize \endlink */
public float thickRaycastDiameter = 1;
/** Make nodes unwalkable when no ground was found with the height raycast. If height raycast is turned off, this doesn't affect anything. */
public bool unwalkableWhenNoGround = true;
/** Use Unity 2D Physics API.
* \see http://docs.unity3d.com/ScriptReference/Physics2D.html
*/
public bool use2D;
/** Toggle collision check */
public bool collisionCheck = true;
/** Toggle height check. If false, the grid will be flat */
public bool heightCheck = true;
/** Direction to use as \a UP.
* \see Initialize */
public Vector3 up;
/** #up * #height.
* \see Initialize */
private Vector3 upheight;
/** #diameter * scale * 0.5.
* Where \a scale usually is \link Pathfinding.GridGraph.nodeSize nodeSize \endlink
* \see Initialize */
private float finalRadius;
/** #thickRaycastDiameter * scale * 0.5. Where \a scale usually is \link Pathfinding.GridGraph.nodeSize nodeSize \endlink \see Initialize */
private float finalRaycastRadius;
/** Offset to apply after each raycast to make sure we don't hit the same point again in CheckHeightAll */
public const float RaycastErrorMargin = 0.005F;
/** Sets up several variables using the specified matrix and scale.
* \see GraphCollision.up
* \see GraphCollision.upheight
* \see GraphCollision.finalRadius
* \see GraphCollision.finalRaycastRadius
*/
public void Initialize (Matrix4x4 matrix, float scale) {
up = matrix.MultiplyVector (Vector3.up);
upheight = up*height;
finalRadius = diameter*scale*0.5F;
finalRaycastRadius = thickRaycastDiameter*scale*0.5F;
}
/** Returns if the position is obstructed.
* If #collisionCheck is false, this will always return true.\n
*/
public bool Check (Vector3 position) {
if (!collisionCheck) {
return true;
}
if ( use2D ) {
switch (type) {
case ColliderType.Capsule:
throw new System.Exception ("Capsule mode cannot be used with 2D since capsules don't exist in 2D. Please change the Physics Testing -> Collider Type setting.");
case ColliderType.Sphere:
return Physics2D.OverlapCircle (position, finalRadius, mask) == null;
default:
return Physics2D.OverlapPoint ( position, mask ) == null;
}
}
position += up*collisionOffset;
switch (type) {
case ColliderType.Capsule:
return !Physics.CheckCapsule (position, position+upheight,finalRadius,mask);
case ColliderType.Sphere:
return !Physics.CheckSphere (position, finalRadius,mask);
default:
switch (rayDirection) {
case RayDirection.Both:
return !Physics.Raycast (position, up, height, mask) && !Physics.Raycast (position+upheight, -up, height, mask);
case RayDirection.Up:
return !Physics.Raycast (position, up, height, mask);
default:
return !Physics.Raycast (position+upheight, -up, height, mask);
}
}
}
/** Returns the position with the correct height. If #heightCheck is false, this will return \a position.\n */
public Vector3 CheckHeight (Vector3 position) {
RaycastHit hit;
bool walkable;
return CheckHeight (position,out hit, out walkable);
}
/** Returns the position with the correct height.
* If #heightCheck is false, this will return \a position.\n
* \a walkable will be set to false if nothing was hit.
* The ray will check a tiny bit further than to the grids base to avoid floating point errors when the ground is exactly at the base of the grid */
public Vector3 CheckHeight (Vector3 position, out RaycastHit hit, out bool walkable) {
walkable = true;
if (!heightCheck || use2D ) {
hit = new RaycastHit ();
return position;
}
if (thickRaycast) {
var ray = new Ray (position+up*fromHeight,-up);
if (Physics.SphereCast (ray, finalRaycastRadius,out hit, fromHeight+0.005F, heightMask)) {
return AstarMath.NearestPoint (ray.origin,ray.origin+ray.direction,hit.point);
}
walkable &= !unwalkableWhenNoGround;
} else {
// Cast a ray from above downwards to try to find the ground
if (Physics.Raycast (position+up*fromHeight, -up,out hit, fromHeight+0.005F, heightMask)) {
return hit.point;
}
walkable &= !unwalkableWhenNoGround;
}
return position;
}
/** Same as #CheckHeight, except that the raycast will always start exactly at \a origin.
* \a walkable will be set to false if nothing was hit.
* The ray will check a tiny bit further than to the grids base to avoid floating point errors when the ground is exactly at the base of the grid */
public Vector3 Raycast (Vector3 origin, out RaycastHit hit, out bool walkable) {
walkable = true;
if (!heightCheck || use2D ) {
hit = new RaycastHit ();
return origin -up*fromHeight;
}
if (thickRaycast) {
var ray = new Ray (origin,-up);
if (Physics.SphereCast (ray, finalRaycastRadius,out hit, fromHeight+0.005F, heightMask)) {
return AstarMath.NearestPoint (ray.origin,ray.origin+ray.direction,hit.point);
}
walkable &= !unwalkableWhenNoGround;
} else {
if (Physics.Raycast (origin, -up,out hit, fromHeight+0.005F, heightMask)) {
return hit.point;
}
walkable &= !unwalkableWhenNoGround;
}
return origin -up*fromHeight;
}
/** Returns all hits when checking height for \a position.
* \warning Does not work well with thick raycast, will only return an object a single time
*/
public RaycastHit[] CheckHeightAll (Vector3 position) {
if (!heightCheck || use2D) {
var hit = new RaycastHit ();
hit.point = position;
hit.distance = 0;
return new [] {hit};
}
if (thickRaycast) {
return new RaycastHit[0];
}
var hits = new List<RaycastHit>();
bool walkable;
Vector3 cpos = position + up*fromHeight;
Vector3 prevHit = Vector3.zero;
int numberSame = 0;
while (true) {
RaycastHit hit;
Raycast (cpos, out hit, out walkable);
if (hit.transform == null) { //Raycast did not hit anything
break;
}
//Make sure we didn't hit the same position
if (hit.point != prevHit || hits.Count == 0) {
cpos = hit.point - up*RaycastErrorMargin;
prevHit = hit.point;
numberSame = 0;
hits.Add (hit);
} else {
cpos -= up*0.001F;
numberSame++;
//Check if we are hitting the same position all the time, even though we are decrementing the cpos variable
if (numberSame > 10) {
Debug.LogError ("Infinite Loop when raycasting. Please report this error (arongranberg.com)\n"+cpos+" : "+prevHit);
break;
}
}
}
return hits.ToArray ();
}
public void SerializeSettings ( GraphSerializationContext ctx ) {
ctx.writer.Write ((int)type);
ctx.writer.Write (diameter);
ctx.writer.Write (height);
ctx.writer.Write (collisionOffset);
ctx.writer.Write ((int)rayDirection);
ctx.writer.Write ((int)mask);
ctx.writer.Write ((int)heightMask);
ctx.writer.Write (fromHeight);
ctx.writer.Write (thickRaycast);
ctx.writer.Write (thickRaycastDiameter);
ctx.writer.Write (unwalkableWhenNoGround);
ctx.writer.Write (use2D);
ctx.writer.Write (collisionCheck);
ctx.writer.Write (heightCheck);
}
public void DeserializeSettings ( GraphSerializationContext ctx ) {
type = (ColliderType)ctx.reader.ReadInt32();
diameter = ctx.reader.ReadSingle ();
height = ctx.reader.ReadSingle ();
collisionOffset = ctx.reader.ReadSingle ();
rayDirection = (RayDirection)ctx.reader.ReadInt32 ();
mask = (LayerMask)ctx.reader.ReadInt32 ();
heightMask = (LayerMask)ctx.reader.ReadInt32 ();
fromHeight = ctx.reader.ReadSingle ();
thickRaycast = ctx.reader.ReadBoolean ();
thickRaycastDiameter = ctx.reader.ReadSingle ();
unwalkableWhenNoGround = ctx.reader.ReadBoolean();
use2D = ctx.reader.ReadBoolean();
collisionCheck = ctx.reader.ReadBoolean();
heightCheck = ctx.reader.ReadBoolean();
}
}
/** Determines collision check shape */
public enum ColliderType {
Sphere, /**< Uses a Sphere, Physics.CheckSphere */
Capsule, /**< Uses a Capsule, Physics.CheckCapsule */
Ray /**< Uses a Ray, Physics.Linecast */
}
/** Determines collision check ray direction */
public enum RayDirection {
Up, /**< Casts the ray from the bottom upwards */
Down, /**< Casts the ray from the top downwards */
Both /**< Casts two rays in both directions */
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Statistics;
using OpenSim.Services.Interfaces;
namespace OpenSim.Framework.Communications.Services
{
public abstract class LoginService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_welcomeMessage = "Welcome to OpenSim";
protected int m_minLoginLevel = 0;
protected UserManagerBase m_userManager = null;
protected Mutex m_loginMutex = new Mutex(false);
/// <summary>
/// Used during login to send the skeleton of the OpenSim Library to the client.
/// </summary>
protected LibraryRootFolder m_libraryRootFolder;
protected uint m_defaultHomeX;
protected uint m_defaultHomeY;
protected bool m_warn_already_logged = true;
/// <summary>
/// Used by the login service to make requests to the inventory service.
/// </summary>
protected IInterServiceInventoryServices m_interInventoryService;
// Hack
protected IInventoryService m_InventoryService;
/// <summary>
/// Constructor
/// </summary>
/// <param name="userManager"></param>
/// <param name="libraryRootFolder"></param>
/// <param name="welcomeMess"></param>
public LoginService(UserManagerBase userManager, LibraryRootFolder libraryRootFolder,
string welcomeMess)
{
m_userManager = userManager;
m_libraryRootFolder = libraryRootFolder;
if (welcomeMess != String.Empty)
{
m_welcomeMessage = welcomeMess;
}
}
/// <summary>
/// If the user is already logged in, try to notify the region that the user they've got is dead.
/// </summary>
/// <param name="theUser"></param>
public virtual void LogOffUser(UserProfileData theUser, string message)
{
}
/// <summary>
/// Called when we receive the client's initial XMLRPC login_to_simulator request message
/// </summary>
/// <param name="request">The XMLRPC request</param>
/// <returns>The response to send</returns>
public virtual XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
// Temporary fix
m_loginMutex.WaitOne();
try
{
//CFK: CustomizeResponse contains sufficient strings to alleviate the need for this.
//CKF: m_log.Info("[LOGIN]: Attempting login now...");
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable)request.Params[0];
SniffLoginKey((Uri)request.Params[2], requestData);
bool GoodXML = (requestData.Contains("first") && requestData.Contains("last") &&
(requestData.Contains("passwd") || requestData.Contains("web_login_key")));
string startLocationRequest = "last";
UserProfileData userProfile;
LoginResponse logResponse = new LoginResponse();
string firstname;
string lastname;
if (GoodXML)
{
if (requestData.Contains("start"))
{
startLocationRequest = (string)requestData["start"];
}
firstname = (string)requestData["first"];
lastname = (string)requestData["last"];
m_log.InfoFormat(
"[LOGIN BEGIN]: XMLRPC Received login request message from user '{0}' '{1}'",
firstname, lastname);
string clientVersion = "Unknown";
if (requestData.Contains("version"))
{
clientVersion = (string)requestData["version"];
}
m_log.DebugFormat(
"[LOGIN]: XMLRPC Client is {0}, start location is {1}", clientVersion, startLocationRequest);
if (!TryAuthenticateXmlRpcLogin(request, firstname, lastname, out userProfile))
{
return logResponse.CreateLoginFailedResponse();
}
}
else
{
m_log.Info(
"[LOGIN END]: XMLRPC login_to_simulator login message did not contain all the required data");
return logResponse.CreateGridErrorResponse();
}
if (userProfile.GodLevel < m_minLoginLevel)
{
return logResponse.CreateLoginBlockedResponse();
}
else
{
// If we already have a session...
if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline)
{
//TODO: The following statements can cause trouble:
// If agentOnline could not turn from true back to false normally
// because of some problem, for instance, the crashment of server or client,
// the user cannot log in any longer.
userProfile.CurrentAgent.AgentOnline = false;
m_userManager.CommitAgent(ref userProfile);
// try to tell the region that their user is dead.
LogOffUser(userProfile, " XMLRPC You were logged off because you logged in from another location");
if (m_warn_already_logged)
{
// This is behavior for for grid, reject login
m_log.InfoFormat(
"[LOGIN END]: XMLRPC Notifying user {0} {1} that they are already logged in",
firstname, lastname);
return logResponse.CreateAlreadyLoggedInResponse();
}
else
{
// This is behavior for standalone (silent logout of last hung session)
m_log.InfoFormat(
"[LOGIN]: XMLRPC User {0} {1} is already logged in, not notifying user, kicking old presence and starting new login.",
firstname, lastname);
}
}
// Otherwise...
// Create a new agent session
// XXYY we don't need this
//m_userManager.ResetAttachments(userProfile.ID);
CreateAgent(userProfile, request);
// We need to commit the agent right here, even though the userProfile info is not complete
// at this point. There is another commit further down.
// This is for the new sessionID to be stored so that the region can check it for session authentication.
// CustomiseResponse->PrepareLoginToRegion
CommitAgent(ref userProfile);
try
{
UUID agentID = userProfile.ID;
InventoryData inventData = null;
try
{
inventData = GetInventorySkeleton(agentID);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[LOGIN END]: Error retrieving inventory skeleton of agent {0} - {1}",
agentID, e);
// Let's not panic
if (!AllowLoginWithoutInventory())
return logResponse.CreateLoginInventoryFailedResponse();
}
if (inventData != null)
{
ArrayList AgentInventoryArray = inventData.InventoryArray;
Hashtable InventoryRootHash = new Hashtable();
InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString();
ArrayList InventoryRoot = new ArrayList();
InventoryRoot.Add(InventoryRootHash);
logResponse.InventoryRoot = InventoryRoot;
logResponse.InventorySkeleton = AgentInventoryArray;
}
// Inventory Library Section
Hashtable InventoryLibRootHash = new Hashtable();
InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000";
ArrayList InventoryLibRoot = new ArrayList();
InventoryLibRoot.Add(InventoryLibRootHash);
logResponse.InventoryLibRoot = InventoryLibRoot;
logResponse.InventoryLibraryOwner = GetLibraryOwner();
logResponse.InventoryLibrary = GetInventoryLibrary();
logResponse.CircuitCode = Util.RandomClass.Next();
logResponse.Lastname = userProfile.SurName;
logResponse.Firstname = userProfile.FirstName;
logResponse.AgentID = agentID;
logResponse.SessionID = userProfile.CurrentAgent.SessionID;
logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID;
logResponse.Message = GetMessage();
logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID));
logResponse.StartLocation = startLocationRequest;
if (CustomiseResponse(logResponse, userProfile, startLocationRequest, remoteClient))
{
userProfile.LastLogin = userProfile.CurrentAgent.LoginTime;
CommitAgent(ref userProfile);
// If we reach this point, then the login has successfully logged onto the grid
if (StatsManager.UserStats != null)
StatsManager.UserStats.AddSuccessfulLogin();
m_log.DebugFormat(
"[LOGIN END]: XMLRPC Authentication of user {0} {1} successful. Sending response to client.",
firstname, lastname);
return logResponse.ToXmlRpcResponse();
}
else
{
m_log.ErrorFormat("[LOGIN END]: XMLRPC informing user {0} {1} that login failed due to an unavailable region", firstname, lastname);
return logResponse.CreateDeadRegionResponse();
}
}
catch (Exception e)
{
m_log.Error("[LOGIN END]: XMLRPC Login failed, " + e);
m_log.Error(e.StackTrace);
}
}
m_log.Info("[LOGIN END]: XMLRPC Login failed. Sending back blank XMLRPC response");
return response;
}
finally
{
m_loginMutex.ReleaseMutex();
}
}
protected virtual bool TryAuthenticateXmlRpcLogin(
XmlRpcRequest request, string firstname, string lastname, out UserProfileData userProfile)
{
Hashtable requestData = (Hashtable)request.Params[0];
userProfile = GetTheUser(firstname, lastname);
if (userProfile == null)
{
m_log.Debug("[LOGIN END]: XMLRPC Could not find a profile for " + firstname + " " + lastname);
return false;
}
else
{
if (requestData.Contains("passwd"))
{
string passwd = (string)requestData["passwd"];
bool authenticated = AuthenticateUser(userProfile, passwd);
if (!authenticated)
m_log.DebugFormat("[LOGIN END]: XMLRPC User {0} {1} failed password authentication",
firstname, lastname);
return authenticated;
}
if (requestData.Contains("web_login_key"))
{
try
{
UUID webloginkey = new UUID((string)requestData["web_login_key"]);
bool authenticated = AuthenticateUser(userProfile, webloginkey);
if (!authenticated)
m_log.DebugFormat("[LOGIN END]: XMLRPC User {0} {1} failed web login key authentication",
firstname, lastname);
return authenticated;
}
catch (Exception e)
{
m_log.DebugFormat(
"[LOGIN END]: XMLRPC Bad web_login_key: {0} for user {1} {2}, exception {3}",
requestData["web_login_key"], firstname, lastname, e);
return false;
}
}
m_log.DebugFormat(
"[LOGIN END]: XMLRPC login request for {0} {1} contained neither a password nor a web login key",
firstname, lastname);
}
return false;
}
protected virtual bool TryAuthenticateLLSDLogin(string firstname, string lastname, string passwd, out UserProfileData userProfile)
{
bool GoodLogin = false;
userProfile = GetTheUser(firstname, lastname);
if (userProfile == null)
{
m_log.Info("[LOGIN]: LLSD Could not find a profile for " + firstname + " " + lastname);
return false;
}
GoodLogin = AuthenticateUser(userProfile, passwd);
return GoodLogin;
}
/// <summary>
/// Called when we receive the client's initial LLSD login_to_simulator request message
/// </summary>
/// <param name="request">The LLSD request</param>
/// <returns>The response to send</returns>
public OSD LLSDLoginMethod(OSD request, IPEndPoint remoteClient)
{
// Temporary fix
m_loginMutex.WaitOne();
try
{
// bool GoodLogin = false;
string startLocationRequest = "last";
UserProfileData userProfile = null;
LoginResponse logResponse = new LoginResponse();
if (request.Type == OSDType.Map)
{
OSDMap map = (OSDMap)request;
if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd"))
{
string firstname = map["first"].AsString();
string lastname = map["last"].AsString();
string passwd = map["passwd"].AsString();
if (map.ContainsKey("start"))
{
m_log.Info("[LOGIN]: LLSD StartLocation Requested: " + map["start"].AsString());
startLocationRequest = map["start"].AsString();
}
m_log.Info("[LOGIN]: LLSD Login Requested for: '" + firstname + "' '" + lastname + "' / " + passwd);
if (!TryAuthenticateLLSDLogin(firstname, lastname, passwd, out userProfile))
{
return logResponse.CreateLoginFailedResponseLLSD();
}
}
else
return logResponse.CreateLoginFailedResponseLLSD();
}
else
return logResponse.CreateLoginFailedResponseLLSD();
if (userProfile.GodLevel < m_minLoginLevel)
{
return logResponse.CreateLoginBlockedResponseLLSD();
}
else
{
// If we already have a session...
if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline)
{
userProfile.CurrentAgent.AgentOnline = false;
m_userManager.CommitAgent(ref userProfile);
// try to tell the region that their user is dead.
LogOffUser(userProfile, " LLSD You were logged off because you logged in from another location");
if (m_warn_already_logged)
{
// This is behavior for for grid, reject login
m_log.InfoFormat(
"[LOGIN END]: LLSD Notifying user {0} {1} that they are already logged in",
userProfile.FirstName, userProfile.SurName);
userProfile.CurrentAgent = null;
return logResponse.CreateAlreadyLoggedInResponseLLSD();
}
else
{
// This is behavior for standalone (silent logout of last hung session)
m_log.InfoFormat(
"[LOGIN]: LLSD User {0} {1} is already logged in, not notifying user, kicking old presence and starting new login.",
userProfile.FirstName, userProfile.SurName);
}
}
// Otherwise...
// Create a new agent session
// XXYY We don't need this
//m_userManager.ResetAttachments(userProfile.ID);
CreateAgent(userProfile, request);
// We need to commit the agent right here, even though the userProfile info is not complete
// at this point. There is another commit further down.
// This is for the new sessionID to be stored so that the region can check it for session authentication.
// CustomiseResponse->PrepareLoginToRegion
CommitAgent(ref userProfile);
try
{
UUID agentID = userProfile.ID;
//InventoryData inventData = GetInventorySkeleton(agentID);
InventoryData inventData = null;
try
{
inventData = GetInventorySkeleton(agentID);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[LOGIN END]: LLSD Error retrieving inventory skeleton of agent {0}, {1} - {2}",
agentID, e.GetType(), e.Message);
return logResponse.CreateLoginFailedResponseLLSD();// .CreateLoginInventoryFailedResponseLLSD ();
}
ArrayList AgentInventoryArray = inventData.InventoryArray;
Hashtable InventoryRootHash = new Hashtable();
InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString();
ArrayList InventoryRoot = new ArrayList();
InventoryRoot.Add(InventoryRootHash);
// Inventory Library Section
Hashtable InventoryLibRootHash = new Hashtable();
InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000";
ArrayList InventoryLibRoot = new ArrayList();
InventoryLibRoot.Add(InventoryLibRootHash);
logResponse.InventoryLibRoot = InventoryLibRoot;
logResponse.InventoryLibraryOwner = GetLibraryOwner();
logResponse.InventoryRoot = InventoryRoot;
logResponse.InventorySkeleton = AgentInventoryArray;
logResponse.InventoryLibrary = GetInventoryLibrary();
logResponse.CircuitCode = (Int32)Util.RandomClass.Next();
logResponse.Lastname = userProfile.SurName;
logResponse.Firstname = userProfile.FirstName;
logResponse.AgentID = agentID;
logResponse.SessionID = userProfile.CurrentAgent.SessionID;
logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID;
logResponse.Message = GetMessage();
logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID));
logResponse.StartLocation = startLocationRequest;
try
{
CustomiseResponse(logResponse, userProfile, startLocationRequest, remoteClient);
}
catch (Exception ex)
{
m_log.Info("[LOGIN]: LLSD " + ex.ToString());
return logResponse.CreateDeadRegionResponseLLSD();
}
userProfile.LastLogin = userProfile.CurrentAgent.LoginTime;
CommitAgent(ref userProfile);
// If we reach this point, then the login has successfully logged onto the grid
if (StatsManager.UserStats != null)
StatsManager.UserStats.AddSuccessfulLogin();
m_log.DebugFormat(
"[LOGIN END]: LLSD Authentication of user {0} {1} successful. Sending response to client.",
userProfile.FirstName, userProfile.SurName);
return logResponse.ToLLSDResponse();
}
catch (Exception ex)
{
m_log.Info("[LOGIN]: LLSD " + ex.ToString());
return logResponse.CreateFailedResponseLLSD();
}
}
}
finally
{
m_loginMutex.ReleaseMutex();
}
}
public Hashtable ProcessHTMLLogin(Hashtable keysvals)
{
// Matches all unspecified characters
// Currently specified,; lowercase letters, upper case letters, numbers, underline
// period, space, parens, and dash.
Regex wfcut = new Regex("[^a-zA-Z0-9_\\.\\$ \\(\\)\\-]");
Hashtable returnactions = new Hashtable();
int statuscode = 200;
string firstname = String.Empty;
string lastname = String.Empty;
string location = String.Empty;
string region = String.Empty;
string grid = String.Empty;
string channel = String.Empty;
string version = String.Empty;
string lang = String.Empty;
string password = String.Empty;
string errormessages = String.Empty;
// the client requires the HTML form field be named 'username'
// however, the data it sends when it loads the first time is 'firstname'
// another one of those little nuances.
if (keysvals.Contains("firstname"))
firstname = wfcut.Replace((string)keysvals["firstname"], String.Empty, 99999);
if (keysvals.Contains("username"))
firstname = wfcut.Replace((string)keysvals["username"], String.Empty, 99999);
if (keysvals.Contains("lastname"))
lastname = wfcut.Replace((string)keysvals["lastname"], String.Empty, 99999);
if (keysvals.Contains("location"))
location = wfcut.Replace((string)keysvals["location"], String.Empty, 99999);
if (keysvals.Contains("region"))
region = wfcut.Replace((string)keysvals["region"], String.Empty, 99999);
if (keysvals.Contains("grid"))
grid = wfcut.Replace((string)keysvals["grid"], String.Empty, 99999);
if (keysvals.Contains("channel"))
channel = wfcut.Replace((string)keysvals["channel"], String.Empty, 99999);
if (keysvals.Contains("version"))
version = wfcut.Replace((string)keysvals["version"], String.Empty, 99999);
if (keysvals.Contains("lang"))
lang = wfcut.Replace((string)keysvals["lang"], String.Empty, 99999);
if (keysvals.Contains("password"))
password = wfcut.Replace((string)keysvals["password"], String.Empty, 99999);
// load our login form.
string loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages);
if (keysvals.ContainsKey("show_login_form"))
{
UserProfileData user = GetTheUser(firstname, lastname);
bool goodweblogin = false;
if (user != null)
goodweblogin = AuthenticateUser(user, password);
if (goodweblogin)
{
UUID webloginkey = UUID.Random();
m_userManager.StoreWebLoginKey(user.ID, webloginkey);
//statuscode = 301;
// string redirectURL = "about:blank?redirect-http-hack=" +
// HttpUtility.UrlEncode("secondlife:///app/login?first_name=" + firstname + "&last_name=" +
// lastname +
// "&location=" + location + "&grid=Other&web_login_key=" + webloginkey.ToString());
//m_log.Info("[WEB]: R:" + redirectURL);
returnactions["int_response_code"] = statuscode;
//returnactions["str_redirect_location"] = redirectURL;
//returnactions["str_response_string"] = "<HTML><BODY>GoodLogin</BODY></HTML>";
returnactions["str_response_string"] = webloginkey.ToString();
}
else
{
errormessages = "The Username and password supplied did not match our records. Check your caps lock and try again";
loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages);
returnactions["int_response_code"] = statuscode;
returnactions["str_response_string"] = loginform;
}
}
else
{
returnactions["int_response_code"] = statuscode;
returnactions["str_response_string"] = loginform;
}
return returnactions;
}
public string GetLoginForm(string firstname, string lastname, string location, string region,
string grid, string channel, string version, string lang,
string password, string errormessages)
{
// inject our values in the form at the markers
string loginform = String.Empty;
string file = Path.Combine(Util.configDir(), "http_loginform.html");
if (!File.Exists(file))
{
loginform = GetDefaultLoginForm();
}
else
{
StreamReader sr = File.OpenText(file);
loginform = sr.ReadToEnd();
sr.Close();
}
loginform = loginform.Replace("[$firstname]", firstname);
loginform = loginform.Replace("[$lastname]", lastname);
loginform = loginform.Replace("[$location]", location);
loginform = loginform.Replace("[$region]", region);
loginform = loginform.Replace("[$grid]", grid);
loginform = loginform.Replace("[$channel]", channel);
loginform = loginform.Replace("[$version]", version);
loginform = loginform.Replace("[$lang]", lang);
loginform = loginform.Replace("[$password]", password);
loginform = loginform.Replace("[$errors]", errormessages);
return loginform;
}
public string GetDefaultLoginForm()
{
string responseString =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
responseString += "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
responseString += "<head>";
responseString += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
responseString += "<meta http-equiv=\"cache-control\" content=\"no-cache\">";
responseString += "<meta http-equiv=\"Pragma\" content=\"no-cache\">";
responseString += "<title>OpenSim Login</title>";
responseString += "<body><br />";
responseString += "<div id=\"login_box\">";
responseString += "<form action=\"/go.cgi\" method=\"GET\" id=\"login-form\">";
responseString += "<div id=\"message\">[$errors]</div>";
responseString += "<fieldset id=\"firstname\">";
responseString += "<legend>First Name:</legend>";
responseString += "<input type=\"text\" id=\"firstname_input\" size=\"15\" maxlength=\"100\" name=\"username\" value=\"[$firstname]\" />";
responseString += "</fieldset>";
responseString += "<fieldset id=\"lastname\">";
responseString += "<legend>Last Name:</legend>";
responseString += "<input type=\"text\" size=\"15\" maxlength=\"100\" name=\"lastname\" value=\"[$lastname]\" />";
responseString += "</fieldset>";
responseString += "<fieldset id=\"password\">";
responseString += "<legend>Password:</legend>";
responseString += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
responseString += "<tr>";
responseString += "<td colspan=\"2\"><input type=\"password\" size=\"15\" maxlength=\"100\" name=\"password\" value=\"[$password]\" /></td>";
responseString += "</tr>";
responseString += "<tr>";
responseString += "<td valign=\"middle\"><input type=\"checkbox\" name=\"remember_password\" id=\"remember_password\" [$remember_password] style=\"margin-left:0px;\"/></td>";
responseString += "<td><label for=\"remember_password\">Remember password</label></td>";
responseString += "</tr>";
responseString += "</table>";
responseString += "</fieldset>";
responseString += "<input type=\"hidden\" name=\"show_login_form\" value=\"FALSE\" />";
responseString += "<input type=\"hidden\" name=\"method\" value=\"login\" />";
responseString += "<input type=\"hidden\" id=\"grid\" name=\"grid\" value=\"[$grid]\" />";
responseString += "<input type=\"hidden\" id=\"region\" name=\"region\" value=\"[$region]\" />";
responseString += "<input type=\"hidden\" id=\"location\" name=\"location\" value=\"[$location]\" />";
responseString += "<input type=\"hidden\" id=\"channel\" name=\"channel\" value=\"[$channel]\" />";
responseString += "<input type=\"hidden\" id=\"version\" name=\"version\" value=\"[$version]\" />";
responseString += "<input type=\"hidden\" id=\"lang\" name=\"lang\" value=\"[$lang]\" />";
responseString += "<div id=\"submitbtn\">";
responseString += "<input class=\"input_over\" type=\"submit\" value=\"Connect\" />";
responseString += "</div>";
responseString += "<div id=\"connecting\" style=\"visibility:hidden\"> Connecting...</div>";
responseString += "<div id=\"helplinks\"><!---";
responseString += "<a href=\"#join now link\" target=\"_blank\"></a> | ";
responseString += "<a href=\"#forgot password link\" target=\"_blank\"></a>";
responseString += "---></div>";
responseString += "<div id=\"channelinfo\"> [$channel] | [$version]=[$lang]</div>";
responseString += "</form>";
responseString += "<script language=\"JavaScript\">";
responseString += "document.getElementById('firstname_input').focus();";
responseString += "</script>";
responseString += "</div>";
responseString += "</div>";
responseString += "</body>";
responseString += "</html>";
return responseString;
}
/// <summary>
/// Saves a target agent to the database
/// </summary>
/// <param name="profile">The users profile</param>
/// <returns>Successful?</returns>
public bool CommitAgent(ref UserProfileData profile)
{
return m_userManager.CommitAgent(ref profile);
}
/// <summary>
/// Checks a user against it's password hash
/// </summary>
/// <param name="profile">The users profile</param>
/// <param name="password">The supplied password</param>
/// <returns>Authenticated?</returns>
public virtual bool AuthenticateUser(UserProfileData profile, string password)
{
bool passwordSuccess = false;
//m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID);
// Web Login method seems to also occasionally send the hashed password itself
// we do this to get our hash in a form that the server password code can consume
// when the web-login-form submits the password in the clear (supposed to be over SSL!)
if (!password.StartsWith("$1$"))
password = "$1$" + Util.Md5Hash(password);
password = password.Remove(0, 3); //remove $1$
string s = Util.Md5Hash(password + ":" + profile.PasswordSalt);
// Testing...
//m_log.Info("[LOGIN]: SubHash:" + s + " userprofile:" + profile.passwordHash);
//m_log.Info("[LOGIN]: userprofile:" + profile.passwordHash + " SubCT:" + password);
passwordSuccess = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase)
|| profile.PasswordHash.Equals(password, StringComparison.InvariantCulture));
return passwordSuccess;
}
public virtual bool AuthenticateUser(UserProfileData profile, UUID webloginkey)
{
bool passwordSuccess = false;
m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID);
// Match web login key unless it's the default weblogin key UUID.Zero
passwordSuccess = ((profile.WebLoginKey == webloginkey) && profile.WebLoginKey != UUID.Zero);
return passwordSuccess;
}
/// <summary>
///
/// </summary>
/// <param name="profile"></param>
/// <param name="request"></param>
public void CreateAgent(UserProfileData profile, XmlRpcRequest request)
{
m_userManager.CreateAgent(profile, request);
}
public void CreateAgent(UserProfileData profile, OSD request)
{
m_userManager.CreateAgent(profile, request);
}
/// <summary>
///
/// </summary>
/// <param name="firstname"></param>
/// <param name="lastname"></param>
/// <returns></returns>
public virtual UserProfileData GetTheUser(string firstname, string lastname)
{
return m_userManager.GetUserProfile(firstname, lastname);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual string GetMessage()
{
return m_welcomeMessage;
}
private static LoginResponse.BuddyList ConvertFriendListItem(List<FriendListItem> LFL)
{
LoginResponse.BuddyList buddylistreturn = new LoginResponse.BuddyList();
foreach (FriendListItem fl in LFL)
{
LoginResponse.BuddyList.BuddyInfo buddyitem = new LoginResponse.BuddyList.BuddyInfo(fl.Friend);
buddyitem.BuddyID = fl.Friend;
buddyitem.BuddyRightsHave = (int)fl.FriendListOwnerPerms;
buddyitem.BuddyRightsGiven = (int)fl.FriendPerms;
buddylistreturn.AddNewBuddy(buddyitem);
}
return buddylistreturn;
}
/// <summary>
/// Converts the inventory library skeleton into the form required by the rpc request.
/// </summary>
/// <returns></returns>
protected virtual ArrayList GetInventoryLibrary()
{
Dictionary<UUID, InventoryFolderImpl> rootFolders
= m_libraryRootFolder.RequestSelfAndDescendentFolders();
ArrayList folderHashes = new ArrayList();
foreach (InventoryFolderBase folder in rootFolders.Values)
{
Hashtable TempHash = new Hashtable();
TempHash["name"] = folder.Name;
TempHash["parent_id"] = folder.ParentID.ToString();
TempHash["version"] = (Int32)folder.Version;
TempHash["type_default"] = (Int32)folder.Type;
TempHash["folder_id"] = folder.ID.ToString();
folderHashes.Add(TempHash);
}
return folderHashes;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected virtual ArrayList GetLibraryOwner()
{
//for now create random inventory library owner
Hashtable TempHash = new Hashtable();
TempHash["agent_id"] = "11111111-1111-0000-0000-000100bba000";
ArrayList inventoryLibOwner = new ArrayList();
inventoryLibOwner.Add(TempHash);
return inventoryLibOwner;
}
public class InventoryData
{
public ArrayList InventoryArray = null;
public UUID RootFolderID = UUID.Zero;
public InventoryData(ArrayList invList, UUID rootID)
{
InventoryArray = invList;
RootFolderID = rootID;
}
}
protected void SniffLoginKey(Uri uri, Hashtable requestData)
{
string uri_str = uri.ToString();
string[] parts = uri_str.Split(new char[] { '=' });
if (parts.Length > 1)
{
string web_login_key = parts[1];
requestData.Add("web_login_key", web_login_key);
m_log.InfoFormat("[LOGIN]: Login with web_login_key {0}", web_login_key);
}
}
/// <summary>
/// Customises the login response and fills in missing values. This method also tells the login region to
/// expect a client connection.
/// </summary>
/// <param name="response">The existing response</param>
/// <param name="theUser">The user profile</param>
/// <param name="startLocationRequest">The requested start location</param>
/// <returns>true on success, false if the region was not successfully told to expect a user connection</returns>
public bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest, IPEndPoint client)
{
// add active gestures to login-response
AddActiveGestures(response, theUser);
// HomeLocation
RegionInfo homeInfo = null;
// use the homeRegionID if it is stored already. If not, use the regionHandle as before
UUID homeRegionId = theUser.HomeRegionID;
ulong homeRegionHandle = theUser.HomeRegion;
if (homeRegionId != UUID.Zero)
{
homeInfo = GetRegionInfo(homeRegionId);
}
else
{
homeInfo = GetRegionInfo(homeRegionHandle);
}
if (homeInfo != null)
{
response.Home =
string.Format(
"{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}",
(homeInfo.RegionLocX * Constants.RegionSize),
(homeInfo.RegionLocY * Constants.RegionSize),
theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z,
theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z);
}
else
{
m_log.InfoFormat("not found the region at {0} {1}", theUser.HomeRegionX, theUser.HomeRegionY);
// Emergency mode: Home-region isn't available, so we can't request the region info.
// Use the stored home regionHandle instead.
// NOTE: If the home-region moves, this will be wrong until the users update their user-profile again
ulong regionX = homeRegionHandle >> 32;
ulong regionY = homeRegionHandle & 0xffffffff;
response.Home =
string.Format(
"{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}",
regionX, regionY,
theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z,
theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z);
m_log.InfoFormat("[LOGIN] Home region of user {0} {1} is not available; using computed region position {2} {3}",
theUser.FirstName, theUser.SurName,
regionX, regionY);
}
// StartLocation
RegionInfo regionInfo = null;
if (startLocationRequest == "home")
{
regionInfo = homeInfo;
theUser.CurrentAgent.Position = theUser.HomeLocation;
response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.HomeLookAt.X.ToString(),
theUser.HomeLookAt.Y.ToString(), theUser.HomeLookAt.Z.ToString());
}
else if (startLocationRequest == "last")
{
UUID lastRegion = theUser.CurrentAgent.Region;
regionInfo = GetRegionInfo(lastRegion);
response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.CurrentAgent.LookAt.X.ToString(),
theUser.CurrentAgent.LookAt.Y.ToString(), theUser.CurrentAgent.LookAt.Z.ToString());
}
else
{
Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+)&(?<y>\d+)&(?<z>\d+)$");
Match uriMatch = reURI.Match(startLocationRequest);
if (uriMatch == null)
{
m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, but can't process it", startLocationRequest);
}
else
{
string region = uriMatch.Groups["region"].ToString();
regionInfo = RequestClosestRegion(region);
if (regionInfo == null)
{
m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, can't locate region {1}", startLocationRequest, region);
}
else
{
theUser.CurrentAgent.Position = new Vector3(float.Parse(uriMatch.Groups["x"].Value, Culture.NumberFormatInfo),
float.Parse(uriMatch.Groups["y"].Value, Culture.NumberFormatInfo), float.Parse(uriMatch.Groups["z"].Value, Culture.NumberFormatInfo));
}
}
response.LookAt = "[r0,r1,r0]";
// can be: last, home, safe, url
response.StartLocation = "url";
}
if ((regionInfo != null) && (PrepareLoginToRegion(regionInfo, theUser, response, client)))
{
return true;
}
// Get the default region handle
ulong defaultHandle = Utils.UIntsToLong(m_defaultHomeX * Constants.RegionSize, m_defaultHomeY * Constants.RegionSize);
// If we haven't already tried the default region, reset regionInfo
if (regionInfo != null && defaultHandle != regionInfo.RegionHandle)
regionInfo = null;
if (regionInfo == null)
{
m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead");
regionInfo = GetRegionInfo(defaultHandle);
}
if (regionInfo == null)
{
m_log.ErrorFormat("[LOGIN]: Sending user to any region");
regionInfo = RequestClosestRegion(String.Empty);
}
theUser.CurrentAgent.Position = new Vector3(128f, 128f, 0f);
response.StartLocation = "safe";
return PrepareLoginToRegion(regionInfo, theUser, response, client);
}
protected abstract RegionInfo RequestClosestRegion(string region);
protected abstract RegionInfo GetRegionInfo(ulong homeRegionHandle);
protected abstract RegionInfo GetRegionInfo(UUID homeRegionId);
/// <summary>
/// Prepare a login to the given region. This involves both telling the region to expect a connection
/// and appropriately customising the response to the user.
/// </summary>
/// <param name="sim"></param>
/// <param name="user"></param>
/// <param name="response"></param>
/// <param name="remoteClient"></param>
/// <returns>true if the region was successfully contacted, false otherwise</returns>
protected abstract bool PrepareLoginToRegion(
RegionInfo regionInfo, UserProfileData user, LoginResponse response, IPEndPoint client);
/// <summary>
/// Add active gestures of the user to the login response.
/// </summary>
/// <param name="response">
/// A <see cref="LoginResponse"/>
/// </param>
/// <param name="theUser">
/// A <see cref="UserProfileData"/>
/// </param>
protected void AddActiveGestures(LoginResponse response, UserProfileData theUser)
{
List<InventoryItemBase> gestures = null;
try
{
if (m_InventoryService != null)
gestures = m_InventoryService.GetActiveGestures(theUser.ID);
else
gestures = m_interInventoryService.GetActiveGestures(theUser.ID);
}
catch (Exception e)
{
m_log.Debug("[LOGIN]: Unable to retrieve active gestures from inventory server. Reason: " + e.Message);
}
//m_log.DebugFormat("[LOGIN]: AddActiveGestures, found {0}", gestures == null ? 0 : gestures.Count);
ArrayList list = new ArrayList();
if (gestures != null)
{
foreach (InventoryItemBase gesture in gestures)
{
Hashtable item = new Hashtable();
item["item_id"] = gesture.ID.ToString();
item["asset_id"] = gesture.AssetID.ToString();
list.Add(item);
}
}
response.ActiveGestures = list;
}
/// <summary>
/// Get the initial login inventory skeleton (in other words, the folder structure) for the given user.
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
/// <exception cref='System.Exception'>This will be thrown if there is a problem with the inventory service</exception>
protected InventoryData GetInventorySkeleton(UUID userID)
{
List<InventoryFolderBase> folders = null;
if (m_InventoryService != null)
{
folders = m_InventoryService.GetInventorySkeleton(userID);
}
else
{
folders = m_interInventoryService.GetInventorySkeleton(userID);
}
// If we have user auth but no inventory folders for some reason, create a new set of folders.
if (folders == null || folders.Count == 0)
{
m_log.InfoFormat(
"[LOGIN]: A root inventory folder for user {0} was not found. Requesting creation.", userID);
// Although the create user function creates a new agent inventory along with a new user profile, some
// tools are creating the user profile directly in the database without creating the inventory. At
// this time we'll accomodate them by lazily creating the user inventory now if it doesn't already
// exist.
if (m_interInventoryService != null)
{
if (!m_interInventoryService.CreateNewUserInventory(userID))
{
throw new Exception(
String.Format(
"The inventory creation request for user {0} did not succeed."
+ " Please contact your inventory service provider for more information.",
userID));
}
}
else if ((m_InventoryService != null) && !m_InventoryService.CreateUserInventory(userID))
{
throw new Exception(
String.Format(
"The inventory creation request for user {0} did not succeed."
+ " Please contact your inventory service provider for more information.",
userID));
}
m_log.InfoFormat("[LOGIN]: A new inventory skeleton was successfully created for user {0}", userID);
if (m_InventoryService != null)
folders = m_InventoryService.GetInventorySkeleton(userID);
else
folders = m_interInventoryService.GetInventorySkeleton(userID);
if (folders == null || folders.Count == 0)
{
throw new Exception(
String.Format(
"A root inventory folder for user {0} could not be retrieved from the inventory service",
userID));
}
}
UUID rootID = UUID.Zero;
ArrayList AgentInventoryArray = new ArrayList();
Hashtable TempHash;
foreach (InventoryFolderBase InvFolder in folders)
{
if (InvFolder.ParentID == UUID.Zero)
{
rootID = InvFolder.ID;
}
TempHash = new Hashtable();
TempHash["name"] = InvFolder.Name;
TempHash["parent_id"] = InvFolder.ParentID.ToString();
TempHash["version"] = (Int32)InvFolder.Version;
TempHash["type_default"] = (Int32)InvFolder.Type;
TempHash["folder_id"] = InvFolder.ID.ToString();
AgentInventoryArray.Add(TempHash);
}
return new InventoryData(AgentInventoryArray, rootID);
}
protected virtual bool AllowLoginWithoutInventory()
{
return false;
}
public XmlRpcResponse XmlRPCCheckAuthSession(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable)request.Params[0];
string authed = "FALSE";
if (requestData.Contains("avatar_uuid") && requestData.Contains("session_id"))
{
UUID guess_aid;
UUID guess_sid;
UUID.TryParse((string)requestData["avatar_uuid"], out guess_aid);
if (guess_aid == UUID.Zero)
{
return Util.CreateUnknownUserErrorResponse();
}
UUID.TryParse((string)requestData["session_id"], out guess_sid);
if (guess_sid == UUID.Zero)
{
return Util.CreateUnknownUserErrorResponse();
}
if (m_userManager.VerifySession(guess_aid, guess_sid))
{
authed = "TRUE";
m_log.InfoFormat("[UserManager]: CheckAuthSession TRUE for user {0}", guess_aid);
}
else
{
m_log.InfoFormat("[UserManager]: CheckAuthSession FALSE");
return Util.CreateUnknownUserErrorResponse();
}
}
Hashtable responseData = new Hashtable();
responseData["auth_session"] = authed;
response.Value = responseData;
return response;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Globalization;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
namespace System.Net
{
// For SSL connections:
internal class SSPISecureChannelType : SSPIInterface
{
public Exception GetException(SecurityStatus status)
{
// TODO (Issue #3362) To be implemented
return new Exception("status = " + status);
}
public void VerifyPackageInfo()
{
}
public SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certificate,
SslProtocols protocols, EncryptionPolicy policy, bool isServer)
{
return new SafeFreeCredentials(certificate, protocols, policy);
}
public SecurityStatus AcceptSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context,
SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool remoteCertRequired)
{
return HandshakeInternal(credential, ref context, inputBuffer, outputBuffer, true, remoteCertRequired);
}
public SecurityStatus InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context,
string targetName, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer)
{
return HandshakeInternal(credential, ref context, inputBuffer, outputBuffer, false, false);
}
public SecurityStatus InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer)
{
Debug.Assert(inputBuffers.Length == 2);
Debug.Assert(inputBuffers[1].token == null);
return HandshakeInternal(credential, ref context, inputBuffers[0], outputBuffer, false, false);
}
public SecurityStatus EncryptMessage(SafeDeleteContext securityContext, byte[] buffer, int size, int headerSize, int trailerSize, out int resultSize)
{
// Unencrypted data starts at an offset of headerSize
return EncryptDecryptHelper(securityContext, buffer, headerSize, size, headerSize, trailerSize, true, out resultSize);
}
public SecurityStatus DecryptMessage(SafeDeleteContext securityContext, byte[] buffer, ref int offset, ref int count)
{
int resultSize;
SecurityStatus retVal = EncryptDecryptHelper(securityContext, buffer, offset, count, 0, 0, false, out resultSize);
if (SecurityStatus.OK == retVal || SecurityStatus.Renegotiate == retVal)
{
count = resultSize;
}
return retVal;
}
public int QueryContextChannelBinding(SafeDeleteContext phContext, ChannelBindingKind attribute,
out SafeFreeContextBufferChannelBinding refHandle)
{
// TODO (Issue #3362) To be implemented
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public int QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes)
{
streamSizes = null;
try
{
streamSizes = new StreamSizes(Interop.libssl.SslSizes.HEADER_SIZE, Interop.libssl.SslSizes.TRAILER_SIZE, Interop.libssl.SslSizes.SSL3_RT_MAX_PLAIN_LENGTH);
return 0;
}
catch
{
return -1;
}
}
public int QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo)
{
connectionInfo = null;
try
{
Interop.libssl.SSL_CIPHER cipher = Interop.OpenSsl.GetConnectionInfo(securityContext.SslContext);
connectionInfo = new SslConnectionInfo(cipher);
return 0;
}
catch
{
return -1;
}
}
public int QueryContextRemoteCertificate(SafeDeleteContext securityContext, out SafeFreeCertContext remoteCertContext)
{
remoteCertContext = null;
try
{
SafeX509Handle remoteCertificate = Interop.OpenSsl.GetPeerCertificate(securityContext.SslContext);
// Note that cert ownership is transferred to SafeFreeCertContext
remoteCertContext = new SafeFreeCertContext(remoteCertificate);
return 0;
}
catch
{
return -1;
}
}
public int QueryContextIssuerList(SafeDeleteContext securityContext, out Object issuerList)
{
// TODO (Issue #3362) To be implemented
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
private long GetOptions(SslProtocols protocols)
{
long retVal = Interop.libssl.Options.SSL_OP_NO_SSLv2 | Interop.libssl.Options.SSL_OP_NO_SSLv3 |
Interop.libssl.Options.SSL_OP_NO_TLSv1 | Interop.libssl.Options.SSL_OP_NO_TLSv1_1 |
Interop.libssl.Options.SSL_OP_NO_TLSv1_2;
if ((protocols & SslProtocols.Ssl2) != 0)
{
retVal &= ~Interop.libssl.Options.SSL_OP_NO_SSLv2;
}
if ((protocols & SslProtocols.Ssl3) != 0)
{
retVal &= ~Interop.libssl.Options.SSL_OP_NO_SSLv3;
}
if ((protocols & SslProtocols.Tls) != 0)
{
retVal &= ~Interop.libssl.Options.SSL_OP_NO_TLSv1;
}
if ((protocols & SslProtocols.Tls11) != 0)
{
retVal &= ~Interop.libssl.Options.SSL_OP_NO_TLSv1_1;
}
if ((protocols & SslProtocols.Tls12) != 0)
{
retVal &= ~Interop.libssl.Options.SSL_OP_NO_TLSv1_2;
}
return retVal;
}
private SecurityStatus HandshakeInternal(SafeFreeCredentials credential, ref SafeDeleteContext context,
SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool isServer, bool remoteCertRequired)
{
Debug.Assert(!credential.IsInvalid);
try
{
if ((null == context) || context.IsInvalid)
{
long options = GetOptions(credential.Protocols);
context = new SafeDeleteContext(credential, options, isServer, remoteCertRequired);
}
IntPtr inputPtr = IntPtr.Zero, outputPtr = IntPtr.Zero;
int outputSize;
bool done;
if (null == inputBuffer)
{
done = Interop.OpenSsl.DoSslHandshake(context.SslContext, inputPtr, 0, out outputPtr, out outputSize);
}
else
{
unsafe
{
fixed (byte* tokenPtr = inputBuffer.token)
{
inputPtr = new IntPtr(tokenPtr + inputBuffer.offset);
done = Interop.OpenSsl.DoSslHandshake(context.SslContext, inputPtr, inputBuffer.size, out outputPtr, out outputSize);
}
}
}
outputBuffer.size = outputSize;
outputBuffer.offset = 0;
if (outputSize > 0)
{
outputBuffer.token = new byte[outputBuffer.size];
Marshal.Copy(outputPtr, outputBuffer.token, 0, outputBuffer.size);
}
else
{
outputBuffer.token = null;
}
if (outputPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(outputPtr);
outputPtr = IntPtr.Zero;
}
return done ? SecurityStatus.OK : SecurityStatus.ContinueNeeded;
}
catch (Exception ex)
{
Debug.Fail("Exception Caught. - " + ex);
return SecurityStatus.InternalError;
}
}
private SecurityStatus EncryptDecryptHelper(SafeDeleteContext securityContext, byte[] buffer, int offset, int size, int headerSize, int trailerSize, bool encrypt, out int resultSize)
{
resultSize = 0;
try
{
Interop.libssl.SslErrorCode errorCode = Interop.libssl.SslErrorCode.SSL_ERROR_NONE;
unsafe
{
fixed (byte* bufferPtr = buffer)
{
IntPtr inputPtr = new IntPtr(bufferPtr);
Interop.libssl.SafeSslHandle scHandle = securityContext.SslContext;
resultSize = encrypt ?
Interop.OpenSsl.Encrypt(scHandle, inputPtr, offset, size, buffer.Length, out errorCode) :
Interop.OpenSsl.Decrypt(scHandle, inputPtr, size, out errorCode);
}
}
switch (errorCode)
{
case Interop.libssl.SslErrorCode.SSL_ERROR_RENEGOTIATE:
return SecurityStatus.Renegotiate;
case Interop.libssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
return SecurityStatus.ContextExpired;
case Interop.libssl.SslErrorCode.SSL_ERROR_NONE:
case Interop.libssl.SslErrorCode.SSL_ERROR_WANT_READ:
return SecurityStatus.OK;
default:
return SecurityStatus.InternalError;
}
}
catch (Exception ex)
{
Debug.Fail("Exception Caught. - " + ex);
return SecurityStatus.InternalError;
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Text;
using System.IO;
using fyiReporting.RDL;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Drillthrough reports; pick report and specify parameters
/// </summary>
internal class DrillParametersDialog : System.Windows.Forms.Form
{
private string _DrillReport;
private DataTable _DataTable;
private DataGridTextBoxColumn dgtbName;
private DataGridTextBoxColumn dgtbValue;
private DataGridTextBoxColumn dgtbOmit;
private System.Windows.Forms.DataGridTableStyle dgTableStyle;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button bFile;
private System.Windows.Forms.TextBox tbReportFile;
private System.Windows.Forms.DataGrid dgParms;
private System.Windows.Forms.Button bRefreshParms;
private System.Windows.Forms.Button bOK;
private System.Windows.Forms.Button bCancel;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal DrillParametersDialog(string report, List<DrillParameter> parameters)
{
_DrillReport = report;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(parameters);
}
private void InitValues(List<DrillParameter> parameters)
{
this.tbReportFile.Text = _DrillReport;
// Initialize the DataGrid columns
dgtbName = new DataGridTextBoxColumn();
dgtbValue = new DataGridTextBoxColumn();
dgtbOmit = new DataGridTextBoxColumn();
this.dgTableStyle.GridColumnStyles.AddRange(new DataGridColumnStyle[] {
this.dgtbName,
this.dgtbValue,
this.dgtbOmit});
//
// dgtbFE
//
dgtbName.HeaderText = "Parameter Name";
dgtbName.MappingName = "ParameterName";
dgtbName.Width = 75;
//
// dgtbValue
//
this.dgtbValue.HeaderText = "Value";
this.dgtbValue.MappingName = "Value";
this.dgtbValue.Width = 75;
//
// dgtbOmit
//
this.dgtbOmit.HeaderText = "Omit";
this.dgtbOmit.MappingName = "Omit";
this.dgtbOmit.Width = 75;
// Initialize the DataTable
_DataTable = new DataTable();
_DataTable.Columns.Add(new DataColumn("ParameterName", typeof(string)));
_DataTable.Columns.Add(new DataColumn("Value", typeof(string)));
_DataTable.Columns.Add(new DataColumn("Omit", typeof(string)));
string[] rowValues = new string[3];
if (parameters != null)
foreach (DrillParameter dp in parameters)
{
rowValues[0] = dp.ParameterName;
rowValues[1] = dp.ParameterValue;
rowValues[2] = dp.ParameterOmit;
_DataTable.Rows.Add(rowValues);
}
// Don't allow new rows; do this by creating a DataView over the DataTable
// DataView dv = new DataView(_DataTable); // this has bad side effects
// dv.AllowNew = false;
this.dgParms.DataSource = _DataTable;
DataGridTableStyle ts = dgParms.TableStyles[0];
ts.GridColumnStyles[0].Width = 140;
ts.GridColumnStyles[0].ReadOnly = true;
ts.GridColumnStyles[1].Width = 140;
ts.GridColumnStyles[2].Width = 70;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(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.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(DrillParametersDialog));
this.dgParms = new System.Windows.Forms.DataGrid();
this.dgTableStyle = new System.Windows.Forms.DataGridTableStyle();
this.label1 = new System.Windows.Forms.Label();
this.tbReportFile = new System.Windows.Forms.TextBox();
this.bFile = new System.Windows.Forms.Button();
this.bRefreshParms = new System.Windows.Forms.Button();
this.bOK = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dgParms)).BeginInit();
this.SuspendLayout();
//
// dgParms
//
this.dgParms.CaptionVisible = false;
this.dgParms.DataMember = "";
this.dgParms.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgParms.Location = new System.Drawing.Point(8, 40);
this.dgParms.Name = "dgParms";
this.dgParms.Size = new System.Drawing.Size(384, 168);
this.dgParms.TabIndex = 2;
this.dgParms.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
this.dgTableStyle});
//
// dgTableStyle
//
this.dgTableStyle.AllowSorting = false;
this.dgTableStyle.DataGrid = this.dgParms;
this.dgTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgTableStyle.MappingName = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(88, 23);
this.label1.TabIndex = 3;
this.label1.Text = "Report name";
//
// tbReportFile
//
this.tbReportFile.Location = new System.Drawing.Point(104, 8);
this.tbReportFile.Name = "tbReportFile";
this.tbReportFile.Size = new System.Drawing.Size(312, 20);
this.tbReportFile.TabIndex = 4;
this.tbReportFile.Text = "";
//
// bFile
//
this.bFile.Location = new System.Drawing.Point(424, 8);
this.bFile.Name = "bFile";
this.bFile.Size = new System.Drawing.Size(24, 23);
this.bFile.TabIndex = 5;
this.bFile.Text = "...";
this.bFile.Click += new System.EventHandler(this.bFile_Click);
//
// bRefreshParms
//
this.bRefreshParms.Location = new System.Drawing.Point(400, 40);
this.bRefreshParms.Name = "bRefreshParms";
this.bRefreshParms.Size = new System.Drawing.Size(56, 23);
this.bRefreshParms.TabIndex = 10;
this.bRefreshParms.Text = "Refresh";
this.bRefreshParms.Click += new System.EventHandler(this.bRefreshParms_Click);
//
// bOK
//
this.bOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.bOK.Location = new System.Drawing.Point(288, 216);
this.bOK.Name = "bOK";
this.bOK.TabIndex = 11;
this.bOK.Text = "OK";
this.bOK.Click += new System.EventHandler(this.bOK_Click);
//
// bCancel
//
this.bCancel.CausesValidation = false;
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(376, 216);
this.bCancel.Name = "bCancel";
this.bCancel.TabIndex = 12;
this.bCancel.Text = "Cancel";
//
// DrillParametersDialog
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.bCancel;
this.CausesValidation = false;
this.ClientSize = new System.Drawing.Size(464, 248);
this.ControlBox = false;
this.Controls.Add(this.bOK);
this.Controls.Add(this.bCancel);
this.Controls.Add(this.bRefreshParms);
this.Controls.Add(this.bFile);
this.Controls.Add(this.tbReportFile);
this.Controls.Add(this.label1);
this.Controls.Add(this.dgParms);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DrillParametersDialog";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "Specify Drillthrough Report and Parameters";
((System.ComponentModel.ISupportInitialize)(this.dgParms)).EndInit();
this.ResumeLayout(false);
}
#endregion
public string DrillthroughReport
{
get {return this._DrillReport;}
}
public List<DrillParameter> DrillParameters
{
get
{
List<DrillParameter> parms = new List<DrillParameter>();
// Loop thru and add all the filters
foreach (DataRow dr in _DataTable.Rows)
{
if (dr[0] == DBNull.Value || dr[1] == DBNull.Value)
continue;
string name = (string) dr[0];
string val = (string) dr[1];
string omit = dr[2] == DBNull.Value? "false": (string) dr[2];
if (name.Length <= 0 || val.Length <= 0)
continue;
DrillParameter dp = new DrillParameter(name, val, omit);
parms.Add(dp);
}
if (parms.Count == 0)
return null;
return parms;
}
}
private void bFile_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Report files (*.rdl)|*.rdl" +
"|All files (*.*)|*.*";
ofd.FilterIndex = 1;
ofd.FileName = "*.rdl";
ofd.Title = "Specify Report File Name";
ofd.DefaultExt = "rdl";
ofd.AddExtension = true;
try
{
if (ofd.ShowDialog() == DialogResult.OK)
{
string file = Path.GetFileNameWithoutExtension(ofd.FileName);
tbReportFile.Text = file;
}
}
finally
{
ofd.Dispose();
}
}
private void bRefreshParms_Click(object sender, System.EventArgs e)
{
// Obtain the source
Cursor savec = Cursor.Current;
Cursor.Current = Cursors.WaitCursor; // this can take some time
try
{
string filename="";
if (tbReportFile.Text.Length > 0)
filename = tbReportFile.Text + ".rdl";
filename = GetFileNameWithPath(filename);
string source = this.GetSource(filename);
if (source == null)
return; // error: message already displayed
// Compile the report
Report report = this.GetReport(source, filename);
if (report == null)
return; // error: message already displayed
ICollection rps = report.UserReportParameters;
string[] rowValues = new string[3];
_DataTable.Rows.Clear();
foreach (UserReportParameter rp in rps)
{
rowValues[0] = rp.Name;
rowValues[1] = "";
rowValues[2] = "false";
_DataTable.Rows.Add(rowValues);
}
this.dgParms.Refresh();
this.dgParms.Focus();
}
finally
{
Cursor.Current = savec;
}
}
private string GetFileNameWithPath(string file)
{ // todo: should prefix this with the path of the open file
return file;
}
private string GetSource(string file)
{
StreamReader fs=null;
string prog=null;
try
{
fs = new StreamReader(file);
prog = fs.ReadToEnd();
}
catch(Exception e)
{
prog = null;
MessageBox.Show(e.Message, "Error reading report file");
}
finally
{
if (fs != null)
fs.Close();
}
return prog;
}
private Report GetReport(string prog, string file)
{
// Now parse the file
RDLParser rdlp;
Report r;
try
{
rdlp = new RDLParser(prog);
string folder = Path.GetDirectoryName(file);
if (folder == "")
{
folder = Environment.CurrentDirectory;
}
rdlp.Folder = folder;
r = rdlp.Parse();
if (r.ErrorMaxSeverity > 4)
{
MessageBox.Show(string.Format("Report {0} has errors and cannot be processed.", "Report"));
r = null; // don't return when severe errors
}
}
catch(Exception e)
{
r = null;
MessageBox.Show(e.Message, "Report load failed");
}
return r;
}
private void DrillParametersDialog_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
foreach (DataRow dr in _DataTable.Rows)
{
if (dr[1] == DBNull.Value)
{
e.Cancel = true;
break;
}
string val = (string) dr[1];
if (val.Length <= 0)
{
e.Cancel = true;
break;
}
}
if (e.Cancel)
{
MessageBox.Show("Value must be specified for every parameter", this.Text);
}
}
private void bOK_Click(object sender, System.EventArgs e)
{
CancelEventArgs ce = new CancelEventArgs();
DrillParametersDialog_Validating(this, ce);
if (ce.Cancel)
{
DialogResult = DialogResult.None;
return;
}
DialogResult = DialogResult.OK;
}
}
internal class DrillParameter
{
internal string ParameterName;
internal string ParameterValue;
internal string ParameterOmit;
internal DrillParameter(string name, string pvalue, string omit)
{
ParameterName = name;
ParameterValue = pvalue;
ParameterOmit = omit;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml;
using UnityEditor;
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// Class containing various utility methods to build a WSA solution from a Unity project.
/// </summary>
public static class BuildSLNUtilities
{
public class CopyDirectoryInfo
{
public string Source { get; set; }
public string Destination { get; set; }
public string Filter { get; set; }
public bool Recursive { get; set; }
public CopyDirectoryInfo()
{
Source = null;
Destination = null;
Filter = "*";
Recursive = false;
}
}
public class BuildInfo
{
public string OutputDirectory { get; set; }
public IEnumerable<string> Scenes { get; set; }
public IEnumerable<CopyDirectoryInfo> CopyDirectories { get; set; }
public Action<BuildInfo> PreBuildAction { get; set; }
public Action<BuildInfo, string> PostBuildAction { get; set; }
public BuildOptions BuildOptions { get; set; }
// EditorUserBuildSettings
public BuildTarget BuildTarget { get; set; }
public WSASDK? WSASdk { get; set; }
public WSAUWPBuildType? WSAUWPBuildType { get; set; }
public Boolean? WSAGenerateReferenceProjects { get; set; }
public ColorSpace? ColorSpace { get; set; }
public bool IsCommandLine { get; set; }
public string BuildSymbols { get; private set; }
public BuildInfo()
{
BuildSymbols = string.Empty;
}
public void AppendSymbols(params string[] symbol)
{
this.AppendSymbols((IEnumerable<string>)symbol);
}
public void AppendSymbols(IEnumerable<string> symbols)
{
string[] toAdd = symbols.Except(this.BuildSymbols.Split(';'))
.Where(sym => !string.IsNullOrEmpty(sym)).ToArray();
if (!toAdd.Any())
{
return;
}
if (!String.IsNullOrEmpty(this.BuildSymbols))
{
this.BuildSymbols += ";";
}
this.BuildSymbols += String.Join(";", toAdd);
}
public bool HasAnySymbols(params string[] symbols)
{
return this.BuildSymbols.Split(';').Intersect(symbols).Any();
}
public bool HasConfigurationSymbol()
{
return HasAnySymbols(
BuildSLNUtilities.BuildSymbolDebug,
BuildSLNUtilities.BuildSymbolRelease,
BuildSLNUtilities.BuildSymbolMaster);
}
public static IEnumerable<string> RemoveConfigurationSymbols(string symbolstring)
{
return symbolstring.Split(';').Except(new[]
{
BuildSLNUtilities.BuildSymbolDebug,
BuildSLNUtilities.BuildSymbolRelease,
BuildSLNUtilities.BuildSymbolMaster
});
}
public bool HasAnySymbols(IEnumerable<string> symbols)
{
return this.BuildSymbols.Split(';').Intersect(symbols).Any();
}
}
// Build configurations. Exactly one of these should be defined for any given build.
public const string BuildSymbolDebug = "DEBUG";
public const string BuildSymbolRelease = "RELEASE";
public const string BuildSymbolMaster = "MASTER";
/// <summary>
/// Event triggered when a build starts.
/// </summary>
public static event Action<BuildInfo> BuildStarted;
/// <summary>
/// Event triggered when a build completes.
/// </summary>
public static event Action<BuildInfo, string> BuildCompleted;
public static void PerformBuild(BuildInfo buildInfo)
{
BuildTargetGroup buildTargetGroup = GetGroup(buildInfo.BuildTarget);
string oldBuildSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup);
if (!string.IsNullOrEmpty(oldBuildSymbols))
{
if (buildInfo.HasConfigurationSymbol())
{
buildInfo.AppendSymbols(BuildInfo.RemoveConfigurationSymbols(oldBuildSymbols));
}
else
{
buildInfo.AppendSymbols(oldBuildSymbols.Split(';'));
}
}
if ((buildInfo.BuildOptions & BuildOptions.Development) == BuildOptions.Development)
{
if (!buildInfo.HasConfigurationSymbol())
{
buildInfo.AppendSymbols(BuildSLNUtilities.BuildSymbolDebug);
}
}
if (buildInfo.HasAnySymbols(BuildSLNUtilities.BuildSymbolDebug))
{
buildInfo.BuildOptions |= BuildOptions.Development | BuildOptions.AllowDebugging;
}
if (buildInfo.HasAnySymbols(BuildSLNUtilities.BuildSymbolRelease))
{
//Unity automatically adds the DEBUG symbol if the BuildOptions.Development flag is
//specified. In order to have debug symbols and the RELEASE symbole we have to
//inject the symbol Unity relies on to enable the /debug+ flag of csc.exe which is "DEVELOPMENT_BUILD"
buildInfo.AppendSymbols("DEVELOPMENT_BUILD");
}
var oldBuildTarget = EditorUserBuildSettings.activeBuildTarget;
EditorUserBuildSettings.SwitchActiveBuildTarget(buildInfo.BuildTarget);
var oldWSASDK = EditorUserBuildSettings.wsaSDK;
if (buildInfo.WSASdk.HasValue)
{
EditorUserBuildSettings.wsaSDK = buildInfo.WSASdk.Value;
}
WSAUWPBuildType? oldWSAUWPBuildType = null;
if (EditorUserBuildSettings.wsaSDK == WSASDK.UWP)
{
oldWSAUWPBuildType = EditorUserBuildSettings.wsaUWPBuildType;
if (buildInfo.WSAUWPBuildType.HasValue)
{
EditorUserBuildSettings.wsaUWPBuildType = buildInfo.WSAUWPBuildType.Value;
}
}
var oldWSAGenerateReferenceProjects = EditorUserBuildSettings.wsaGenerateReferenceProjects;
if (buildInfo.WSAGenerateReferenceProjects.HasValue)
{
EditorUserBuildSettings.wsaGenerateReferenceProjects = buildInfo.WSAGenerateReferenceProjects.Value;
}
var oldColorSpace = PlayerSettings.colorSpace;
if (buildInfo.ColorSpace.HasValue)
{
PlayerSettings.colorSpace = buildInfo.ColorSpace.Value;
}
if (buildInfo.BuildSymbols != null)
{
PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, buildInfo.BuildSymbols);
}
string buildError = "Error";
try
{
// For the WSA player, Unity builds into a target directory.
// For other players, the OutputPath parameter indicates the
// path to the target executable to build.
if (buildInfo.BuildTarget == BuildTarget.WSAPlayer)
{
Directory.CreateDirectory(buildInfo.OutputDirectory);
}
OnPreProcessBuild(buildInfo);
buildError = BuildPipeline.BuildPlayer(
buildInfo.Scenes.ToArray(),
buildInfo.OutputDirectory,
buildInfo.BuildTarget,
buildInfo.BuildOptions);
if (buildError.StartsWith("Error"))
{
throw new Exception(buildError);
}
}
finally
{
OnPostProcessBuild(buildInfo, buildError);
PlayerSettings.colorSpace = oldColorSpace;
PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, oldBuildSymbols);
EditorUserBuildSettings.wsaSDK = oldWSASDK;
if (oldWSAUWPBuildType.HasValue)
{
EditorUserBuildSettings.wsaUWPBuildType = oldWSAUWPBuildType.Value;
}
EditorUserBuildSettings.wsaGenerateReferenceProjects = oldWSAGenerateReferenceProjects;
EditorUserBuildSettings.SwitchActiveBuildTarget(oldBuildTarget);
}
}
public static void ParseBuildCommandLine(ref BuildInfo buildInfo)
{
string[] arguments = System.Environment.GetCommandLineArgs();
buildInfo.IsCommandLine = true;
for (int i = 0; i < arguments.Length; ++i)
{
// Can't use -buildTarget which is something Unity already takes as an argument for something.
if (string.Equals(arguments[i], "-duskBuildTarget", StringComparison.InvariantCultureIgnoreCase))
{
buildInfo.BuildTarget = (BuildTarget)Enum.Parse(typeof(BuildTarget), arguments[++i]);
}
else if (string.Equals(arguments[i], "-wsaSDK", StringComparison.InvariantCultureIgnoreCase))
{
string wsaSdkArg = arguments[++i];
buildInfo.WSASdk = (WSASDK)Enum.Parse(typeof(WSASDK), wsaSdkArg);
}
else if (string.Equals(arguments[i], "-wsaUWPBuildType", StringComparison.InvariantCultureIgnoreCase))
{
buildInfo.WSAUWPBuildType = (WSAUWPBuildType)Enum.Parse(typeof(WSAUWPBuildType), arguments[++i]);
}
else if (string.Equals(arguments[i], "-wsaGenerateReferenceProjects", StringComparison.InvariantCultureIgnoreCase))
{
buildInfo.WSAGenerateReferenceProjects = Boolean.Parse(arguments[++i]);
}
else if (string.Equals(arguments[i], "-buildOutput", StringComparison.InvariantCultureIgnoreCase))
{
buildInfo.OutputDirectory = arguments[++i];
}
else if (string.Equals(arguments[i], "-buildDesc", StringComparison.InvariantCultureIgnoreCase))
{
ParseBuildDescriptionFile(arguments[++i], ref buildInfo);
}
else if (string.Equals(arguments[i], "-unityBuildSymbols", StringComparison.InvariantCultureIgnoreCase))
{
string newBuildSymbols = arguments[++i];
buildInfo.AppendSymbols(newBuildSymbols.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
}
}
}
public static void PerformBuild_CommandLine()
{
BuildInfo buildInfo = new BuildInfo()
{
// Use scenes from the editor build settings.
Scenes = EditorBuildSettings.scenes.Where(scene => scene.enabled).Select(scene => scene.path),
};
ParseBuildCommandLine(ref buildInfo);
PerformBuild(buildInfo);
}
public static void ParseBuildDescriptionFile(string filename, ref BuildInfo buildInfo)
{
Debug.Log(string.Format(CultureInfo.InvariantCulture, "Build: Using \"{0}\" as build description", filename));
// Parse the XML file
XmlTextReader reader = new XmlTextReader(filename);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (string.Equals(reader.Name, "SceneList", StringComparison.InvariantCultureIgnoreCase))
{
// Set the scenes we want to build
buildInfo.Scenes = ReadSceneList(reader);
}
else if (string.Equals(reader.Name, "CopyList", StringComparison.InvariantCultureIgnoreCase))
{
// Set the directories we want to copy
buildInfo.CopyDirectories = ReadCopyList(reader);
}
break;
}
}
}
private static BuildTargetGroup GetGroup(BuildTarget buildTarget)
{
switch (buildTarget)
{
case BuildTarget.WSAPlayer:
return BuildTargetGroup.WSA;
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
return BuildTargetGroup.Standalone;
default:
return BuildTargetGroup.Unknown;
}
}
private static IEnumerable<string> ReadSceneList(XmlTextReader reader)
{
List<string> result = new List<string>();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (string.Equals(reader.Name, "Scene", StringComparison.InvariantCultureIgnoreCase))
{
while (reader.MoveToNextAttribute())
{
if (string.Equals(reader.Name, "Name", StringComparison.InvariantCultureIgnoreCase))
{
result.Add(reader.Value);
Debug.Log(string.Format(CultureInfo.InvariantCulture, "Build: Adding scene \"{0}\"", reader.Value));
}
}
}
break;
case XmlNodeType.EndElement:
if (string.Equals(reader.Name, "SceneList", StringComparison.InvariantCultureIgnoreCase))
return result;
break;
}
}
return result;
}
private static IEnumerable<CopyDirectoryInfo> ReadCopyList(XmlTextReader reader)
{
List<CopyDirectoryInfo> result = new List<CopyDirectoryInfo>();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (string.Equals(reader.Name, "Copy", StringComparison.InvariantCultureIgnoreCase))
{
string source = null;
string dest = null;
string filter = null;
bool recursive = false;
while (reader.MoveToNextAttribute())
{
if (string.Equals(reader.Name, "Source", StringComparison.InvariantCultureIgnoreCase))
{
source = reader.Value;
}
else if (string.Equals(reader.Name, "Destination", StringComparison.InvariantCultureIgnoreCase))
{
dest = reader.Value;
}
else if (string.Equals(reader.Name, "Recursive", StringComparison.InvariantCultureIgnoreCase))
{
recursive = System.Convert.ToBoolean(reader.Value);
}
else if (string.Equals(reader.Name, "Filter", StringComparison.InvariantCultureIgnoreCase))
{
filter = reader.Value;
}
}
if (source != null)
{
// Either the file specifies the Destination as well, or else CopyDirectory will use Source for Destination
CopyDirectoryInfo info = new CopyDirectoryInfo();
info.Source = source;
if (dest != null)
{
info.Destination = dest;
}
if (filter != null)
{
info.Filter = filter;
}
info.Recursive = recursive;
Debug.Log(string.Format(CultureInfo.InvariantCulture, @"Build: Adding {0}copy ""{1}\{2}"" => ""{3}""", info.Recursive ? "Recursive " : "", info.Source, info.Filter, info.Destination ?? info.Source));
result.Add(info);
}
}
break;
case XmlNodeType.EndElement:
if (string.Equals(reader.Name, "CopyList", StringComparison.InvariantCultureIgnoreCase))
return result;
break;
}
}
return result;
}
public static void CopyDirectory(string sourceDirectoryPath, string destinationDirectoryPath, CopyDirectoryInfo directoryInfo)
{
sourceDirectoryPath = Path.Combine(sourceDirectoryPath, directoryInfo.Source);
destinationDirectoryPath = Path.Combine(destinationDirectoryPath, directoryInfo.Destination ?? directoryInfo.Source);
Debug.Log(string.Format(CultureInfo.InvariantCulture, @"{0} ""{1}\{2}"" to ""{3}""", directoryInfo.Recursive ? "Recursively copying" : "Copying", sourceDirectoryPath, directoryInfo.Filter, destinationDirectoryPath));
foreach (string sourceFilePath in Directory.GetFiles(sourceDirectoryPath, directoryInfo.Filter, directoryInfo.Recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
{
string destinationFilePath = sourceFilePath.Replace(sourceDirectoryPath, destinationDirectoryPath);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(destinationFilePath));
if (File.Exists(destinationFilePath))
{
File.SetAttributes(destinationFilePath, FileAttributes.Normal);
}
File.Copy(sourceFilePath, destinationFilePath, true);
File.SetAttributes(destinationFilePath, FileAttributes.Normal);
}
catch (Exception exception)
{
Debug.LogError(string.Format(CultureInfo.InvariantCulture, "Failed to copy \"{0}\" to \"{1}\" with \"{2}\"", sourceFilePath, destinationFilePath, exception));
}
}
}
private static void OnPreProcessBuild(BuildInfo buildInfo)
{
// Raise the global event for listeners
BuildStarted.RaiseEvent(buildInfo);
// Call the pre-build action, if any
if (buildInfo.PreBuildAction != null)
{
buildInfo.PreBuildAction(buildInfo);
}
}
private static void OnPostProcessBuild(BuildInfo buildInfo, string buildError)
{
if (string.IsNullOrEmpty(buildError))
{
if (buildInfo.CopyDirectories != null)
{
string inputProjectDirectoryPath = GetProjectPath();
string outputProjectDirectoryPath = Path.Combine(GetProjectPath(), buildInfo.OutputDirectory);
foreach (var directory in buildInfo.CopyDirectories)
{
CopyDirectory(inputProjectDirectoryPath, outputProjectDirectoryPath, directory);
}
}
}
// Raise the global event for listeners
BuildCompleted.RaiseEvent(buildInfo, buildError);
// Call the post-build action, if any
if (buildInfo.PostBuildAction != null)
{
buildInfo.PostBuildAction(buildInfo, buildError);
}
}
private static string GetProjectPath()
{
return Path.GetDirectoryName(Path.GetFullPath(Application.dataPath));
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Function Node", "Functions", "Function Node", KeyCode.None, false, 0, int.MaxValue, typeof( AmplifyShaderFunction ) )]
public class FunctionNode : ParentNode
{
[SerializeField]
private AmplifyShaderFunction m_function;
//[SerializeField]
private ParentGraph m_functionGraph;
[SerializeField]
private int m_functionGraphId = -1;
[SerializeField]
private List<FunctionInput> m_allFunctionInputs;
[SerializeField]
private List<FunctionOutput> m_allFunctionOutputs;
[SerializeField]
private ReordenatorNode m_reordenator;
[SerializeField]
private string m_filename;
[SerializeField]
private string m_headerTitle = string.Empty;
[SerializeField]
private int m_orderIndex;
[SerializeField]
private string m_functionCheckSum;
private bool m_parametersFoldout = true;
private ParentGraph m_outsideGraph = null;
string LastLine( string text )
{
string[] lines = text.Replace( "\r", "" ).Split( '\n' );
return lines[ lines.Length - 1 ];
}
public void CommonInit( AmplifyShaderFunction function )
{
if ( function == null )
return;
m_function = function;
SetTitleText( Function.FunctionName );
if ( m_functionGraph == null )
{
m_functionGraph = new ParentGraph();
m_functionGraph.ParentWindow = ContainerGraph.ParentWindow;
}
m_functionGraphId = Mathf.Max( m_functionGraphId, ContainerGraph.ParentWindow.GraphCount );
ContainerGraph.ParentWindow.GraphCount = m_functionGraphId + 1;
m_functionGraph.SetGraphId( m_functionGraphId );
ParentGraph cachedGraph = ContainerGraph.ParentWindow.CustomGraph;
ContainerGraph.ParentWindow.CustomGraph = m_functionGraph;
AmplifyShaderEditorWindow.LoadFromMeta( ref m_functionGraph, ContainerGraph.ParentWindow.ContextMenuInstance, ContainerGraph.ParentWindow.CurrentVersionInfo, Function.FunctionInfo );
m_functionCheckSum = LastLine( m_function.FunctionInfo );
List<ParentNode> propertyList = UIUtils.PropertyNodesList();
ContainerGraph.ParentWindow.CustomGraph = cachedGraph;
m_allFunctionInputs = new List<FunctionInput>();
m_allFunctionOutputs = new List<FunctionOutput>();
for ( int i = 0; i < m_functionGraph.AllNodes.Count; i++ )
{
//Debug.Log( m_functionGraph.AllNodes[ i ].GetType()+" "+ m_functionGraph.AllNodes[ i ].IsConnected );
if ( m_functionGraph.AllNodes[ i ].GetType() == typeof( FunctionInput ) )
{
m_allFunctionInputs.Add( m_functionGraph.AllNodes[ i ] as FunctionInput );
}
else if ( m_functionGraph.AllNodes[ i ].GetType() == typeof( FunctionOutput ) )
{
m_allFunctionOutputs.Add( m_functionGraph.AllNodes[ i ] as FunctionOutput );
}
}
m_allFunctionInputs.Sort( ( x, y ) => { return x.OrderIndex.CompareTo( y.OrderIndex ); } );
m_allFunctionOutputs.Sort( ( x, y ) => { return x.OrderIndex.CompareTo( y.OrderIndex ); } );
int inputCount = m_allFunctionInputs.Count;
for ( int i = 0; i < inputCount; i++ )
{
AddInputPort( m_allFunctionInputs[ i ].SelectedInputType, false, m_allFunctionInputs[ i ].InputName );
PortSwitchRestriction( m_inputPorts[ i ] );
}
int outputCount = m_allFunctionOutputs.Count;
for ( int i = 0; i < outputCount; i++ )
{
AddOutputPort( m_allFunctionOutputs[ i ].AutoOutputType, m_allFunctionOutputs[ i ].OutputName );
PortSwitchRestriction( m_outputPorts[ i ] );
}
//create reordenator to main graph
bool inside = false;
if ( ContainerGraph.ParentWindow.CustomGraph != null )
inside = true;
if ( /*hasConnectedProperties*/propertyList.Count > 0 )
{
m_reordenator = ScriptableObject.CreateInstance<ReordenatorNode>();
m_reordenator.Init( "_" + Function.FunctionName, Function.FunctionName, propertyList );
m_reordenator.OrderIndex = m_orderIndex;
m_reordenator.HeaderTitle = Function.FunctionName;
m_reordenator.IsInside = inside;
}
if ( m_reordenator != null )
{
cachedGraph = ContainerGraph.ParentWindow.CustomGraph;
ContainerGraph.ParentWindow.CustomGraph = null;
UIUtils.RegisterPropertyNode( m_reordenator );
ContainerGraph.ParentWindow.CustomGraph = cachedGraph;
}
m_textLabelWidth = 100;
}
public void PortSwitchRestriction( WirePort port )
{
switch ( port.DataType )
{
case WirePortDataType.OBJECT:
break;
case WirePortDataType.FLOAT:
case WirePortDataType.FLOAT2:
case WirePortDataType.FLOAT3:
case WirePortDataType.FLOAT4:
case WirePortDataType.COLOR:
case WirePortDataType.INT:
{
port.CreatePortRestrictions( WirePortDataType.FLOAT, WirePortDataType.FLOAT2, WirePortDataType.FLOAT3, WirePortDataType.FLOAT4, WirePortDataType.COLOR, WirePortDataType.INT, WirePortDataType.OBJECT );
}
break;
case WirePortDataType.FLOAT3x3:
case WirePortDataType.FLOAT4x4:
{
port.CreatePortRestrictions( WirePortDataType.FLOAT3x3, WirePortDataType.FLOAT4x4, WirePortDataType.OBJECT );
}
break;
case WirePortDataType.SAMPLER1D:
case WirePortDataType.SAMPLER2D:
case WirePortDataType.SAMPLER3D:
case WirePortDataType.SAMPLERCUBE:
{
port.CreatePortRestrictions( WirePortDataType.SAMPLER1D, WirePortDataType.SAMPLER2D, WirePortDataType.SAMPLER3D, WirePortDataType.SAMPLERCUBE, WirePortDataType.OBJECT );
}
break;
default:
break;
}
}
protected override void OnUniqueIDAssigned()
{
base.OnUniqueIDAssigned();
UIUtils.RegisterFunctionNode( this );
}
public override void SetupFromCastObject( UnityEngine.Object obj )
{
base.SetupFromCastObject( obj );
AmplifyShaderFunction function = obj as AmplifyShaderFunction;
CommonInit( function );
}
public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true )
{
base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode );
if ( m_allFunctionInputs[ portId ].AutoCast )
{
m_inputPorts[ portId ].MatchPortToConnection();
ParentGraph cachedGraph = ContainerGraph.ParentWindow.CustomGraph;
ContainerGraph.ParentWindow.CustomGraph = m_functionGraph;
m_allFunctionInputs[ portId ].ChangeOutputType( m_inputPorts[ portId ].DataType, false );
ContainerGraph.ParentWindow.CustomGraph = cachedGraph;
}
for ( int i = 0; i < m_allFunctionOutputs.Count; i++ )
{
m_outputPorts[ i ].ChangeType( m_allFunctionOutputs[ i ].InputPorts[ 0 ].DataType, false );
}
}
public override void OnConnectedOutputNodeChanges( int inputPortId, int otherNodeId, int otherPortId, string name, WirePortDataType type )
{
base.OnConnectedOutputNodeChanges( inputPortId, otherNodeId, otherPortId, name, type );
if ( m_allFunctionInputs[ inputPortId ].AutoCast )
{
m_inputPorts[ inputPortId ].MatchPortToConnection();
ParentGraph cachedGraph = ContainerGraph.ParentWindow.CustomGraph;
ContainerGraph.ParentWindow.CustomGraph = m_functionGraph;
m_allFunctionInputs[ inputPortId ].ChangeOutputType( m_inputPorts[ inputPortId ].DataType, false );
ContainerGraph.ParentWindow.CustomGraph = cachedGraph;
}
for ( int i = 0; i < m_allFunctionOutputs.Count; i++ )
{
m_outputPorts[ i ].ChangeType( m_allFunctionOutputs[ i ].InputPorts[ 0 ].DataType, false );
}
}
public override void DrawProperties()
{
base.DrawProperties();
if ( Function == null )
return;
if ( Function.Description.Length > 0 )
NodeUtils.DrawPropertyGroup( ref m_parametersFoldout, "Parameters", DrawDescription );
}
private void DrawDescription()
{
EditorGUILayout.HelpBox( "Description:\n" + Function.Description, MessageType.None );
}
public override void Destroy()
{
base.Destroy();
if ( m_reordenator != null )
{
m_reordenator.Destroy();
m_reordenator = null;
ParentGraph cachedGraph = ContainerGraph.ParentWindow.CustomGraph;
ContainerGraph.ParentWindow.CustomGraph = null;
UIUtils.UnregisterPropertyNode( m_reordenator );
ContainerGraph.ParentWindow.CustomGraph = cachedGraph;
}
UIUtils.UnregisterFunctionNode( this );
ParentGraph cachedGraph2 = ContainerGraph.ParentWindow.CustomGraph;
ContainerGraph.ParentWindow.CustomGraph = m_functionGraph;
if ( m_allFunctionInputs != null )
m_allFunctionInputs.Clear();
m_allFunctionInputs = null;
if ( m_allFunctionOutputs != null )
m_allFunctionOutputs.Clear();
m_allFunctionOutputs = null;
if ( m_functionGraph != null )
m_functionGraph.Destroy();
m_functionGraph = null;
ContainerGraph.ParentWindow.CustomGraph = cachedGraph2;
m_function = null;
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( ContainerGraph.ParentWindow.CheckFunctions && m_function != null )
{
string newCheckSum = LastLine( m_function.FunctionInfo );
if ( !m_functionCheckSum.Equals( newCheckSum ) )
{
m_functionCheckSum = newCheckSum;
ContainerGraph.OnDuplicateEvent += DuplicateMe;
}
}
}
public void DuplicateMe()
{
ParentNode newNode = ContainerGraph.CreateNode( m_function, false, Vec2Position );
for ( int i = 0; i < m_outputPorts.Count; i++ )
{
if ( m_outputPorts[ i ].IsConnected )
{
if ( newNode.OutputPorts != null && newNode.OutputPorts[ i ] != null )
{
for ( int j = m_outputPorts[ i ].ExternalReferences.Count - 1; j >= 0; j-- )
{
ContainerGraph.CreateConnection( m_outputPorts[ i ].ExternalReferences[ j ].NodeId, m_outputPorts[ i ].ExternalReferences[ j ].PortId, newNode.OutputPorts[ i ].NodeId, newNode.OutputPorts[ i ].PortId );
}
}
}
else
{
if ( newNode.OutputPorts != null && newNode.OutputPorts[ i ] != null )
{
ContainerGraph.DeleteConnection( false, newNode.UniqueId, i, false, false, false );
}
}
}
for ( int i = 0; i < m_inputPorts.Count; i++ )
{
if ( m_inputPorts[ i ].IsConnected )
{
if ( newNode.InputPorts != null && newNode.InputPorts[ i ] != null )
{
ContainerGraph.CreateConnection( newNode.InputPorts[ i ].NodeId, newNode.InputPorts[ i ].PortId, m_inputPorts[ i ].ExternalReferences[ 0 ].NodeId, m_inputPorts[ i ].ExternalReferences[ 0 ].PortId );
}
}
}
ContainerGraph.OnDuplicateEvent -= DuplicateMe;
ContainerGraph.DestroyNode( this, false );
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
ParentGraph cachedGraph = ContainerGraph.ParentWindow.CustomGraph;
m_outsideGraph = cachedGraph;
ContainerGraph.ParentWindow.CustomGraph = m_functionGraph;
if ( m_reordenator != null && m_reordenator.RecursiveCount() > 0 && m_reordenator.HasTitle )
{
dataCollector.AddToProperties( UniqueId, "[Header(" + m_reordenator.HeaderTitle + ")]", m_reordenator.OrderIndex );
}
string result = string.Empty;
for ( int i = 0; i < m_allFunctionInputs.Count; i++ )
{
if ( m_inputPorts[ i ].IsConnected )
m_allFunctionInputs[ i ].OnPortGeneration += FunctionNodeOnPortGeneration;
}
result += m_allFunctionOutputs[ outputId ].GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalvar );
for ( int i = 0; i < m_allFunctionInputs.Count; i++ )
{
if ( m_inputPorts[ i ].IsConnected )
m_allFunctionInputs[ i ].OnPortGeneration -= FunctionNodeOnPortGeneration;
}
ContainerGraph.ParentWindow.CustomGraph = cachedGraph;
return result;
}
private string FunctionNodeOnPortGeneration( ref MasterNodeDataCollector dataCollector, int index, ParentGraph graph )
{
ParentGraph cachedGraph = ContainerGraph.ParentWindow.CustomGraph;
ContainerGraph.ParentWindow.CustomGraph = m_outsideGraph;
string result = m_inputPorts[ index ].GeneratePortInstructions( ref dataCollector );
ContainerGraph.ParentWindow.CustomGraph = cachedGraph;
return result;
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
if ( Function != null )
IOUtils.AddFieldValueToString( ref nodeInfo, m_function.name );
else
IOUtils.AddFieldValueToString( ref nodeInfo, m_filename );
IOUtils.AddFieldValueToString( ref nodeInfo, m_reordenator != null ? m_reordenator.RawOrderIndex : -1 );
IOUtils.AddFieldValueToString( ref nodeInfo, m_headerTitle );
IOUtils.AddFieldValueToString( ref nodeInfo, m_functionGraphId );
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
m_filename = GetCurrentParam( ref nodeParams );
m_orderIndex = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
m_headerTitle = GetCurrentParam( ref nodeParams );
if ( UIUtils.CurrentShaderVersion() > 7203 )
{
m_functionGraphId = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
}
string[] guids = AssetDatabase.FindAssets( "t:AmplifyShaderFunction " + m_filename );
if ( guids.Length > 0 )
{
AmplifyShaderFunction loaded = AssetDatabase.LoadAssetAtPath<AmplifyShaderFunction>( AssetDatabase.GUIDToAssetPath( guids[ 0 ] ) );
if ( loaded != null )
{
CommonInit( loaded );
}
else
{
SetTitleText( "ERROR" );
}
}
else
{
SetTitleText( "Missing Function" );
}
}
public override void ReadOutputDataFromString( ref string[] nodeParams )
{
if ( Function == null )
return;
base.ReadOutputDataFromString( ref nodeParams );
ConfigureInputportsAfterRead();
}
public override void OnNodeDoubleClicked( Vector2 currentMousePos2D )
{
if ( Function == null )
return;
ContainerGraph.DeSelectAll();
this.Selected = true;
ContainerGraph.ParentWindow.OnLeftMouseUp();
AmplifyShaderEditorWindow.LoadShaderFunctionToASE( Function, true );
this.Selected = false;
}
private void ConfigureInputportsAfterRead()
{
if ( InputPorts != null )
{
int inputCount = InputPorts.Count;
for ( int i = 0; i < inputCount; i++ )
{
InputPorts[ i ].ChangeProperties( m_allFunctionInputs[ i ].InputName, m_allFunctionInputs[ i ].SelectedInputType, false );
}
}
if ( OutputPorts != null )
{
int outputCount = OutputPorts.Count;
for ( int i = 0; i < outputCount; i++ )
{
OutputPorts[ i ].ChangeProperties( m_allFunctionOutputs[ i ].OutputName, m_allFunctionOutputs[ i ].AutoOutputType, false );
}
}
}
public bool HasProperties { get { return m_reordenator != null; } }
public ParentGraph FunctionGraph
{
get
{
return m_functionGraph;
}
set
{
m_functionGraph = value;
}
}
public AmplifyShaderFunction Function
{
get { return m_function; }
set { m_function = value; }
}
public override void SetContainerGraph( ParentGraph newgraph )
{
base.SetContainerGraph( newgraph );
if ( m_functionGraph == null )
return;
for ( int i = 0; i < m_functionGraph.AllNodes.Count; i++ )
{
m_functionGraph.AllNodes[ i ].SetContainerGraph( m_functionGraph );
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using BulletSharp.Math;
namespace BulletSharp
{
public class IndexedMesh : IDisposable
{
internal IntPtr _native;
bool _preventDelete;
private bool _ownsData;
internal IndexedMesh(IntPtr native, bool preventDelete)
{
_native = native;
_preventDelete = preventDelete;
}
public IndexedMesh()
{
_native = btIndexedMesh_new();
}
public void Allocate(int numTriangles, int numVertices, int triangleIndexStride = sizeof(int) * 3, int vertexStride = sizeof(float) * 3)
{
if (_ownsData)
{
Free();
}
else
{
_ownsData = true;
}
switch (triangleIndexStride)
{
case sizeof(byte) * 3:
IndexType = PhyScalarType.UChar;
break;
case sizeof(short) * 3:
IndexType = PhyScalarType.Short;
break;
case sizeof(int) * 3:
default:
IndexType = PhyScalarType.Integer;
break;
}
VertexType = PhyScalarType.Float;
NumTriangles = numTriangles;
TriangleIndexBase = Marshal.AllocHGlobal(numTriangles * triangleIndexStride);
TriangleIndexStride = triangleIndexStride;
NumVertices = numVertices;
VertexBase = Marshal.AllocHGlobal(numVertices * vertexStride);
VertexStride = vertexStride;
}
public void Free()
{
if (_ownsData)
{
Marshal.FreeHGlobal(TriangleIndexBase);
Marshal.FreeHGlobal(VertexBase);
_ownsData = false;
}
}
public unsafe UnmanagedMemoryStream GetTriangleStream()
{
int length = btIndexedMesh_getNumTriangles(_native) * btIndexedMesh_getTriangleIndexStride(_native);
return new UnmanagedMemoryStream((byte*)btIndexedMesh_getTriangleIndexBase(_native).ToPointer(), length, length, FileAccess.ReadWrite);
}
public unsafe UnmanagedMemoryStream GetVertexStream()
{
int length = btIndexedMesh_getNumVertices(_native) * btIndexedMesh_getVertexStride(_native);
return new UnmanagedMemoryStream((byte*)btIndexedMesh_getVertexBase(_native).ToPointer(), length, length, FileAccess.ReadWrite);
}
public PhyScalarType IndexType
{
get { return btIndexedMesh_getIndexType(_native); }
set { btIndexedMesh_setIndexType(_native, value); }
}
public int NumTriangles
{
get { return btIndexedMesh_getNumTriangles(_native); }
set { btIndexedMesh_setNumTriangles(_native, value); }
}
public int NumVertices
{
get { return btIndexedMesh_getNumVertices(_native); }
set { btIndexedMesh_setNumVertices(_native, value); }
}
public IntPtr TriangleIndexBase
{
get { return btIndexedMesh_getTriangleIndexBase(_native); }
set { btIndexedMesh_setTriangleIndexBase(_native, value); }
}
public int TriangleIndexStride
{
get { return btIndexedMesh_getTriangleIndexStride(_native); }
set { btIndexedMesh_setTriangleIndexStride(_native, value); }
}
public IntPtr VertexBase
{
get { return btIndexedMesh_getVertexBase(_native); }
set { btIndexedMesh_setVertexBase(_native, value); }
}
public int VertexStride
{
get { return btIndexedMesh_getVertexStride(_native); }
set { btIndexedMesh_setVertexStride(_native, value); }
}
public PhyScalarType VertexType
{
get { return btIndexedMesh_getVertexType(_native); }
set { btIndexedMesh_setVertexType(_native, value); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_native != IntPtr.Zero)
{
Free();
if (!_preventDelete)
{
btIndexedMesh_delete(_native);
}
_native = IntPtr.Zero;
}
}
~IndexedMesh()
{
Dispose(false);
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btIndexedMesh_new();
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern PhyScalarType btIndexedMesh_getIndexType(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btIndexedMesh_getNumTriangles(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btIndexedMesh_getNumVertices(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btIndexedMesh_getTriangleIndexBase(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btIndexedMesh_getTriangleIndexStride(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btIndexedMesh_getVertexBase(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btIndexedMesh_getVertexStride(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern PhyScalarType btIndexedMesh_getVertexType(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btIndexedMesh_setIndexType(IntPtr obj, PhyScalarType value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btIndexedMesh_setNumTriangles(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btIndexedMesh_setNumVertices(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btIndexedMesh_setTriangleIndexBase(IntPtr obj, IntPtr value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btIndexedMesh_setTriangleIndexStride(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btIndexedMesh_setVertexBase(IntPtr obj, IntPtr value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btIndexedMesh_setVertexStride(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btIndexedMesh_setVertexType(IntPtr obj, PhyScalarType value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btIndexedMesh_delete(IntPtr obj);
}
public class TriangleIndexVertexArray : StridingMeshInterface
{
private List<IndexedMesh> _meshes = new List<IndexedMesh>();
private IndexedMesh _initialMesh;
private AlignedIndexedMeshArray _indexedMeshArray;
internal TriangleIndexVertexArray(IntPtr native)
: base(native)
{
}
public TriangleIndexVertexArray()
: base(btTriangleIndexVertexArray_new())
{
}
public TriangleIndexVertexArray(ICollection<int> triangles, ICollection<float> vertices)
: base(btTriangleIndexVertexArray_new())
{
_initialMesh = new IndexedMesh();
_initialMesh.Allocate(triangles.Count / 3, vertices.Count / 3);
int[] triangleArray = triangles as int[];
if (triangleArray == null)
{
triangleArray = new int[triangles.Count];
triangles.CopyTo(triangleArray, 0);
}
Marshal.Copy(triangleArray, 0, _initialMesh.TriangleIndexBase, triangles.Count);
float[] vertexArray = vertices as float[];
if (vertexArray == null)
{
vertexArray = new float[vertices.Count];
vertices.CopyTo(vertexArray, 0);
}
Marshal.Copy(vertexArray, 0, _initialMesh.VertexBase, vertices.Count);
AddIndexedMesh(_initialMesh);
}
public TriangleIndexVertexArray(ICollection<int> triangles, ICollection<Vector3> vertices)
: base(btTriangleIndexVertexArray_new())
{
_initialMesh = new IndexedMesh();
_initialMesh.Allocate(triangles.Count / 3, vertices.Count);
int[] triangleArray = triangles as int[];
if (triangleArray == null)
{
triangleArray = new int[triangles.Count];
triangles.CopyTo(triangleArray, 0);
}
Marshal.Copy(triangleArray, 0, _initialMesh.TriangleIndexBase, triangles.Count);
float[] vertexArray = new float[vertices.Count * 3];
int i = 0;
foreach (Vector3 v in vertices)
{
vertexArray[i] = v.X;
vertexArray[i + 1] = v.Y;
vertexArray[i + 2] = v.Z;
i += 3;
}
Marshal.Copy(vertexArray, 0, _initialMesh.VertexBase, vertices.Count);
AddIndexedMesh(_initialMesh);
}
public TriangleIndexVertexArray(int numTriangles, IntPtr triangleIndexBase, int triangleIndexStride, int numVertices, IntPtr vertexBase, int vertexStride)
: base(btTriangleIndexVertexArray_new2(numTriangles, triangleIndexBase, triangleIndexStride, numVertices, vertexBase, vertexStride))
{
}
public void AddIndexedMesh(IndexedMesh mesh)
{
_meshes.Add(mesh);
btTriangleIndexVertexArray_addIndexedMesh(_native, mesh._native);
}
public void AddIndexedMesh(IndexedMesh mesh, PhyScalarType indexType)
{
_meshes.Add(mesh);
btTriangleIndexVertexArray_addIndexedMesh2(_native, mesh._native, indexType);
}
public AlignedIndexedMeshArray IndexedMeshArray
{
get
{
// TODO: link _indexedMeshArray to _meshes
if (_indexedMeshArray == null)
{
_indexedMeshArray = new AlignedIndexedMeshArray(btTriangleIndexVertexArray_getIndexedMeshArray(_native));
}
return _indexedMeshArray;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_initialMesh != null)
{
_initialMesh.Dispose();
_initialMesh = null;
}
}
base.Dispose(disposing);
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btTriangleIndexVertexArray_new();
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btTriangleIndexVertexArray_new2(int numTriangles, IntPtr triangleIndexBase, int triangleIndexStride, int numVertices, IntPtr vertexBase, int vertexStride);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btTriangleIndexVertexArray_addIndexedMesh(IntPtr obj, IntPtr mesh);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btTriangleIndexVertexArray_addIndexedMesh2(IntPtr obj, IntPtr mesh, PhyScalarType indexType);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btTriangleIndexVertexArray_getIndexedMeshArray(IntPtr obj);
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata;
using AsmResolver.PE.DotNet.Metadata.Strings;
namespace AsmResolver.DotNet.Builder.Metadata.Strings
{
/// <summary>
/// Provides a mutable buffer for building up a strings stream in a .NET portable executable.
/// </summary>
public class StringsStreamBuffer : IMetadataStreamBuffer
{
private Dictionary<Utf8String, StringIndex> _index = new();
private List<StringsStreamBlob> _blobs = new();
private uint _currentOffset = 1;
private int _fixedBlobCount = 0;
/// <summary>
/// Creates a new strings stream buffer with the default strings stream name.
/// </summary>
public StringsStreamBuffer()
: this(StringsStream.DefaultName)
{
}
/// <summary>
/// Creates a new strings stream buffer.
/// </summary>
/// <param name="name">The name of the stream.</param>
public StringsStreamBuffer(string name)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
}
/// <inheritdoc />
public string Name
{
get;
}
/// <inheritdoc />
public bool IsEmpty => _blobs.Count == 0;
/// <summary>
/// Imports the contents of a strings stream and indexes all present strings.
/// </summary>
/// <param name="stream">The stream to import.</param>
/// <exception cref="InvalidOperationException">Occurs when the stream buffer is not empty.</exception>
public void ImportStream(StringsStream stream)
{
if (!IsEmpty)
throw new InvalidOperationException("Cannot import a stream if the buffer is not empty.");
uint offset = 1;
uint size = stream.GetPhysicalSize();
while (offset < size)
{
var value = stream.GetStringByIndex(offset)!;
uint newOffset = AppendString(value, true);
_index[value] = new StringIndex(_blobs.Count - 1, newOffset);
offset += (uint) value.ByteCount + 1;
_fixedBlobCount++;
}
}
private uint AppendString(Utf8String value, bool isFixed)
{
uint offset = _currentOffset;
_blobs.Add(new StringsStreamBlob(value, isFixed));
_currentOffset += (uint)value.ByteCount + 1;
return offset;
}
/// <summary>
/// Gets the index to the provided string. If the string is not present in the buffer, it will be appended to
/// the end of the stream.
/// </summary>
/// <param name="value">The string to lookup or add.</param>
/// <returns>The index of the string.</returns>
public uint GetStringIndex(Utf8String? value)
{
if (Utf8String.IsNullOrEmpty(value))
return 0;
if (Array.IndexOf(value.GetBytesUnsafe(), (byte) 0x00) >= 0)
throw new ArgumentException("String contains a zero byte.");
if (!_index.TryGetValue(value, out var offsetId))
{
uint offset = AppendString(value, false);
offsetId = new StringIndex(_blobs.Count - 1, offset);
_index.Add(value, offsetId);
}
return offsetId.Offset;
}
/// <summary>
/// Optimizes the buffer by removing string entries that have a common suffix with another.
/// </summary>
/// <returns>A translation table that maps old offsets to the new ones after optimizing.</returns>
/// <remarks>
/// This method might invalidate all offsets obtained by <see cref="GetStringIndex"/>.
/// </remarks>
public IDictionary<uint, uint> Optimize()
{
uint finalOffset = 1;
var newIndex = new Dictionary<Utf8String, StringIndex>();
var newBlobs = new List<StringsStreamBlob>(_fixedBlobCount);
var translationTable = new Dictionary<uint, uint>
{
[0] = 0
};
// Import fixed blobs.
for (int i = 0; i < _fixedBlobCount; i++)
AppendBlob(_blobs[i]);
// Sort all blobs based on common suffix.
var sortedEntries = _index.ToList();
sortedEntries.Sort(StringsStreamBlobSuffixComparer.Instance);
for (int i = 0; i < sortedEntries.Count; i++)
{
var currentEntry = sortedEntries[i];
var currentBlob = _blobs[currentEntry.Value.BlobIndex];
// Ignore blobs that are already added.
if (currentBlob.IsFixed)
continue;
if (i == 0)
{
// First blob should always be added, since it has no common prefix with anything else.
AppendBlob(currentBlob);
}
else
{
// Check if any blobs have a common suffix.
int reusedIndex = i;
while (reusedIndex > 0 && BytesEndsWith(sortedEntries[reusedIndex - 1].Key.GetBytesUnsafe(), currentEntry.Key.GetBytesUnsafe()))
reusedIndex--;
// Reuse blob if blob had a common suffix.
if (reusedIndex != i)
ReuseBlob(currentEntry, reusedIndex);
else
AppendBlob(currentBlob);
}
}
// Replace contents of current buffer with the newly constructed buffer.
_blobs = newBlobs;
_index = newIndex;
_currentOffset = finalOffset;
return translationTable;
void AppendBlob(in StringsStreamBlob blob)
{
newBlobs.Add(blob);
var oldIndex = _index[blob.Blob];
translationTable[oldIndex.Offset] = finalOffset;
newIndex[blob.Blob] = new StringIndex(newBlobs.Count - 1, finalOffset);
finalOffset += blob.GetPhysicalSize();
}
void ReuseBlob(in KeyValuePair<Utf8String, StringIndex> currentEntry, int reusedIndex)
{
var reusedEntry = sortedEntries[reusedIndex];
uint reusedEntryNewOffset = translationTable[reusedEntry.Value.Offset];
int relativeOffset = reusedEntry.Key.ByteCount - currentEntry.Key.ByteCount;
uint newOffset = (uint)(reusedEntryNewOffset + relativeOffset);
translationTable[currentEntry.Value.Offset] = newOffset;
newIndex[currentEntry.Key] = new StringIndex(reusedEntry.Value.BlobIndex, newOffset);
}
}
private static bool BytesEndsWith(byte[] x, byte[] y)
{
if (x.Length < y.Length)
return false;
for (int i = x.Length - 1, j = y.Length - 1; i >= 0 && j >= 0; i--, j--)
{
if (x[i] != y[j])
return false;
}
return true;
}
/// <summary>
/// Serializes the strings stream buffer to a metadata stream.
/// </summary>
/// <returns>The metadata stream.</returns>
public StringsStream CreateStream()
{
using var outputStream = new MemoryStream();
var writer = new BinaryStreamWriter(outputStream);
writer.WriteByte(0);
foreach (var blob in _blobs)
blob.Write(writer);
writer.Align(4);
return new SerializedStringsStream(Name, outputStream.ToArray());
}
/// <inheritdoc />
IMetadataStream IMetadataStreamBuffer.CreateStream() => CreateStream();
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Actor;
using Akka.Cluster.Sharding;
using Akka.Event;
using Akka.Persistence;
using GridDomain.Aggregates;
using GridDomain.Aggregates.Abstractions;
using GridDomain.Common;
using GridDomain.Common.Akka;
using GridDomain.Domains;
using GridDomain.Node.Akka.Extensions.Aggregates;
namespace GridDomain.Node.Akka.Actors.Aggregates
{
/// <summary>
/// Name should be parse by AggregateActorName
/// </summary>
/// <typeparam name="TAggregate"></typeparam>
public class AggregateActor<TAggregate> : ReceivePersistentActor where TAggregate : class, IAggregate
{
protected override ILoggingAdapter Log { get; } = Context.GetLogger();
public override string PersistenceId { get; }
protected string Id { get; }
public TAggregate Aggregate { get; }
private AggregateCommandExecutionContext ExecutionContext { get; } = new AggregateCommandExecutionContext();
protected readonly BehaviorQueue Behavior;
private readonly DateTime _startedTime;
private readonly IActorRef _commandChecker;
private readonly ICommandsResultAdapter _commandsResultAdapter;
public AggregateActor()
{
Behavior = new BehaviorQueue(Become);
Behavior.Become(AwaitingCommandBehavior, nameof(AwaitingCommandBehavior));
PersistenceId = Self.Path.Name;
Id = AggregateAddress.Parse<TAggregate>(Self.Path.Name).Id;
var aggregateExtensions = Context.System.GetAggregatesExtension();
var dependencies = aggregateExtensions.GetConfiguration<TAggregate>();
Aggregate = dependencies.AggregateFactory.Build();
_commandsResultAdapter = aggregateExtensions.GetAdapter<TAggregate>();
Context.SetReceiveTimeout(dependencies.Settings.MaxInactivityPeriod);
Recover<DomainEvent>(e => Aggregate.Apply(e));
_commandChecker = Context.ActorOf(Props.Create<CommandIdempotencyActor>(), "CommandIdempotencyWatcher");
_startedTime = BusinessDateTime.UtcNow;
}
protected virtual void AwaitingCommandBehavior()
{
Command<ReceiveTimeout>(t =>
{
Context.Parent.Tell(new Passivate(AggregateActor.ShutdownGratefully.Instance));
});
Command<AggregateActor.ShutdownGratefully>(s => { Context.Stop(Self); });
Command<AggregateActor.CheckHealth>(c => Sender.Tell(new AggregateHealthReport(Self.Path.ToString(),
BusinessDateTime.UtcNow - _startedTime,
Context.System.GetAddress().ToString())));
Command<AggregateActor.ExecuteCommand>(m =>
{
var cmd = m.Command;
if (cmd.Recipient.Id != Id)
throw new AggregateIdMismatchException();
Log.Debug("Received command {cmdId}", cmd.Id);
ExecutionContext.Command = cmd;
ExecutionContext.CommandMetadata = m.Metadata;
ExecutionContext.CommandSender = Sender;
ExecutionContext.IsWaitingForConfirmation = m.IsWaitingAcknowledgement;
try
{
Aggregate.Execute(cmd).PipeTo(Self);
}
catch (Exception ex)
{
StopOnException("Aggregate could not produce domain events", ex);
}
Behavior.Become(ProcessingCommandBehavior, nameof(ProcessingCommandBehavior));
});
}
protected override void OnPersistFailure(Exception cause, object @event, long sequenceNr)
{
ExecutionContext.CommandSender.Tell(new AggregateActor.CommandFailed(cause));
base.OnPersistFailure(cause, @event, sequenceNr);
}
private void ProcessingCommandBehavior()
{
Command<IReadOnlyCollection<IDomainEvent>>(domainEvents =>
{
Log.Debug("command executed, starting to persist events");
if (!domainEvents.Any())
{
Log.Warning("Trying to persist events but no events is presented. {@context}", ExecutionContext);
return;
}
ExecutionContext.ProducedEvents = domainEvents;
ExecutionContext.EventsPersisted = false;
//check if we already executed this command
_commandChecker.Tell(new CommandIdempotencyActor.CheckCommand(ExecutionContext.Command));
});
Command<CommandIdempotencyActor.CommandAccepted>(s =>
{
if (ExecutionContext.ProducedEvents != null && !ExecutionContext.EventsPersisted)
{
PersistProducedEvents(ExecutionContext.ProducedEvents);
}
});
Command<CommandIdempotencyActor.CommandRejected>(f =>
{
StopOnException("Command was rejected as already executed", new CommandAlreadyExecutedException());
});
//aggregate raised an error during command execution
Command<Status.Failure>(f => { StopOnException("Aggregate command execution timeout or could not produce domain events", f.Cause); });
CommandAny(StashMessage);
}
private void PersistProducedEvents(IReadOnlyCollection<IDomainEvent> domainEvents)
{
ExecutionContext.EventsPersisted = true;
int messagesToPersistCount = domainEvents.Count;
PersistAll(domainEvents,
persistedEvent =>
{
Aggregate.ApplyByVersion(persistedEvent);
if (--messagesToPersistCount != 0) return;
CompleteExecution();
});
}
private void StopOnException(string message,Exception reason)
{
//restart myself to get new state
var commandExecutionException = new AggregateActor.CommandExecutionException(message, reason);
ExecutionContext.CommandSender.Tell(new AggregateActor.CommandFailed(commandExecutionException));
throw commandExecutionException;
}
protected void StashMessage(object message)
{
Log.Debug("Stashing message {@message} current behavior is {behavior}", message, Behavior.Current);
Stash.Stash();
}
private void CompleteExecution()
{
Log.Info("Command executed. {@context}", ExecutionContext.CommandMetadata);
if (Aggregate == null)
throw new InvalidOperationException("Aggregate state was null after command execution");
if (ExecutionContext.IsWaitingForConfirmation)
{
var commandResult = _commandsResultAdapter.Adapt(ExecutionContext.Command, ExecutionContext.ProducedEvents);
var confirmation = commandResult == null
? AggregateActor.CommandExecuted.Instance
: new AggregateActor.CommandExecuted(commandResult);
ExecutionContext.CommandSender.Tell(confirmation);
}
ExecutionContext.Clear();
Behavior.Become(AwaitingCommandBehavior, nameof(AwaitingCommandBehavior));
Stash.Unstash();
}
}
public static class AggregateActor
{
public class ExecuteCommand : IHaveMetadata
{
public IMessageMetadata Metadata { get; }
public ICommand Command { get; }
public bool IsWaitingAcknowledgement { get; }
public ExecuteCommand(ICommand command, IMessageMetadata metadata, bool ack=false)
{
Command = command;
Metadata = metadata;
IsWaitingAcknowledgement = true;
}
}
public class CommandExecuted
{
public object Value { get; }
public CommandExecuted(object value)
{
Value = value;
}
public static CommandExecuted Instance { get; } = new CommandExecuted(new object());
}
public class CommandFailed : CommandExecuted
{
public Exception Reason => (Exception) Value;
public CommandFailed(Exception reason):base(reason)
{
}
}
public class CommandExecutionException : Exception
{
public CommandExecutionException(string msg,Exception reason):base(msg, reason)
{
}
}
public class ShutdownGratefully
{
private ShutdownGratefully()
{
}
public static ShutdownGratefully Instance { get; } = new ShutdownGratefully();
}
public class CheckHealth
{
private CheckHealth()
{
}
public static CheckHealth Instance { get; } = new CheckHealth();
}
}
}
| |
#region Header
/**
* JsonData.cs
* Generic type to hold JSON data (objects, arrays, and so on). This is
* the default type returned by JsonMapper.ToObject().
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
namespace LitJson
{
public class JsonData : IJsonWrapper, IEquatable<JsonData>
{
#region Fields
private IList<JsonData> inst_array;
private bool inst_boolean;
private double inst_double;
private int inst_int;
private long inst_long;
private IDictionary<string, JsonData> inst_object;
private string inst_string;
private string json;
private JsonType type;
// Used to implement the IOrderedDictionary interface
private IList<KeyValuePair<string, JsonData>> object_list;
#endregion
#region Properties
public int Count {
get { return EnsureCollection ().Count; }
}
public bool IsArray {
get { return type == JsonType.Array; }
}
public bool IsBoolean {
get { return type == JsonType.Boolean; }
}
public bool IsDouble {
get { return type == JsonType.Double; }
}
public bool IsInt {
get { return type == JsonType.Int; }
}
public bool IsLong {
get { return type == JsonType.Long; }
}
public bool IsObject {
get { return type == JsonType.Object; }
}
public bool IsString {
get { return type == JsonType.String; }
}
public ICollection<string> Keys {
get { EnsureDictionary (); return inst_object.Keys; }
}
/// <summary>
/// Determines whether the json contains an element that has the specified key.
/// </summary>
/// <param name="key">The key to locate in the json.</param>
/// <returns>true if the json contains an element that has the specified key; otherwise, false.</returns>
public Boolean ContainsKey(String key) {
EnsureDictionary();
return this.inst_object.Keys.Contains(key);
}
#endregion
#region ICollection Properties
int ICollection.Count {
get {
return Count;
}
}
bool ICollection.IsSynchronized {
get {
return EnsureCollection ().IsSynchronized;
}
}
object ICollection.SyncRoot {
get {
return EnsureCollection ().SyncRoot;
}
}
#endregion
#region IDictionary Properties
bool IDictionary.IsFixedSize {
get {
return EnsureDictionary ().IsFixedSize;
}
}
bool IDictionary.IsReadOnly {
get {
return EnsureDictionary ().IsReadOnly;
}
}
ICollection IDictionary.Keys {
get {
EnsureDictionary ();
IList<string> keys = new List<string> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
keys.Add (entry.Key);
}
return (ICollection) keys;
}
}
ICollection IDictionary.Values {
get {
EnsureDictionary ();
IList<JsonData> values = new List<JsonData> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
values.Add (entry.Value);
}
return (ICollection) values;
}
}
#endregion
#region IJsonWrapper Properties
bool IJsonWrapper.IsArray {
get { return IsArray; }
}
bool IJsonWrapper.IsBoolean {
get { return IsBoolean; }
}
bool IJsonWrapper.IsDouble {
get { return IsDouble; }
}
bool IJsonWrapper.IsInt {
get { return IsInt; }
}
bool IJsonWrapper.IsLong {
get { return IsLong; }
}
bool IJsonWrapper.IsObject {
get { return IsObject; }
}
bool IJsonWrapper.IsString {
get { return IsString; }
}
#endregion
#region IList Properties
bool IList.IsFixedSize {
get {
return EnsureList ().IsFixedSize;
}
}
bool IList.IsReadOnly {
get {
return EnsureList ().IsReadOnly;
}
}
#endregion
#region IDictionary Indexer
object IDictionary.this[object key] {
get {
return EnsureDictionary ()[key];
}
set {
if (! (key is String))
throw new ArgumentException (
"The key has to be a string");
JsonData data = ToJsonData (value);
this[(string) key] = data;
}
}
#endregion
#region IOrderedDictionary Indexer
object IOrderedDictionary.this[int idx] {
get {
EnsureDictionary ();
return object_list[idx].Value;
}
set {
EnsureDictionary ();
JsonData data = ToJsonData (value);
KeyValuePair<string, JsonData> old_entry = object_list[idx];
inst_object[old_entry.Key] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (old_entry.Key, data);
object_list[idx] = entry;
}
}
#endregion
#region IList Indexer
object IList.this[int index] {
get {
return EnsureList ()[index];
}
set {
EnsureList ();
JsonData data = ToJsonData (value);
this[index] = data;
}
}
#endregion
#region Public Indexers
public JsonData this[string prop_name] {
get {
EnsureDictionary ();
return inst_object[prop_name];
}
set {
EnsureDictionary ();
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (prop_name, value);
if (inst_object.ContainsKey (prop_name)) {
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == prop_name) {
object_list[i] = entry;
break;
}
}
} else
object_list.Add (entry);
inst_object[prop_name] = value;
json = null;
}
}
public JsonData this[int index] {
get {
EnsureCollection ();
if (type == JsonType.Array)
return inst_array[index];
return object_list[index].Value;
}
set {
EnsureCollection ();
if (type == JsonType.Array)
inst_array[index] = value;
else {
KeyValuePair<string, JsonData> entry = object_list[index];
KeyValuePair<string, JsonData> new_entry =
new KeyValuePair<string, JsonData> (entry.Key, value);
object_list[index] = new_entry;
inst_object[entry.Key] = value;
}
json = null;
}
}
#endregion
#region Constructors
public JsonData ()
{
}
public JsonData (bool boolean)
{
type = JsonType.Boolean;
inst_boolean = boolean;
}
public JsonData (double number)
{
type = JsonType.Double;
inst_double = number;
}
public JsonData (int number)
{
type = JsonType.Int;
inst_int = number;
}
public JsonData (long number)
{
type = JsonType.Long;
inst_long = number;
}
public JsonData (object obj)
{
if (obj is Boolean) {
type = JsonType.Boolean;
inst_boolean = (bool) obj;
return;
}
if (obj is Double) {
type = JsonType.Double;
inst_double = (double) obj;
return;
}
if (obj is Int32) {
type = JsonType.Int;
inst_int = (int) obj;
return;
}
if (obj is Int64) {
type = JsonType.Long;
inst_long = (long) obj;
return;
}
if (obj is String) {
type = JsonType.String;
inst_string = (string) obj;
return;
}
throw new ArgumentException (
"Unable to wrap the given object with JsonData");
}
public JsonData (string str)
{
type = JsonType.String;
inst_string = str;
}
#endregion
#region Implicit Conversions
public static implicit operator JsonData (Boolean data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Double data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int32 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int64 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (String data)
{
return new JsonData (data);
}
#endregion
#region Explicit Conversions
public static explicit operator Boolean (JsonData data)
{
if (data.type != JsonType.Boolean)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_boolean;
}
public static explicit operator Double (JsonData data)
{
if (data.type != JsonType.Double)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_double;
}
public static explicit operator Int32(JsonData data)
{
if (data.type != JsonType.Int && data.type != JsonType.Long)
{
throw new InvalidCastException(
"Instance of JsonData doesn't hold an int");
}
// cast may truncate data... but that's up to the user to consider
return data.type == JsonType.Int ? data.inst_int : (int)data.inst_long;
}
public static explicit operator Int64(JsonData data)
{
if (data.type != JsonType.Long && data.type != JsonType.Int)
{
throw new InvalidCastException(
"Instance of JsonData doesn't hold a long");
}
return data.type == JsonType.Long ? data.inst_long : data.inst_int;
}
public static explicit operator String (JsonData data)
{
if (data.type != JsonType.String)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a string");
return data.inst_string;
}
#endregion
#region ICollection Methods
void ICollection.CopyTo (Array array, int index)
{
EnsureCollection ().CopyTo (array, index);
}
#endregion
#region IDictionary Methods
void IDictionary.Add (object key, object value)
{
JsonData data = ToJsonData (value);
EnsureDictionary ().Add (key, data);
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> ((string) key, data);
object_list.Add (entry);
json = null;
}
void IDictionary.Clear ()
{
EnsureDictionary ().Clear ();
object_list.Clear ();
json = null;
}
bool IDictionary.Contains (object key)
{
return EnsureDictionary ().Contains (key);
}
IDictionaryEnumerator IDictionary.GetEnumerator ()
{
return ((IOrderedDictionary) this).GetEnumerator ();
}
void IDictionary.Remove (object key)
{
EnsureDictionary ().Remove (key);
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == (string) key) {
object_list.RemoveAt (i);
break;
}
}
json = null;
}
#endregion
#region IEnumerable Methods
IEnumerator IEnumerable.GetEnumerator ()
{
return EnsureCollection ().GetEnumerator ();
}
#endregion
#region IJsonWrapper Methods
bool IJsonWrapper.GetBoolean ()
{
if (type != JsonType.Boolean)
throw new InvalidOperationException (
"JsonData instance doesn't hold a boolean");
return inst_boolean;
}
double IJsonWrapper.GetDouble ()
{
if (type != JsonType.Double)
throw new InvalidOperationException (
"JsonData instance doesn't hold a double");
return inst_double;
}
int IJsonWrapper.GetInt ()
{
if (type != JsonType.Int)
throw new InvalidOperationException (
"JsonData instance doesn't hold an int");
return inst_int;
}
long IJsonWrapper.GetLong ()
{
if (type != JsonType.Long)
throw new InvalidOperationException (
"JsonData instance doesn't hold a long");
return inst_long;
}
string IJsonWrapper.GetString ()
{
if (type != JsonType.String)
throw new InvalidOperationException (
"JsonData instance doesn't hold a string");
return inst_string;
}
void IJsonWrapper.SetBoolean (bool val)
{
type = JsonType.Boolean;
inst_boolean = val;
json = null;
}
void IJsonWrapper.SetDouble (double val)
{
type = JsonType.Double;
inst_double = val;
json = null;
}
void IJsonWrapper.SetInt (int val)
{
type = JsonType.Int;
inst_int = val;
json = null;
}
void IJsonWrapper.SetLong (long val)
{
type = JsonType.Long;
inst_long = val;
json = null;
}
void IJsonWrapper.SetString (string val)
{
type = JsonType.String;
inst_string = val;
json = null;
}
string IJsonWrapper.ToJson ()
{
return ToJson ();
}
void IJsonWrapper.ToJson (JsonWriter writer)
{
ToJson (writer);
}
#endregion
#region IList Methods
int IList.Add (object value)
{
return Add (value);
}
void IList.Clear ()
{
EnsureList ().Clear ();
json = null;
}
bool IList.Contains (object value)
{
return EnsureList ().Contains (value);
}
int IList.IndexOf (object value)
{
return EnsureList ().IndexOf (value);
}
void IList.Insert (int index, object value)
{
EnsureList ().Insert (index, value);
json = null;
}
void IList.Remove (object value)
{
EnsureList ().Remove (value);
json = null;
}
void IList.RemoveAt (int index)
{
EnsureList ().RemoveAt (index);
json = null;
}
#endregion
#region IOrderedDictionary Methods
IDictionaryEnumerator IOrderedDictionary.GetEnumerator ()
{
EnsureDictionary ();
return new OrderedDictionaryEnumerator (
object_list.GetEnumerator ());
}
void IOrderedDictionary.Insert (int idx, object key, object value)
{
string property = (string) key;
JsonData data = ToJsonData (value);
this[property] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (property, data);
object_list.Insert (idx, entry);
}
void IOrderedDictionary.RemoveAt (int idx)
{
EnsureDictionary ();
inst_object.Remove (object_list[idx].Key);
object_list.RemoveAt (idx);
}
#endregion
#region Private Methods
private ICollection EnsureCollection ()
{
if (type == JsonType.Array)
return (ICollection) inst_array;
if (type == JsonType.Object)
return (ICollection) inst_object;
throw new InvalidOperationException (
"The JsonData instance has to be initialized first");
}
private IDictionary EnsureDictionary ()
{
if (type == JsonType.Object)
return (IDictionary) inst_object;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a dictionary");
type = JsonType.Object;
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
return (IDictionary) inst_object;
}
private IList EnsureList ()
{
if (type == JsonType.Array)
return (IList) inst_array;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a list");
type = JsonType.Array;
inst_array = new List<JsonData> ();
return (IList) inst_array;
}
private JsonData ToJsonData (object obj)
{
if (obj == null)
return null;
if (obj is JsonData)
return (JsonData) obj;
return new JsonData (obj);
}
private static void WriteJson (IJsonWrapper obj, JsonWriter writer)
{
if (obj == null) {
writer.Write (null);
return;
}
if (obj.IsString) {
writer.Write (obj.GetString ());
return;
}
if (obj.IsBoolean) {
writer.Write (obj.GetBoolean ());
return;
}
if (obj.IsDouble) {
writer.Write (obj.GetDouble ());
return;
}
if (obj.IsInt) {
writer.Write (obj.GetInt ());
return;
}
if (obj.IsLong) {
writer.Write (obj.GetLong ());
return;
}
if (obj.IsArray) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteJson ((JsonData) elem, writer);
writer.WriteArrayEnd ();
return;
}
if (obj.IsObject) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in ((IDictionary) obj)) {
writer.WritePropertyName ((string) entry.Key);
WriteJson ((JsonData) entry.Value, writer);
}
writer.WriteObjectEnd ();
return;
}
}
#endregion
public int Add (object value)
{
JsonData data = ToJsonData (value);
json = null;
return EnsureList ().Add (data);
}
public void Clear ()
{
if (IsObject) {
((IDictionary) this).Clear ();
return;
}
if (IsArray) {
((IList) this).Clear ();
return;
}
}
public bool Equals (JsonData x)
{
if (x == null)
return false;
if (x.type != this.type)
{
// further check to see if this is a long to int comparison
if ((x.type != JsonType.Int && x.type != JsonType.Long)
|| (this.type != JsonType.Int && this.type != JsonType.Long))
{
return false;
}
}
switch (this.type) {
case JsonType.None:
return true;
case JsonType.Object:
return this.inst_object.Equals (x.inst_object);
case JsonType.Array:
return this.inst_array.Equals (x.inst_array);
case JsonType.String:
return this.inst_string.Equals (x.inst_string);
case JsonType.Int:
{
if (x.IsLong)
{
if (x.inst_long < Int32.MinValue || x.inst_long > Int32.MaxValue)
return false;
return this.inst_int.Equals((int)x.inst_long);
}
return this.inst_int.Equals(x.inst_int);
}
case JsonType.Long:
{
if (x.IsInt)
{
if (this.inst_long < Int32.MinValue || this.inst_long > Int32.MaxValue)
return false;
return x.inst_int.Equals((int)this.inst_long);
}
return this.inst_long.Equals(x.inst_long);
}
case JsonType.Double:
return this.inst_double.Equals (x.inst_double);
case JsonType.Boolean:
return this.inst_boolean.Equals (x.inst_boolean);
}
return false;
}
public JsonType GetJsonType ()
{
return type;
}
public void SetJsonType (JsonType type)
{
if (this.type == type)
return;
switch (type) {
case JsonType.None:
break;
case JsonType.Object:
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
break;
case JsonType.Array:
inst_array = new List<JsonData> ();
break;
case JsonType.String:
inst_string = default (String);
break;
case JsonType.Int:
inst_int = default (Int32);
break;
case JsonType.Long:
inst_long = default (Int64);
break;
case JsonType.Double:
inst_double = default (Double);
break;
case JsonType.Boolean:
inst_boolean = default (Boolean);
break;
}
this.type = type;
}
public string ToJson ()
{
if (json != null)
return json;
StringWriter sw = new StringWriter ();
JsonWriter writer = new JsonWriter (sw);
writer.Validate = false;
WriteJson (this, writer);
json = sw.ToString ();
return json;
}
public void ToJson (JsonWriter writer)
{
bool old_validate = writer.Validate;
writer.Validate = false;
WriteJson (this, writer);
writer.Validate = old_validate;
}
public override string ToString ()
{
switch (type) {
case JsonType.Array:
return "JsonData array";
case JsonType.Boolean:
return inst_boolean.ToString ();
case JsonType.Double:
return inst_double.ToString ();
case JsonType.Int:
return inst_int.ToString ();
case JsonType.Long:
return inst_long.ToString ();
case JsonType.Object:
return "JsonData object";
case JsonType.String:
return inst_string;
}
return "Uninitialized JsonData";
}
}
internal class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
IEnumerator<KeyValuePair<string, JsonData>> list_enumerator;
public object Current {
get { return Entry; }
}
public DictionaryEntry Entry {
get {
KeyValuePair<string, JsonData> curr = list_enumerator.Current;
return new DictionaryEntry (curr.Key, curr.Value);
}
}
public object Key {
get { return list_enumerator.Current.Key; }
}
public object Value {
get { return list_enumerator.Current.Value; }
}
public OrderedDictionaryEnumerator (
IEnumerator<KeyValuePair<string, JsonData>> enumerator)
{
list_enumerator = enumerator;
}
public bool MoveNext ()
{
return list_enumerator.MoveNext ();
}
public void Reset ()
{
list_enumerator.Reset ();
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
//
// Read/Write string and byte arrays
//
namespace SilentOrbit.ProtocolBuffers
{
public static partial class ProtocolParser
{
public static string ReadString(Stream stream)
{
var bytes = ReadBytes(stream);
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
/// <summary>
/// Reads a length delimited byte array
/// </summary>
public static byte[] ReadBytes(Stream stream)
{
//VarInt length
int length = (int)ReadUInt32(stream);
//Bytes
byte[] buffer = new byte[length];
int read = 0;
while (read < length)
{
int r = stream.Read(buffer, read, length - read);
if (r == 0)
throw new ProtocolBufferException("Expected " + (length - read) + " got " + read);
read += r;
}
return buffer;
}
/// <summary>
/// Skip the next varint length prefixed bytes.
/// Alternative to ReadBytes when the data is not of interest.
/// </summary>
public static void SkipBytes(Stream stream)
{
int length = (int)ReadUInt32(stream);
if (stream.CanSeek)
stream.Seek(length, SeekOrigin.Current);
else
ReadBytes(stream);
}
public static void WriteString(Stream stream, string val)
{
WriteBytes(stream, Encoding.UTF8.GetBytes(val));
}
/// <summary>
/// Writes length delimited byte array
/// </summary>
public static void WriteBytes(Stream stream, byte[] val)
{
WriteUInt32(stream, (uint)val.Length);
stream.Write(val, 0, val.Length);
}
}
[Obsolete("Renamed to PositionStream")]
public class StreamRead : PositionStream
{
public StreamRead(Stream baseStream) : base(baseStream)
{
}
}
/// <summary>
/// Wrapper for streams that does not support the Position property.
/// Adds support for the Position property.
/// </summary>
public class PositionStream : Stream
{
readonly Stream stream;
/// <summary>
/// Bytes read in the stream starting from the beginning.
/// </summary>
public int BytesRead { get; private set; }
/// <summary>
/// Define how many bytes are allowed to read
/// </summary>
/// <param name='baseStream'>
/// Base stream.
/// </param>
/// <param name='maxLength'>
/// Max length allowed to read from the stream.
/// </param>
public PositionStream(Stream baseStream)
{
this.stream = baseStream;
}
public override void Flush()
{
throw new NotImplementedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
int read = stream.Read(buffer, offset, count);
BytesRead += read;
return read;
}
public override int ReadByte()
{
int b = stream.ReadByte();
BytesRead += 1;
return b;
}
public override long Seek(long offset, SeekOrigin origin)
{
if (stream.CanSeek)
return stream.Seek(offset, origin);
if (origin == SeekOrigin.Current && offset >= 0)
{
var buffer = new byte[Math.Min(offset, 10000)];
long end = BytesRead + offset;
while (BytesRead < end)
{
int read = stream.Read(buffer, 0, (int)Math.Min(end - BytesRead, buffer.Length));
if (read == 0)
break;
BytesRead += read;
}
return BytesRead;
}
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override long Length
{
get
{
return stream.Length;
}
}
public override long Position
{
get
{
return this.BytesRead;
}
set
{
throw new NotImplementedException();
}
}
protected override void Dispose(bool disposing)
{
stream.Dispose();
base.Dispose(disposing);
}
}
}
| |
//
// WebOSDevice.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
// Jeff Wheeler <jeff@jeffwheeler.name>
//
// Copyright (C) 2008 Novell, Inc.
// Copyright (C) 2009 Jeff Wheeler
//
// 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 Mono.Unix;
using Banshee.Base;
using Banshee.Hardware;
using Banshee.Library;
using Banshee.Collection;
using Banshee.Collection.Database;
namespace Banshee.Dap.MassStorage
{
public class WebOSDevice : CustomMassStorageDevice
{
private static string [] playback_mime_types = new string [] {
// Video
"video/mp4-generic",
"video/quicktime",
"video/mp4",
"video/mpeg4",
"video/3gp",
"video/3gpp2",
"application/sdp",
// Audio
"audio/3gpp",
"audio/3ga",
"audio/3gpp2",
"audio/amr",
"audio/x-amr",
"audio/mpa",
"audio/mp3",
"audio/x-mp3",
"audio/x-mpg",
"audio/mpeg",
"audio/mpeg3",
"audio/mpg3",
"audio/mpg",
"audio/mp4",
"audio/m4a",
"audio/aac",
"audio/x-aac",
"audio/mp4a-latm",
"audio/wav"
};
// The Pre theoretically supports these formats, but it does not
// recognize them within the media player.
private static string [] playlist_formats = new string [] {
// "audio/x-scpls",
"audio/mpegurl",
"audio/x-mpegurl"
};
private static string playlists_path = "Music/";
private static string [] audio_folders = new string [] {
"Music/",
"Videos/",
//"ringtones/",
"AmazonMP3/"
};
private static string [] video_folders = new string [] {
"Videos/"
};
private static string [] icon_names = new string [] {
"phone-palm-pre", DapSource.FallbackIcon
};
private AmazonMp3GroupSource amazon_source;
private string amazon_base_dir;
private RingtonesGroupSource ringtones_source;
public override void SourceInitialize ()
{
amazon_base_dir = System.IO.Path.Combine (Source.Volume.MountPoint, audio_folders[2]);
amazon_source = new AmazonMp3GroupSource (Source, "AmazonMP3", amazon_base_dir);
amazon_source.AutoHide = true;
ringtones_source = new RingtonesGroupSource (Source);
ringtones_source.AutoHide = true;
}
public override bool LoadDeviceConfiguration ()
{
LoadConfig ();
return true;
}
protected override string DefaultName {
get { return VendorProductInfo.ProductName; }
}
protected override string [] DefaultAudioFolders {
get { return audio_folders; }
}
protected override string [] DefaultVideoFolders {
get { return video_folders; }
}
protected override string [] DefaultPlaybackMimeTypes {
get { return playback_mime_types; }
}
protected override int DefaultFolderDepth {
get { return 2; }
}
protected override string DefaultCoverArtFileType {
get { return "jpeg"; }
}
protected override int DefaultCoverArtSize {
get { return 320; }
}
protected override string [] DefaultPlaylistFormats {
get { return playlist_formats; }
}
protected override string DefaultPlaylistPath {
get { return playlists_path; }
}
public override string [] GetIconNames ()
{
return icon_names;
}
#region Amazon MP3 Store Purchased Tracks Management
public override bool DeleteTrackHook (DatabaseTrackInfo track)
{
// Do not allow removing purchased tracks if not in the
// Amazon Purchased Music source; this should prevent
// accidental deletion of purchased music that may not
// have been copied from the device yet.
//
// TODO: Provide some feedback when a purchased track is
// skipped from deletion
//
// FIXME: unfortunately this does not work due to
// the cache models being potentially different
// even though they will always reference the same tracks
// amazon_source.TrackModel.IndexOf (track) >= 0
if (!amazon_source.Active && amazon_source.Count > 0 && track.Uri.LocalPath.StartsWith (amazon_base_dir)) {
return false;
}
return true;
}
#endregion
#region Ringtones Support
private class RingtonesGroupSource : MediaGroupSource
{
// TODO: Support dropping files onto this playlist to copy into the ringtones directory
public RingtonesGroupSource (DapSource parent)
: base (parent, Catalog.GetString ("Ringtones"))
{
ConditionSql = "(CoreTracks.Uri LIKE \"%ringtones/%\")";
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.Serialization;
// http://bungee-view.googlecode.com/svn-history/r120/trunk/lbfgs/edu/cmu/cs/bungee/lbfgs/Mcsrch.java
//package edu.cmu.cs.bungee.lbfgs;
///* Mcsrch.java
// * Copyright (C) 1999, Robert Dodier (robert_dodier@yahoo.com)
// *
// * This program is free software; you can redistribute it and/or modify
// * it under the terms of version 2.1 of the GNU Lesser General Public License
// * as published by the Free Software Foundation.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU Lesser General Public License for more details.
// *
// * You should have received a copy of the GNU Lesser General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA, 02111-1307, USA,
// * or visit the GNU web site, www.gnu.org.
// *
///**
// * This class implements an algorithm for multi-dimensional line search. This
// * file is a translation of Fortran code written by Jorge Nocedal. See comments
// * in the file <tt>LBFGS.java</tt> for more information.
// *
namespace HTLib2
{
public class Mcsrch
{
private static int[] infoc = new int[1];
private static int j = 0;
private static double dg = 0, dgm = 0, dginit = 0, dgtest = 0;
private static double[] dgx = new double[1];
private static double[] dgxm = new double[1];
private static double[] dgy = new double[1];
private static double[] dgym = new double[1];
private static double finit = 0;
private static double ftest1 = 0, fm = 0;
private static double[] fx = new double[1];
private static double[] fxm = new double[1];
private static double[] fy = new double[1];
private static double[] fym = new double[1];
public static double[] stx = new double[1];
public static double[] sty = new double[1];
static double stmin = 0, stmax = 0, width = 0, width1 = 0;
public static bool[] brackt = new bool[1];
static bool stage1 = false;
private const double ONE_HALF = 0.5, TWO_THIRDS = 0.66, FOUR = 4;
static double sqr(double x) {
return x * x;
}
static double max3(double x, double y, double z) {
return x < y ? (y < z ? z : y) : (x < z ? z : x);
}
///**
// * Minimize a function along a search direction. This code is a Java
// * translation of the function <code>MCSRCH</code> from <code>lbfgs.f</code>
// * , which in turn is a slight modification of the subroutine
// * <code>CSRCH</code> of More' and Thuente. The changes are to allow reverse
// * communication, and do not affect the performance of the routine. This
// * function, in turn, calls <code>mcstep</code>.
// * <p>
// *
// * The Java translation was effected mostly mechanically, with some manual
// * clean-up; in particular, array indices start at 0 instead of 1. Most of
// * the comments from the Fortran code have been pasted in here as well.
// * <p>
// *
// * The purpose of <code>mcsrch</code> is to find a step which satisfies a
// * sufficient decrease condition and a curvature condition.
// * <p>
// *
// * At each stage this function updates an interval of uncertainty with
// * endpoints <code>stx</code> and <code>sty</code>. The interval of
// * uncertainty is initially chosen so that it contains a minimizer of the
// * modified function
// *
// * <pre>
// * f(x+stp*s) - f(x) - ftol*stp*(gradf(x)'s).
// * </pre>
// *
// * If a step is obtained for which the modified function has a nonpositive
// * function value and nonnegative derivative, then the interval of
// * uncertainty is chosen so that it contains a minimizer of
// * <code>f(x+stp*s)</code>.
// * <p>
// *
// * The algorithm is designed to find a step which satisfies the sufficient
// * decrease condition
// *
// * <pre>
// * f(x+stp*s) <= f(X) + ftol*stp*(gradf(x)'s),
// * </pre>
// *
// * and the curvature condition
// *
// * <pre>
// * abs(gradf(x+stp*s)'s)) <= gtol*abs(gradf(x)'s).
// * </pre>
// *
// * If <code>ftol</code> is less than <code>gtol</code> and if, for example,
// * the function is bounded below, then there is always a step which
// * satisfies both conditions. If no step can be found which satisfies both
// * conditions, then the algorithm usually stops when rounding errors prevent
// * further progress. In this case <code>stp</code> only satisfies the
// * sufficient decrease condition.
// * <p>
// *
// * @author Original Fortran version by Jorge J. More' and David J. Thuente
// * as part of the Minpack project, June 1983, Argonne National
// * Laboratory. Java translation by Robert Dodier, August 1997.
// *
// * @param n
// * The number of variables.
// *
// * @param x
// * On entry this contains the base point for the line search. On
// * exit it contains <code>x + stp*s</code>.
// *
// * @param f
// * On entry this contains the value of the objective function at
// * <code>x</code>. On exit it contains the value of the objective
// * function at <code>x + stp*s</code>.
// *
// * @param g
// * On entry this contains the gradient of the objective function
// * at <code>x</code>. On exit it contains the gradient at
// * <code>x + stp*s</code>.
// *
// * @param s
// * The search direction.
// *
// * @param stp
// * On entry this contains an initial estimate of a satifactory
// * step length. On exit <code>stp</code> contains the final
// * estimate.
// *
// * @param ftol
// * Tolerance for the sufficient decrease condition.
// *
// * @param xtol
// * Termination occurs when the relative width of the interval of
// * uncertainty is at most <code>xtol</code>.
// *
// * @param maxfev
// * Termination occurs when the number of evaluations of the
// * objective function is at least <code>maxfev</code> by the end
// * of an iteration.
// *
// * @param info
// * This is an output variable, which can have these values:
// * <ul>
// * <li><code>info = 0</code> Improper input parameters. <li>
// * <code>info = -1</code> A return is made to compute the
// * function and gradient. <li><code>info = 1</code> The
// * sufficient decrease condition and the directional derivative
// * condition hold. <li><code>info = 2</code> Relative width of
// * the interval of uncertainty is at most <code>xtol</code>. <li>
// * <code>info = 3</code> Number of function evaluations has
// * reached <code>maxfev</code>. <li><code>info = 4</code> The
// * step is at the lower bound <code>stpmin</code>. <li><code>info
// * = 5</code> The step is at the upper bound <code>stpmax</code>.
// * <li><code>info = 6</code> Rounding errors prevent further
// * progress. There may not be a step which satisfies the
// * sufficient decrease and curvature conditions. Tolerances may
// * be too small.
// * </ul>
// *
// * @param nfev
// * On exit, this is set to the number of function evaluations.
// *
// * @param wa
// * Temporary storage array, of length <code>n</code>.
// *
public static void mcsrch(int n, double[] x, double f, double[] g,
double[] s, int is0, double[] stp, double ftol, double xtol,
int maxfev, int[] info, int[] nfev, double[] wa, int[] iprint)
{
// System.err.println("mc " + f + " " + stp[0]);
if (info[0] != -1) {
infoc[0] = 1;
if (n <= 0 || stp[0] <= 0 || ftol < 0 || LBFGS.gtol < 0 || xtol < 0
|| LBFGS.stpmin < 0 || LBFGS.stpmax < LBFGS.stpmin
|| maxfev <= 0)
return;
// Compute the initial gradient in the search direction
// and check that s is a descent direction.
dginit = 0;
for (j = 1; j <= n; j += 1) {
dginit += g[j - 1] * s[is0 + j - 1];
if (Double.IsNaN(dginit))
System_err_println("NaN " + g[j - 1] + " " + s[is0 + j - 1]);
}
if (dginit >= 0) {
System_out_println("The search direction is not a descent direction.");
return;
}
brackt[0] = false;
stage1 = true;
nfev[0] = 0;
finit = f;
dgtest = ftol * dginit;
width = LBFGS.stpmax - LBFGS.stpmin;
width1 = width / ONE_HALF;
for (j = 1; j <= n; j += 1) {
wa[j - 1] = x[j - 1];
}
// The variables stx, fx, dgx contain the values of the step,
// function, and directional derivative at the best step.
// The variables sty, fy, dgy contain the value of the step,
// function, and derivative at the other endpoint of
// the interval of uncertainty.
// The variables stp, f, dg contain the values of the step,
// function, and derivative at the current step.
stx[0] = 0;
fx[0] = finit;
dgx[0] = dginit;
sty[0] = 0;
fy[0] = finit;
dgy[0] = dginit;
if (iprint[0] > 0)
System_err_println("new line search f=" + finit + " dg="
+ dginit + " stp=" + stp[0]);
}
while (true) {
if (info[0] != -1) {
// Set the minimum and maximum steps to correspond
// to the present interval of uncertainty.
if (brackt[0]) {
stmin = Math.Min(stx[0], sty[0]);
stmax = Math.Max(stx[0], sty[0]);
} else {
stmin = stx[0];
stmax = stp[0] + FOUR * (stp[0] - stx[0]);
}
// Force the step to be within the bounds stpmax and stpmin.
setSTP(stp, Math.Max(stp[0], LBFGS.stpmin));
setSTP(stp, Math.Min(stp[0], LBFGS.stpmax));
// If an unusual termination is to occur then let
// stp be the lowest point obtained so far.
if ((brackt[0] && (stp[0] <= stmin || stp[0] >= stmax || stmax
- stmin <= xtol * stmax))
|| nfev[0] >= maxfev - 1 || infoc[0] == 0)
setSTP(stp, stx[0]);
// Evaluate the function and gradient at stp
// and compute the directional derivative.
// We return to main program to obtain F and G.
for (j = 1; j <= n; j += 1) {
x[j - 1] = wa[j - 1] + stp[0] * s[is0 + j - 1];
if (Math.Abs(x[j - 1]) > 40) {
System_err_println("big wt " + j + " " + stp[0] + " "
+ s[is0 + j - 1]);
}
}
info[0] = -1;
return;
}
info[0] = 0;
nfev[0] = nfev[0] + 1;
dg = 0;
for (j = 1; j <= n; j += 1) {
dg = dg + g[j - 1] * s[is0 + j - 1];
}
ftest1 = finit + stp[0] * dgtest;
// Test for convergence.
if ((brackt[0] && (stp[0] <= stmin || stp[0] >= stmax))
|| infoc[0] == 0)
// Rounding errors prevent further
// progress. There may not be a step which satisfies the
// sufficient decrease and curvature conditions. Tolerances
// may
// be too small.
info[0] = 6;
if (stp[0] == LBFGS.stpmax && f <= ftest1 && dg <= dgtest)
// The step is at the upper bound <code>stpmax</code>.
info[0] = 5;
if (stp[0] == LBFGS.stpmin && (f > ftest1 || dg >= dgtest))
// The step is at the lower bound <code>stpmin</code>.
info[0] = 4;
if (nfev[0] >= maxfev)
// Number of function evaluations has reached
// <code>maxfev</code>
info[0] = 3;
if (brackt[0] && stmax - stmin <= xtol * stmax)
// Relative width of the interval of uncertainty is at most
// <code>xtol</code>
info[0] = 2;
if (f <= ftest1 && Math.Abs(dg) <= LBFGS.gtol * (-dginit))
// The sufficient decrease condition and the directional
// derivative condition hold.
info[0] = 1;
// Check for termination.
if (info[0] != 0) {
info[0] = 1;
return;
}
// In the first stage we seek a step for which the modified
// function has a nonpositive value and nonnegative derivative.
if (stage1 && f <= ftest1
&& dg >= Math.Min(ftol, LBFGS.gtol) * dginit)
stage1 = false;
// A modified function is used to predict the step only if
// we have not obtained a step for which the modified
// function has a nonpositive function value and nonnegative
// derivative, and if a lower function value has been
// obtained but the decrease is not sufficient.
if (stage1 && f <= fx[0] && f > ftest1) {
// Define the modified function and derivative values.
fm = f - stp[0] * dgtest;
fxm[0] = fx[0] - stx[0] * dgtest;
fym[0] = fy[0] - sty[0] * dgtest;
dgm = dg - dgtest;
dgxm[0] = dgx[0] - dgtest;
dgym[0] = dgy[0] - dgtest;
// Call cstep to update the interval of uncertainty
// and to compute the new step.
mcstep(stx, fxm, dgxm, sty, fym, dgym, stp, fm, dgm, brackt,
stmin, stmax, infoc, iprint);
// Reset the function and gradient values for f.
fx[0] = fxm[0] + stx[0] * dgtest;
fy[0] = fym[0] + sty[0] * dgtest;
dgx[0] = dgxm[0] + dgtest;
dgy[0] = dgym[0] + dgtest;
} else {
// Call mcstep to update the interval of uncertainty
// and to compute the new step.
mcstep(stx, fx, dgx, sty, fy, dgy, stp, f, dg, brackt, stmin,
stmax, infoc, iprint);
}
if (iprint[0] > 0)
System_err_println(" msrch internal f=" + f + " dg=" + dg
+ " stx=" + stx[0] + " sty=" + sty[0] + " brackt="
+ brackt[0] + " stp=" + stp[0]);
// Force a sufficient decrease in the size of the
// interval of uncertainty.
if (brackt[0]) {
if (Math.Abs(sty[0] - stx[0]) >= TWO_THIRDS * width1)
setSTP(stp, (sty[0] + stx[0]) / 2.0);
width1 = width;
width = Math.Abs(sty[0] - stx[0]);
}
}
}
///**
// * The purpose of this function is to compute a safeguarded step for a
// * linesearch and to update an interval of uncertainty for a minimizer of
// * the function.
// * <p>
// *
// * The parameter <code>stx</code> contains the step with the least function
// * value. The parameter <code>stp</code> contains the current step. It is
// * assumed that the derivative at <code>stx</code> is negative in the
// * direction of the step. If <code>brackt[0]</code> is <code>true</code>
// * when <code>mcstep</code> returns then a minimizer has been bracketed in
// * an interval of uncertainty with endpoints <code>stx</code> and
// * <code>sty</code>.
// * <p>
// *
// * Variables that must be modified by <code>mcstep</code> are implemented as
// * 1-element arrays.
// *
// * @param stx1
// * Step at the best step obtained so far. This variable is
// * modified by <code>mcstep</code>.
// * @param fx1
// * Function value at the best step obtained so far. This variable
// * is modified by <code>mcstep</code>.
// * @param dx
// * Derivative at the best step obtained so far. The derivative
// * must be negative in the direction of the step, that is,
// * <code>dx</code> and <code>stp-stx</code> must have opposite
// * signs. This variable is modified by <code>mcstep</code>.
// *
// * @param sty1
// * Step at the other endpoint of the interval of uncertainty.
// * This variable is modified by <code>mcstep</code>.
// * @param fy1
// * Function value at the other endpoint of the interval of
// * uncertainty. This variable is modified by <code>mcstep</code>.
// * @param dy
// * Derivative at the other endpoint of the interval of
// * uncertainty. This variable is modified by <code>mcstep</code>.
// *
// * @param stp
// * Step at the current step. If <code>brackt</code> is set then
// * on input <code>stp</code> must be between <code>stx</code> and
// * <code>sty</code>. On output <code>stp</code> is set to the new
// * step.
// * @param fp
// * Function value at the current step.
// * @param dp
// * Derivative at the current step.
// *
// * @param brackt1
// * Tells whether a minimizer has been bracketed. If the minimizer
// * has not been bracketed, then on input this variable must be
// * set <code>false</code>. If the minimizer has been bracketed,
// * then on output this variable is <code>true</code>.
// *
// * @param stpmin
// * Lower bound for the step.
// * @param stpmax
// * Upper bound for the step.
// *
// * @param info
// * On return from <code>mcstep</code>, this is set as follows: If
// * <code>info</code> is 1, 2, 3, or 4, then the step has been
// * computed successfully. Otherwise <code>info</code> = 0, and
// * this indicates improper input parameters.
// *
// * @author Jorge J. More, David J. Thuente: original Fortran version, as
// * part of Minpack project. Argonne Nat'l Laboratory, June 1983.
// * Robert Dodier: Java translation, August 1997.
// *
public static void mcstep(double[] stx1, double[] fx1, double[] dx,
double[] sty1, double[] fy1, double[] dy, double[] stp, double fp,
double dp, bool[] brackt1, double stpmin, double stpmax,
int[] info, int[] iprint)
{
bool bound;
double gamma, p, q, r, s, sgnd, stpc, stpf, stpq, theta;
info[0] = 0;
if ((brackt1[0] && (stp[0] <= Math.Min(stx1[0], sty1[0]) || stp[0] >= Math
.Max(stx1[0], sty1[0])))
|| dx[0] * (stp[0] - stx1[0]) >= 0.0 || stpmax < stpmin) {
if (iprint[0] > 0)
System_err_println("mcstep=0 " + brackt1[0] + " " + stp[0]
+ " " + stx1[0] + " " + sty1[0] + " " + dx[0] + " "
+ stpmax + " " + stpmin);
return;
}
// Determine if the derivatives have opposite sign.
sgnd = dp * (dx[0] / Math.Abs(dx[0]));
if (fp > fx1[0]) {
// First case. A higher function value.
// The minimum is bracketed. If the cubic step is closer
// to stx than the quadratic step, the cubic step is taken,
// else the average of the cubic and quadratic steps is taken.
info[0] = 1;
bound = true;
theta = 3 * (fx1[0] - fp) / (stp[0] - stx1[0]) + dx[0] + dp;
s = max3(Math.Abs(theta), Math.Abs(dx[0]), Math.Abs(dp));
gamma = s * Math.Sqrt(sqr(theta / s) - (dx[0] / s) * (dp / s));
if (stp[0] < stx1[0])
gamma = -gamma;
p = (gamma - dx[0]) + theta;
q = ((gamma - dx[0]) + gamma) + dp;
r = p / q;
stpc = stx1[0] + r * (stp[0] - stx1[0]);
stpq = stx1[0]
+ ((dx[0] / ((fx1[0] - fp) / (stp[0] - stx1[0]) + dx[0])) / 2)
* (stp[0] - stx1[0]);
if (Math.Abs(stpc - stx1[0]) < Math.Abs(stpq - stx1[0])) {
stpf = stpc;
} else {
stpf = stpc + (stpq - stpc) / 2;
}
brackt1[0] = true;
} else if (sgnd < 0.0) {
// Second case. A lower function value and derivatives of
// opposite sign. The minimum is bracketed. If the cubic
// step is closer to stx than the quadratic (secant) step,
// the cubic step is taken, else the quadratic step is taken.
info[0] = 2;
bound = false;
theta = 3 * (fx1[0] - fp) / (stp[0] - stx1[0]) + dx[0] + dp;
s = max3(Math.Abs(theta), Math.Abs(dx[0]), Math.Abs(dp));
gamma = s * Math.Sqrt(sqr(theta / s) - (dx[0] / s) * (dp / s));
if (stp[0] > stx1[0])
gamma = -gamma;
p = (gamma - dp) + theta;
q = ((gamma - dp) + gamma) + dx[0];
r = p / q;
stpc = stp[0] + r * (stx1[0] - stp[0]);
stpq = stp[0] + (dp / (dp - dx[0])) * (stx1[0] - stp[0]);
if (Math.Abs(stpc - stp[0]) > Math.Abs(stpq - stp[0])) {
stpf = stpc;
} else {
stpf = stpq;
}
brackt1[0] = true;
} else if (Math.Abs(dp) < Math.Abs(dx[0])) {
// Third case. A lower function value, derivatives of the
// same sign, and the magnitude of the derivative decreases.
// The cubic step is only used if the cubic tends to infinity
// in the direction of the step or if the minimum of the cubic
// is beyond stp. Otherwise the cubic step is defined to be
// either stpmin or stpmax. The quadratic (secant) step is also
// computed and if the minimum is bracketed then the the step
// closest to stx is taken, else the step farthest away is taken.
info[0] = 3;
bound = true;
theta = 3 * (fx1[0] - fp) / (stp[0] - stx1[0]) + dx[0] + dp;
s = max3(Math.Abs(theta), Math.Abs(dx[0]), Math.Abs(dp));
gamma = s
* Math.Sqrt(Math.Max(0, sqr(theta / s) - (dx[0] / s)
* (dp / s)));
if (stp[0] > stx1[0])
gamma = -gamma;
p = (gamma - dp) + theta;
q = (gamma + (dx[0] - dp)) + gamma;
r = p / q;
if (r < 0.0 && gamma != 0.0) {
stpc = stp[0] + r * (stx1[0] - stp[0]);
} else if (stp[0] > stx1[0]) {
stpc = stpmax;
} else {
stpc = stpmin;
}
stpq = stp[0] + (dp / (dp - dx[0])) * (stx1[0] - stp[0]);
if (brackt1[0]) {
if (Math.Abs(stp[0] - stpc) < Math.Abs(stp[0] - stpq)) {
stpf = stpc;
} else {
stpf = stpq;
}
} else {
if (Math.Abs(stp[0] - stpc) > Math.Abs(stp[0] - stpq)) {
stpf = stpc;
} else {
stpf = stpq;
}
}
} else {
// Fourth case. A lower function value, derivatives of the
// same sign, and the magnitude of the derivative does
// not decrease. If the minimum is not bracketed, the step
// is either stpmin or stpmax, else the cubic step is taken.
info[0] = 4;
bound = false;
if (brackt1[0]) {
theta = 3 * (fp - fy1[0]) / (sty1[0] - stp[0]) + dy[0] + dp;
s = max3(Math.Abs(theta), Math.Abs(dy[0]), Math.Abs(dp));
gamma = s * Math.Sqrt(sqr(theta / s) - (dy[0] / s) * (dp / s));
if (stp[0] > sty1[0])
gamma = -gamma;
p = (gamma - dp) + theta;
q = ((gamma - dp) + gamma) + dy[0];
r = p / q;
stpc = stp[0] + r * (sty1[0] - stp[0]);
stpf = stpc;
} else if (stp[0] > stx1[0]) {
stpf = stpmax;
} else {
stpf = stpmin;
}
}
// Update the interval of uncertainty. This update does not
// depend on the new step or the case analysis above.
if (fp > fx1[0]) {
sty1[0] = stp[0];
fy1[0] = fp;
dy[0] = dp;
} else {
if (sgnd < 0.0) {
sty1[0] = stx1[0];
fy1[0] = fx1[0];
dy[0] = dx[0];
}
stx1[0] = stp[0];
fx1[0] = fp;
dx[0] = dp;
}
// Compute the new step and safeguard it.
stpf = Math.Min(stpmax, stpf);
stpf = Math.Max(stpmin, stpf);
setSTP(stp, stpf);
if (brackt1[0] && bound) {
double possibleStep = stx1[0] + TWO_THIRDS * (sty1[0] - stx1[0]);
if (sty1[0] > stx1[0]) {
setSTP(stp, Math.Min(possibleStep, stp[0]));
} else {
setSTP(stp, Math.Max(possibleStep, stp[0]));
}
}
// System.err.println("mcsetp stp => " + stp[0] + " info=" + info[0]);
return;
}
public static void setSTP(double[] stp, double value)
{
if (value < 0)// || value > 10)
throw new ArgumentException(value + "");
if (value > 1000) {
stp[0] = 1000;
System_err_println("Reducing step from " + value + " to 1000");
} else {
stp[0] = value;
}
// curStp = stp[0];
}
static void System_err_print(string msg) { System.Console.Error.Write(msg); }
static void System_err_println(string msg) { System.Console.Error.WriteLine(msg); }
static void System_out_println(string msg) { System.Console.WriteLine(msg); }
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
namespace ZXing.Common.Test
{
/// <summary>
/// <author>Sean Owen</author>
/// </summary>
[TestFixture]
public sealed class BitArrayTestCase
{
[Test]
public void testGetSet()
{
BitArray array = new BitArray(33);
for (int i = 0; i < 33; i++)
{
Assert.IsFalse(array[i]);
array[i] = true;
Assert.IsTrue(array[i]);
}
}
[Test]
public void testGetNextSet1()
{
BitArray array = new BitArray(32);
for (int i = 0; i < array.Size; i++)
{
Assert.AreEqual(32, array.getNextSet(i));
}
array = new BitArray(33);
for (int i = 0; i < array.Size; i++)
{
Assert.AreEqual(33, array.getNextSet(i));
}
}
[Test]
public void testGetNextSet2()
{
BitArray array = new BitArray(33);
array[31] = true;
for (int i = 0; i < array.Size; i++)
{
Assert.AreEqual(i <= 31 ? 31 : 33, array.getNextSet(i));
}
array = new BitArray(33);
array[32] = true;
for (int i = 0; i < array.Size; i++)
{
Assert.AreEqual(32, array.getNextSet(i));
}
}
[Test]
public void testGetNextSet3()
{
BitArray array = new BitArray(63);
array[31] = true;
array[32] = true;
for (int i = 0; i < array.Size; i++)
{
int expected;
if (i <= 31)
{
expected = 31;
}
else if (i == 32)
{
expected = 32;
}
else
{
expected = 63;
}
Assert.AreEqual(expected, array.getNextSet(i));
}
}
[Test]
public void testGetNextSet4()
{
BitArray array = new BitArray(63);
array[33] = true;
array[40] = true;
for (int i = 0; i < array.Size; i++)
{
int expected;
if (i <= 33)
{
expected = 33;
}
else if (i <= 40)
{
expected = 40;
}
else
{
expected = 63;
}
Assert.AreEqual(expected, array.getNextSet(i));
}
}
[Test]
public void testGetNextSet5()
{
Random r = new Random(0x0EADBEEF);
for (int i = 0; i < 10; i++)
{
BitArray array = new BitArray(1 + r.Next(100));
int numSet = r.Next(20);
for (int j = 0; j < numSet; j++)
{
array[r.Next(array.Size)] = true;
}
int numQueries = r.Next(20);
for (int j = 0; j < numQueries; j++)
{
int query = r.Next(array.Size);
int expected = query;
while (expected < array.Size && !array[expected])
{
expected++;
}
int actual = array.getNextSet(query);
if (actual != expected)
{
array.getNextSet(query);
}
Assert.AreEqual(expected, actual);
}
}
}
[Test]
public void testSetBulk()
{
BitArray array = new BitArray(64);
array.setBulk(32, -65536);
for (int i = 0; i < 48; i++)
{
Assert.IsFalse(array[i]);
}
for (int i = 48; i < 64; i++)
{
Assert.IsTrue(array[i]);
}
}
[Test]
public void testClear()
{
BitArray array = new BitArray(32);
for (int i = 0; i < 32; i++)
{
array[i] = true;
}
array.clear();
for (int i = 0; i < 32; i++)
{
Assert.IsFalse(array[i]);
}
}
[Test]
public void testGetArray()
{
BitArray array = new BitArray(64);
array[0] = true;
array[63] = true;
var ints = array.Array;
Assert.AreEqual(1, ints[0]);
Assert.AreEqual(Int32.MinValue, ints[1]);
}
[Test]
public void testIsRange()
{
BitArray array = new BitArray(64);
Assert.IsTrue(array.isRange(0, 64, false));
Assert.IsFalse(array.isRange(0, 64, true));
array[32] = true;
Assert.IsTrue(array.isRange(32, 33, true));
array[31] = true;
Assert.IsTrue(array.isRange(31, 33, true));
array[34] = true;
Assert.IsFalse(array.isRange(31, 35, true));
for (int i = 0; i < 31; i++)
{
array[i] = true;
}
Assert.IsTrue(array.isRange(0, 33, true));
for (int i = 33; i < 64; i++)
{
array[i] = true;
}
Assert.IsTrue(array.isRange(0, 64, true));
Assert.IsFalse(array.isRange(0, 64, false));
}
#if !SILVERLIGHT
[Test]
public void ReverseAlgorithmTest()
{
var oldBits = new[] { 128, 256, 512, 6453324, 50934953 };
for (var size = 1; size < 160; size++)
{
var newBitsOriginal = reverseOriginal(oldBits, size);
var newBitsNew = reverseNew(oldBits, size);
if (!arrays_are_equal(newBitsOriginal, newBitsNew, size / 32 + 1))
{
System.Diagnostics.Trace.WriteLine(size);
System.Diagnostics.Trace.WriteLine(BitsToString(oldBits, size));
System.Diagnostics.Trace.WriteLine(BitsToString(newBitsOriginal, size));
System.Diagnostics.Trace.WriteLine(BitsToString(newBitsNew, size));
}
Assert.IsTrue(arrays_are_equal(newBitsOriginal, newBitsNew, size / 32 + 1));
}
}
[Test]
public void ReverseSpeedTest()
{
var size = 140;
var oldBits = new[] {128, 256, 512, 6453324, 50934953};
var newBitsOriginal = reverseOriginal(oldBits, size);
var newBitsNew = reverseNew(oldBits, size);
System.Diagnostics.Trace.WriteLine(BitsToString(oldBits, size));
System.Diagnostics.Trace.WriteLine(BitsToString(newBitsOriginal, size));
System.Diagnostics.Trace.WriteLine(BitsToString(newBitsNew, size));
Assert.IsTrue(arrays_are_equal(newBitsOriginal, newBitsNew, newBitsNew.Length));
var startOld = DateTime.Now;
for (int runs = 0; runs < 1000000; runs++)
{
reverseOriginal(oldBits, 140);
}
var endOld = DateTime.Now;
var startNew = DateTime.Now;
for (int runs = 0; runs < 1000000; runs++)
{
reverseNew(oldBits, 140);
}
var endNew = DateTime.Now;
System.Diagnostics.Trace.WriteLine(endOld - startOld);
System.Diagnostics.Trace.WriteLine(endNew - startNew);
}
/// <summary> Reverses all bits in the array.</summary>
private int[] reverseOriginal(int[] oldBits, int oldSize)
{
int[] newBits = new int[oldBits.Length];
int size = oldSize;
for (int i = 0; i < size; i++)
{
if (bits_index(oldBits, size - i - 1))
{
newBits[i >> 5] |= 1 << (i & 0x1F);
}
}
return newBits;
}
private bool bits_index(int[] bits, int i)
{
return (bits[i >> 5] & (1 << (i & 0x1F))) != 0;
}
/// <summary> Reverses all bits in the array.</summary>
private int[] reverseNew(int[] oldBits, int oldSize)
{
// doesn't work if more ints are used as necessary
int[] newBits = new int[oldBits.Length];
var oldBitsLen = (int)Math.Ceiling(oldSize / 32f);
var len = oldBitsLen - 1;
for (var i = 0; i < oldBitsLen; i++)
{
var x = (long)oldBits[i];
x = ((x >> 1) & 0x55555555u) | ((x & 0x55555555u) << 1);
x = ((x >> 2) & 0x33333333u) | ((x & 0x33333333u) << 2);
x = ((x >> 4) & 0x0f0f0f0fu) | ((x & 0x0f0f0f0fu) << 4);
x = ((x >> 8) & 0x00ff00ffu) | ((x & 0x00ff00ffu) << 8);
x = ((x >> 16) & 0xffffu) | ((x & 0xffffu) << 16);
newBits[len - i] = (int)x;
}
if (oldSize != oldBitsLen * 32)
{
var leftOffset = oldBitsLen * 32 - oldSize;
var mask = 1;
for (var i = 0; i < 31 - leftOffset; i++ )
mask = (mask << 1) | 1;
var currentInt = (newBits[0] >> leftOffset) & mask;
for (var i = 1; i < oldBitsLen; i++)
{
var nextInt = newBits[i];
currentInt |= nextInt << (32 - leftOffset);
newBits[i - 1] = currentInt;
currentInt = (nextInt >> leftOffset) & mask;
}
newBits[oldBitsLen - 1] = currentInt;
}
return newBits;
}
private bool arrays_are_equal(int[] left, int[] right, int size)
{
for (var i = 0; i < size; i++)
{
if (left[i] != right[i])
return false;
}
return true;
}
private string BitsToString(int[] bits, int size)
{
var result = new System.Text.StringBuilder(size);
for (int i = 0; i < size; i++)
{
if ((i & 0x07) == 0)
{
result.Append(' ');
}
result.Append(bits_index(bits, i) ? 'X' : '.');
}
return result.ToString();
}
[Test]
public void testBitArrayNet()
{
var netArray = new System.Collections.BitArray(140, false);
var zxingArray = new BitArray(140);
var netVal = netArray[100];
var zxingVal = zxingArray[100];
Assert.AreEqual(netVal, zxingVal);
var startOld = DateTime.Now;
for (int runs = 0; runs < 1000000; runs++)
{
netVal = netArray[100];
netArray[100] = netVal;
}
var endOld = DateTime.Now;
var startNew = DateTime.Now;
for (int runs = 0; runs < 1000000; runs++)
{
zxingVal = zxingArray[100];
zxingArray[100] = zxingVal;
}
var endNew = DateTime.Now;
System.Diagnostics.Trace.WriteLine(endOld - startOld);
System.Diagnostics.Trace.WriteLine(endNew - startNew);
}
#endif
}
}
| |
// 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.V9.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.V9.Services
{
/// <summary>Settings for <see cref="CustomerUserAccessServiceClient"/> instances.</summary>
public sealed partial class CustomerUserAccessServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CustomerUserAccessServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CustomerUserAccessServiceSettings"/>.</returns>
public static CustomerUserAccessServiceSettings GetDefault() => new CustomerUserAccessServiceSettings();
/// <summary>
/// Constructs a new <see cref="CustomerUserAccessServiceSettings"/> object with default settings.
/// </summary>
public CustomerUserAccessServiceSettings()
{
}
private CustomerUserAccessServiceSettings(CustomerUserAccessServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetCustomerUserAccessSettings = existing.GetCustomerUserAccessSettings;
MutateCustomerUserAccessSettings = existing.MutateCustomerUserAccessSettings;
OnCopy(existing);
}
partial void OnCopy(CustomerUserAccessServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerUserAccessServiceClient.GetCustomerUserAccess</c> and
/// <c>CustomerUserAccessServiceClient.GetCustomerUserAccessAsync</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 GetCustomerUserAccessSettings { 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>CustomerUserAccessServiceClient.MutateCustomerUserAccess</c> and
/// <c>CustomerUserAccessServiceClient.MutateCustomerUserAccessAsync</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 MutateCustomerUserAccessSettings { 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="CustomerUserAccessServiceSettings"/> object.</returns>
public CustomerUserAccessServiceSettings Clone() => new CustomerUserAccessServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CustomerUserAccessServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class CustomerUserAccessServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerUserAccessServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CustomerUserAccessServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CustomerUserAccessServiceClientBuilder()
{
UseJwtAccessWithScopes = CustomerUserAccessServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CustomerUserAccessServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerUserAccessServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CustomerUserAccessServiceClient Build()
{
CustomerUserAccessServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CustomerUserAccessServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CustomerUserAccessServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CustomerUserAccessServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CustomerUserAccessServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CustomerUserAccessServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CustomerUserAccessServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CustomerUserAccessServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CustomerUserAccessServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerUserAccessServiceClient.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>CustomerUserAccessService client wrapper, for convenient use.</summary>
/// <remarks>
/// This service manages the permissions of a user on a given customer.
/// </remarks>
public abstract partial class CustomerUserAccessServiceClient
{
/// <summary>
/// The default endpoint for the CustomerUserAccessService 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 CustomerUserAccessService scopes.</summary>
/// <remarks>
/// The default CustomerUserAccessService 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="CustomerUserAccessServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CustomerUserAccessServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CustomerUserAccessServiceClient"/>.</returns>
public static stt::Task<CustomerUserAccessServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CustomerUserAccessServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CustomerUserAccessServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CustomerUserAccessServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CustomerUserAccessServiceClient"/>.</returns>
public static CustomerUserAccessServiceClient Create() => new CustomerUserAccessServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CustomerUserAccessServiceClient"/> 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="CustomerUserAccessServiceSettings"/>.</param>
/// <returns>The created <see cref="CustomerUserAccessServiceClient"/>.</returns>
internal static CustomerUserAccessServiceClient Create(grpccore::CallInvoker callInvoker, CustomerUserAccessServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CustomerUserAccessService.CustomerUserAccessServiceClient grpcClient = new CustomerUserAccessService.CustomerUserAccessServiceClient(callInvoker);
return new CustomerUserAccessServiceClientImpl(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 CustomerUserAccessService client</summary>
public virtual CustomerUserAccessService.CustomerUserAccessServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the CustomerUserAccess 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::CustomerUserAccess GetCustomerUserAccess(GetCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the CustomerUserAccess 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::CustomerUserAccess> GetCustomerUserAccessAsync(GetCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the CustomerUserAccess 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::CustomerUserAccess> GetCustomerUserAccessAsync(GetCustomerUserAccessRequest request, st::CancellationToken cancellationToken) =>
GetCustomerUserAccessAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the customer user access.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerUserAccess GetCustomerUserAccess(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerUserAccess(new GetCustomerUserAccessRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the customer user access.
/// </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::CustomerUserAccess> GetCustomerUserAccessAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerUserAccessAsync(new GetCustomerUserAccessRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the customer user access.
/// </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::CustomerUserAccess> GetCustomerUserAccessAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetCustomerUserAccessAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the customer user access.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerUserAccess GetCustomerUserAccess(gagvr::CustomerUserAccessName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerUserAccess(new GetCustomerUserAccessRequest
{
ResourceNameAsCustomerUserAccessName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the customer user access.
/// </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::CustomerUserAccess> GetCustomerUserAccessAsync(gagvr::CustomerUserAccessName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerUserAccessAsync(new GetCustomerUserAccessRequest
{
ResourceNameAsCustomerUserAccessName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the CustomerUserAccess in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the customer user access.
/// </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::CustomerUserAccess> GetCustomerUserAccessAsync(gagvr::CustomerUserAccessName resourceName, st::CancellationToken cancellationToken) =>
GetCustomerUserAccessAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [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 MutateCustomerUserAccessResponse MutateCustomerUserAccess(MutateCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [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<MutateCustomerUserAccessResponse> MutateCustomerUserAccessAsync(MutateCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [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<MutateCustomerUserAccessResponse> MutateCustomerUserAccessAsync(MutateCustomerUserAccessRequest request, st::CancellationToken cancellationToken) =>
MutateCustomerUserAccessAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer being modified.
/// </param>
/// <param name="operation">
/// Required. The operation to perform on the customer
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerUserAccessResponse MutateCustomerUserAccess(string customerId, CustomerUserAccessOperation operation, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerUserAccess(new MutateCustomerUserAccessRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)),
}, callSettings);
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer being modified.
/// </param>
/// <param name="operation">
/// Required. The operation to perform on the customer
/// </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<MutateCustomerUserAccessResponse> MutateCustomerUserAccessAsync(string customerId, CustomerUserAccessOperation operation, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerUserAccessAsync(new MutateCustomerUserAccessRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)),
}, callSettings);
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer being modified.
/// </param>
/// <param name="operation">
/// Required. The operation to perform on the customer
/// </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<MutateCustomerUserAccessResponse> MutateCustomerUserAccessAsync(string customerId, CustomerUserAccessOperation operation, st::CancellationToken cancellationToken) =>
MutateCustomerUserAccessAsync(customerId, operation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CustomerUserAccessService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// This service manages the permissions of a user on a given customer.
/// </remarks>
public sealed partial class CustomerUserAccessServiceClientImpl : CustomerUserAccessServiceClient
{
private readonly gaxgrpc::ApiCall<GetCustomerUserAccessRequest, gagvr::CustomerUserAccess> _callGetCustomerUserAccess;
private readonly gaxgrpc::ApiCall<MutateCustomerUserAccessRequest, MutateCustomerUserAccessResponse> _callMutateCustomerUserAccess;
/// <summary>
/// Constructs a client wrapper for the CustomerUserAccessService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="CustomerUserAccessServiceSettings"/> used within this client.
/// </param>
public CustomerUserAccessServiceClientImpl(CustomerUserAccessService.CustomerUserAccessServiceClient grpcClient, CustomerUserAccessServiceSettings settings)
{
GrpcClient = grpcClient;
CustomerUserAccessServiceSettings effectiveSettings = settings ?? CustomerUserAccessServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetCustomerUserAccess = clientHelper.BuildApiCall<GetCustomerUserAccessRequest, gagvr::CustomerUserAccess>(grpcClient.GetCustomerUserAccessAsync, grpcClient.GetCustomerUserAccess, effectiveSettings.GetCustomerUserAccessSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetCustomerUserAccess);
Modify_GetCustomerUserAccessApiCall(ref _callGetCustomerUserAccess);
_callMutateCustomerUserAccess = clientHelper.BuildApiCall<MutateCustomerUserAccessRequest, MutateCustomerUserAccessResponse>(grpcClient.MutateCustomerUserAccessAsync, grpcClient.MutateCustomerUserAccess, effectiveSettings.MutateCustomerUserAccessSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCustomerUserAccess);
Modify_MutateCustomerUserAccessApiCall(ref _callMutateCustomerUserAccess);
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_GetCustomerUserAccessApiCall(ref gaxgrpc::ApiCall<GetCustomerUserAccessRequest, gagvr::CustomerUserAccess> call);
partial void Modify_MutateCustomerUserAccessApiCall(ref gaxgrpc::ApiCall<MutateCustomerUserAccessRequest, MutateCustomerUserAccessResponse> call);
partial void OnConstruction(CustomerUserAccessService.CustomerUserAccessServiceClient grpcClient, CustomerUserAccessServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CustomerUserAccessService client</summary>
public override CustomerUserAccessService.CustomerUserAccessServiceClient GrpcClient { get; }
partial void Modify_GetCustomerUserAccessRequest(ref GetCustomerUserAccessRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateCustomerUserAccessRequest(ref MutateCustomerUserAccessRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the CustomerUserAccess 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::CustomerUserAccess GetCustomerUserAccess(GetCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerUserAccessRequest(ref request, ref callSettings);
return _callGetCustomerUserAccess.Sync(request, callSettings);
}
/// <summary>
/// Returns the CustomerUserAccess 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::CustomerUserAccess> GetCustomerUserAccessAsync(GetCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerUserAccessRequest(ref request, ref callSettings);
return _callGetCustomerUserAccess.Async(request, callSettings);
}
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [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 MutateCustomerUserAccessResponse MutateCustomerUserAccess(MutateCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerUserAccessRequest(ref request, ref callSettings);
return _callMutateCustomerUserAccess.Sync(request, callSettings);
}
/// <summary>
/// Updates, removes permission of a user on a given customer. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CustomerUserAccessError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [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<MutateCustomerUserAccessResponse> MutateCustomerUserAccessAsync(MutateCustomerUserAccessRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerUserAccessRequest(ref request, ref callSettings);
return _callMutateCustomerUserAccess.Async(request, callSettings);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel;
using Csla.Validation;
namespace Northwind.CSLA.Library
{
/// <summary>
/// EmployeeOrder Generated by MyGeneration using the CSLA Object Mapping template
/// </summary>
[Serializable()]
[TypeConverter(typeof(EmployeeOrderConverter))]
public partial class EmployeeOrder : BusinessBase<EmployeeOrder>, IVEHasBrokenRules
{
#region Business Methods
private string _ErrorMessage = string.Empty;
public string ErrorMessage
{
get { return _ErrorMessage; }
}
private int _OrderID;
[System.ComponentModel.DataObjectField(true, true)]
public int OrderID
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MyOrder != null) _OrderID = _MyOrder.OrderID;
return _OrderID;
}
}
private Order _MyOrder;
[System.ComponentModel.DataObjectField(true, true)]
public Order MyOrder
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MyOrder == null && _OrderID != 0) _MyOrder = Order.Get(_OrderID);
return _MyOrder;
}
}
private string _CustomerID = string.Empty;
public string CustomerID
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MyCustomer != null) _CustomerID = _MyCustomer.CustomerID;
return _CustomerID;
}
}
private Customer _MyCustomer;
public Customer MyCustomer
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MyCustomer == null && _CustomerID != null) _MyCustomer = Customer.Get((string)_CustomerID);
return _MyCustomer;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (_MyCustomer != value)
{
_MyCustomer = value;
_CustomerID = (value == null ? null : (string) value.CustomerID);
PropertyHasChanged();
}
}
}
private string _OrderDate = string.Empty;
public string OrderDate
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _OrderDate;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
_OrderDate = value;
try
{
SmartDate tmp = new SmartDate(value);
if (_OrderDate != tmp.ToString())
{
_OrderDate = tmp.ToString();
// TODO: Any Cross Property Validation
}
}
catch
{
}
PropertyHasChanged();
}
}
private string _RequiredDate = string.Empty;
public string RequiredDate
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _RequiredDate;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
_RequiredDate = value;
try
{
SmartDate tmp = new SmartDate(value);
if (_RequiredDate != tmp.ToString())
{
_RequiredDate = tmp.ToString();
// TODO: Any Cross Property Validation
}
}
catch
{
}
PropertyHasChanged();
}
}
private string _ShippedDate = string.Empty;
public string ShippedDate
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _ShippedDate;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
_ShippedDate = value;
try
{
SmartDate tmp = new SmartDate(value);
if (_ShippedDate != tmp.ToString())
{
_ShippedDate = tmp.ToString();
// TODO: Any Cross Property Validation
}
}
catch
{
}
PropertyHasChanged();
}
}
private int? _ShipVia;
public int? ShipVia
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MyShipper != null) _ShipVia = _MyShipper.ShipperID;
return _ShipVia;
}
}
private Shipper _MyShipper;
public Shipper MyShipper
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MyShipper == null && _ShipVia != null) _MyShipper = Shipper.Get((int)_ShipVia);
return _MyShipper;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (_MyShipper != value)
{
_MyShipper = value;
_ShipVia = (value == null ? null : (int?) value.ShipperID);
PropertyHasChanged();
}
}
}
private decimal? _Freight;
public decimal? Freight
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Freight;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (_Freight != value)
{
_Freight = value;
PropertyHasChanged();
}
}
}
private string _ShipName = string.Empty;
public string ShipName
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _ShipName;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_ShipName != value)
{
_ShipName = value;
PropertyHasChanged();
}
}
}
private string _ShipAddress = string.Empty;
public string ShipAddress
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _ShipAddress;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_ShipAddress != value)
{
_ShipAddress = value;
PropertyHasChanged();
}
}
}
private string _ShipCity = string.Empty;
public string ShipCity
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _ShipCity;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_ShipCity != value)
{
_ShipCity = value;
PropertyHasChanged();
}
}
}
private string _ShipRegion = string.Empty;
public string ShipRegion
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _ShipRegion;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_ShipRegion != value)
{
_ShipRegion = value;
PropertyHasChanged();
}
}
}
private string _ShipPostalCode = string.Empty;
public string ShipPostalCode
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _ShipPostalCode;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_ShipPostalCode != value)
{
_ShipPostalCode = value;
PropertyHasChanged();
}
}
}
private string _ShipCountry = string.Empty;
public string ShipCountry
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _ShipCountry;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_ShipCountry != value)
{
_ShipCountry = value;
PropertyHasChanged();
}
}
}
// TODO: Check EmployeeOrder.GetIdValue to assure that the ID returned is unique
/// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary>
/// <returns>A Unique ID for the current EmployeeOrder</returns>
protected override object GetIdValue()
{
return _OrderID;
}
// TODO: Replace base EmployeeOrder.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current EmployeeOrder</returns>
//public override string ToString()
//{
// return base.ToString();
//}
#endregion
#region ValidationRules
[NonSerialized]
private bool _CheckingBrokenRules=false;
public IVEHasBrokenRules HasBrokenRules
{
get
{
if(_CheckingBrokenRules)return null;
if (BrokenRulesCollection.Count > 0) return this;
try
{
_CheckingBrokenRules=true;
IVEHasBrokenRules hasBrokenRules = null;
if (_MyCustomer != null && (hasBrokenRules = _MyCustomer.HasBrokenRules) != null) return hasBrokenRules;
if (_MyShipper != null && (hasBrokenRules = _MyShipper.HasBrokenRules) != null) return hasBrokenRules;
return hasBrokenRules;
}
finally
{
_CheckingBrokenRules=false;
}
}
}
public BrokenRulesCollection BrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null);
}
}
protected override void AddBusinessRules()
{
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("CustomerID", 5));
ValidationRules.AddRule<EmployeeOrder>(OrderDateValid, "OrderDate");
ValidationRules.AddRule<EmployeeOrder>(RequiredDateValid, "RequiredDate");
ValidationRules.AddRule<EmployeeOrder>(ShippedDateValid, "ShippedDate");
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShipName", 40));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShipAddress", 60));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShipCity", 15));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShipRegion", 15));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShipPostalCode", 10));
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShipCountry", 15));
// TODO: Add other validation rules
}
private static bool OrderDateValid(EmployeeOrder target, Csla.Validation.RuleArgs e)
{
try
{
DateTime tmp = SmartDate.StringToDate(target._OrderDate);
}
catch
{
e.Description = "Invalid Date";
return false;
}
return true;
}
private static bool RequiredDateValid(EmployeeOrder target, Csla.Validation.RuleArgs e)
{
try
{
DateTime tmp = SmartDate.StringToDate(target._RequiredDate);
}
catch
{
e.Description = "Invalid Date";
return false;
}
return true;
}
private static bool ShippedDateValid(EmployeeOrder target, Csla.Validation.RuleArgs e)
{
try
{
DateTime tmp = SmartDate.StringToDate(target._ShippedDate);
}
catch
{
e.Description = "Invalid Date";
return false;
}
return true;
}
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion
#region Authorization Rules
protected override void AddAuthorizationRules()
{
//TODO: Who can read/write which fields
//AuthorizationRules.AllowRead(OrderID, "<Role(s)>");
//AuthorizationRules.AllowRead(CustomerID, "<Role(s)>");
//AuthorizationRules.AllowWrite(CustomerID, "<Role(s)>");
//AuthorizationRules.AllowRead(OrderDate, "<Role(s)>");
//AuthorizationRules.AllowWrite(OrderDate, "<Role(s)>");
//AuthorizationRules.AllowRead(RequiredDate, "<Role(s)>");
//AuthorizationRules.AllowWrite(RequiredDate, "<Role(s)>");
//AuthorizationRules.AllowRead(ShippedDate, "<Role(s)>");
//AuthorizationRules.AllowWrite(ShippedDate, "<Role(s)>");
//AuthorizationRules.AllowRead(ShipVia, "<Role(s)>");
//AuthorizationRules.AllowWrite(ShipVia, "<Role(s)>");
//AuthorizationRules.AllowRead(Freight, "<Role(s)>");
//AuthorizationRules.AllowWrite(Freight, "<Role(s)>");
//AuthorizationRules.AllowRead(ShipName, "<Role(s)>");
//AuthorizationRules.AllowWrite(ShipName, "<Role(s)>");
//AuthorizationRules.AllowRead(ShipAddress, "<Role(s)>");
//AuthorizationRules.AllowWrite(ShipAddress, "<Role(s)>");
//AuthorizationRules.AllowRead(ShipCity, "<Role(s)>");
//AuthorizationRules.AllowWrite(ShipCity, "<Role(s)>");
//AuthorizationRules.AllowRead(ShipRegion, "<Role(s)>");
//AuthorizationRules.AllowWrite(ShipRegion, "<Role(s)>");
//AuthorizationRules.AllowRead(ShipPostalCode, "<Role(s)>");
//AuthorizationRules.AllowWrite(ShipPostalCode, "<Role(s)>");
//AuthorizationRules.AllowRead(ShipCountry, "<Role(s)>");
//AuthorizationRules.AllowWrite(ShipCountry, "<Role(s)>");
}
public static bool CanAddObject()
{
// TODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// TODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// TODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// TODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion
#region Factory Methods
public int CurrentEditLevel
{ get { return EditLevel; } }
internal static EmployeeOrder New()
{
return new EmployeeOrder();
}
internal static EmployeeOrder Get(SafeDataReader dr)
{
return new EmployeeOrder(dr);
}
public EmployeeOrder()
{
MarkAsChild();
_OrderID = Order.NextOrderID;
_Freight = _EmployeeOrderExtension.DefaultFreight;
ValidationRules.CheckRules();
}
internal EmployeeOrder(SafeDataReader dr)
{
MarkAsChild();
Fetch(dr);
}
#endregion
#region Data Access Portal
private void Fetch(SafeDataReader dr)
{
Database.LogInfo("EmployeeOrder.FetchDR", GetHashCode());
try
{
_OrderID = dr.GetInt32("OrderID");
_CustomerID = dr.GetString("CustomerID");
_OrderDate = dr.GetSmartDate("OrderDate").Text;
_RequiredDate = dr.GetSmartDate("RequiredDate").Text;
_ShippedDate = dr.GetSmartDate("ShippedDate").Text;
_ShipVia = (int?)dr.GetValue("ShipVia");
_Freight = (decimal?)dr.GetValue("Freight");
_ShipName = dr.GetString("ShipName");
_ShipAddress = dr.GetString("ShipAddress");
_ShipCity = dr.GetString("ShipCity");
_ShipRegion = dr.GetString("ShipRegion");
_ShipPostalCode = dr.GetString("ShipPostalCode");
_ShipCountry = dr.GetString("ShipCountry");
}
catch (Exception ex) // FKItem Fetch
{
Database.LogException("EmployeeOrder.FetchDR", ex);
throw new DbCslaException("EmployeeOrder.Fetch", ex);
}
MarkOld();
}
internal void Insert(Employee myEmployee)
{
// if we're not dirty then don't update the database
if (!this.IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
Order.Add(cn, ref _OrderID, _MyCustomer, myEmployee, new SmartDate(_OrderDate), new SmartDate(_RequiredDate), new SmartDate(_ShippedDate), _MyShipper, _Freight, _ShipName, _ShipAddress, _ShipCity, _ShipRegion, _ShipPostalCode, _ShipCountry);
MarkOld();
}
internal void Update(Employee myEmployee)
{
// if we're not dirty then don't update the database
if (!this.IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
Order.Update(cn, ref _OrderID, _MyCustomer, myEmployee, new SmartDate(_OrderDate), new SmartDate(_RequiredDate), new SmartDate(_ShippedDate), _MyShipper, _Freight, _ShipName, _ShipAddress, _ShipCity, _ShipRegion, _ShipPostalCode, _ShipCountry);
MarkOld();
}
internal void DeleteSelf(Employee myEmployee)
{
// if we're not dirty then don't update the database
if (!this.IsDirty) return;
// if we're new then don't update the database
if (this.IsNew) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
Order.Remove(cn, _OrderID);
MarkNew();
}
#endregion
// Standard Default Code
#region extension
EmployeeOrderExtension _EmployeeOrderExtension = new EmployeeOrderExtension();
[Serializable()]
partial class EmployeeOrderExtension : extensionBase
{
}
[Serializable()]
class extensionBase
{
// Default Values
public virtual decimal? DefaultFreight
{
get { return 0; }
}
// Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{
// Needs to be overriden to add new authorization rules
}
// Instance Authorization Rules
public virtual void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
{
// Needs to be overriden to add new authorization rules
}
// Validation Rules
public virtual void AddValidationRules(Csla.Validation.ValidationRules rules)
{
// Needs to be overriden to add new validation rules
}
// InstanceValidation Rules
public virtual void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
{
// Needs to be overriden to add new validation rules
}
}
#endregion
} // Class
#region Converter
internal class EmployeeOrderConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is EmployeeOrder)
{
// Return the ToString value
return ((EmployeeOrder)value).ToString();
}
return base.ConvertTo(context, culture, value, destType);
}
}
#endregion
} // Namespace
//// The following is a sample Extension File. You can use it to create EmployeeOrderExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace Northwind.CSLA.Library
//{
// public partial class EmployeeOrder
// {
// partial class EmployeeOrderExtension : extensionBase
// {
// // TODO: Override automatic defaults
// public virtual decimal? DefaultFreight
// {
// get { return 0; }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.